3.6 手写数字的识别
3.6.1 MNIST 数据集
import sys, os
sys.path.append(os.pardir) # 为了导入父目录中的文件而进行的设定
from dataset.mnist import load_mnist
# 第一次调用会花费几分钟……
(x_train, t_train), (x_test, t_test) = load_mnist(flatten=True, normalize=False)
Converting train-images-idx3-ubyte.gz to NumPy Array ...
Done
Converting train-labels-idx1-ubyte.gz to NumPy Array ...
Done
Converting t10k-images-idx3-ubyte.gz to NumPy Array ...
Done
Converting t10k-labels-idx1-ubyte.gz to NumPy Array ...
Done
Creating pickle file ...
Done!
# 输出各个数据的形状
print(x_train.shape) # (60000, 784)
print(t_train.shape) # (60000,)
print(x_test.shape) # (10000, 784)
print(t_test.shape) # (10000,)
(60000, 784)
(60000,)
(10000, 784)
(10000,)
注意:784 = 28 * 28
因为原图像为28 * 28像素的,按照一维数组展开即为1 * 784
import sys, os
sys.path.append(os.pardir)
import numpy as np
from dataset.mnist import load_mnist
from PIL import Image
def img_show(img):
pil_img = Image.fromarray(np.uint8(img)) # 把保存为NumPy数组的图像数据转换为PIL用的数据对象
pil_img.show()
# (x_train, t_train), (x_test, t_test) = load_mnist(flatten=True,normalize=False)
img = x_train[0]
label = t_train[0]
print(label) # 5
print(img.shape) # (784,)
img = img.reshape(28, 28) # 把图像的形状变成原来的尺寸
print(img.shape) # (28, 28)
img_show(img)
5
(784,)
(28, 28)
3.6.2 神经网络的推理处理
def sigmoid(x):
return 1 / (1 + np.exp(-x))
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
import pickle
# 主函数
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)))
Accuracy:0.9352
3.6.3 批处理
x, _ = get_data()
network = init_network()
W1, W2, W3 = network['W1'], network['W2'], network['W3']
x.shape
(10000, 784)
x[0].shape
(784,)
W1.shape
(784, 50)
W2.shape
(50, 100)
W3.shape
(100, 10)
x, t = get_data()
network = init_network()
batch_size = 100 # 批数量
accuracy_cnt = 0
下面编程方式所涉及不会的方法,请看下面的方法介绍:
for i in range(0, len(x), batch_size):
x_batch = x[i:i+batch_size] # 取一批batch_size数据
y_batch = predict(network, x_batch) # 将该批数据进行预测分类得到列表
p = np.argmax(y_batch, axis=1) #argmax方法找到每个输入数据的最大值下标,也就是对应的最大可能性数字
accuracy_cnt += np.sum(p == t[i:i+batch_size]) # 将数字结果和实际label进行比对,得到相同的个数
print("Accuracy:" + str(float(accuracy_cnt) / len(x))) # 计算正确率
Accuracy:0.9352
关于argmax()方法:
通过argmax()获取值最大的元素的索引。不过这里需要注意的是,
我们给定了参数axis=1
。这指定了在100 × 10 的数组中,沿着第1 维方向
(以第1 维为轴)找到值最大的元素的索引(第0 维对应第1 个维度)
x = np.array([[0.1, 0.8, 0.1], [0.3, 0.1, 0.6], [0.2, 0.5, 0.3], [0.8, 0.1, 0.1]])
x
array([[0.1, 0.8, 0.1],
[0.3, 0.1, 0.6],
[0.2, 0.5, 0.3],
[0.8, 0.1, 0.1]])
y = np.argmax(x, axis=1)
y
array([1, 2, 1, 0], dtype=int64)
在NumPy数组之间使用比较运算符(==)生成由True/False构成的布尔型数组,并计算True的个数。
y = np.array([1, 2, 1, 0])
t = np.array([1, 2, 0, 0])
y==t
array([ True, True, False, True])
np.sum(y==t)
3