当前位置: 首页 > news >正文

手写数字识别(python实现)

手写数字识别

这里一共三个文件,see_data.py(用来查看数据),myModel.py(自己建立的模型),Train_model_net.py(训练模型)

这个是我们的全部文件,上面的四个是我们的手写数字数据集,自己从其他地方随便就能下载,比如阿里云,训练集有60000个数字,测试集有10000个数字,还有训练集和测试集的标签文件。``

这个是see_data.py,用来查看数据,和对数据进行处理。

importwarningsfrommatplotlibimportMatplotlibDeprecationWarning warnings.filterwarnings("ignore",category=MatplotlibDeprecationWarning)importnumpyasnpimportstructfromtensorflow.keras.utilsimportto_categoricaldefload_mnist_images(filename):withopen(filename,'rb')asf:magic,num,rows,cols=struct.unpack(">IIII",f.read(16))images=np.fromfile(f,dtype=np.uint8).reshape(num,rows,cols)returnimagesdefload_mnist_labels(filename):withopen(filename,'rb')asf:magic,num=struct.unpack(">II",f.read(8))labels=np.fromfile(f,dtype=np.uint8)returnlabels# 加载训练图像train_images=load_mnist_images('train-images-idx3-ubyte/train-images.idx3-ubyte')# 加载训练标签train_labels=load_mnist_labels('train-labels-idx1-ubyte/train-labels.idx1-ubyte')train_labels_np=np.array(train_labels)train_one_hot_labels=to_categorical(train_labels_np,num_classes=10)# print(train_one_hot_labels[:10])# 加载测试图像test_images=load_mnist_images('t10k-images-idx3-ubyte/t10k-images.idx3-ubyte')# 加载测试标签test_labels=load_mnist_labels('t10k-labels-idx1-ubyte/t10k-labels.idx1-ubyte')test_labels_np=np.array(test_labels)test_one_hot_labels=to_categorical(test_labels_np,num_classes=10)# print("---------------")# print(test_one_hot_labels[:10])# # 打印一些信息# print("Number of images:", len(train_images))# print("Shape of each image:", train_images[0].shape)# # 打印一些信息# print("Number of labels:", len(train_labels))# print("First 10 labels:", train_labels[:10])# # 可以进一步处理标签,例如统计每个类别的数量# label_counts = np.bincount(train_labels)# print("Label counts:", label_counts)## # 显示第一个图像(可选)# import matplotlib.pyplot as plt# plt.imshow(train_images[0], cmap='gray')# plt.show()

这个是myModel.py,是我们的模型。

fromtensorflow.kerasimportlayers,modelsclassMyModel:def__init__(self):self.model=models.Sequential()self.model.add(layers.Dense(128,activation='relu',input_shape=(784,)))self.model.add(layers.Dropout(0.2))self.model.add(layers.Dense(64,activation='relu'))self.model.add(layers.Dropout(0.2))self.model.add(layers.Dense(10,activation='softmax'))deftrain(self,x_train,y_train,epochs=10,batch_size=32):self.model.compile(optimizer='adam',loss='categorical_crossentropy',metrics=['accuracy'])self.model.fit(x_train,y_train,epochs=epochs,batch_size=batch_size)defevaluate(self,test_images,test_labels):returnself.model.evaluate(test_images,test_labels)

这是Train_model_net.py,用来训练模型。

fromnumber_identify.see_dataimporttrain_images,train_labels,test_images,test_labelsimporttensorflowastfimportnumpyasnpimporttimefromnumber_identify.myModelimportMyModeldefreshape_images(images):num_images=images.shape[0]returnnp.array([image.reshape(-1)forimageinimages])start_time=time.time()# 将图像数据进行归一化处理,把像素值从0-255归一化到0-1范围,有助于模型训练train_images=reshape_images(train_images)test_images=reshape_images(test_images)train_images=train_images/255.0test_images=test_images/255.0train_labels=tf.keras.utils.to_categorical(train_labels,num_classes=10)test_labels=tf.keras.utils.to_categorical(test_labels,num_classes=10)# 假设x_train和y_train是已经准备好的训练数据my_model=MyModel()my_model.train(train_images,train_labels)# 在测试集上评估模型test_loss,test_accuracy=my_model.evaluate(test_images,test_labels)print(f"在测试集上的损失:{test_loss}")print(f"在测试集上的准确率:{test_accuracy}")

需要注意的是,有时候我们这里会爆红,但是可以运行,这是因为我们下载的包的版本可能不同。

http://www.jsqmd.com/news/606473/

相关文章:

  • Linux服务器上保姆级部署ComfyUI+Flux:从Anaconda环境到低显存GGUF模型实战
  • Phi-3 Forest Laboratory 技术文档翻译与润色效果:中英互译质量对比
  • 快速上手Qwen3-ASR-0.6B:无需代码基础,Gradio界面点点鼠标就能用
  • AI像素艺术新体验:像素幻梦创意工坊开箱即用,打造复古游戏风作品
  • QMCDecode如何实现音频格式兼容性:3步解锁音乐跨平台自由
  • 提升写作效率:9大AI工具实现选题优化与自动降重
  • Java 多线程详解(持续更新)
  • 13-教务课程管理系统
  • Linux(Centos 7.6)命令详解:lsof
  • WarcraftHelper终极优化方案:魔兽争霸III完整兼容性修复指南
  • 基于STM32F407与miniMP3库的流式音频解码系统设计与实现
  • Janus-Pro-7B电商场景实战:商品主图智能生成与营销文案创作
  • 内置权重真省心!通用物体识别-ResNet18镜像稳定部署避坑指南
  • Swift 析构过程
  • 小型的自动洗勺机结构设计【三维proe+cad图纸+毕业论文+仿真】
  • FLUX.1-dev-fp8-dit文生图+SDXL_Prompt风格案例:国风文创产品视觉设计全流程
  • Visual Studio Code远程开发:无缝调试云端Pixel Dimension Fissioner
  • AI显微镜-Swin2SR效果展示:AI理解图像内容实现无损4倍放大的作品集
  • 义乌幼小衔接班口碑如何?2026年推荐这些靠谱机构,优质的幼小衔接重德教育显著提升服务 - 品牌推荐师
  • QMCDecode终极指南:3步解锁QQ音乐加密格式,免费实现音乐跨平台播放
  • DeepSeek-R1-Distill-Qwen-1.5B模型体验:数学80+分的1.5B参数小钢炮
  • Z-Image Atelier 中国风水墨画与现代抽象艺术生成效果对比研究
  • Nginx何以征服高性能之巅?深入剖析其架构设计哲学
  • Dify低代码平台对接Phi-3-mini:快速构建企业级AI应用工作流
  • Windows任务栏透明化终极指南:5种视觉方案与智能场景切换
  • Krita AI Diffusion插件全链路技术指南:从故障排查到企业部署
  • 释放系统潜能:DriverStore Explorer驱动清理与优化指南
  • 终极LSTM时间序列预测实战指南:从零基础到专家级的快速入门
  • OBS-Multi-RTMP:多平台直播高效同步解决方案
  • FastAPI日志配置终极指南:如何高效设置和管理应用日志