一、簡介
1. 目標:
已知股票的「開盤價」和「收盤價」,利用神經網絡來預測「收盤均價」
2. 數據源:
日期(data):[ 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15.]
開盤價(beginPrice):[2438.71,2500.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]
收盤價(endPrice):[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]
3. 預測方法
(1)背景知識介紹
神經網絡介紹:https://blog.csdn.net/leiting_imecas/article/details/60463897
激勵函數relu()介紹:https://www.cnblogs.com/neopenx/p/4453161.html
(2)案例分析
-
原始數據:data、endPrice
-
輸入層:data/1.4 —> x:dateNormal、 endPrice / 3000 —> y:priceNormal
-
隱藏層:wb1(15x10) = x(15x1) * w1(1x10) + b1(1x10)
layer1 = tf.nn.relu(wb1) -
輸出層:wb2(15x1) = layer1(15x10) * w2(10x1) + b2(15x1)
layer2 = tf.nn.relu(wb2) -
梯度下降: 真實值y和計算值layer2的標準差用進行梯度下降,每次下降0.1;
-
預測結果:pred = sess.run(layer2,feed_dict={x:dateNormal})
predPrice = pred*3000
二、輸入數據
import tensorflow as tfimport numpy as npimport matplotlib.pyplot as plt
date = np.linspace(1,15,15)# 開始是1,結束是15,有15個數的等差數列print(date)
beginPrice = np.array([2438.71,2500.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])# 開盤價
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]
)# 收盤價
結果:
[ 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15.]
函數解析:
numpy.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None)
-
解析:
該函數返回一組具有相同間隔的數據/採樣值,數據的間隔通過計算獲得(常用與來創建等差數列) -
參數:
start:序列的起始值
stop:序列的終止值,除非endpoint被設置爲False。當endpoint爲True時,數據的間隔:(stop-start)/num。當endpoint爲False時,數據的間隔:(stop-start)/(num+1)。
num:採樣的數目,默認值爲50
endpoint:爲真則stop爲最後一個採樣值,默認爲真。
retstep:爲真則返回(samples, step),step爲不同採樣值的間距
dtype:輸出序列的類型。
-
返回:
samples:n維的數組
step:採樣值的間距
三、繪製圖表
plt.figure()for i in range(0,15):
dateOne = np.zeros([2]) # 建一個兩列值爲0的矩陣
dateOne[0] = i; # 第一列的 0-14
dateOne[1] = i; # 第二列的 0-14
priceOne = np.zeros([2]) # 建一個兩列值爲0的矩陣
priceOne[0] = beginPrice[i] # 把開盤價輸入第一列
priceOne[1] = endPrice[i] # 把收盤價輸入第二列
if endPrice[i] > beginPrice[i]: # 如果收盤價 大於 開盤價
plt.plot(dateOne,priceOne,'r',lw=8) # 條形是紅色,寬度爲8
else:
plt.plot(dateOne,priceOne,'g',lw=8) # 條形是綠色,寬度爲8
結果:
函數解析:
1、range(start,stop,step)
-
只給一個參數 s,表示 從0到s
例如:range(5)
結果:[0,1,2,3,4] -
兩個參數,s,e,表示從s到e
例如:range(5,10)
結果:5,6,7,8,9 -
三個參數 s,e,i 表示從s到e,間隔i取數
例如:range(0,10,2)
結果:[0,2,4,6,8]
四、輸入層 input layer
dateNormal = np.zeros([15,1])# 創建一個15行,1列的矩陣priceNormal = np.zeros([15,1])for i in range(0,15):
dateNormal[i,0] = i/14.0; # 日期的值,最大值爲14
priceNormal[i,0] = endPrice[i]/3000.0; # 價格的值,最大值爲3000x = tf.placeholder(tf.float32,[None,1])
y = tf.placeholder(tf.float32,[None,1])
函數解析:
tf.placeholder(dtype, shape=None, name=None)
-
解析:此函數可以理解爲形參,用於定義過程,在執行的時候再賦具體的值
-
參數:
dtype:數據類型。常用的是tf.float32,tf.float64等數值類型
shape:數據形狀。默認是None,就是一維值,也可以是**,比如[2,3], [None, 3]表示列是3,行不定
name:名稱。 -
返回:
Tensor 類型
五、隱藏層(hidden layer)
w1 = tf.Variable(tf.random_uniform([1,10],0,1))
# 創建一個1行10列的矩陣,最小值爲0,最大值爲1
b1 = tf.Variable(tf.zeros([1,10]))
# 創建一個1行10列的矩陣,值都爲0
wb1 = tf.matmul(x,w1)+b1
# wb1 = x * w1 + b1
layer1 = tf.nn.relu(wb1)
# 激勵函數的類型:
https://tensorflow.google.cn/api_guides/python/nn#Activation_Functions
# 激勵函數的作用:
https://zhuanlan.zhihu.com/p/25279356
六、輸出層(output layer)
w2 = tf.Variable(tf.random_uniform([10,1],0,1))
b2 = tf.Variable(tf.zeros([15,1]))
wb2 = tf.matmul(layer1,w2)+b2
# wb2 = wb1 * w2 + b2
layer2 = tf.nn.relu(wb2)
loss = tf.reduce_mean(tf.square(y-layer2))
# 計算真實值y和計算值layer2的標準差
# 方差 s^2=[(x1-x)^2+(x2-x)^2+......(xn-x)^2]/(n) (x爲平均數)
# 標準差=方差的算術平方根
train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)
# 每次梯度下降0.1,目的是縮小真實值y和計算值layer2的差值
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
for i in range(0,10000):
sess.run(train_step,feed_dict={x:dateNormal,y:priceNormal})
# feed_dict是一個字典,在字典中需要給出每一個用到的佔位符的取值,每次迭代選取的數據只會擁有佔位符這一個結點。
# 訓練出w1、w2、b1、b2,但是還需要檢測是否有效
pred = sess.run(layer2,feed_dict={x:dateNormal})
# 訓練完的預測結果值
predPrice = np.zeros([15,1])
for i in range(0,15):
predPrice[i,0]=(pred*3000)[i,0]
# pred需要乘以3000是因爲前面 priceNormal[i,0] = endPrice[i]/3000.0;
plt.plot(date,predPrice,'b',lw=1)
plt.show()
結果:
函數解析:
tf.reduce_mean(input_tensor,axis=None,keepdims=None,name=None,reduction_indices=None,keep_dims=None)
-
解析:計算張量維度上元素的平均值。
-
參數:
input_tensor:張量減少。應該有數字類型。
axis:要減小的尺寸。如果None(默認)縮小所有尺寸。必須在範圍內 [ rank(input_tensor), rank(input_tensor) )。
keepdims:如果爲true,則保留長度爲1的縮小尺寸。
name:操作的名稱(可選)。
reduction_indices:軸的舊(已棄用)名稱。
keep_dims:已過時的別名keepdims。
延伸閱讀: