用keras 和 tensorflow 构建手写字识别神经网路

Posted wbloger

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了用keras 和 tensorflow 构建手写字识别神经网路相关的知识,希望对你有一定的参考价值。

#导入数据
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
from keras.datasets import mnist

(train_images, train_labels), (test_images, test_labels) = mnist.load_data()
print(train_images.shape)
print(train_images.dtype)
print(train_labels.shape)

print(test_images.shape)
print(test_labels.shape)

#图像转换
train_images = train_images.reshape((60000, 28*28))
train_images = train_images.astype(float32)/255

test_images = test_images.reshape((10000, 28*28))
test_images = test_images.astype(float32)/ 255

#构建网络
from keras import models
from keras import layers

network = models.Sequential()
network.add(layers.Dense(512, activation = relu, input_shape = (28*28, )))
network.add(layers.Dense(10, activation = softmax))

network.compile(optimizer = rmsprop, loss = categorical_crossentropy, metrics = [accuracy])

#准备标签
from keras.utils import to_categorical

train_labels = to_categorical(train_labels)
test_labels = to_categorical(test_labels)

#模型拟合
network.fit(train_images, train_labels, epochs=5, batch_size = 128)

#测试模型
test_loss, test_acc = network.evaluate(test_images, test_labels)
print(test_acc:, test_acc)

 

以上是关于用keras 和 tensorflow 构建手写字识别神经网路的主要内容,如果未能解决你的问题,请参考以下文章

图像分类手撕ResNet——复现ResNet(Keras,Tensorflow 2.x)

在没有 Keras 的情况下使用 Tensorflow 2.0 和急切执行

如何评价深度学习框架Keras

TensorFlow2.0教程-Keras 快速入门:用于构建和训练深度学习模型的高阶 API

Keras实例教程之构建模型的第三种方式

从零开始,手把手教你使用Keras和TensorFlow构建自己的CNN模型