嗨,我有一个线性回归模型,我正在尝试优化它。我正在优化指数移动平均值的跨度和我在回归中使用的滞后变量的数量。
然而,我不断发现,结果和计算的mse不断得出不同的最终结果。不知道为什么有人能帮忙?
启动循环后的过程:1.使用三个变量创建新的数据帧2.删除零值3.为每个变量创建ewma4.为每个变量创建滞后5.删除NA6.创建X,y7.如果MSE更好,则回归并保存ema跨度和滞后数8.使用下一个值开始循环
我知道这可能是一个交叉验证的问题,但由于它可能是一种程序,我在这里发布了:
bestema = 0
bestlag = 0
mse = 1000000
for e in range(2, 30):
for lags in range(1, 20):
df2 = df[['diffbn','diffbl','diffbz']]
df2 = df2[(df2 != 0).all(1)]
df2['emabn'] = pd.ewma(df2.diffbn, span=e)
df2['emabl'] = pd.ewma(df2.diffbl, span=e)
df2['emabz'] = pd.ewma(df2.diffbz, span=e)
for i in range(0,lags):
df2["lagbn%s" % str(i+1)] = df2["emabn"].shift(i+1)
df2["lagbz%s" % str(i+1)] = df2["emabz"].shift(i+1)
df2["lagbl%s" % str(i+1)] = df2["emabl"].shift(i+1)
df2 = df2.dropna()
b = list(df2)
#print(a)
b.remove('diffbl')
b.remove('emabn')
b.remove('emabz')
b.remove('emabl')
b.remove('diffbn')
b.remove('diffbz')
X = df2[b]
y = df2["diffbl"]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3)
#print(X_train.shape)
regr = linear_model.LinearRegression()
regr.fit(X_train, y_train)
if(mean_squared_error(y_test,regr.predict(X_test)) < mse):
mse = mean_squared_error(y_test,regr.predict(X_test) ** 2)
#mse = mean_squared_error(y_test,regr.predict(X_test))
bestema = e
bestlag = lags
print(regr.coef_)
print(bestema)
print(bestlag)
print(mse)
sklearn中的train_test_split
函数(请参阅文档:http://scikit-learn.org/stable/modules/generated/sklearn.cross_validation.train_testrongplit.html)是随机的,所以每次得到不同的结果是合乎逻辑的
您可以将参数传递给random_state
关键字,使其每次都相同。