从pandas DataFrame开始,d_train
(774行):
想法是按照此处的示例研究脊系数路径。
在该示例中,以下是变量类型:
X, y, w = make_regression(n_samples=10, n_features=10, coef=True,
random_state=1, bias=3.5)
print X.shape, type(X), y.shape, type(y), w.shape, type(w)
>> (10, 10) <type 'numpy.ndarray'> (10,) <type 'numpy.ndarray'> (10,) <type'numpy.ndarray'>
为了避免在这个stackoverflow讨论中提到的问题,我将所有内容都转换为numpy数组:
predictors = ['p1', 'p2', 'p3', 'p4']
target = ['target_bins']
X = d_train[predictors].as_matrix()
### X = np.transpose(d_train[predictors].as_matrix())
y = d_train['target_bins'].as_matrix()
w = numpy.full((774,), 3, dtype=float)
print X.shape, type(X), y.shape, type(y), w.shape, type(w)
>> (774, 4) <type 'numpy.ndarray'> y_shape: (774,) <type 'numpy.ndarray'> w_shape: (774,) <type 'numpy.ndarray'>
然后,我只运行了(a)示例中的确切代码,(b)将参数添加fit_intercept = True, normalize = True
到ridge调用(我的数据未缩放)以获得相同的错误消息:
my_ridge = Ridge()
coefs = []
errors = []
alphas = np.logspace(-6, 6, 200)
for a in alphas:
my_ridge.set_params(alpha=a, fit_intercept = True, normalize = True)
my_ridge.fit(X, y)
coefs.append(my_ridge.coef_)
errors.append(mean_squared_error(my_ridge.coef_, w))
>> ValueError: Found input variables with inconsistent numbers of samples: [4, 774]
正如代码的注释部分指出的那样,我也尝试了“相同”代码,但使用了转置的X矩阵。在创建之前,我还尝试缩放数据X matrix
。得到了相同的错误消息。
最后,我使用“ RidgeClassifier”做了同样的事情,并且得到了不同的错误消息。
>> Found input variables with inconsistent numbers of samples: [1, 774]
问题:我不知道这是怎么回事-您能帮忙吗?
在Canopy 1.7.4.3348(64位)上使用python 2.7和scikit-learn 18.01-3和pandas 0.19.2-2
谢谢你。
您需要具有与w
要素数量一样多的权重(因为您学习了每个要素的权重),但是在代码中,权重向量的维数为774(这是训练数据集中的行数),这就是为什么这没用。将代码修改为以下代码(改为具有4个权重),一切将正常进行:
w = np.full((4,), 3, dtype=float) # number of features = 4, namely p1, p2, p3, p4
print X.shape, type(X), y.shape, type(y), w.shape, type(w)
#(774L, 4L) <type 'numpy.ndarray'> (774L,) <type 'numpy.ndarray'> (4L,) <type 'numpy.ndarray'>
现在,您可以从运行代码的其余部分http://scikit-learn.org/stable/auto_examples/linear_model/plot_ridge_coeffs.html#sphx-glr-auto-examples-linear-model-plot-ridge-coeffs-py到alpha
通过grid-search了解权重和误差如何随正则化参数变化,并获得下图
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句