神经网络模型数字推理预测

MNIST数据集

MNIST是机器学习领域 最有名的数据集之一,被应用于从简单的实验到发表的论文研究等各种场合。 实际上,在阅读图像识别或机器学习的论文时,MNIST数据集经常作为实验用的数据出现。

MNIST数据集是由0到9的数字图像构成的。训练图像有6万张, 测试图像有1万张,这些图像可以用于学习和推理。MNIST数据集的一般使用方法是,先用训练图像进行学习,再用学习到的模型度量能在多大程度上对测试图像进行正确的分类。

1.png

MNIST的图像数据是28像素 × 28像素的灰度图像(1通道),各个像素的取值在0到255之间。每个图像数据都相应地标有"7" "2" "1"等标签。

使用如下脚本可以下载数据集

# coding: utf-8
try:
    import urllib.request
except ImportError:
    raise ImportError('You should use Python 3.x')
import os.path
import gzip
import pickle
import os
import numpy as np


url_base = 'http://yann.lecun.com/exdb/mnist/'
key_file = {
    'train_img':'train-images-idx3-ubyte.gz',
    'train_label':'train-labels-idx1-ubyte.gz',
    'test_img':'t10k-images-idx3-ubyte.gz',
    'test_label':'t10k-labels-idx1-ubyte.gz'
}

dataset_dir = os.path.dirname(os.path.abspath(__file__))
save_file = dataset_dir + "/mnist.pkl"

train_num = 60000
test_num = 10000
img_dim = (1, 28, 28)
img_size = 784


def _download(file_name):
    file_path = dataset_dir + "/" + file_name
    
    if os.path.exists(file_path):
        return

    print("Downloading " + file_name + " ... ")
    urllib.request.urlretrieve(url_base + file_name, file_path)
    print("Done")
    
def download_mnist():
    for v in key_file.values():
       _download(v)
        
def _load_label(file_name):
    file_path = dataset_dir + "/" + file_name
    
    print("Converting " + file_name + " to NumPy Array ...")
    with gzip.open(file_path, 'rb') as f:
            labels = np.frombuffer(f.read(), np.uint8, offset=8)
    print("Done")
    
    return labels

def _load_img(file_name):
    file_path = dataset_dir + "/" + file_name
    
    print("Converting " + file_name + " to NumPy Array ...")    
    with gzip.open(file_path, 'rb') as f:
            data = np.frombuffer(f.read(), np.uint8, offset=16)
    data = data.reshape(-1, img_size)
    print("Done")
    
    return data
    
def _convert_numpy():
    dataset = {}
    dataset['train_img'] =  _load_img(key_file['train_img'])
    dataset['train_label'] = _load_label(key_file['train_label'])    
    dataset['test_img'] = _load_img(key_file['test_img'])
    dataset['test_label'] = _load_label(key_file['test_label'])
    
    return dataset

def init_mnist():
    download_mnist()
    dataset = _convert_numpy()
    print("Creating pickle file ...")
    with open(save_file, 'wb') as f:
        pickle.dump(dataset, f, -1)
    print("Done!")

def _change_one_hot_label(X):
    T = np.zeros((X.size, 10))
    for idx, row in enumerate(T):
        row[X[idx]] = 1
        
    return T
    

def load_mnist(normalize=True, flatten=True, one_hot_label=False):
    """读入MNIST数据集
    
    Parameters
    ----------
    normalize : 将图像的像素值正规化为0.0~1.0
    one_hot_label : 
        one_hot_label为True的情况下,标签作为one-hot数组返回
        one-hot数组是指[0,0,1,0,0,0,0,0,0,0]这样的数组
    flatten : 是否将图像展开为一维数组
    
    Returns
    -------
    (训练图像, 训练标签), (测试图像, 测试标签)
    """
    if not os.path.exists(save_file):
        init_mnist()
        
    with open(save_file, 'rb') as f:
        dataset = pickle.load(f)
    
    if normalize:
        for key in ('train_img', 'test_img'):
            dataset[key] = dataset[key].astype(np.float32)
            dataset[key] /= 255.0
            
    if one_hot_label:
        dataset['train_label'] = _change_one_hot_label(dataset['train_label'])
        dataset['test_label'] = _change_one_hot_label(dataset['test_label'])
    
    if not flatten:
         for key in ('train_img', 'test_img'):
            dataset[key] = dataset[key].reshape(-1, 1, 28, 28)

    return (dataset['train_img'], dataset['train_label']), (dataset['test_img'], dataset['test_label']) 


if __name__ == '__main__':
    init_mnist()

load_mnist函数以"(训练图像 ,训练标签 ),(测试图像,测试标签 )"的多元组形式返回读入的MNIST数据。

load_mnist(normalize=True, flatten=True, one_hot_label=False) 这 样,设 置 3 个 参 数。
第 1 个参数normalize设置是否将输入图像正规化为0.0~1.0的值。如果将该参数设置为False,则输入图像的像素会保持原来的0~255。
第2个参数flatten设置是否展开输入图像(变成一维数组)。如果将该参数设置为False,则输入图像为1 × 28 × 28的三维数组;若设置为True,则输入图像会保存为由784个元素构成的一维数组。
第3个参数one_hot_label设置是否将标签保存为one-hot表示(one-hot representation)。one-hot表示是仅正确解标签为1,其余皆为0的数组,就像[0,0,1,0,0,0,0,0,0,0]这样。当one_hot_label为False时,只是像7、2这样简单保存正确解标签;当one_hot_label为True时,标签则 保存为one-hot表示。

