Introduction to Tensoflow Practical Computer Vision

Introduction to Tensoflow Practical Computer Vision

import tensorflow as tf
from tensorflow import keras
fashion_mnist = keras.datasets.fashion_mnist#导入数据集
(train_images,train_labels),(test_images,test_labels) = fashion_mnist.load_data()
print(train_images.shape)#60000张,每张28*28
import matplotlib.pyplot as plt
plt.imshow(train_images[0])
#全连接网络模型
model = keras.Sequential([
    keras.layers.Flatten(input_shape = (28,28)),
    keras.layers.Dense(128,activation=tf.nn.relu),
    keras.layers.Dense(10,activation = tf.nn.softmax)
    
])
#model = keras.Sequential()
#model.add(keras.layers.Flatten(input_shape=(28,28)))
#model.add(keras.layer.Dense(128,activation =tf.nn.relu))
#model.add(keras.layer.Dense(10,activation= tf.nn.softmax))


model.summary()#100480  784像素*128神经元=100352(因为输入层和中间层每层都有一个bias,加上就是100480)
#1290 = (128+1)*10
#Adam()一种经常使用的优化办法
#train_label[0] = 9,使用sparse_categorical_crossentropy作为损失函数,若[0,0,0,0,0,0,0,0,0,0,0,1](称为ont-hot)则使用categorical_crossentropy作为损失函数
model.compile(optimizer = tf.optimizers.Adam(),loss = tf.losses.sparse_categorical_crossentropy,metrics=['accuracy'])
model.fit(train_images,train_labels,epochs=5)
#为了提高模型精确度,可以通过对原始数据进行归一化处理再进行模型拟合
train_images = train_images/255
model.compile(optimizer = tf.optimizers.Adam(),loss = tf.losses.sparse_categorical_crossentropy,metrics=['accuracy'])
model.fit(train_images,train_labels,epochs=5)
#评估模型
test_images_scaled = test_images/255
model.evaluate(test_images_scaled,test_labels)
#预测
#教程中没有加reshape,会报错
model.predict([[test_images[0].reshape(1,28,28,1)/255]])

The neural network is not trained as much as possible. If there is more, overfitting will occur. That is to say, it recognizes all training pictures well, but recognizes new pictures poorly. You can compare the test LOSS with the training LOSS. Bifurcation is over-fitting. In tensorflow, the callback class is used to judge and terminate the training in time

Guess you like

Origin blog.csdn.net/qq_43720646/article/details/112914987