【tensorflow】利用神經網絡繪制股票價格擬合曲線


神經網絡有三層,輸入層A,隱藏層B,輸出層C,滿足:

A(10x1)*W1(1x10)+b1(1x10)=B(10x10)

B(10x10)*W2(10x1)+b2(10x1)=C(10x1)

我們需要做的,便是通過多次訓練(嘗試不同 w、b 的值),找到合適的 w1w2、b1b2,使預測結果更接近真實結果。

 

代碼:

import tensorflow.compat.v1 as tf import numpy as np import matplotlib.pyplot as plt # 兼容 tensorflow 1.0
tf.disable_eager_execution() # 日期,0-9
date = np.linspace(0, 9, 10) # 收盤價格
endPrice = np.array([2511.90, 2538.26, 2510.68, 2591.66, 2732.98, 2701.69, 2701.29, 2678.67, 2726.50, 2681.50]) # 開盤價格
beginPrice = np.array([2438.71, 2739.17, 2715.07, 2823.58, 2864.90, 2919.08, 2500.88, 2534.95, 2512.52, 2594.04]) # 繪制漲幅趨勢 # 價格上漲,紅色 # 價格下跌,綠色
plt.figure() for i in range(10): temData = np.zeros([2]) temData[0] = i temData[1] = i temPrice = np.zeros([2]) temPrice[0] = beginPrice[i] temPrice[1] = endPrice[i] if beginPrice[i] > endPrice[i]: plt.plot(temData, temPrice, "green", lw="2") else: plt.plot(temData, temPrice, "red", lw="2") # 神經網絡有三層,輸入層A,隱藏層B,輸出層C # A(10x1)*W1(1x10)+b1(1x10)=B(10x10) # B(10x10)*W2(10x1)+b2(10x1)=C(10x1)

# 輸入層 # 歸一化處理,減小計算量
dateNormal = np.zeros([10, 1]) priceNormal = np.zeros(([10, 1])) for i in range(10): dateNormal[i] = i / 9.0 priceNormal[i] = endPrice[i]/3000.0
    
# 聲明輸入輸出參數,xy
x = tf.placeholder(tf.float32, [None, 1]) y = tf.placeholder(tf.float32, [None, 1]) # 隱藏層
w1 = tf.Variable(tf.random_uniform([1, 10], 0, 1)) b1 = tf.Variable(tf.zeros([1, 10])) wb1 = tf.matmul(x, w1) + b1 # 激勵函數
layer1 = tf.nn.relu(wb1) # 輸出層
w2 = tf.Variable(tf.random_uniform([10, 1], 0, 1)) b2 = tf.Variable(tf.zeros([10, 1])) wb2 = tf.matmul(layer1, w2) + b2 # 激勵函數
layer2 = tf.nn.relu(wb2) # 預測值與實際值的標准差
loss = tf.reduce_mean(tf.square(y - layer2)) # 使用梯度下降法,減小差異
tran_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss) # 變量初始化
init = tf.global_variables_initializer() with tf.Session() as sess: sess.run(init) # 訓練10000次
    for i in range(10000): sess.run(tran_step, feed_dict={x: dateNormal, y: priceNormal}) # 查看擬合結果
    pre = sess.run(layer2, feed_dict={x: dateNormal}) prePrice = np.zeros([10, 1]) # 反歸一化
    for i in range(10): prePrice[i, 0] = (pre * 3000)[i, 0] # 繪制折線
    plt.plot(date, prePrice, "blue", lw=2) plt.show()

運行效果:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM