【Python实战】——神经网络识别手写数字(一)

简介: 【Python实战】——神经网络识别手写数字

该篇文章以Python实战的形式利用神经网络识别mnist手写数字数据集,包括pickle操作,神经网络关键模型关键函数定义,识别效果评估及可视化等内容,建议收藏练手!

1 探索数据集

1.1 读取并显示数据示例

  运行程序:

import numpy as np
import matplotlib.pyplot as plt
image_size = 28 # width and length
num_of_different_labels = 10 #  i.e. 0, 1, 2, 3, ..., 9
image_pixels = image_size * image_size
train_data = np.loadtxt("D:\\mnist_train.csv", delimiter=",")
test_data = np.loadtxt("D:\\mnist_test.csv", delimiter=",") 
test_data[:10]#测试集前十行

  运行结果:

array([[7., 0., 0., ..., 0., 0., 0.],
       [2., 0., 0., ..., 0., 0., 0.],
       [1., 0., 0., ..., 0., 0., 0.],
       ...,
       [9., 0., 0., ..., 0., 0., 0.],
       [5., 0., 0., ..., 0., 0., 0.],
       [9., 0., 0., ..., 0., 0., 0.]])

1.2 数据集大小

  运行程序:

print(test_data.shape)
print(train_data.shape)

  运行结果:

(10000, 785)
(60000, 785)

  该mnist数据集训练集共10000个数据,有785维,测试集有60000个数据,785维。

1.3 自变量因变量构建

  运行程序:

##第一列为预测类别
train_imgs = np.asfarray(train_data[:, 1:]) / 255
test_imgs = np.asfarray(test_data[:, 1:]) / 255 
train_labels = np.asfarray(train_data[:, :1])
test_labels = np.asfarray(test_data[:, :1])

1.4 One-hot编码

  运行程序

import numpy as np
lable_range = np.arange(10)
for label in range(10):
    one_hot = (lable_range==label).astype(int)
    print("label: ", label, " in one-hot representation: ", one_hot)
    
    
# 将数据集的标签转换为one-hot label
label_range = np.arange(num_of_different_labels)
train_labels_one_hot = (label_range==train_labels).astype(float)
test_labels_one_hot = (label_range==test_labels).astype(float)

1.5 图像数据示例

  运行程序:

# 示例
for i in range(10):
    img = train_imgs[i].reshape((28,28))
    plt.imshow(img, cmap="Greys")
    plt.show()

  运行结果:

1.6 pickle包保存python对象

因为csv文件读取到内存比较慢,我们用pickle这个包来保存python对象(这里面python对象指的是numpy array格式的train_imgs, test_imgs, train_labels, test_labels)

  运行程序:

import pickle
with open("D:\\pickled_mnist.pkl", "bw") as fh:
    data = (train_imgs, 
            test_imgs, 
            train_labels,
            test_labels)
    pickle.dump(data, fh)

2 构建神经网络并训练

2.1 读取pickle文件

  运行程序:

import pickle
with open("D:\\19实验\\实验课大作业\\pickled_mnist.pkl", "br") as fh:
    data = pickle.load(fh)
train_imgs = data[0]
test_imgs = data[1]
train_labels = data[2]
test_labels = data[3]
train_labels_one_hot = (lable_range==train_labels).astype(float)
test_labels_one_hot = (label_range==test_labels).astype(float)
image_size = 28 # width and length
num_of_different_labels = 10 #  i.e. 0, 1, 2, 3, ..., 9
image_pixels = image_size * image_size

2.2 神经网络核心关键函数定义

  运行程序:

import numpy as np
def sigmoid(x):
    return 1 / (1 + np.e ** -x)
##激活函数
activation_function = sigmoid
from scipy.stats import truncnorm
##数据标准化
def truncated_normal(mean=0, sd=1, low=0, upp=10):
    return truncnorm((low - mean) / sd, 
                     (upp - mean) / sd, 
                     loc=mean, 
                     scale=sd)
