【发布时间】:2019-03-01 03:47:21
【问题描述】:
我目前正在使用 TensorFlow 和 SkLearn 来尝试制作一个模型,该模型可以根据室外摄氏温度来预测某个产品 X 的销售额。
我将温度数据集设置为 x 变量,并将销售额设置为 y 变量。如下图所示,温度和销售额之间存在某种相关性:
首先,我尝试进行线性回归以查看它的拟合程度。这是它的代码:
from sklearn.linear_model import LinearRegression
model = LinearRegression()
model.fit(x_train, y_train) #fit tries to fit the x variable and y variable.
#Let's try to plot it out.
y_pred = model.predict(x_train)
plt.scatter(x_train,y_train)
plt.plot(x_train,y_pred,'r')
plt.legend(['Predicted Line', 'Observed data'])
plt.show()
这导致预测线的拟合非常差:
但是,sklearn 的一个非常好的功能是您可以尝试根据温度来预测一个值,所以如果我要写
model.predict(15)
我会得到输出
array([6949.05567873])
这正是我想要的,我只是想更好地拟合,所以我尝试使用 sklearn 进行多项式回归,方法如下:
from sklearn.preprocessing import PolynomialFeatures
poly = PolynomialFeatures(degree=8, include_bias=False) #the bias is avoiding the need to intercept
x_new = poly.fit_transform(x_train)
new_model = LinearRegression()
new_model.fit(x_new,y_train)
#plotting
y_prediction = new_model.predict(x_new) #this actually predicts x...?
plt.scatter(x_train,y_train)
plt.plot(x_new[:,0], y_prediction, 'r')
plt.legend(['Predicted line', 'Observed data'])
plt.show()
我的问题不是我不能使用 new_model.predict(x) 因为它会导致 "ValueError: shapes (1,1) and (8,) not aligned: 1 (dim 1) != 8 (dim 0)"。我知道这是因为我使用的是 8 度多项式,但是有什么方法可以让我使用多项式回归模型根据 ONE 温度预测 y 轴?
【问题讨论】:
-
你能试试
new_model.predict([x for _ in range(8)])吗? -
如果我写在
new_model.predict([[30 for x_train in range(8)]])我确实得到了一个输出,但输出是 array([2862.55322278]) 根据模型我希望输出超过15k,你知道我为什么得到这么低的数字吗?
标签: python tensorflow machine-learning scikit-learn