人工智能实践——第六周作业【使用fashion_mnist数据集并进行图像化和优化】

课后练习:
题目一:改为fashion_mnist数据集 数据集
题目二:显示y_train[0] ( 文本) 和 和 x_train[0] ( 文本和图片)
题目三:改变网络层数和各层神经元数: 1 层512 个、4 层每层递减512/256/128/10
题目四:增加loss/acc可视化 可视化
题目五:更改层数和神经元数、优化器等,提升 准确率

fashion_mnist数据集

fashion_mnist是keras自带的数据集合,主要目的是为了替代现在的热门数据集 mnist。

#导入数据集,包含70000张灰度图像,10个类别
fashion_mnist = keras.datasets.fashion_mnist
#60000张用于训练,10000张用于测试
(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’]

Matplotlib:

一个基本的绘图程序:
第一步:设定x,y的关系
x = np.arange(1,11)
y = 2 * x + 5
第二步:图名,横纵轴名绘制
plt.title(“Matplotlib demo”)
plt.xlabel(“x axis caption”)
plt.ylabel(“y axis caption”)
plt.legend(“functionA”)
第三部:绘制
plt.plot(x,y)
plt.show()

进阶:
1:
绘制不同形状的图形
plt.plot(x,y,“ob”) #绘制蓝色点图  'o’点图,‘b’蓝色
2:同一个图中绘制多个图
#建立 subplot 网格,高为 2,宽为 1
#激活第一个 subplot
plt.subplot(2, 1, 1)

实例:
import numpy as np
import matplotlib.pyplot as plt
#计算正弦和余弦曲线上的点的 x 和 y 坐标
x = np.arange(0, 3 * np.pi, 0.1)
y_sin = np.sin(x)
y_cos = np.cos(x)
#建立 subplot 网格,高为 2,宽为 1
#激活第一个 subplot并且绘制第一个图像
plt.subplot(2, 1, 1)
plt.plot(x, y_sin)
plt.title(‘Sine’)
#将第二个 subplot 激活,并绘制第二个图像
plt.subplot(2, 1, 2)
plt.plot(x, y_cos)
plt.title(‘Cosine’)
#展示图像
plt.show()
人工智能实践——第六周作业【使用fashion_mnist数据集并进行图像化和优化】_第1张图片
3:展示二维图像
plt.imshow(train_images[0])

4:绘制特殊图像
绘制方形图:
plt.bar
绘制散点图:
plt.scatter

5:将图像数组转化为图像输出
plt.imshow(train_images[0])

history

由model.fit的返回值histtory
history=model.fit(train_images,train_labels,epochs=10,validation_data=(test_images,test_labels),validation_freq=1)
print(history.history)

History类对象包含两个属性,分别为epoch和history,epoch为训练轮数。
history为字典类型,
对于 model.compile(metrics=[‘accuracy’])时,包含val_loss,val_acc,loss,acc四个key值。
对于model.compile(metrics=[‘sparse_categorical_accuracy’]),包含’loss’, ‘sparse_categorical_accuracy’, ‘val_loss’,‘val_sparse_categorical_accuracy’
每一个值都是一个list,记录的是每一次epoch所得到的值

可以根据上述值绘制曲线
#绘制 val_loss 曲线
plt.title(‘Loss Function Curve’)
plt.xlabel(‘Epoch’)
plt.ylabel(‘val_loss’)
plt.plot(history.history[‘val_loss’], label=" L o s s Loss Loss")
plt.legend()
plt.show()

#绘制 accuracy曲线
plt.title(’ sparse_categorical_accuracy’)
plt.xlabel(‘Epoch’)
plt.ylabel(‘sparse_categorical_accuracy’)
plt.plot(history.history[‘sparse_categorical_accuracy’], label=" A c c u r a c y Accuracy Accuracy")
plt.legend()
plt.show()

补充:loss和val_loss的区别
loss是训练集的损失值,val_loss是测试集的损失值
以下是loss与val_loss的变化反映出训练走向的规律总结:
train loss 不断下降,test loss不断下降,说明网络仍在学习;(最好的)
train loss 不断下降,test loss趋于不变,说明网络过拟合;(max pool或者正则化)
train loss 趋于不变,test loss不断下降,说明数据集100%有问题;(检查dataset)
train loss 趋于不变,test loss趋于不变,说明学习遇到瓶颈,需要减小学习率或批量数目;(减少学习率)
train loss 不断上升,test loss不断上升,说明网络结构设计不当,训练超参数设置不当,数据集经过清洗等问题。(最不好的情况)

防止过拟合

DropOut

