代码:
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
#日期15天
data = np.linspace(0,14,15) #生成1到15个数
#收盘
endPrice = np.array([2511.90,2538.26,2510.68,2591.66,2732.98,2701.69,2701.29,2678.67,2726.50,2681.50,2739.17,2715.07,2823.58,2864.90,2919.08])
#开盘
beginPrice = np.array([2438.71,2535.88,2534.95,2512.52,2594.04,2743.26,2697.47,2695.24,2678.23,2722.13,2674.93,2744.13,2717.46,2832.73,2877.40])
#plt.figure()
for i in range(0,15):
dataOne = np.zeros([2])
dataOne[0] = i
dataOne[1] = i
priceOne = np.zeros([2]) #纵坐标 开盘与收盘的平均范围
priceOne[0] = beginPrice[i] #开盘价
priceOne[1] = endPrice[i] #收盘价
if endPrice[i] > beginPrice[i]:
plt.plot(dataOne,priceOne,'r',lw = 8) #参数12是np数组
else:
plt.plot(dataOne,priceOne, 'g',lw = 8)
#模型预测
#plt.show()
#A:输入层 B:隐藏层 C:输出层
#A(15*1) * w1(1*10) + b1(1*10) = B(15*10) 隐藏层
#B(15*10) * w2(10*1) + b2(15*1) = C(15*1) 输出层
dataNormal = np.zeros([15,1]) #15行1列 天数
priceNormal = np.zeros([15,1]) # 营收
#天数与盈收归一化处理
for i in range(0,15):
dataNormal[i,0] = i/14.0
priceNormal[i,0] = endPrice[i] / 3000.0
#输入层A
#n行1列
x = tf.placeholder(tf.float32,[None,1])
y = tf.placeholder(tf.float32,[None,1])
#隐藏层B
w1 = tf.Variable(tf.random_uniform([1,10],0,1)) #权值 随机生成1行10列,范围在[0,1]
b1 = tf.Variable(tf.zeros([1,10])) #偏移量 1行10列
wb1 = tf.matmul(x,w1)+b1
layer1 = tf.nn.relu(wb1) #激励函数
'''
激励函数
如果wb1的值大于0值不变,如果wb1小于0值变为0
'''
#输出层C
w2 = tf.Variable(tf.random_uniform([10,1],0,1)) #权值 随机生成10行1列,范围在[0,1]
b2 = tf.Variable(tf.zeros([15,1])) #偏移量 15行1列
wb2 = tf.matmul(layer1,w2)+b2
layer2 = tf.nn.relu(wb2) #激励函数
#求平均值
loss = tf.reduce_mean(tf.square(y - layer2))
#梯度下降 每次下降0.1
train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer()) #初始化变量
#训练10000次
for i in range(0,10000):
sess.run(train_step,feed_dict = {x:dataNormal, y:priceNormal})
#获得准确w1 w2 b1 b2
#获得预测的价格
pred = sess.run(layer2,feed_dict = {x:dataNormal})
predPrice = np.zeros([15,1])
for i in range(0,15):
predPrice[i,0] = (pred * 3000)[i,0]
plt.plot(data,predPrice,'b',lw = 1)
plt.show()`在这里插入代码片`
|