##构建神经网络模型
class NeuralNetwork:
    
    def __init__(self, 
                 num_of_in_nodes, #输入节点数
                 num_of_out_nodes, #输出节点数
                 num_of_hidden_nodes,#隐藏节点数
                 learning_rate):#学习率
        self.num_of_in_nodes = num_of_in_nodes
        self.num_of_out_nodes = num_of_out_nodes
        self.num_of_hidden_nodes = num_of_hidden_nodes
        self.learning_rate = learning_rate 
        self.create_weight_matrices()
    #初始为一个隐藏节点    
    def create_weight_matrices(self):#创建权重矩阵
 
       # A method to initialize the weight 
        #matrices of the neural network#一种初始化神经网络权重矩阵的方法
        rad = 1 / np.sqrt(self.num_of_in_nodes)  
        X = truncated_normal(mean=0, sd=1, low=-rad, upp=rad)  #形成指定分布
        self.weight_1 = X.rvs((self.num_of_hidden_nodes, self.num_of_in_nodes)) #rvs:产生服从指定分布的随机数
        
        rad = 1 / np.sqrt(self.num_of_hidden_nodes)
        X = truncated_normal(mean=0, sd=1, low=-rad, upp=rad)
        self.weight_2 = X.rvs((self.num_of_out_nodes, self.num_of_hidden_nodes)) #rvs: 产生服从指定分布的随机数
        
    
    def train(self, input_vector, target_vector):
      #
       # input_vector and target_vector can 
        #be tuple, list or ndarray
        #
        
        input_vector = np.array(input_vector, ndmin=2).T#输入
        target_vector = np.array(target_vector, ndmin=2).T#输出
        
        output_vector1 = np.dot(self.weight_1, input_vector) #隐藏层值
        output_hidden = activation_function(output_vector1)#删除不激活
        
        output_vector2 = np.dot(self.weight_2, output_hidden)#输出
        output_network = activation_function(output_vector2)##删除不激活
        
        # calculate output errors:计算输出误差
        output_errors = target_vector - output_network
        
        # update the weights:更新权重
        tmp = output_errors * output_network * (1.0 - output_network)     
        self.weight_2 += self.learning_rate  * np.dot(tmp, output_hidden.T)
        # calculate hidden errors:计算隐藏层误差
        hidden_errors = np.dot(self.weight_2.T, output_errors)
        
        # update the weights:
        tmp = hidden_errors * output_hidden * (1.0 - output_hidden)
        self.weight_1 += self.learning_rate * np.dot(tmp, input_vector.T)
        
    #测试集
    def run(self, input_vector):
        # input_vector can be tuple, list or ndarray
        input_vector = np.array(input_vector, ndmin=2).T
        
        output_vector = np.dot(self.weight_1, input_vector)
        output_vector = activation_function(output_vector)
        
        output_vector = np.dot(self.weight_2, output_vector)
        output_vector = activation_function(output_vector)
    
        return output_vector
    #判别矩阵
    def confusion_matrix(self, data_array, labels):
        cm = np.zeros((10, 10), int)
        for i in range(len(data_array)):
            res = self.run(data_array[i])
            res_max = res.argmax()
            target = labels[i][0]
            cm[res_max, int(target)] += 1
        return cm    
     #精确度
    def precision(self, label, confusion_matrix):
        col = confusion_matrix[:, label]
        return confusion_matrix[label, label] / col.sum()
    #评估
    def evaluate(self, data, labels):
        corrects, wrongs = 0, 0
        for i in range(len(data)):
            res = self.run(data[i])
            res_max = res.argmax()
            if res_max == labels[i]:
                corrects += 1
            else:
                wrongs += 1
        return corrects, wrongs

【Python实战】——神经网络识别手写数字(二)+https://developer.aliyun.com/article/1506501

