# coding: utf-8
# 构建cnn,利用历史时刻的值来预测下一时刻的收盘价
from sklearn.preprocessing import StandardScaler,MinMaxScaler
from sklearn.metrics import r2_score
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif']=['SimHei']
plt.rcParams['axes.unicode_minus'] = False
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Input,Flatten,Dense,Conv1D,MaxPool1D
import tensorflow as tf
# tf.random.set_seed(0)
# In[]定义一些需要的函数
def build_model(seq,fea,out):
inputs=Input(shape=(seq,fea))
x = Conv1D(4, kernel_size=16, strides=1, activation='sigmoid', padding='same')(inputs)
x = MaxPool1D(pool_size=2, strides=2)(x)
x = Conv1D(8, kernel_size=3, strides=1, activation='sigmoid', padding='same')(x)
x = MaxPool1D(pool_size=2, strides=2)(x)
x = Flatten(name='feature')(x)
output_ = Dense(out, activation='linear', name='output')(x)
model = Model(inputs=inputs, outputs=output_)
return model
def split_data(data, n):
in_ = []
out_ = []
N = data.shape[0] - n
for i in range(N):
in_.append(data[i:i + n,:])
out_.append(data[i + n,0])
in_ = np.array(in_).reshape(len(in_), -1)
out_ = np.array(out_).reshape(len(out_), -1)
return in_, out_
def result(real,pred,name):
# ss_X = MinMaxScaler(feature_range=(-1, 1))
# real = ss_X.fit_transform(real).reshape(-1,)
# pred = ss_X.transform(pred).reshape(-1,)
# mape
test_mape = np.mean(np.abs((pred - real) / real))
# rmse
test_rmse = np.sqrt(np.mean(np.square(pred - real)))
# mae
test_mae = np.mean(np.abs(pred - real))
# R2
test_r2 = r2_score(real, pred)
print(name,'的mape:%.4f,rmse:%.4f,mae:%.4f,R2:%.4f'%(test_mape ,test_rmse, test_mae, test_r2))
# In[]
df=pd.read_excel('399106(1).xlsx').fillna(0).iloc[:,2:]
data=df.values
time_steps=20#时间步
in_,out_=split_data(data,time_steps)
n=range(in_.shape[0])
m=int(0.8*in_.shape[0])
train_data = in_[n[0:m],]
test_data = in_[n[m:],]
train_label = out_[n[0:m],]
test_label = out_[n[m:],]
# 归一化
ss_X = MinMaxScaler(feature_range=(0, 1)).fit(train_data)
ss_Y = MinMaxScaler(feature_range=(0, 1)).fit(train_label)
train_data = ss_X.transform(train_data).reshape(train_data.shape[0], time_steps, -1)
train_label = ss_Y.transform(train_label)
test_data = ss_X.transform(test_data).reshape(test_data.shape[0], time_steps, -1)
test_label = ss_Y.transform(test_label)
# In[]
model=build_model(train_data.shape[-2],train_data.shape[-1],train_label.shape[-1])
#查看网络结构
model.summary()
#编译模型
model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=0.001), loss='mse')
train_again = True # 为 False 的时候就直接加载训练好的模型进行测试
# 训练模型
if train_again:
history = model.fit(train_data, train_label, epochs=100,
validation_data=(test_data, test_label),
batch_size=64, verbose=1)
model.save('result/model.h5')
# 画loss曲线
plt.figure()
plt.ylabel('MSE')
plt.xlabel('Epoch')
plt.plot(history.history['loss'], label='training')
plt.plot(history.history['val_loss'], label='validation')
plt.title('loss curve')
plt.legend()
plt.savefig('result/loss_curve.jpg')
else: # 加载模型
model = tf.keras.models.load_model('result/model.h5')
# In[]
test_pred = model.predict(test_data)
# 对测试集的预测结果进行反归一化
test_label1 = ss_Y.inverse_transform(test_label)
test_pred1 = ss_Y.inverse_transform(test_pred)
# In[]计算各种指标
result(test_label1,test_pred1,'CNN')
np.savez('result/cnn.npz',real=test_label1,pred=test_pred1)
# plot test_set result
plt.figure()
plt.plot(test_label1, c='r', label='real')
plt.plot(test_pred1, c='b', label='pred')
plt.legend()
plt.xlabel('样本点')
plt.ylabel('收盘价')
plt.title('测试集')
plt.savefig('result/cnnjieguo.png')
plt.show()
没有合适的资源?快使用搜索试试~ 我知道了~
基于CNN-SVM数据预测模型(python)
共19个文件
xml:4个
py:4个
pyc:3个
5星 · 超过95%的资源 29 下载量 14 浏览量
2022-10-26
23:20:28
上传
评论 7
收藏 619KB ZIP 举报
温馨提示
基于CNN-SVM数据预测模型(python) 卷积支持向量机数据预测模型,CNN-SVM数据预测模型(python) 卷积支持向量机数据预测模型,CNN-SVM数据预测模型(python)
资源推荐
资源详情
资源评论
收起资源包目录
基于CNN-SVM数据预测模型(python).zip (19个子文件)
基于CNN-SVM数据预测模型(python)
file1_CNN.py 4KB
optim.py 2KB
__pycache__
Layers.cpython-38.pyc 6KB
optim.cpython-39.pyc 2KB
optim.cpython-38.pyc 2KB
file0_高斯核平滑.py 673B
result
cnn_svm.npz 11KB
cnnsvm.png 37KB
model.h5 46KB
cnn.npz 8KB
.idea
misc.xml 311B
python的核平滑+CNN+SVR预测TF2.keras.iml 337B
modules.xml 341B
workspace.xml 3KB
.gitignore 50B
inspectionProfiles
profiles_settings.xml 174B
file2_CNN_SVM.py 4KB
399106.xls 751KB
399106(1).xlsx 281KB
共 19 条
- 1
前程算法屋
- 粉丝: 3918
- 资源: 671
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功
- 1
- 2
前往页