Tensoflow2.0学习笔记 之 分类模型

Tensoflow2.0

tf,keras(构建和训练模型的核心高级API)

单输入单输出的sequential顺序模型

函数式API

eager模式

eager模式
直接迭代和直观调试

自定义

tf.GradientTape求解梯度,自定义训练逻辑
tf.data 加载图片和结构化数据

第一节 分类模型

利用keras来进行分类模型的数据读取和展示
使用plt.show()进行图像展示。

import tensorflow as tf  #导入TensorFlow
from tensorflow import keras #导入Keras
import matplotlib as mpl #该函数用来在python画图
import matplotlib.pyplot as plt #子类     %matplotlib inline 该方法是jupyter显示图,pycharm中使用plt.show()即可
import numpy as np
import sklearn #回归(Regression)、降维(Dimensionality Reduction)、分类(Classfication)、聚类(Clustering)等方法
import pandas as pd #python处理数据的库
import os
import sys
import time
fashion_mnist = keras.datasets.fashion_mnist#导入fashion——mnist数据集
(x_train_all,y_train_all),(x_test,y_test) = fashion_mnist.load_data()#下载数据
#将前五千张作为验证集,后五千张作为训练集
x_valid,x_train = x_train_all[:5000],x_train_all[5000:]
y_valid,y_train = y_train_all[:5000],y_train_all[5000:]
#查看数据集的正确性
# print(x_valid.shape,y_valid.shape)
# print(x_train.shape,y_train.shape)
# print(x_test.shape,y_test.shape)
# print(y_test.shape,y_test.shape)

#定义一个函数,
# 输入为一个图片的数组
# 输出为一个图像
def show_single_image(img_arr):
    plt.imshow(img_arr,cmap="binary") #cmap定义一个颜色图谱
    plt.show()
show_single_image(x_train[0])

输出结果为一张图片
在这里插入图片描述
输入多张图片

def show_imgs(n_rows,n_cols,x_data,y_data,class_name):
    assert len(x_data) == len(y_data)#验证两组数据是否相等
    assert n_cols *n_rows < len(x_data)
    plt.figure(figsize=(n_cols*1.4,n_rows*1.6))#图片大小的尺寸
    for row in range(n_rows):
        for col in range(n_cols):
            #n_cols*row+col
            #按列来排序,假设是3列3行 当col=1 row =1
            # 1 4
            # 2
            # 3
            index = n_cols*row+col#找到那张图片的索引
            plt.subplot(n_rows,n_cols,index+1)#画子图
            plt.imshow(x_data[index],cmap="binary",
                       interpolation= 'nearest')#interpolation= 'nearest'释放图片的方法
            plt.axis('off')#坐标轴的释放
            plt.title(class_name[y_data[index]])
    plt.show()
class_name = ['T-shirt','Trouser','Pullover','Dress','Coat','Sandal','Shirt','Sneaker','Bag','Ankle boot']
show_imgs(3,5,x_train,y_train,class_name)

输出结果如图所示
在这里插入图片描述

模型的建立

tf.kears.models.Sequential
Sequential模型,就是多个网络层的线性堆叠。它建立模型有两中方式,一种是向layer中添加list,一种是通.add()的方式一层层的添加。

Flatten层用来将输入“压平”,即把多维的输入一维化
dense就只中间的隐藏层在这里插入图片描述

#第一步建立模型
#对象的使用
model = keras.models.Sequential()
#使用add方法将Flatten添加到模型中
model.add(keras.layers.Flatten(input_shape[28,28]))
#Dense隐藏的神经网络层 activation激活函数
# relu线性整流函数 y = max(0,x)
# softmax 将向量变成概率分布
model.add(keras.layers.Dense(300,activation='relu'))
model.add(keras.layers.Dense(100,activation='relu'))
model.add(keras.layers.Dense(10,activation='softmax'))

损失函数和参数调节

如果你的 数据是 one-hot 编码,用 categorical_crossentropy
  one-hot 编码:[0, 0, 1], [1, 0, 0], [0, 1, 0]
如果你的 数据 是 数字编码 ,用 sparse_categorical_crossentropy
  数字编码:2, 0, 1

#损失函数,参数调节
# loss目的将y的值转换为向量
# optimizer参数的调节。
# metrics其他的性能指标,metrics=[‘accuracy’]为典型用法
model.compile(loss='sparse_categorical_crossentropy',
              optimizer='adam',
              metrics=['accuracy'])
# model.summary()

