全部代码
import tensorflow as tf
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
(train_image, train_label), (test_image, test_label) = tf.keras.datasets.fashion_mnist.load_data()
#进行归一化处理
train_image = train_image/255
test_image = test_image/255
# 将label转化为onehot的编码形式
train_label_onehot = tf.keras.utils.to_categorical(train_label)
# plt.imshow(train_image[3])
# plt.show()
# print(train_label[3], train_label_onehot[3])
test_label_onehot = tf.keras.utils.to_categorical(test_label)
# print(test_label_onehot)
model = tf.keras.Sequential()
model.add(tf.keras.layers.Flatten(input_shape=(28,28)))
model.add(tf.keras.layers.Dense(128, activation='relu'))
model.add(tf.keras.layers.Dense(10, activation='softmax'))
model.compile(optimizer='adam',
loss='categorical_crossentropy',
metrics=['acc']
)
model.fit(train_image, train_label_onehot, epochs=5)
predict = model.predict(test_image)
print(predict.shape)
print(predict[3])
print(np.argmax(predict[3]))
print(test_label[3])
分块详解
import tensorflow as tf
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
(train_image, train_label), (test_image, test_label) = tf.keras.datasets.fashion_mnist.load_data()
train_label_onehot = tf.keras.utils.to_categorical(train_label)
plt.imshow(train_image[3])
plt.show()
print(train_label[3], train_label_onehot[3])
还是上一次用到的数据集
我们将训练集的label转化为one-hot的形式
比如拿出第四个图片的label,如下
代表裙子的label由3变成了 [0. 0. 0. 1. 0. 0. 0. 0. 0. 0. 0]
那个向量就叫One-hot,也很形象啦,就是一个向量中只有一个是1其他的都是0,就是3所对应的位置是1
对于这种训练集我们用到的
损失函数loss: loss=‘categorical_crossentropy’
#进行归一化处理
train_image = train_image/255
test_image = test_image/255
# 将label转化为onehot的编码形式
train_label_onehot = tf.keras.utils.to_categorical(train_label)
# plt.imshow(train_image[3])
# plt.show()
# print(train_label[3], train_label_onehot[3])
test_label_onehot = tf.keras.utils.to_categorical(test_label)
# print(test_label_onehot)
model = tf.keras.Sequential()
model.add(tf.keras.layers.Flatten(input_shape=(28,28)))
model.add(tf.keras.layers.Dense(128, activation='relu'))
model.add(tf.keras.layers.Dense(10, activation='softmax'))
model.compile(optimizer='adam',
loss='categorical_crossentropy',
metrics=['acc']
)
model.fit(train_image, train_label_onehot, epochs=5)
步骤和上一次一样,只是将loss函数改变了
训练以后发现精度没有影响
predict = model.predict(test_image)
print(predict.shape)
用模型对测试集进行预测,看看结果的size
10000个向量每一个向量有10个dimension
和预想的一样是onehot的样子
print(predict[3])
print(np.argmax(predict[3]))
print(test_label[3])
输出预测的第四个数据,可以看到是一个10维向量,每一维代表的是它的概率
用np.argmax(predict[3])输出向量中的最大值得index,可以看到是1
让我们来看看它实际的值,也是1
也就是说预测正确了
model.compile(optimizer=tf.keras.optimizers.Adam(lr=0.01),
loss='categorical_crossentropy',
metrics=['acc']
)
这是另一种优化器的选择方法,实例化一个,并且将learning_rate设置为0.01比较大,默认是0.001
看看结果
同样是五次,最后的准确度为85.7%,从第三次开始就一直在这个数上下震荡,说明learning_rate选的太大了