from tensorflow.keras.layers import Dropout
对于某个层Dense,将其加入到Dense的后方,有概率使其失效
方法一:对于Model
model.add(Dense(units=10))
model.add(Activation(‘softmax’))
model.add(Dropout(0.4))

方法二:对于Sequential
model=Sequential([
Dense(units=200,input_dim=784,bias_initializer=‘zeros’,activation=‘tanh’), #双曲正切激活函数
#Dropout(0.4), #百分之40的神经元不工作
Dense(units=100,bias_initializer=‘zeros’,activation=‘tanh’), #双曲正切激活函数
#Dropout(0.4), #百分之40的神经元不工作
Dense(units=10,bias_initializer=‘zeros’,activation=‘softmax’)
])

方法三:对于class
class Fashion_MnistModel_Dropout(Model):
def init(self):
super(Fashion_MnistModel_Dropout, self).init()
self.d1 = Dense(128, activation=‘relu’)
self.drop = Dropout(0.5)

def call(self, x):
	x = self.d1(x)
    x = self.drop(x)

正则化

分为l1和l2正则化,包含一个超参数。
对于class
from tensorflow.keras import regularizers
class Fashion_MnistModel_Dropout(Model):
def init(self):
super(Fashion_MnistModel_Dropout, self).init()
self.d1 = Dense(128, activation=‘relu’,kernel_regularizer=regularizers.l2(0.001))
self.drop = Dropout(0.5)

def call(self, x):
	x = self.d1(x)
    x = self.drop(x)

批量标准化,简称BN

Batch Normalization(批量标准化,简称BN)同样是对单层使用

BN能带来如下优点:
加速训练过程;
可以使用较大的学习率;
允许在深层网络中使用sigmoid这种易导致梯度消失的激活函数;
具有轻微地正则化效果,以此可以降低dropout的使用【作为dropout和正则化的上位替代】
 
from tensorflow.keras.layers import BatchNormalization
class Fashion_MnistModel_BN(Model):
def init(self):
super(Fashion_MnistModel_BN, self).init()
self.flatten = Flatten()
self.d1 = Dense(512, activation=‘relu’)
self.BN1 = BatchNormalization()
def call(self, x):
x = self.flatten(x)
x = self.d1(x)
x = self.BN1(x)
return y

源码:

# -*- coding: utf-8 -*-
import os
import tensorflow as tf
from tensorflow import keras
import numpy as np
import matplotlib.pyplot as plt
from tensorflow.keras.layers import Dense,Flatten,Dropout,BatchNormalization
from tensorflow.keras import Model
from tensorflow.keras import Model, regularizers

print (tf.__version__)
#导入数据集,包含70000张灰度图像,10个类别
fashion_mnist = keras.datasets.fashion_mnist
#60000张用于训练,10000张用于测试
(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[0])
print(train_labels[0])
#将将图像数组转化为图像输出
plt.imshow(train_images[0])
plt.show()
train_images,test_images=train_images/255.0,test_images/255.0
#改变网络层数和各层神经元数: 1 层512 个、4 层每层递减512/256/128/10
class IrisModel(Model):
    def __init__(self):
        super(IrisModel,self).__init__()
        #是(28,28)的数据,需要延展为一维度数据
        self.flatten=Flatten()
        self.d1=Dense(512,activation='relu')
        self.d2=Dense(256,activation='relu', kernel_regularizer=regularizers.l2(0.001))#正则化
        self.d3=Dense(128,activation='relu')
        self.drop=Dropout(0.4)#dropout
        self.d4=Dense(10,activation='sigmoid')
        self.BN1 = BatchNormalization()#BN批量标准化

    def call(self,x):
        x=self.flatten(x);
        x=self.d1(x)
        x=self.d2(x)
        x=self.d3(x)
        x=self.drop(x)#这里dropout相当于作用于d3层
        y=self.d4(x)
        x = self.BN1(x)
        return y

model=IrisModel()
model.compile(optimizer='adam',
              loss='sparse_categorical_crossentropy',
              metrics=['sparse_categorical_accuracy'])
history=model.fit(train_images,train_labels,epochs=10,validation_data=(test_images,test_labels),validation_freq=1)
print(history.history)
model.summary()
print(type(history.history['val_loss']))

# 绘制 val_loss 曲线
plt.title('Loss Function Curve')
plt.xlabel('Epoch')
plt.ylabel('val_loss')
plt.plot(history.history['val_loss'], label="$Loss$")
plt.legend()
plt.show()

#绘制 accuracy曲线
plt.title(' sparse_categorical_accuracy')
plt.xlabel('Epoch')
plt.ylabel('sparse_categorical_accuracy')
plt.plot(history.history['sparse_categorical_accuracy'], label="$Accuracy$")
plt.legend()
plt.show()

你可能感兴趣的:(人工智能实践)