scikit-learn中的Scaler
生活随笔
收集整理的這篇文章主要介紹了
scikit-learn中的Scaler
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
對測試數據集的歸一化
注:測試數據集用的方差與均值應是訓練數據集的方差與均值。
scikit-learn中的Scaler
import numpy as np from sklearn import datasets from sklearn.model_selection import train_test_splitiris = datasets.load_iris()X = iris.data y = iris.targetX_train, X_test, y_train, y_test = train_test_split(iris.data, iris.target, test_size = 0.2, random_state = 666)scikit-learn中的StandardScaler
from sklearn.preprocessing import StandardScalerstandardScaler = StandardScaler() standardScaler.fit(X_train)之后我們可以看一下他的均值和標準差:
standardScaler.mean_ standardScaler.scale_然后我們就可以進行歸一化:
X_train = standardScaler.transform(X_train) X_test_standard = standardScaler.transform(X_test)最后我們可以看一下效果:
封裝
import numpy as npclass StandardScaler:def __init__(self):self.mean_ = Noneself.scale_ = Nonedef fit(self, X):assert X.ndim == 2, "The dimension of X must be 2"self.mean_ = np.array([np.mean(X[:,i]) for i in range(X.shape[1])])self.scale_ = np.array([np.std(X[:, i]) for i in range(X.shape[1])])return selfdef tranform(self, X):assert X.ndim == 2, "The dimension of X must be 2"assert self.mean_ is not None and self.scale_ is not None, \"must fit before transform!"assert X.shape[1] == len(self.mean_), \"the feature number of X must be equal to mean_ and std_"resX = np.empty(shape=X.shape, dtype=float)for col in range(X.shape[1]):resX[:,col] = (X[:, col] - self.mean_[col]) / self.scale_[col]return resX總結
以上是生活随笔為你收集整理的scikit-learn中的Scaler的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Cisco AnyConnect Cli
- 下一篇: 美女上班迟到的N个理由