在重现这个交叉验证示例时,我得到一个 2x4 训练矩阵 (xtrain) 的 len(b.get_support()) 为 1 000 000。这是否意味着模型中创建了 1 000 000 个特征?或仅 2,因为有影响的要素数为 2。谢谢!
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
from sklearn.feature_selection import SelectKBest, f_regression
from sklearn.cross_validation import cross_val_score, KFold
from sklearn.linear_model import LinearRegression
### create data
def hidden_model(x):
#y is a linear combination of columns 5 and 10...
result = x[:, 5] + x[:, 10]
#... with a little noise
result += np.random.normal(0, .005, result.shape)
return result
def make_x(nobs):
return np.random.uniform(0, 3, (nobs, 10 ** 6))
x = make_x(20)
y = hidden_model(x)
scores = []
clf = LinearRegression()
for train, test in KFold(len(y), n_folds=5):
xtrain, xtest, ytrain, ytest = x[train], x[test], y[train], y[test]
b = SelectKBest(f_regression, k=2)
b.fit(xtrain,ytrain)
xtrain = xtrain[:, b.get_support()] #get_support: get mask or integer index of selected features
xtest = xtest[:, b.get_support()]
print len(b.get_support())
clf.fit(xtrain, ytrain)
scores.append(clf.score(xtest, ytest))
yp = clf.predict(xtest)
plt.plot(yp, ytest, 'o')
plt.plot(ytest, ytest, 'r-')
plt.xlabel('Predicted')
plt.ylabel('Observed')
print("CV Score (R_square) is", np.mean(scores))
它表示可以应用于x
以获取使用 SelectKBest
例程选择的功能的掩码。
print x.shape
print b.get_support().shape
print np.bincount(b.get_support())
输出:
(20, 1000000)
(1000000,)
[999998 2]
这表明您有 20 个 1000000 维数据的示例,一个长度为 1000000 的布尔数组,其中只有两个是 1。
希望对您有所帮助!