目录
打赏
0
0
0
0
31
分享
相关文章
如何用 eBPF 实现 Kubernetes 网络可观测性?实战指南
本文深入探讨了Kubernetes网络观测的挑战与eBPF技术的应用。首先分析了传统工具在数据碎片化、上下文缺失和性能瓶颈上的局限性,接着阐述了eBPF通过零拷贝观测、全链路关联和动态过滤等特性带来的优势。文章进一步解析了eBPF观测架构的设计与实现,包括关键数据结构、内核探针部署及生产环境拓扑。实战部分展示了如何构建全栈观测系统,并结合NetworkPolicy验证、跨节点流量分析等高级场景,提供具体代码示例。最后,通过典型案例分析和性能数据对比,验证了eBPF方案的有效性,并展望了未来演进方向,如智能诊断系统与Wasm集成。
1688商品详情API实战:Python调用全流程与数据解析技巧
本文介绍了1688电商平台的商品详情API接口,助力电商从业者高效获取商品信息。接口可返回商品基础属性、价格体系、库存状态、图片描述及商家详情等多维度数据,支持全球化语言设置。通过Python示例代码展示了如何调用该接口,帮助用户快速上手,适用于选品分析、市场研究等场景。
基于时间图神经网络多的产品需求预测:跨序列依赖性建模实战指南
本文展示了如何通过学习稀疏影响图、应用图卷积融合邻居节点信息,并结合时间卷积捕获演化模式的完整技术路径,深入分析每个步骤的机制原理和数学基础。
47 1
Jupyter MCP服务器部署实战:AI模型与Python环境无缝集成教程
Jupyter MCP服务器基于模型上下文协议(MCP),实现大型语言模型与Jupyter环境的无缝集成。它通过标准化接口,让AI模型安全访问和操作Jupyter核心组件,如内核、文件系统和终端。本文深入解析其技术架构、功能特性及部署方法。MCP服务器解决了传统AI模型缺乏实时上下文感知的问题,支持代码执行、变量状态获取、文件管理等功能,提升编程效率。同时,严格的权限控制确保了安全性。作为智能化交互工具,Jupyter MCP为动态计算环境与AI模型之间搭建了高效桥梁。
149 2
Jupyter MCP服务器部署实战:AI模型与Python环境无缝集成教程
|
2月前
|
探索Python高级并发与网络编程技术。
可以看出,Python的高级并发和网络编程极具挑战,却也饱含乐趣。探索这些技术,你将会发现:它们好比是Python世界的海洋,有穿越风暴的波涛,也有寂静深海的奇妙。开始旅途,探索无尽可能吧!
62 15
Playwright 多语言一体化——Python/Java/.NET 全栈采集实战
本文以反面教材形式,剖析了在使用 Playwright 爬取懂车帝车友圈问答数据时常见的配置错误(如未设置代理、Cookie 和 User-Agent),并提供了 Python、Java 和 .NET 三种语言的修复代码示例。通过错误示例 → 问题剖析 → 修复过程 → 总结教训的完整流程,帮助读者掌握如何正确配置爬虫代理及其它必要参数,避免 IP 封禁和反爬检测,实现高效数据采集与分析。
Playwright 多语言一体化——Python/Java/.NET 全栈采集实战
淘宝商品详情API接口解析与 Python 实战指南
淘宝商品详情API接口是淘宝开放平台提供的编程工具,支持开发者获取商品详细信息,包括基础属性、价格、库存、销售策略及卖家信息等。适用于电商数据分析、竞品分析与价格策略优化等场景。接口功能涵盖商品基础信息、详情描述、图片视频资源、SKU属性及评价统计的查询。通过构造请求URL和签名,可便捷调用数据。典型应用场景包括电商比价工具、商品数据分析平台、供应链管理及营销活动监控等,助力高效运营与决策。
182 26
图神经网络在信息检索重排序中的应用:原理、架构与Python代码解析
本文探讨了基于图的重排序方法在信息检索领域的应用与前景。传统两阶段检索架构中,初始检索速度快但结果可能含噪声,重排序阶段通过强大语言模型提升精度,但仍面临复杂需求挑战
78 0
图神经网络在信息检索重排序中的应用:原理、架构与Python代码解析
多模态RAG实战指南:完整Python代码实现AI同时理解图片、表格和文本
本文探讨了多模态RAG系统的最优实现方案,通过模态特定处理与后期融合技术,在性能、准确性和复杂度间达成平衡。系统包含文档分割、内容提取、HTML转换、语义分块及向量化存储五大模块,有效保留结构和关系信息。相比传统方法,该方案显著提升了复杂查询的检索精度(+23%),并支持灵活升级。文章还介绍了查询处理机制与优势对比,为构建高效多模态RAG系统提供了实践指导。
377 0
多模态RAG实战指南:完整Python代码实现AI同时理解图片、表格和文本
Python+YOLO v8 实战:手把手教你打造专属 AI 视觉目标检测模型
本文介绍了如何使用 Python 和 YOLO v8 开发专属的 AI 视觉目标检测模型。首先讲解了 YOLO 的基本概念及其高效精准的特点,接着详细说明了环境搭建步骤,包括安装 Python、PyCharm 和 Ultralytics 库。随后引导读者加载预训练模型进行图片验证,并准备数据集以训练自定义模型。最后,展示了如何验证训练好的模型并提供示例代码。通过本文,你将学会从零开始打造自己的目标检测系统,满足实际场景需求。
420 0
Python+YOLO v8 实战:手把手教你打造专属 AI 视觉目标检测模型

热门文章

最新文章

推荐镜像

更多
AI助理

你好,我是AI助理

可以解答问题、推荐解决方案等