[英]Scikit-learn: role of weights in Ridge Regression
我正在使用scikit-learn
库来对单个样本进行权重进行岭回归。 这可以通过以下方式完成: esimator.fit(X, y, sample_weight=some_array)
。 直观地说,我希望较大的权重意味着相应样本的相关性更大。
但是,我在以下2-D示例中测试了上述方法:
from sklearn import linear_model
import numpy
import matplotlib.pyplot as plt
#Data
x= numpy.array([[0], [1],[2]])
y= numpy.array([[0], [2],[2]])
sample_weight = numpy.array([1,1, 1])
#Ridge regression
clf = linear_model.Ridge(alpha = 0.1)
clf.fit(x, y, sample_weight = sample_weight)
#Plot
xp = numpy.linspace(-1,3)
yp=list()
for x_i in xp:
yp.append(clf.predict(x_i)[0,0])
plt.plot(xp,yp)
plt.hold(True)
x = list(x)
y = list(y)
plt.plot(x,y,'or')
我运行这段代码,然后再次运行它,使第一个样本的重量加倍:
sample_weight = numpy.array([2,1, 1])
生成的线条远离重量较大的样品。 这是违反直觉的,因为我预计重量较大的样本具有较大的相关性。
我错误地使用了库,还是有错误?
权重不反转。 可能你犯了一个愚蠢的错误,或者sklearn
存在一个现在修复的错误。 编码
from sklearn import linear_model
import numpy
import matplotlib.pyplot as plt
#Data
x = numpy.array([[0], [1],[2]])
y = numpy.array([[0], [2],[2]])
sample_weight1 = numpy.array([1, 1, 1])
sample_weight2 = numpy.array([2, 1, 1])
#Ridge regressions
clf1 = linear_model.Ridge(alpha = 0.1).fit(x, y, sample_weight = sample_weight1)
clf2 = linear_model.Ridge(alpha = 0.1).fit(x, y, sample_weight = sample_weight2)
#Plot
plt.scatter(x,y)
xp = numpy.linspace(-1,3)
plt.plot(xp,clf1.predict(xp.reshape(-1, 1)))
plt.plot(xp,clf2.predict(xp.reshape(-1, 1)))
plt.legend(['equal weights', 'first obs weights more'])
plt.title('Increasing weight of the first obs moves the line closer to it');
绘制我的图表,其中第二行(增加的第一重量)更接近第一个观察:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.