python數據標准化


def datastandard(): from sklearn import preprocessing import numpy as np x = np.array([ [ 1., -1., 2.], [ 2., 0., 0.], [ 0., 1., -1.]]) print('原始數據為:\n',x) print('method1:指定均值方差數據標准化(默認均值0 方差 1):') print('使用scale()函數 按列標准化') x_scaled = preprocessing.scale(x) print('標准化后矩陣為:\n',x_scaled,end='\n\n') print('cur mean:', x_scaled.mean(axis=0), 'cur std:', x_scaled.std(axis=0)) print('使用scale()函數 按行標准化') x_scaled = preprocessing.scale(x,axis=1) print('標准化后矩陣為:\n',x_scaled,end='\n') print('cur mean:', x_scaled.mean(axis=1), 'cur std:', x_scaled.std(axis=1)) print('\nmethod2:StandardScaler類,可以保存訓練集中的參數') scaler = preprocessing.StandardScaler().fit(x) print('標准化前 均值方差為:',scaler.mean_,scaler.scale_) print('標准化后矩陣為:\n',scaler.transform(x),end='\n\n') print('***2.數據歸一化,映射到區間[min,max]:') min_max_scaler = preprocessing.MinMaxScaler(feature_range=(0,10)) print(min_max_scaler.fit_transform(x)) if __name__ == '__main__': datastandard()

結果如下:

原始數據為:
 [[ 1. -1. 2.] [ 2. 0. 0.] [ 0. 1. -1.]] method1:指定均值方差數據標准化(默認均值0 方差 1): 使用scale()函數 按列標准化 標准化后矩陣為: [[ 0. -1.22474487 1.33630621] [ 1.22474487 0. -0.26726124] [-1.22474487 1.22474487 -1.06904497]] cur mean: [ 0. 0. 0.] cur std: [ 1. 1. 1.] 使用scale()函數 按行標准化 標准化后矩陣為: [[ 0.26726124 -1.33630621 1.06904497] [ 1.41421356 -0.70710678 -0.70710678] [ 0. 1.22474487 -1.22474487]] cur mean: [ 1.48029737e-16 7.40148683e-17 0.00000000e+00] cur std: [ 1. 1. 1.] method2:StandardScaler類,可以保存訓練集中的參數 標准化前 均值方差為: [ 1. 0. 0.33333333] [ 0.81649658 0.81649658 1.24721913] 標准化后矩陣為: [[ 0. -1.22474487 1.33630621] [ 1.22474487 0. -0.26726124] [-1.22474487 1.22474487 -1.06904497]] ***2.數據歸一化,映射到區間[min,max]: [[ 5. 0. 10. ] [ 10. 5. 3.33333333] [ 0. 10. 0. ]]

python 常用代碼

# coding:utf8 ''' 提取文檔中含有某個字符的所有行,並打印出來 ''' file_path = 'E:/gengyanpeng/義烏調研資料/客運gyp資料/keyun-bi.sql' fix_str = 'FROM' def print_line(txt,fix_str): lines = txt.split('\n') for line in lines: if fix_str in line: print(line.strip()) with open(file_path,'r+',encoding='utf8') as f: text = f.read() print_line(text,fix_str)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM