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

用Python实现神经网络(一)

Python实现神经网络有多种方法。这里我们使用keras框架。你必须安装 tensorflow或theano, 和 keras然后才能实现神经网络。

1. 下载数据集并提取训练和测试集(见“NN.ipynb”)

from keras.datasets import mnist

import matplotlib.pyplot as plt

%matplotlib inline

# load (downloaded if needed) the MNIST dataset

(X_train, y_train), (X_test, y_test) = mnist.load_data()

# plot 4 images as gray scale

plt.subplot(221)

plt.imshow(X_train[0], cmap=plt.get_cmap('gray'))

plt.subplot(222)

plt.imshow(X_train[1], cmap=plt.get_cmap('gray'))

plt.subplot(223)

plt.imshow(X_train[2], cmap=plt.get_cmap('gray'))

plt.subplot(224)

plt.imshow(X_train[3], cmap=plt.get_cmap('gray'))

# show the plot

plt.show()

4-18. 输出

2. 导入相关包:

import numpy as np

from keras.datasets import mnist

from keras.models import Sequential

from keras.layers import Dense

from keras.layers import Dropout

from keras.utils import np_utils

3. 预处理数据集:

num_pixels = X_train.shape[1] * X_train.shape[2]

# reshape the inputs so that they can be passed to the

vanilla NN

X_train = X_train.reshape(X_train.shape[0],num_pixels

).astype('float32')

X_test = X_test.reshape(X_test.shape[0],num_pixels).

astype('float32')

# scale inputs

X_train = X_train / 255

X_test = X_test / 255

# one hot encode the output

y_train = np_utils.to_categorical(y_train)

y_test = np_utils.to_categorical(y_test)

num_classes = y_test.shape[1]

4. 构建模型:

# building the model

model = Sequential()

# add 1000 units in the hidden layer

# apply relu activation in hidden layer

model.add(Dense(1000, input_dim=num_pixels,activation='relu'))

# initialize the output layer

model.add(Dense(num_classes, activation='softmax'))

# compile the model

model.compile(loss='categorical_crossentropy',optimizer='adam', metrics=['accuracy'])

# extract the summary of model

model.summary()

5. 运行模型:

model.fit(X_train, y_train, validation_data=(X_test,

y_test), epochs=5, batch_size=1024, verbose=1)

注意随着epochs增加, 测试集的准确率也增加。另外在keras里我们只要在第一层指明输入的维,它会自己动的推出余下各层的维。

http://www.xdnf.cn/news/15751.html

相关文章:

  • 御控县级供水调度系统:数字化整合,构建全流程智能调度体系
  • day055-Dockerfile与常用指令
  • OPS飞腾主板:开启教与学的深层次互动
  • [IRF/Stack]华为/新华三交换机堆叠配置
  • onenote千年老bug,字体bug (calibri微软雅黑) 的解决
  • 神经网络构建
  • AI+医疗!VR和MR解剖学和针灸平台,智能时代如何重塑健康未来
  • Java常用命令汇总
  • Windows10笔记本电脑开启BIOS
  • (四)OpenCV——特征点检测与匹配
  • 6. 工程化实践类:《Webpack 5 性能优化全指南:从构建速度到输出质量》
  • Flutter状态管理篇之ChangeNotifier(一)
  • 使用 docker 安装 openldap
  • 板凳-------Mysql cookbook学习 (十二--------1)
  • 从零开始的云计算生活——第三十三天,关山阻隔,ELK日志分析
  • 【Leetcode】栈和队列算法题(逆波兰表达式、二叉树层序遍历、最小栈、栈的压入弹出序列)
  • MySQL详解一
  • Oracle 成本优化器(CBO)与数据库统计信息:核心原理与实践
  • 【前端】Power BI自动化指南:从API接入到Web嵌入
  • docker安装与简单项目上手
  • 使用docker安装、启动jenkins服务(mac系统)
  • 3D工业相机是什么?如何选择和使用它?
  • 如何构建一个基于大模型的实时对话3D数字人?
  • 3D Gaussian Splatting (3DGS) 从入门到精通:安装、训练与常见问题全解析
  • c++:类型转换函数
  • 【神经网络在MATLAB中是如何实现的?】
  • 什么是 M4A 和 WAV?这两种音频互转会导致音质发生变化吗
  • kimi故事提示词 + deepseekR1 文生图提示
  • 不同相机CMOS噪点对荧光计算的影响
  • day23——Java网络编程终极指南:从基础到实战,全面掌握CS/BS架构通信