神经网络

import tensorflow as tf
from tensorflow.keras.layers import Dense, Flatten
from tensorflow.keras.models import Sequential
from tensorflow.keras.losses import SparseCategoricalCrossentropy
from tensorflow.keras.optimizers import Adam
import numpy as np
mnist = tf.keras.datasets.mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0 # 归一化像素值
print(x_train.shape)
print(x_test.shape)
model = Sequential([
Flatten(input_shape=(28, 28)), # 将28x28的图像展平成784个元素的一维数组
Dense(128, activation='relu'), # 第一层隐藏层,128个节点,ReLU激活函数
Dense(64, activation='relu'), # 第二层隐藏层,64个节点,ReLU激活函数
Dense(10, activation='softmax') # 输出层,10个节点,对应10个类别,使用softmax激活函数进行多分类
])
model.compile(optimizer=Adam(), # 使用Adam优化器
loss=SparseCategoricalCrossentropy(), # 使用稀疏分类交叉熵损失函数
metrics=['accuracy']) # 评估指标为准确率
model.summary()
model.fit(x_train, y_train, epochs=10, validation_data=(x_test, y_test)) # 训练模型并在测试集上验证
test_loss, test_acc = model.evaluate(x_test, y_test, verbose=2)
print('\nTest accuracy:', test_acc)
predictions = model.predict(x_test)
print("Predictions:\n", predictions) # 查看预测结果(概率分布)
imagePath = "D:\\work\\mygithub\\docs\\intoAI\\src\\chapter2\\images\\intoAI_2_0.png"
img = tf.keras.utils.load_img(imagePath, color_mode='grayscale')
print(img.size) # 输出图像尺寸
print(img.mode) # 输出图像模式,应为 'L' 表示灰度图像
img_array = (np.expand_dims(img,0))
print(img_array.shape)
predictions = model.predict(img_array)
print(predictions)