CNN卷积神经网络,Fashion是数据集,Tensorflow代码
前一篇深度学习中已经介绍了,这里就不再多介绍了。
代码如下(示例):
import datetime
import tensorflow as tf
from sklearn.metrics import precision_score
import matplotlib.pyplot as plt
import numpy as np
代码如下(示例):
fashion = tf.keras.datasets.fashion_mnist
(X_train,Y_train),(X_test,Y_test) = fashion.load_data()
该处数据是用自带的数据集
将图片数据。转换为向量格式。n(图片数量),h,w,rgb(颜色通道数)黑白就是1,这里n = -1,可以自动计算图片的数量,或则n = x_train.shape()相同的效果
# 数据预处理
# 最开始的-1,是会自动计算样本个数
X_train = X_train.reshape([-1,28,28,1]) / 255.0
X_test = X_test.reshape([-1,28,28,1]) / 255.0
# 查看数据
plt.figure(figsize = (6,6))
for i in range(9):
plt.subplot(3,3,i+1)
plt.grid(False)# 去除网格线
# cmap设置图片格式,gray是图像灰色
plt.imshow(X_train[i],cmap='gray')
plt.show()
上一篇手写数字数据集,已经简单讲解了模型结构。这里不同的点是tf.keras.layers.Dropout(0.1)
Dropout的作用是,随机让每层0.1比例的神经元不进行操作,避免神经元太多,网络太深而速度很慢。
# 模型搭建
model = tf.keras.models.Sequential([
tf.keras.layers.Conv2D(filters = 32,kernel_size = (5,5),
activation = tf.nn.relu ,input_shape=(28,28,1)),
tf.keras.layers.MaxPooling2D(pool_size=(2, 2)),
tf.keras.layers.Dropout(0.1),
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(units = 128,activation = tf.nn.relu),
tf.keras.layers.Dense(units = 10,activation = 'softmax')
])
model.summary()
模型结构
Model: "sequential"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
conv2d_4 (Conv2D) (None, 24, 24, 32) 832
max_pooling2d_4 (MaxPooling (None, 12, 12, 32) 0
2D)
dropout_4 (Dropout) (None, 12, 12, 32) 0
flatten_2 (Flatten) (None, 4608) 0
dense (Dense) (None, 128) 589952
dense_1 (Dense) (None, 10) 1290
=================================================================
Total params: 592,074
Trainable params: 592,074
Non-trainable params: 0
# 优化器
learning_rate = 0.001 #学习率
adam_optimizer = tf.keras.optimizers.Adam(learning_rate)
# 编译模型
model.compile(optimizer=adam_optimizer,
loss=tf.keras.losses.sparse_categorical_crossentropy,
metrics=['accuracy'])
# 模型开始训练时间
start_time = datetime.datetime.now()
# 训练模型
num_epochs = 20 # 训练次数
batch_size = 128 # 批大小
model.fit(x=X_train, y=Y_train, batch_size=batch_size, epochs=num_epochs)
# 模型结束训练,记录训练时间
end_time = datetime.datetime.now()
time_cost = end_time - start_time
import random
Fashion_dict = {0:'T恤',1:'裤子',2:'套衫',3:'裙子',4:'外套',5:'凉鞋',
6:'汗衫',7:'运动鞋',8:'包',9:'踝靴'}
# 进行预测
image_index = random.randint(1,100) # 选一张图片
pred = model.predict(X_test[image_index].reshape(1,28,28,1))
print(Fashion_dict[pred.argmax()]) # 打印出预测值
plt.figure(figsize = (1.5,1.5))
#plt.figure(figsize = (6,6))
plt.imshow(X_test[image_index].reshape(28,28), cmap='Greys')
plt.show()
scores = model.evaluate(X_test, Y_test, verbose=0)
print("使用CNN网络的正确率为:" ,'%.2f' %(scores[1]*100) , "%")
使用CNN网络的正确率为: 91.55 %
以上就是CNN卷积神经网络模型预测Fashion数据集的代码。谢谢大家。