题目要求:完成对手写数字数据集的读取、神经网络的推理和批处理过程,3层网络结构(第一隐藏层100个神经元,第二隐藏层50个神经元,输出层10个神经元,神经网络的参数随机生成),计算模型的准确率
# coding:utf-8
# 库导入
import numpy as np
import pickle
def sigmoid(x):
"""
:param x: 进入隐藏层的参数
:return: 激活函数的值
"""
return 1 / (1 + np.exp(-x))
def softmax(x):
'''
:param x: 进入输出层的参数
:return: 输出层的结果
'''
max = np.max(x)
exp_x = np.exp(x - max)
return exp_x / np.sum(exp_x)
# 输入的导入以及初始化
def init():
'''
:return: 文件中的数据集
'''
# 数据输入
with open(r'C:\Users\86135\Desktop\mnist.pkl', 'rb') as file:
dataset = pickle.load(file)
x_train, y_train, x_test, y_test = dataset["train_img"], dataset["train_label"],\
dataset["test_img"], dataset["test_label"]
return x_train, y_train, x_test, y_test
def work(x_train, y_train, x_test, y_test):
'''
:param x_train: 训练集
:param y_train: 测试集
:param x_test: 训练集标签
:param y_test: 测试集标签
:return: 正确划分数据集标签的个数
'''
# 隐藏层, 输出层的权重参数和偏置初始化
w1 = np.random.rand(784, 100)
b1 = np.random.rand(100)
w2 = np.random.rand(100, 50)
b2 = np.random.rand(50)
w3 = np.random.rand(50, 10)
b3 = np.random.rand(10)
correct = 0 # 用来记录正确预测的数量
# 遍历所有的测试集
for i in range(len(x_test)):
x = x_test[i]
# 第一层隐藏层
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)
y_label = np.argmax(y)
# 如果预测的和正确标签一直,则正确预测数量+1
if y_label == y_test[i]:
correct += 1
return correct
# 数据初始化
x_train, y_train, x_test, y_test = init()
correct = work(x_train, y_train, x_test, y_test)
# 结果展示
print(f"预测的正确的数量有{correct}个")
print(f"正确率为{correct / len(x_test) * 100:.2f}%")
手写数据集文件下载地址 mnist.pkl
标签:return,random,param,学习,np,train,深度,test,手写 From: https://www.cnblogs.com/Reina-love/p/16759858.html