gpt4 book ai didi

python - 如何在 scikit-learn 中对 SVM 应用标准化?

转载 作者:IT老高 更新时间:2023-10-28 20:20:54 44 4
gpt4 key购买 nike

我正在使用 scikit-learn 的当前稳定版本 0.13。我正在使用类 sklearn.svm.LinearSVC 对一些数据应用线性支持向量分类器。 .

chapter about preprocessing在 scikit-learn 的文档中,我阅读了以下内容:

Many elements used in the objective function of a learning algorithm (such as the RBF kernel of Support Vector Machines or the l1 and l2 regularizers of linear models) assume that all features are centered around zero and have variance in the same order. If a feature has a variance that is orders of magnitude larger that others, it might dominate the objective function and make the estimator unable to learn from other features correctly as expected.

问题 1:标准化对一般的 SVM 有用吗?也适用于像我这样具有线性核函数的那些?

问题 2: 据我了解,我必须计算训练数据的均值和标准差,并使用类 sklearn.preprocessing.StandardScaler 对测试数据应用相同的转换。 .但是,我不明白的是,在将训练数据输入 SVM 分类器之前,我是否必须同时转换训练数据或仅转换测试数据。

也就是说,我必须这样做吗:

scaler = StandardScaler()
scaler.fit(X_train) # only compute mean and std here
X_test = scaler.transform(X_test) # perform standardization by centering and scaling

clf = LinearSVC()
clf.fit(X_train, y_train)
clf.predict(X_test)

或者我必须这样做:

scaler = StandardScaler()
X_train = scaler.fit_transform(X_train) # compute mean, std and transform training data as well
X_test = scaler.transform(X_test) # same as above

clf = LinearSVC()
clf.fit(X_train, y_train)
clf.predict(X_test)

简而言之,我是否必须在训练数据上使用 scaler.fit(X_train)scaler.fit_transform(X_train) 才能获得合理的结果 LinearSVC?

最佳答案

都没有。

scaler.transform(X_train) 没有任何效果。 transform 操作未就地。你必须这样做

X_train = scaler.fit_transform(X_train)

X_test = scaler.transform(X_test)

X_train = scaler.fit(X_train).transform(X_train)

您始终需要对训练或测试数据进行相同的预处理。是的,标准化总是好的,如果它反射(reflect)了你对数据的信念。特别是对于 kernel-svm,它通常是至关重要的。

关于python - 如何在 scikit-learn 中对 SVM 应用标准化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14688391/

44 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com