import numpy as np
from sklearn.linear_model import LinearRegression
import matplotlib.pyplot as plt
np.random.seed(42)
X1 = 2*np.random.rand(100,1)
X2 = 2*np.random.rand(100,2)
X = np.c_[X1,X2]
print("Input X shape: {}".format(X.shape))
y = 4*np.random.randn(100,1)
print("Input y shape: {}".format(y.shape))
reg = LinearRegression(fit_intercept=True)
reg.fit(X, y)
print("Intercept: {}\nEstimated coefficients: {}".format(reg.intercept_, reg.coef_))
# 预测
# X_new与X的维度应该一致,都是3列
X_new = np.array([[0,0,0],[2,1,2],[2,4,3]])
y_predict = reg.predict(X_new)
print("Predicted values:\n{}".format(y_predict))
#绘图
plt.plot(X, y, 'b.')
plt.plot(X_new, y_predict, 'r-')
plt.axis([0,2,0,15])
plt.show()
老师,如果我们的数据集没有办法分辨y和维度x是属于线性变化关系,也就是我们没办法提供类似y = a + bx的表达式,那么是不是我们就不应该使用简单线性回归去训练模型?因为很多时候在工作上,对于训练集里面的数据,我们是不太清楚维度与真实值之间的关系的(譬如:y=sales, x1=广告投入, x2=人力成本, x3=原材料成本)。我尝试了一下去算输入的X和y,结果很怪,绘图出来的分界线很差很怪,感觉它们不是线性关系,不应该用简单LR去做,麻烦老师纠正我的理解。