精确度acc的计算

3层神经网络下手写数字识别

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

#获取训练数据,训练标签,测试数据,测试标签
#x_test.shape为(10000,784),y_test.shape为(10000,10)
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

#假设学习已经完成,所学到的参数被保存下来,,假设保存在同一目录下的sample_weight.pkl文件中,在预测阶段直接加载相应的模型即可。
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()

batch_size = 100 # 批数量
accuracy_cnt = 0

for i in range(0, len(x), batch_size):#一次处理100张图片,间隔100采样
    x_batch = x[i:i+batch_size] #X的形状是100x784
    y_batch = predict(network, x_batch) #y的形状是100 x 10
    p = np.argmax(y_batch, axis=1)#只对10这个维度里面的数据取最大值,并返回索引,返回p的维度为100
    accuracy_cnt += np.sum(p == t[i:i+batch_size])#比较神经网络预测解与正确标签,将回答正确的概率作为识别精度

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

你可能感兴趣的:(深度学习,python)