以下内容均在jupyterlab中实现
## 1.添加提示
%config IPComplter.greedy=True
## 2.加载Fashion MNIST数据集
from tensorflow import keras
# fashion_mnist = keras.datasets.fashion_mnist
# (train_images, train_labels),(test_images, test_labels) = fashion_mnist.load_data()
## 加载本地
import numpy as np
import os
import gzip
def load_data(data_folder):
files = [
'train-labels-idx1-ubyte.gz', 'train-images-idx3-ubyte.gz',
't10k-labels-idx1-ubyte.gz', 't10k-images-idx3-ubyte.gz'
]
paths = []
for fname in files:
paths.append(os.path.join(data_folder,fname))
with gzip.open(paths[0], 'rb') as lbpath:
y_train = np.frombuffer(lbpath.read(), np.uint8, offset=8)
with gzip.open(paths[1], 'rb') as imgpath:
x_train = np.frombuffer(
imgpath.read(), np.uint8, offset=16).reshape(len(y_train), 28, 28)
with gzip.open(paths[2], 'rb') as lbpath:
y_test = np.frombuffer(lbpath.read(), np.uint8, offset=8)
with gzip.open(paths[3], 'rb') as imgpath:
x_test = np.frombuffer(
imgpath.read(), np.uint8, offset=16).reshape(len(y_test), 28, 28)
return (x_train, y_train), (x_test, y_test)
(train_images, train_labels), (test_images, test_labels) = load_data('fashion')
## 3.建立三层神经元网络模型
import tensorflow as tf
model = keras.Sequential()
model.add(keras.layers.Flatten(input_shape=(28,28)))
model.add(keras.layers.Dense(128,activation=tf.nn.relu))
model.add(keras.layers.Dense(10,activation=tf.nn.softmax))
## 4.查看model的概述
model.summary()
## 5.对输入的数据正则化,使其映射到0,1之间+编译模型:包括三方面(优化函数optimizer、损失函数loss、显示精度metrics)
train_images_scaled = train_images/255
model.compile(optimizer=tf.optimizers.Adam(),loss=tf.losses.sparse_categorical_crossentropy,metrics=['accuracy'])
## 6.训练模型 fit函数包括 训练数据集images、训练集的标签tabels、训练的次数epochs=
model.fit(train_images_scaled,train_labels,epochs=5)
## 7.使用测试数据检测使用model.ecaluate() ,修改test_images的值,(接收的数据,原来数据的label)
test_images_scaled = test_images/255
model.evaluate(test_images_scaled,test_labels)
## 8.单体检测使用model.predict()
import numpy as np
predict = model.predict(test_images)
print(np.argmax(predict[0]))
print(test_labels[0])
## 9.查看test的第一张图片
import matplotlib.pyplot as plt
plt.imshow(test_images[0])
Tips:虽然成功了,但是我这里model.predict直接对所有的测试数据预测,使用predict[index]表示对应的预测结果,当我对test_images[0]/255 单独进行预测的时候会出错误,不知道咋回事小白求告知,万分感谢!