TensorFlow官方入门实操课程-全连接神经网络分类

#设置显卡内存使用率,根据使用率占用
import os
os.environ["TF_FORCE_GPU_ALLOW_GROWTH"] = "true"
#引入必要的库
import tensorflow as tf
print(tf.__version__)
from tensorflow import keras
import matplotlib.pyplot as plt
%matplotlib inline
import seaborn as sns       #基于matplotlib绘制图像封装的
import numpy as np


fashion_mnist = keras.datasets.fashion_mnist  #导入数据集
(train_images,train_labels),(test_images,test_labels) = fashion_mnist.load_data()  #导入数据集
#显示数据集的数据
class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat',
               'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']
print(train_images.shape)  #训练集的数据样子
print(len(train_images))   #训练集的大小
print(test_images.shape)   #测试集的数据样子
print(len(test_labels))    #测试集的大小

plt.figure(figsize=(5,5))   #设置绘图区域大小
plt.imshow(train_images[0]) #把数据绘制成伪彩图
plt.colorbar()              #添加一条色带
plt.grid(False)             #绘图区域不显示网格
plt.show()

以下为上一段代码输出
在这里插入图片描述

model = keras.Sequential()  #创建一个前向传播模型
#输入层,平铺展开,28*28个参数输入
model.add(keras.layers.Flatten(input_shape=(28,28))) #添加输入的参数为28*28,由于fashion_mnists数据集是28*28的图片
#中间层,使用relu激活函数
model.add(keras.layers.Dense(128,activation=tf.nn.relu))
#输出层使用softmax做分类
model.add(keras.layers.Dense(10,activation=tf.nn.softmax))

model.summary()  #展示层的样子
#第一层 28*28 = 784个参数输入
#第二层 (784+1)*128 = 100480 那个新加的一个参数就是bias,在输入跟中间层有,输出层没有
#第三层 (128+1)*10 = 1290 这是全连接的网络结构

这里为上一段代码的输出
在这里插入图片描述

#为模型装配优化器,损失函数
train_images = train_images/255 #归一化变成0~1之间数
#使用Adam优化器,交叉熵损失函数
model.compile(optimizer=tf.optimizers.Adam(),loss=tf.losses.sparse_categorical_crossentropy,metrics=['accuracy'])
history = model.fit(train_images,train_labels,epochs=50,validation_split=0.3,shuffle=True)

以下为上一段代码输出
在这里插入图片描述

epochs = len(history.history['loss']) #获取X轴长度

fig, axes = plt.subplots(2, sharex=True, figsize=(12, 8))
fig.suptitle('Training Metrics')

axes[0].set_ylabel("Loss", fontsize=14)
axes[0].set_xlabel("Epoch", fontsize=14)
axes[0].plot(range(epochs),history.history['loss'], label='Loss')
axes[0].plot(range(epochs),history.history['val_loss'], label='Loss')
plt.legend()

axes[1].set_ylabel("Accuracy(%)", fontsize=14)
axes[1].set_xlabel("Epoch", fontsize=14)
axes[1].plot(range(epochs),history.history['accuracy'], label='Accuracy')
axes[1].plot(range(epochs),history.history['val_accuracy'], label='Val_accuracy')
# plt.savefig('./epoch.jpg')
# plt.suptitle('自定义图表', fontsize=400, ha='center')  # 即标题在x轴和y轴形成的方框内部,如下图(详细用法见下注释)。如果需要标题在这上方,使用 plt.title(blabla) 
plt.legend()
plt.show()

以下为loss与准确率曲线可以看出训练过拟合了,训练集的loss下降多,但是测试集的训练loss增加了,训练参数不匹配
在这里插入图片描述

# model.predict(test_images[10])   #输入参数10进行数据预测
plt.figure(figsize=(5,5))   #设置绘图区域大小
plt.imshow(test_images[10]) #把数据绘制成伪彩图
plt.colorbar()              #添加一条色带
plt.grid(False)             #绘图区域不显示网格
plt.show()

#用测试集来评估训练的模型
test_images_scaled = test_images/255
model.evaluate(test_images_scaled,test_labels)   #评估获得Loss与准确率

predictions = model.predict(test_images)    #获取全部数据的预测类别,每一行代表这个图片属于那个类别,值越大,概率越大
# np.argmax(model.predict(test_images_scaled))

for i, logits in enumerate(predictions):
  class_idx = tf.argmax(logits).numpy()
  p = tf.nn.softmax(logits)[class_idx]   
  name = class_names[class_idx]
  print(p)
  print("Example {} prediction: {} ({:4.1f}%)".format(i, name, 100*p))

在这里插入图片描述
改成如下的输出

#用测试集来评估训练的模型
test_images_scaled = test_images/255
model.evaluate(test_images_scaled,test_labels)   #评估获得Loss与准确率

predictions = model.predict(test_images_scaled[0].reshape(1, 28, 28))   #获取第一个数据的各个分类概率
print(predictions)
predlab = np.argmax(predictions)
print(predlab)

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值