softmax分类
Fashion MNIST数据集
import tensorflow as tf
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
# 下载数据集并划分为训练集和测试集
(train_image,train_lable),(test_image,test_label) = tf.keras.datasets.fashion_mnist.load_data()
train_image.shape,train_lable.shape #查看训练集
test_image.shape,test_label.shape # 查看测试集
plt.imshow(train_image[0]) # 通过切片取出测试机第一张图片查看
train_image[0] # 查看取值
np.max(train_image[0]) #查看最大值得出取值范围0-255
train_lable # 查看对应的分类 9代表鞋子
# 归一化
train_image=train_image/255
test_image=test_image/255
train_image.shape
# 建立模型
model = tf.keras.Sequential()
model.add(tf.keras.layers.Flatten(input_shape=(28,28))) # 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="sparse_categorical_crossentropy",
metrics=["acc"]
)
# 使用训练集集训练模型
model.fit(train_image,train_lable,epochs=5)
# 使用测试集进行评价
model.evaluate(test_image,test_label)
完整代码
# -*- coding: utf-8 -*-
# -*- coding: utf-8 -*-
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' # 修改警告级别,不显示警告
import tensorflow as tf
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# 下载数据集并划分为训练集和测试集
(train_image,train_lable),(test_image,test_label) = tf.keras.datasets.fashion_mnist.load_data()
# 归一化
train_image=train_image/255
test_image=test_image/255
# 建立模型
model = tf.keras.Sequential()
model.add(tf.keras.layers.Flatten(input_shape=(28,28))) # 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="sparse_categorical_crossentropy",
metrics=["acc"]
)
# 使用训练集训练模型
model.fit(train_image,train_lable,epochs=5)
# 使用测试集进行评价
model.evaluate(test_image,test_label)
独热编码one_hot
如: 北京 [1,0,0] 上海 [0,1,0] 深圳 [0,0,1]
train_lable_onehot = tf.keras.utils.to_categorical(train_lable)
train_lable_onehot
test_lable_onehot = tf.keras.utils.to_categorical(test_label)
test_lable_onehot
# 建立模型
model = tf.keras.Sequential()
model.add(tf.keras.layers.Flatten(input_shape=(28,28))) # 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_lable_onehot,epochs=5)
predict =model.predict(test_image)
test_image.shape
predict.shape # 查看预测结果 长度10000,向量10
predict[0]# 查看第一个预测结果 最大值9.2445886e-01
np.argmax(predict[0])# 查看预测最大概率值为9
test_label[0] # 查看真实结果为9