阅读 3863

使用 MNIST 集入门 Tensoflow(1)

在入门之前,我们需要开发工具,本文使用 JupyterLab,可以用 conda 或者 pip 方式安装。

// conda 方式
conda install -c conda-forge jupyterlab

// or pip 方式
pip install jupyterlab
复制代码

conda 源更新比较缓慢,推荐还是用 pip。

启用:

jupyter-lab
复制代码

为了在不同的 conda 虚拟环境下使用 jupyterlab,可以安装插件 nb_conda_kernels

conda install -n tf2 nb_conda_kernels
复制代码

下面就可以运行一个 hello world 了。

引用

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 数据集

# MNIST data.
mnist_train = tfds.load(name="mnist", split="train", data_dir = os.path.join(os.getcwd(), "data"))
复制代码

效果:

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

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

转为图片

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())
复制代码

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

获取训练集和测试集

(x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data(
    path = os.path.join(os.getcwd(), "data/mnist.npz")
)
复制代码

初始化和灰度化

统一图片大小和灰度化:

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])
复制代码

建立自然网络模型

# 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))
复制代码

编译模型

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)
复制代码

测试

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())
复制代码

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 的入门。

THE MNIST DATABASE of handwritten digits

Image Classification in 10 Minutes with MNIST Dataset

文章分类
人工智能
文章标签