<jupyter_start><jupyter_text>Tensorflow MNIST訓練<jupyter_code>import numpy as np
import tensorflow as tf
# MNISTデータロード
(x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()
# 正規化
x_train = x_train.reshape((60000, 28, 28, 1))
x_test = x_test.reshape((10000, 28, 28, 1))
x_train = x_train / 255.0
x_test = x_test / 255.0
# 多層パーセプトロン(MLP)構築
model = tf.keras.models.Sequential([
    tf.keras.layers.Input((28, 28, 1)),
    tf.keras.layers.Conv2D(32, (3, 3), activation='relu'),
    tf.keras.layers.MaxPooling2D((2, 2)),
    tf.keras.layers.Conv2D(64, (3, 3), activation='relu'),
    tf.keras.layers.MaxPooling2D((2, 2)),
    tf.keras.layers.Conv2D(64, (3, 3), activation='relu'),
    tf.keras.layers.Flatten(),
    tf.keras.layers.Dense(64, activation='relu'),
    tf.keras.layers.Dense(10, activation='softmax')
])
# モデル可視化
model.summary()
# モデルコンパイル
model.compile(
    optimizer='adam',
    loss='sparse_categorical_crossentropy',
    metrics=['accuracy']
)
# 訓練
EPOCHS=50
model.fit(
    x_train,
    y_train,
    epochs=EPOCHS,
    batch_size=128,
    validation_data=(x_test, y_test)
)
# モデル評価
val_loss, val_acc = model.evaluate(x_test, y_test, batch_size=128)
# モデル保存
model.save('saved_model', save_format='tf')<jupyter_output><empty_output><jupyter_text>Tensorflow MNIST推論テスト<jupyter_code># 保存したモデルのロード
load_model = tf.keras.models.load_model('saved_model')
# テスト画像ダウンロード
!wget 'https://raw.githubusercontent.com/Kazuhito00/tensorflow2-keras-learn/master/01_mlp_mnist/image/03.jpg'
# テスト画像を1枚ロード
from IPython.display import Image, display_png
from PIL import Image

img = Image.open('03.jpg')
img = img.resize((28, 28))
display_png(img)
# 入力画像成形、および正規化
x = img.convert('L')
x = np.asarray(x)
x = x.reshape(-1, 28, 28, 1)
x = x.astype('float32')
x /= 255
print(x)
%%time
# 推論実行
predict_result = load_model.predict(x)
# 推論結果表示
print(predict_result)
print(np.squeeze(predict_result))
print(np.argmax(np.squeeze(predict_result)))<jupyter_output><empty_output><jupyter_text>ONNXへ変換<jupyter_code>!pip install onnxruntime
!pip install tf2onnx
!python -m tf2onnx.convert --saved-model='saved_model' \
                           --opset=9 \
                           --output='mnist.onnx'
import onnxruntime
sess_onnxruntime = onnxruntime.InferenceSession('mnist.onnx')
res = sess_onnxruntime.run(output_names=['Identity:0'], input_feed={'input_1:0': x})
print("The digit is classified as \"%s\" in ONNXRruntime"%np.argmax(res))<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.15262949782522736, 'fraction_numerical': 0.03835508105970739, 'mean_word_length': 4.405982905982906, 'pattern_counts': {'":': 0, '<': 13, '<?xml version=': 0, '>': 13, 'https://': 1, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '3', 'dir': 'jupyter-structured-clean-dedup', 'id': '557546', 'license': 'Apache-2.0', 'n_tokens_mistral': 1189, 'n_tokens_neox': 1126, 'n_words': 157, 'path': 'MNIST_Tensorflow2ONNX.ipynb', 'repo_name': 'Kazuhito00/Unity-Barracuda-MNIST-WebGL-Sample', 'size': '2529'}