100 days to get the machine learning | day39 Tensorflow Keras Digital Recognition

Tip: look at the content of day36-38

TensorFlow ™ is a data flow diagram employed (data flow graphs), open source software library for numerical calculation. Nodes (Nodes) mathematical operation represented in the drawings, in FIG line (Edges) represents the multidimensional data array in the inter-node links, i.e. tensor (tensor). Its flexible architecture allows you to expand on a variety of computing platforms, such as desktop computers, one or more CPU (or GPU), servers, mobile devices and so on.

TensorFlow originally developed by Google brain group (affiliated with Google machine intelligence research institution) researchers and engineers have developed to study machine learning and neural networks for depth, but the versatility of this system is that it can be widely used in other calculations field.

1, the installation library tensorflow

Some tutorials will recommend installation nightly, it applies to conduct TensorFlow installed in a new environment, will need to rely on the default libraries also fitted together. I am using anaconda, this article we are installing a clean version tensorflow, very simple, just open the Prompt:

pip install tensorflow

Successful installation
image

Import success

#导入keras
from tensorflow import keras
#导入tensorflow
import tensorflow as tf

Note: Some tutorial import Keras use the import tensorflow.keras as keras will prompt No module named 'tensorflow.keras'

2, the data import mnist

In the last article we have already mentioned MNIST, and explain the gradient descent algorithm in interesting ways
it is a collection of a lot of 28 x 28 pixels handwritten digital images (grayscale value matrix storage) and its corresponding digital data set , it can be appreciated that in this way the following figure:
image

For reasons known, Keras comes minist download the data set will complain, you can not be downloaded. Park Cuixiao Qiu classmates blog gives a good solution:

1, find the file in the local keras mnist.py directory, usually in this directory.
image

2、下载mnist.npz文件到本地,下载链接如下。
https://pan.baidu.com/s/1C3c2Vn-_616GqeEn7hQQ2Q
3、修改mnist.py文件为以下内容,并保存

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

from ..utils.data_utils import get_file
import numpy as np

def load_data(path='mnist.npz'):
    """Loads the MNIST dataset. # Arguments
        path: path where to cache the dataset locally
            (relative to ~/.keras/datasets).

    # Returns
        Tuple of Numpy arrays: `(x_train, y_train), (x_test, y_test)`.
    """
    path = 'E:/Data/Mnist/mnist.npz' #此处的path为你刚刚存放mnist.py的目录。注意斜杠
    f = np.load(path)
    x_train, y_train = f['x_train'], f['y_train']
    x_test, y_test = f['x_test'], f['y_test']
    f.close()
    return (x_train, y_train), (x_test, y_test)

看一下数据

mnist = tf.keras.datasets.mnist
(x_train, y_train),(x_test, y_test) = mnist.load_data()
print(x_train[0].shape)

(28, 28)

import matplotlib.pyplot as plt
plt.imshow(x_train[0],cmap=plt.cm.binary)
plt.show()

image

print(y_train[0])

5
对数据进行归一化处理

x_train = tf.keras.utils.normalize(x_train, axis=1)
x_test = tf.keras.utils.normalize(x_test, axis=1)

再看一下,图像的像素值被限定在了 [0,1]

plt.imshow(x_train[0],cmap=plt.cm.binary)
plt.show()

image

3 构建与训练模型我们使用 Keras 的 Sequential 模型(顺序模型),顺序模型是多个网络层的线性堆叠。本文旨在介绍TensorFlow 及Keras用法,不再展开,有兴趣的同学们学习其具体用法,可以参考Keras文档:
https://keras.io/zh/getting-started/sequential-model-guide/

model = tf.keras.models.Sequential()
model.add(tf.keras.layers.Flatten(input_shape=(28,28)))
model.add(tf.keras.layers.Dense(128, activation=tf.nn.relu))
model.add(tf.keras.layers.Dense(128, activation=tf.nn.relu))
model.add(tf.keras.layers.Dense(10, activation=tf.nn.softmax))
model.compile(optimizer='adam',
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])
model.fit(x_train, y_train, epochs=3)

我们构建出的模型大概是这个样子的,区别是我们的隐藏层有128个单元
image

在训练的过程中,我们会发现损失值(loss)在降低,而准确度(accuracy)在提高,最后达到了一个令人满意的程度。
Epoch 1/3
60000/60000  - 8s 127us/step - loss: 0.2677 - acc: 0.9211Epoch 2/3
60000/60000  - 8s 130us/step - loss: 0.1106 - acc: 0.9655Epoch 3/3
60000/60000  - 8s 136us/step - loss: 0.0751 - acc: 0.9764

4 测试模型

val_loss, val_acc = model.evaluate(x_test, y_test)
print(val_loss)
print(val_acc)

10000/10000  - 0s 45us/step0.0916121033909265
0.9713
损失和准确度看起来还凑合,尝试识别训练集

predictions = model.predict(x_test)
print(predictions)

image

With argmax resolve what (it is to find the maximum number of corresponding index, is the recognized digital)

import numpy as np
print(np.argmax(predictions[0]))

7

plt.imshow(x_test[0],cmap=plt.cm.binary)
plt.show()

image

OK, the model can identify the figures.
5. Save the model
is mainly used for storage and recovery model.

model.save('epic_num_reader.model')
# 加载保存的模型
new_model = tf.keras.models.load_model('epic_num_reader.model')
# 测试保存的模型
predictions = new_model.predict(x_test)print(np.argmax(predictions[0]))

image

See here is love, another recommended a Keras tutorial

Keras Colab ultra fire / TPU deep learning free combat, the foundation will be able to understand a little Python Quick Course

reference:

https://www.cnblogs.com/shinny/p/9283372.html

https://www.cnblogs.com/wj-1314/p/9579490.html

https://github.com/MLEveryday/100-Days-Of-ML-Code/blob/master/Code/Day%2039.ipynb

Guess you like

Origin www.cnblogs.com/jpld/p/11370648.html
Recommended