[开源]基于SVM的时间序列预测python代码

整理了SVM的时间序列预测python代码分享给大家。记得点赞哦

#!/usr/bin/env python
# coding: utf-8



import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from sklearn import preprocessing
from sklearn.metrics import mean_squared_error
from math import sqrt
from sklearn import preprocessing
from sklearn.svm import SVR
from sklearn.metrics import mean_squared_error,mean_absolute_error,r2_score
import math
from numpy import concatenate




feanum=1
window=5
Ra = 0.8
df1=pd.read_csv('shao - 单.csv', usecols=[1]) #读取数据
train_d, test_d = df1[0:int(len(df1)*Ra)], df1[int(len(df1)*Ra):]



min_max_scaler = preprocessing.MinMaxScaler()
df0=min_max_scaler.fit_transform(df1)
df = pd.DataFrame(df0, columns=df1.columns)




#这一部分在处理数据 将原始数据改造为模型需要的输入
stock=df
seq_len=window
amount_of_features = len(stock.columns)#有几列
data = stock.values #pd.DataFrame(stock) 表格转化为矩阵
sequence_length = seq_len + 1#序列长度+1
result = []
for index in range(len(data) - sequence_length):#循环 数据长度-时间窗长度 次
    result.append(data[index: index + sequence_length])#第i行到i+5
result = np.array(result)#得到样本,样本形式为 window*feanum

cut=len(test_d)
train = result[:-cut, :]
x_train = train[:, :-1]
y_train = train[:, -1][:,-1]
x_test = result[-cut:, :-1]
y_test = result[-cut:, -1][:,-1]
X_train = np.reshape(x_train, (x_train.shape[0], x_train.shape[1], amount_of_features))
X_test = np.reshape(x_test, (x_test.shape[0], x_test.shape[1], amount_of_features))  


print("X_train", X_train.shape)
print("y_train", y_train.shape)
print("X_test", X_test.shape)
print("y_test", y_test.shape)



X_train=X_train.reshape(len(X_train),window)
y_train=y_train.reshape(len(X_train))
X_test=X_test.reshape(cut,window)
y_test=y_test.reshape(cut)
print("X_train", X_train.shape)
print("y_train", y_train.shape)
print("X_test", X_test.shape)
print("y_test", y_test.shape)


svr = SVR(C=1.0, cache_size=200,degree=3, gamma=0.01,kernel='linear', max_iter=-1) 
model = svr.fit(X_train, y_train)


#在训练集上的拟合结果
y_train_predict=model.predict(X_train)




draw=pd.concat([pd.DataFrame(y_train),pd.DataFrame(y_train_predict)],axis=1)
draw.iloc[0:len(train_d),0].plot(figsize=(12,6))
draw.iloc[0:len(train_d),1].plot(figsize=(12,6))
plt.legend(('real', 'predict'),loc='upper right',fontsize='15')
plt.title("Train Data",fontsize='30') 




#在测试集上的预测
y_test_predict=model.predict(X_test)


X = pd.DataFrame(y_test)
Y = pd.DataFrame(y_test_predict)
X = min_max_scaler.inverse_transform(X)
Y = min_max_scaler.inverse_transform(Y)




testScore = math.sqrt(mean_squared_error(X, Y))
print('RMSE为:%.3f ' %(testScore))
testScore = mean_absolute_error(X, Y)
print('MAE为:%.3f ' %(testScore))
testScore = r2_score(X, Y)
print('R2为:%.3f ' %(testScore))



plt.figure(figsize=(10, 4),dpi=150)
plt.plot(X, label="Actual", color='red',linewidth=4)
plt.plot(Y, color='blue',label='Prediction',linewidth=2.5,linestyle="--")
plt.title('Prediction', size=15)
plt.ylabel('DO',size=15)
plt.xlabel('time',size=15)
plt.legend()
plt.show()




更多时间序列预测代码获取时间序列预测算法全集合--深度学习

  • 4
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
SVM支持向量机)是一种常用的分类和回归算法,也可用于时间序列预测。以下是一个用Python实现时间序列预测SVM代码示例。 首先,我们需要导入所需的库,如numpy、matplotlib和sklearn中的svm模块。 ```python import numpy as np import matplotlib.pyplot as plt from sklearn import svm ``` 接下来,我们可以创建一个示例时间序列数据集。在这个示例中,我们创建了一个简单的正弦波形状的时间序列。 ```python # 创建示例时间序列数据 X = np.array(range(100)).reshape(-1, 1) # 时间步 y = np.sin(X) # 目标值 ``` 然后,我们将数据集划分为训练集和测试集。 ```python # 划分训练集和测试集 train_size = int(len(X) * 0.7) X_train, X_test = X[:train_size], X[train_size:] y_train, y_test = y[:train_size], y[train_size:] ``` 接下来,我们可以使用svm模块中的SVR(支持向量回归)类来创建一个回归模型,并将训练集数据拟合到模型中。 ```python # 创建SVM回归模型 model = svm.SVR() model.fit(X_train, y_train) ``` 然后,我们可以使用训练后的模型来进行预测。 ```python # 进行预测 y_pred = model.predict(X_test) ``` 最后,我们可以使用matplotlib库来绘制预测结果。 ```python # 绘制预测结果 plt.plot(X_test, y_test, label='Actual') plt.plot(X_test, y_pred, label='Predicted') plt.legend() plt.show() ``` 这是一个简单的使用SVM实现时间序列预测的示例代码。你可以根据自己的需求进行修改和调整。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值