系列文章
知識點
np.linsapce(-0.5, 0.5, 200)
生成從-0.5到0.5的均勻分佈的200個數據點。包含首尾
numpy中花式索引的一個實例——數據升維,即原來是1維的數據列表,經過升維後形成每個數值爲1維列表的2爲列表。結果類似如下:
[1, 2, 3, 4] ==> [[1], [2], [3]]
arr = arr[:, np.newaxis]
np.random.normal(mean, stddev, shape)
用於生成一個隨機正態分佈(高斯分佈)的數據,正態分佈的均值爲mean
,方差爲stddev
,數據的維度爲shape
。
tf.random_normal([1,10])
在tensorflow中形成[1,10 ]大小的張量,數據服從高斯分佈。默認的均值爲0,方差爲0.1。
tf.nn.tanh()
是激活函數,圖形類似於sigmod,但是tanh比sigmod更陡。
tf.global_variables_initializer()
初始化整個計算圖中的變量。
示例
#%% md
# 迴歸模型
#%%
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
#%% md
## 使用numpy生成200個隨機的數據點
#%% md
生成從-0.5到0.5均勻分佈的200個數據點,包含首尾數據
#%%
x_data = np.linspace(-0.5, 0.5, 200)
#%%
x_data
#%% md
將1維數據升成2維數據
#%%
x_data = x_data[:, np.newaxis]
#%%
x_data
#%% md
生成噪聲數據與`x_data`的shape一致
#%%
noise = np.random.normal(0, 0.02, x_data.shape)
#%% md
noise爲均值爲0,方差爲0.02的高斯分佈
#%%
noise
#%% md
構建數據y_data
$y\_data = x\_data^2 + noise$
#%%
y_data = np.square(x_data) + noise
#%%
y_data
#%% md
## 定義placeholder用於接收訓練的數據
可以認爲是輸入層
#%%
x = tf.placeholder(tf.float32, [None, 1], name="x_input")
y = tf.placeholder(tf.float32, [None, 1], name="y_input")
#%%
x
#%%
y
#%% md
定義隱藏層
即:
$$a_1 = w_1 \times x + b_1$$
$$out_1 = activation(a_1)$$
#%%
W_1 = tf.Variable(tf.random_normal([1, 10]))
b_1 = tf.Variable(tf.zeros([1, 10]))
a_1 = tf.matmul(x, W_1) + b_1
out_1 = tf.nn.tanh(a_1)
#%%
W_1
#%%
b_1
#%%
a_1
#%%
out_1
#%% md
## 定義輸出層
即輸出變爲維度爲1的數據
$$a_2=out_1 \times w_2 + b_2$$
$$out_2 = activation(a_2)$$
#%%
W_2 = tf.Variable(tf.random_normal([10, 1]))
b_2 = tf.Variable(tf.zeros([1, 1]))
a_2 = tf.matmul(out_1, W_2) + b_2
out_2 = tf.nn.tanh(a_2)
#%%
W_2
#%%
b_2
#%%
a_2
#%%
out_2
#%% md
## 定義損失函數
#%%
loss = tf.reduce_mean(tf.square(out_2- y_data))
#%%
loss
#%%
train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)
#%%
train_step
#%% md
## 初始化變量
#%%
init = tf.global_variables_initializer()
#%%
init
#%% md
## 訓練
#%%
with tf.Session() as sess:
sess.run(init)
for epc in range(10000):
sess.run([loss, train_step], {x:x_data,y:y_data})
if epc % 10 == 0:
# loss_value = sess.run([loss])
loss_value = sess.run([loss], {x:x_data,y:y_data})
print(epc, loss_value)
prediction_value = sess.run(out_2, feed_dict={x:x_data})
#%% md
## 畫圖
#%%
prediction_value
#%%
plt.figure()
plt.scatter(x_data, y_data)
plt.plot(x_data, prediction_value, "r-", lw=3)
plt.show()
#%%
#%%
注意
當使用tf.nn.relu()
替換tf.nn.tanh()
就會繪製的圖像就會出現一條折線,並且loss也不會降到很低。這可能是由於relu激活函數不光滑(不連續可導)導致的。