Before getting started, we need development tools. This article uses JupyterLab, which can be installed in conda or PIP mode.

// Conda install -c conda-forge jupyterlab // or PIP PIP install jupyterlabCopy the code

The conda source is updated slowly, so it is recommended to use PIP.

Enable:

jupyter-lab
Copy the code

To use JupyterLab in different Conda virtual environments, you can install the plug-in NB_conda_Kernels.

conda install -n tf2 nb_conda_kernels
Copy the code

Now you’re ready to run a Hello World.

reference

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
Copy the code

Download the MNIST dataset

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

Effect:

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

The image format is mainly 28*28, we can write a message to save the data set as an image and see how the image looks.

To the picture

for mnist_example in mnist_train.take(1): Mnist_example ["image"], mnist_example["label"] plt.imshow(image.numpy()[:, :, 0].astype(np.float32), cmap=plt.get_cmap("gray")) print("Label: %d" % label.numpy())Copy the code

It means that we have the data, and with the data, we can move on.

Get the training set and test set

(x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data(
    path = os.path.join(os.getcwd(), "data/mnist.npz")
)
Copy the code

Initialize and grayscale

Unify image size and graying:

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])
Copy the code

Model natural networks

# 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. The 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. The add (Dropout (0.2)) model. The add (Dense (10, activation = tf. Nn. Softmax))Copy the code

Compilation model

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)
Copy the code

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())
Copy the code

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())
Copy the code

conclusion

Initially learn to use MNIST data set to do training and recognition test of hand-written numbers, and start the introduction of TensorFlow.

THE MNIST DATABASE of handwritten digits

Image Classification in 10 Minutes with MNIST Dataset