《Deep Learning from Scratch》鱼书学习笔记 3-6,7 手写数字的识别

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

3.7 本章小结

• 神经网络中的激活函数使用平滑变化的sigmoid 函数或ReLU函数。
• 通过巧妙地使用NumPy多维数组,可以高效地实现神经网络。
• 机器学习的问题大体上可以分为回归问题和分类问题。
• 关于输出层的激活函数,回归问题中一般用恒等函数,分类问题中一般用softmax 函数。
• 分类问题中,输出层的神经元的数量设置为要分类的类别数。
• 输入数据的集合称为批。通过以批为单位进行推理处理,能够实现高速的运算。
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值