1. 程式人生 > 實用技巧 >前向傳播 (Forward Propagation)

前向傳播 (Forward Propagation)

前向傳播 (Forward Propagation)

前向傳播通過對一層的結點以及對應的連線權值進行加權和運算,結果加上一個偏置項,然後通過一個非線性函式(即啟用函式),如ReLu,sigmoid等函式,得到的結果就是下一層結點的輸出。從第一層(輸入層)開始不斷的通過這種方法一層層的運算,最後得到輸出層結果。

下面是一個簡單的例子,暫不考慮偏置項和啟用函式。輸入層有結點A,B;隱藏層有結點C,D;輸出層是結點E。

結點的計算公式可以是

, 這裡啟用函式用的是sigmoid,根據需要可以用其他函式。

如不考慮偏置項和啟用函式,公式就簡化成。由此可以得出,結點C的值就是:3x1 + 4x2 = 11; 同理結點D的值就是:3x2 + 4x1 = 10; 結點E的值就是:11x3 + 10x(-1) = 23。

PYTHON實現的程式是:

import numpy as np
# 輸入層資料
input_data = np.array([3, 4])
# 計算隱藏層
weight1 = np.array([[1, 2], [2, 1]])
hidden_layer_values = input_data.dot(weight1)
print(hidden_layer_values)
# 計算輸出
weight2 = np.array([3, -1])
output = (hidden_layer_values * weight2).sum()
print(output)

下面程式考慮了啟用函式:

import numpy as np

def sigmoid(x):
    # 計算sigmoid
    return 1/(1+np.exp(-x))

# 網路尺寸
input_node = 5
hidden_node = 3
output_node = 2

np.random.seed(42)
# 產生隨機輸入資料
X = np.random.randn(input_node)

# 用高斯分佈產生隨機權重資料
weights_input_to_hidden = np.random.normal(0, scale=0.1, size=(input_node, hidden_node))
weights_hidden_to_output = np.random.normal(0, scale=0.1, size=(hidden_node, output_node))


# 計算前向傳播
hidden_layer_in = np.dot(X, weights_input_to_hidden)
hidden_layer_out = sigmoid(hidden_layer_in)

output_layer_in = np.dot(hidden_layer_out, weights_hidden_to_output)
output_layer_out = sigmoid(output_layer_in)

# 顯示輸出
print('Output-layer Output:')
print(output_layer_out) output_layer_out = sigmoid(output_layer_in)

print('Output-layer Output:')
print(output_layer_out)