0


基于BP神经网络使用开盘价、最高价、最低价预测收盘价

以下是本文所用数据~~~

一、直接上手撸代码

import pandas as pd
import numpy as np
import math

data = pd.read_excel('上证指数.xls')
data = np.array(data.iloc[3:-1,1:])

e = 1
ita = 0.0035
#sigmoid
def sigmoid(x):
    return 1/(1+np.exp(-x))
#sigmoid导函数
def sigmoid_derivation(x):
    return np.exp(x)/(np.exp(x)+1)**2
#将整个矩阵归一化
max1 = data.max(axis = 0)
min1 = data.min(axis = 0)
t = np.empty((len(data),4))
for i in range(4):
    t[:,i] = (data[:,i]-min1[i])/(max1[i]-min1[i])
#截取训练集和测试集,这里使用了最后一天为测试集
train = t[:-1,:-1]#训练集
train_result = t[:-1,-1]#训练结果
test = t[-1,:-1]#测试集
test_result = t[-1,-1]#测试结果
#初始化权重和偏置值
w2 = np.random.random((3,3))
b2 = np.random.random((3,1))
w3 = np.random.random((1,3))
b3 = np.random.random((1,1))
i = 0
while i<len(train):
    #前向计算
    z2 = w2.dot(train[i].T) + b2.T
    a2 = sigmoid(z2)
    z3 = w3.dot(a2.T) + b3
    a3 = z3
    #计算误差
    ex = train_result[i] - a3
    #反向计算
    delta3 = -((ex)*(z3))
    delta2 = w3.T.dot(delta3)*sigmoid_derivation(z2)
    dw3 = delta3.dot(a2)
    db3 = delta3
    dw2 = delta2.dot(train[i])
    db2 = delta3
    #更新矩阵
    w3 = w3 + ita*(-dw3)
    b3 = b3 + ita*(-db3)
    w2 = w2 + ita*(-dw2)
    b2 = b2 + ita*(-db2)
    #误差均值
    e = (e + ex)/i
    #迭代次数
    i = i + 1
print('w2矩阵为:',w2)
print('w3矩阵为:',w3)
print('b2矩阵为:',b2)
print('b3矩阵为:',b3)
#计算预测值
z2 = w2.dot(test.T) + b2.T
a2 = sigmoid(z2)
z3 = w3.dot(a2.T) + b3
a3 = z3
#返归一化
print('预测值为:',a3*(max1[3]-min1[3])+min1[3])
print('真实数据为:{}'.format(test_result*(max1[3]-min1[3])+min1[3]))
print('误差为:{}'.format((a3*(max1[3]-min1[3])+min1[3]) - (test_result*(max1[3]-min1[3])+min1[3])))

输出结果为:

二、调库代码

import pandas as pd
import numpy as np
import math
from sklearn.neural_network import MLPRegressor,MLPClassifier

data = pd.read_excel('上证指数.xls')
data = np.array(data.iloc[3:-1,1:])

data1 = np.array(data)

X = data1[:, 0:2]
Y = data1[:, 2]
max1 = data.max(axis = 0)
min1 = data.min(axis = 0)
t = np.empty((len(data),4))
for i in range(4):
    t[:,i] = (data[:,i]-min1[i])/(max1[i]-min1[i])
#截取训练集和测试集,这里使用了最后一天为测试集
train = t[:-1,:-1]#训练集
train_result = t[:-1,-1]#训练结果
test = t[-1,:-1]#测试集
test_result = t[-1,-1]#测试结果 

clf = MLPRegressor(hidden_layer_sizes=(4,1), activation='relu',solver='adam',alpha=0.0001,max_iter=2000)
clf = clf.fit(train,train_result)
pred = clf.predict(test.reshape(1, -1))
print('回归预测结果:', pred)

print('预测值为:',pred*(max1[3]-min1[3])+min1[3])
print('真实数据为:{}'.format(test_result*(max1[3]-min1[3])+min1[3]))
print('误差为:{}'.format((pred*(max1[3]-min1[3])+min1[3]) - (test_result*(max1[3]-min1[3])+min1[3])))

输出结果为:


本文转载自: https://blog.csdn.net/weixin_46657323/article/details/122991231
版权归原作者 嘟嘟肚腩仔 所有, 如有侵权,请联系我们删除。

“基于BP神经网络使用开盘价、最高价、最低价预测收盘价”的评论:

还没有评论