tensorflow2.3 mnist

liu100286發表於2020-12-07

與時俱進,tensoflow 已經到2.3 了,是時候學習keras了。
習慣於圖結構,官網的demo看著不爽,拿來改寫一下。

import tensorflow as tf
import numpy as np
import cv2

(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0

x_inputs = tf.keras.layers.Input(shape=(28, 28))

net = tf.keras.layers.Flatten(input_shape=(28, 28))(x_inputs) #壓平 (None,784)

net = tf.keras.layers.Dense(128, activation='relu')(net)#全連線層 +relu

net = tf.keras.layers.Dropout(0.2)(net) #遺忘層

net = tf.keras.layers.Dense(10, activation="softmax")(net) #全連線層 +迴歸

model = tf.keras.models.Model(inputs=x_inputs, outputs=net) 

train_loss = tf.keras.metrics.Mean(name='train_loss')
#計算準確度都封裝好了
train_accuracy = tf.keras.metrics.SparseCategoricalAccuracy(name='train_accuracy')
optimizer = tf.keras.optimizers.Adam()# 優化函式
while True:#這樣訓練效果不是很好,應該把資料打亂,分批次訓練。有心的同學自己改寫一下。
    train_loss.reset_states()
    train_accuracy.reset_states()
    with tf.GradientTape() as tape:
        predictions = model(x_train)#返回即預測,不錯
        # loss都換成在這裡定義了
        loss = tf.keras.losses.sparse_categorical_crossentropy(y_train, predictions)
    gradients = tape.gradient(loss, model.trainable_variables)
    optimizer.apply_gradients(zip(gradients, model.trainable_variables))
    train_loss(loss)
    train_accuracy(y_train, predictions) 
    print(train_loss.result(), train_accuracy.result())
    if float(train_accuracy.result()) > 0.98:
        break
model.save("./mnist.h5")
converter = tf.lite.TFLiteConverter.from_keras_model(model)
converter.optimizations = [tf.lite.Optimize.DEFAULT]# 據說量化模型很快...
tflite_model = converter.convert()

open("mnist.tflite", "wb").write(tflite_model)


拿個圖測試一下試試

interpreter = tf.lite.Interpreter(
    model_path="./mnist.tflite")
interpreter.allocate_tensors()

# 模型輸入和輸出細節
input_details = interpreter.get_input_details()
print(input_details)

output_details = interpreter.get_output_details()
print(output_details)

(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0
x_test = x_test.astype(np.float32)#原來的型別是 float64 

interpreter.set_tensor(input_details[0]['index'], [x_test[3]]) 
interpreter.invoke()
output_data = interpreter.get_tensor(output_details[0]['index'])
out = output_data[0].tolist()
print(out.index(max(out)))
cv2.imshow("1", x_test[3])
cv2.waitKey(0)

效果應該不錯。

相關文章