在scikit learn中使用SVR进行时间序列预测



我有按日期索引的每日温度数据集,我需要在scikit-learn中使用[SVR][1]预测未来的温度。

我坚持选择训练X和测试YX设置。例如,如果我想在时间t预测Y,那么我需要 训练集包含t-1, t-2, ..., t-NXY,其中N是用于预测Yt的前几天数。

我该怎么做?

就是这样。

df=daily_temp1
# define function for create N lags
def create_lags(df, N):
for i in range(N):
df['datetime' + str(i+1)] = df.datetime.shift(i+1)
df['dewpoint' + str(i+1)] = df.dewpoint.shift(i+1)
df['humidity' + str(i+1)] = df.humidity.shift(i+1)
df['pressure' + str(i+1)] = df.pressure.shift(i+1)
df['temperature' + str(i+1)] = df.temperature.shift(i+1)
df['vism' + str(i+1)] = df.vism.shift(i+1)
df['wind_direcd' + str(i+1)] = df.wind_direcd.shift(i+1)
df['wind_speed' + str(i+1)] = df.wind_speed.shift(i+1)
df['wind_direct' + str(i+1)] = df.wind_direct.shift(i+1)
return df
# create 10 lags
df = create_lags(df,10)

# the first 10 days will have missing values. can't use them.
df = df.dropna()
# create X and y
y = df['temperature']
X = df.iloc[:, 9:]
# Train on 70% of the data
train_idx = int(len(df) * .7)
# create train and test data
X_train, y_train, X_test, y_test = X[:train_idx], y[:train_idx], X[train_idx:], y[train_idx:]

# fit and predict
clf = SVR()
clf.fit(X_train, y_train)
clf.predict(X_test)

这是一个解决方案,它将特征矩阵X构建为简单的 lag1 - lagN,其中 lag1 是前几天的温度,lagN 是 N 天前的温度。

# create fake temperature
df = pd.DataFrame({'temp':np.random.rand(500)})
# define function for create N lags
def create_lags(df, N):
for i in range(N):
df['Lag' + str(i+1)] = df.temp.shift(i+1)
return df
# create 10 lags
df = create_lags(df,10)
# the first 10 days will have missing values. can't use them.
df = df.dropna()
# create X and y
y = df.temp.values
X = df.iloc[:, 1:].values
# Train on 70% of the data
train_idx = int(len(df) * .7)
# create train and test data
X_train, y_train, X_test, y_test = X[:train_idx], y[:train_idx], X[train_idx:], y[:train_idx]
# fit and predict
clf = SVR()
clf.fit(X_train, y_train)
clf.predict(X_test)

相关内容

  • 没有找到相关文章

最新更新