标准化

可以用StandardScaler函数进行标准化,好处是可以保存训练集中的参数(均值、方差)直接使用其对象转换测试集数据

import numpy as np
import pandas as pd
import xlrd 
from sklearn import preprocessing
from pandas import DataFrame
def standardScaler(path):
    table = xlrd.open_workbook(path).sheets()[0]#获取第一个sheet表
    row = table.nrows  # 行数
    col = table.ncols  # 列数
    datamatrix = np.zeros((row, col))#生成一个nrows行ncols列,且元素均为0的初始矩阵
    for x in range(col):
        cols = np.matrix(table.col_values(x))  # 把list转换为矩阵进行矩阵操作
        datamatrix[:, x] = cols # 按列把数据存进矩阵中
    #标准化
    scaler=preprocessing.StandardScaler().fit(datamatrix)
    return (scaler.transform(datamatrix))
    #返回的就是标准化好的矩阵了
path = r'c:\Users\Liugengxin\Desktop\test.xlsx'
data = standardScaler(path) #标准化好的矩阵存在了data中
DataFrame(data).to_excel(r'c:\Users\Liugengxin\Desktop\test_end.xlsx')#写入test_end中

 

posted @ 2019-01-12 11:33  GXLiu  阅读(236)  评论(0编辑  收藏  举报