在python中安装tensorflow
使用阿里源镜像安装
pip install tensorflow -i https://mirrors.aliyun.com/pypi/simple/
导入 Fashion MNIST 数据集
导入keras数据
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()
归一化
train_images = train_images / 255.0
test_images = test_images / 255.0
建立模型
输入层,添加层和输出层
model = keras.Sequential([
keras.layers.Flatten(input_shape=(28, 28)),
keras.layers.Dense(128, activation='relu'),
keras.layers.Dense(10)
])
编译模型
model.compile(optimizer='adam',
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=['accuracy'])
训练模型
history =model.fit(train_images, train_labels,epochs=100)
评估模型
test_loss, test_acc = model.evaluate(test_images, test_labels, verbose=2)
保存模型
mp = "G://机器学习1/iris_model2.h5"
model.save(mp)
由于每次操作都要训练一次模型,我采用保存模型的方式
安装keras
pip install keras -i https://mirrors.aliyun.com/pypi/simple/
加载模型
mp = "G://机器学习1/iris_model1.h5"
model = load_model(mp)
使用模型进行预测
(train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()
predictions = model.predict(test_images)
建立一个列表保存测试失败的数据
error = []
for i in range(len(predictions)):
if np.argmax(predictions[i]) != test_labels[i]:
error.append(i)
对测试集错误的前100个图形查看
for i in range(100):
plt.subplot(10, 10, i + 1)
plt.grid(False)
plt.imshow(test_images[error[i]], cmap=plt.cm.binary)
plt.xlabel((np.argmax(predictions[error[i]]),test_labels[error[i]]))
plt.show()