1. 程式人生 >實用技巧 >其它 >神經網路之softmax函式,np.argmax()方法

神經網路之softmax函式,np.argmax()方法


輸出層softmax函式公式:

神經網路之softmax函式,np.argmax()方法


神經網路之softmax函式,np.argmax()方法


由公式和圖可知輸出yi和每一個ai有關。
例項python3.程式碼:

神經網路之softmax函式,np.argmax()方法

def softmax(a):
    c = np.max(a)
    exp_a = np.exp(a - c) # 溢位對策
    sum_exp_a = np.sum(exp_a)
    y = exp_a / sum_exp_a
    return y
# coding: utf-8
import sys, os
sys.path.append(os.pardir)  # 為了匯入父目錄的檔案而進行的設定
import numpy as np
import pickle
from dataset.mnist import load_mnist
from common.functions import sigmoid, softmax


def get_data():
    (x_train, t_train), (x_test, t_test) = load_mnist(normalize=True, flatten=True, one_hot_label=False)
    return x_test, t_test


def init_network():
    with open("sample_weight.pkl", 'rb') as f:
        network = pickle.load(f)
    return network


def predict(network, x):
    W1, W2, W3 = network['W1'], network['W2'], network['W3']
    b1, b2, b3 = network['b1'], network['b2'], network['b3']

    a1 = np.dot(x, W1) + b1
    z1 = sigmoid(a1)
    a2 = np.dot(z1, W2) + b2
    z2 = sigmoid(a2)
    a3 = np.dot(z2, W3) + b3
    y = softmax(a3)

    return y


x, t = get_data()
network = init_network()
accuracy_cnt = 0
for i in range(len(x)):
    y = predict(network, x[i])
    p= np.argmax(y) # 獲取概率最高的元素的索引
    if p == t[i]:
        accuracy_cnt += 1

print("Accuracy:" + str(float(accuracy_cnt) / len(x)))

首先獲得MNIST資料集,生成網路。接著,用for語句逐一取出儲存在x中的影象資料,用predict()函式進行分類。predict()函式以NumPy陣列的形式輸出各個標籤對應的概率。比如輸出[0.1, 0.3, 0.2, …, 0.04]的陣列,該陣列表示“0”的概率為0.1,“1”的概率為0.3,等等。然後,我們取出這個概率列表中的最大值的索引(第幾個元素的概率最高),作為預測結果。可以用**np.argmax(x)函式取出陣列中的最大值的索引,np.argmax(x)將獲取被賦給引數x的陣列中的最大值元素的索引。**最後,比較神經網路所預測的答案和正確解標籤,將回答正確的概率作為識別精度。