# プログラム名: ai_digit_recognition_easy.py
# 目的: AIが数字の絵を見て「これは〇!」ってあてる体験ができる
import numpy as np
import matplotlib.pyplot as plt
from tensorflow.keras.datasets import mnist
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Flatten
from tensorflow.keras.utils import to_categorical
# ① 手書き数字のデータをよみこむ / Load MNIST dataset
# x_train, y_train: AIが勉強する用の画像と答え
# x_test, y_test: テスト用(AIが当ててみる)
(x_train, y_train), (x_test, y_test) = mnist.load_data()
# ② 画像の色を0〜1にする(AIが読みやすいように) / Normalize
x_train = x_train / 255.0
x_test = x_test / 255.0
# ③ AIの「数字あてクイズモデル」を作る / Build a simple neural network
model = Sequential([
Flatten(input_shape=(28, 28)), # 画像をまっすぐ1列にする(28×28 → 784)
Dense(128, activation='relu'), # 「かしこい考える場所」が128個
Dense(10, activation='softmax') # 出力は「0〜9の中からどれ?」を確率で出す
])
model.compile(optimizer='adam',
loss='categorical_crossentropy',
metrics=['accuracy'])
# ④ 勉強スタート!(3回くりかえして覚える)/ Train the model
model.fit(x_train, to_categorical(y_train), epochs=3, batch_size=128)
# ⑤ AIにクイズを出す:1枚ランダムに選んでみせる / Pick one image randomly
index = np.random.randint(0, len(x_test))
img = x_test[index]
# ⑥ 画像を表示して、「これはなんの数字?」とたずねる / Show the image
plt.imshow(img, cmap='gray')
plt.title("What number is this?")
plt.axis('off')
plt.show()
# ⑦ AIに予想させよう!/ Let AI guess
prediction = model.predict(np.array([img]))
predicted_number = np.argmax(prediction)
# ⑧ 結果を表示!/ Show prediction result
print(f"🤖 AIのこたえ: {predicted_number}")
print(f"✅ ほんとうのこたえ: {y_test[index]}")