可以通过如下代码读出下载的图片

# coding: utf-8
import sys, os
sys.path.append(os.pardir)  # 为了导入父目录的文件而进行的设定
import numpy as np
from DeepLearn_Base.dataset.mnist import load_mnist
from PIL import Image


def img_show(img):
    pil_img = Image.fromarray(np.uint8(img))
    pil_img.show()

(x_train, t_train), (x_test, t_test) = load_mnist(flatten=True, normalize=False)

img = x_train[1]
label = t_train[1]
print(label)  # 5

print(img.shape)  # (784,)
img = img.reshape(28, 28)  # 把图像的形状变为原来的尺寸
print(img.shape)  # (28, 28)

img_show(img)

读出来的数据如下所示:

2.png

神经网络的推理

现在使用python的numpy结合神经网络的算法来推理图片的内容。整个流程其实就是两个部分:数据集准备、权重与偏置超参数准备。

数据集准备

使用如下代码块下载准备测试数据集:

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


# 下载mnist数据集
# 分别下载测试图像包、测试标签包、训练图像包、训练标签包
x, t = get_data()

打印输出x, t参数shape

3.png

读取实现准备好的权重参数文件pkl,同时打印出来看看其参数shape

def init_network():
    with open("E:\\workcode\\code\\DeepLearn_Base\\ch03\\sample_weight.pkl", 'rb') as f:
        network = pickle.load(f)
    return network

# 获取预训练好的权重与偏置参数
network = init_network()

4.png

可以看到,超参数分别是3个权重参数与3个偏置参数,为了方便,稍后再打印出其shape .

超参数文件 sample_weight.pkl 是预训练好的,本文主要是从神经网络的推理角度考虑,预训练文件的准备,暂不涉及。

推理

开始执行神经网络的推理,同时打印出其各个参数的shape

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

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)))

predict方法中,执行了推理过程,主要是各个数学公式的计算(sigmoid,softmax,线性计算),这些公式都是在numpy的基础上根据公式用程序语言表述出来的,具体的计算逻辑可以查阅functions.py文件。

看看各个参数的shape:

5.png

可以看看计算过程中的各个数据维度是否满足匹配:

6.png

### 使用PyTorch构建和训练BP神经网络预测模型 在低维神经网络结构中,每层仅有两个神经元可以作为简单的示例来理解基本概念[^1]。然而,在实际应用中,更复杂的架构通常用于处理现实世界的数据集。 对于使用PyTorch构建并训练BP(反向传播)神经网络预测模型的任务来说,主要关注的是网络的设计、损失函数的选择以及优化算法的应用[^2]。下面是一个具体的实现例子: #### 定义网络结构 ```python import torch from torch import nn, optim from torchvision import datasets, transforms class SimpleNet(nn.Module): def __init__(self): super(SimpleNet, self).__init__() self.fc1 = nn.Linear(784, 50) # 输入维度取决于数据特征数;这里假设输入图像大小为28*28=784像素 self.relu = nn.ReLU() self.fc2 = nn.Linear(50, 10) # 输出类别数量设为10类 def forward(self, x): x = x.view(-1, 784) # 将图片展平成一维向量 x = self.fc1(x) x = self.relu(x) x = self.fc2(x) return x ``` 此部分定义了一个具有单隐藏层的全连接前馈神经网络,其中包含了线性变换与激活函数ReLU组合而成的基础组件。 #### 设置超参数及加载数据集 ```python batch_size = 64 learning_rate = 0.01 epochs = 5 transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,))]) train_loader = torch.utils.data.DataLoader( datasets.MNIST('./data', train=True, download=True, transform=transform), batch_size=batch_size, shuffle=True) test_loader = torch.utils.data.DataLoader( datasets.MNIST('./data', train=False, transform=transform), batch_size=batch_size, shuffle=False) ``` 这段代码设置了批量大小、学习率等重要参数,并通过`torchvision.datasets`模块获取MNIST手写数字识别任务所需的数据集。 #### 训练过程 ```python device = 'cuda' if torch.cuda.is_available() else 'cpu' model = SimpleNet().to(device) criterion = nn.CrossEntropyLoss() # 对于分类问题常用交叉熵作为损失函数 optimizer = optim.SGD(model.parameters(), lr=learning_rate) for epoch in range(epochs): running_loss = 0.0 for data, target in train_loader: data, target = data.to(device), target.to(device) optimizer.zero_grad() # 清除梯度缓存 output = model(data) # 前向传播计算输出 loss = criterion(output, target)# 根据真实标签计算当前批次样本上的平均损失值 loss.backward() # 反向传播更新权重参数 optimizer.step() running_loss += loss.item() print(f"Epoch {epoch+1}/{epochs}, Loss: {(running_loss / len(train_loader)):.4f}") ``` 上述片段展示了完整的训练循环逻辑,包括初始化设备环境、实例化模型对象、指定损失衡量标准以及选择随机梯度下降法来进行迭代式的权值调整操作。 #### 测试评估性能 ```python correct = 0 total = 0 with torch.no_grad(): # 关闭自动求导机制以节省内存空间 for images, labels in test_loader: outputs = model(images.to(device)) _, predicted = torch.max(outputs.data, 1) total += labels.size(0) correct += (predicted.cpu() == labels).sum().item() print('Accuracy of the network on the 10000 test images: %d %%' % ( 100 * correct / total)) ``` 最后这部分实现了对测试集中所有样例进行推理运算,并统计最终得到的结果准确性指标。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

meslog

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值