#进行函数的训练
history = model.fit(x_train,y_train,epochs=10,
          validation_data=(x_valid,y_valid))

全代码

import tensorflow as tf  #导入TensorFlow
from tensorflow import keras #导入Keras
import matplotlib as mpl #该函数用来在python画图
import matplotlib.pyplot as plt #子类     %matplotlib inline 该方法是jupyter显示图,pycharm中使用plt.show()即可
import numpy as np
import sklearn #回归(Regression)、降维(Dimensionality Reduction)、分类(Classfication)、聚类(Clustering)等方法
import pandas as pd #python处理数据的库
import os
import sys
import time
fashion_mnist = keras.datasets.fashion_mnist#导入fashion——mnist数据集
(x_train_all,y_train_all),(x_test,y_test) = fashion_mnist.load_data()#下载数据
#将前五千张作为验证集,后五千张作为训练集
x_valid,x_train = x_train_all[:5000],x_train_all[5000:]
y_valid,y_train = y_train_all[:5000],y_train_all[5000:]
#查看数据集的正确性
# print(x_valid.shape,y_valid.shape)
# print(x_train.shape,y_train.shape)
# print(x_test.shape,y_test.shape)
# print(y_test.shape,y_test.shape)

# # 定义一个函数,
# # 输入为一个图片的数组
# # 输出为一个图像
# def show_single_image(img_arr):
#     plt.imshow(img_arr,cmap="binary") #cmap定义一个颜色图谱
#     plt.show()
#
# show_single_image(x_train[2])
# class_name对应图像的类别名称
def show_imgs(n_rows,n_cols,x_data,y_data,class_name):
    assert len(x_data) == len(y_data)#验证两组数据是否相等
    assert n_cols *n_rows < len(x_data)
    plt.figure(figsize=(n_cols*1.4,n_rows*1.6))#图片大小的尺寸
    for row in range(n_rows):
        for col in range(n_cols):
            #n_cols*row+col
            #按列来排序,假设是3列3行 当col=1 row =1
            # 1 4
            # 2
            # 3
            index = n_cols*row+col#找到那张图片的索引
            plt.subplot(n_rows,n_cols,index+1)#画子图
            plt.imshow(x_data[index],cmap="binary",
                       interpolation= 'nearest')#interpolation= 'nearest'释放图片的方法
            plt.axis('off')#坐标轴的释放
            plt.title(class_name[y_data[index]])
    plt.show()
class_name = ['T-shirt','Trouser','Pullover','Dress',
              'Coat','Sandal','Shirt','Sneaker','Bag','Ankle boot']
show_imgs(3,5,x_train,y_train,class_name)
#第一步建立模型
#对象的使用
model = keras.models.Sequential()
#使用add方法将Flatten添加到模型中
model.add(keras.layers.Flatten(input_shape=[28,28]))
#Dense隐藏的神经网络层 activation激活函数
# relu线性整流函数 y = max(0,x)
# softmax 将向量变成概率分布
model.add(keras.layers.Dense(300,activation='relu'))
model.add(keras.layers.Dense(100,activation='relu'))
model.add(keras.layers.Dense(10,activation='softmax'))

#损失函数,参数调节
# loss目的将y的值转换为向量
# optimizer参数的调节。
# metrics其他的性能指标,metrics=[‘accuracy’]为典型用法
model.compile(loss='sparse_categorical_crossentropy',
              optimizer='adam',
              metrics=['accuracy'])
# model.summary()查看Damn的运行结果

#进行函数的训练
#epochs=10 代表进行了十期的模型训练
history = model.fit(x_train,y_train,epochs=10,
          validation_data=(x_valid,y_valid))
 #定义一个函数将数据按图输出
def plot_learning_curves(history):
    pd.DataFrame(history.history).plot(figsize=(8,5))
    plt.grid(True)#设置网格线
    plt.gca().set_ylim(0,1)#设置范围
    plt.show()

plot_learning_curves(history)

最终准确率:
在这里插入图片描述
在这里插入图片描述
对于optimizer中的方法刚开始使用的是sgd,然后出现了loss = nan 代表爆表,然后准确率很低,看了网上的方法说的是调节学习率,因为我是一名初学。所以我没找出来哪个代表的是学习率,开始有想过是不是epoch,但是结果一样,如果有大牛知道的话,希望可以指出一下,谢谢您了,然后,后面把sgd改成Adam方法就没出现爆表
希望可以在深度学习的路上越走越远。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值