Coding01

Coding 点滴

0%

使用 MNIST 集入门 Tensoflow

引用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import matplotlib.pyplot as plt
from typing import Dict, Text

import numpy as np
import tensorflow as tf

import tensorflow_datasets as tfds
import tensorflow_recommenders as tfrs
import os
import ssl

os.environ['HTTP_PROXY'] = 'http://0.0.0.0:8888'
os.environ['HTTPS_PROXY'] = 'http://0.0.0.0:8888'
ssl._create_default_https_context = ssl._create_unverified_context

下载 MNIST 数据集

1
2
# MNIST data.
mnist_train = tfds.load(name="mnist", split="train", data_dir = os.path.join(os.getcwd(), "data"))

效果:

1
<PrefetchDataset shapes: {image: (28, 28, 1), label: ()}, types: {image: tf.uint8, label: tf.int64}>

图片格式主要是 28*28,我们可以写个发给将数据集保存为图片,看看图片效果。

转为图片

1
2
3
4
for mnist_example in mnist_train.take(1):  # 只取一个样本
image, label = mnist_example["image"], mnist_example["label"]
plt.imshow(image.numpy()[:, :, 0].astype(np.float32), cmap=plt.get_cmap("gray"))
print("Label: %d" % label.numpy())

说明数据我们已经拿到手,有了数据,我们可以开始往下进行。

获取训练集和测试集

1
2
3
(x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data(
path = os.path.join(os.getcwd(), "data/mnist.npz")
)

初始化和灰度化

统一图片大小和灰度化:

1
2
3
4
5
6
7
8
9
10
11
12
x_train = x_train.reshape(x_train.shape[0], 28, 28, 1)
x_test = x_test.reshape(x_test.shape[0], 28, 28, 1)
input_shape = (28, 28, 1)
x_train = x_train.astype('float32')
x_test = x_test.astype('float32')

x_train /= 255
x_test /= 255

print('x_train shape: ', x_train.shape)
print('Number of images in x_train', x_train.shape[0])
print('Number of images in x_test', x_test.shape[0])

建立自然网络模型

1
2
3
4
5
6
7
8
9
10
11
# Importing the required Keras modules containing model and layers
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Conv2D, Dropout, Flatten, MaxPooling2D
# Creating a Sequential Model and adding the layers
model = Sequential()
model.add(Conv2D(28, kernel_size=(3,3), input_shape=input_shape))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Flatten()) # Flattening the 2D arrays for fully connected layers
model.add(Dense(128, activation=tf.nn.relu))
model.add(Dropout(0.2))
model.add(Dense(10,activation=tf.nn.softmax))

编译模型

1
2
3
4
5
6
model.compile(optimizer='adam', 
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
model.fit(x=x_train,y=y_train, epochs=10)

model.evaluate(x_test, y_test)

测试

1
2
3
4
image_index = 5555
plt.imshow(x_test[image_index].reshape(28, 28),cmap='Greys')
pred = model.predict(x_test[image_index].reshape(1, 28, 28, 1))
print(pred.argmax())

1
2
3
4
image_index = 6666
plt.imshow(x_test[image_index].reshape(28, 28),cmap='Greys')
pred = model.predict(x_test[image_index].reshape(1, 28, 28, 1))
print(pred.argmax())

总结

初步学习使用 MNIST 数据集做训练和对手写数字的识别测试,开启 tensorflow 的入门。

Welcome to my other publishing channels