目录
一.tf.keras相关操作
1.获取相关现有数据集
保证在keras.datasets中,
.mnist:手写数字。
.fashion_mnist:服装分类,
.cifar10(100):10个类别分类
from tensorflow import keras
fashion_mnist=keras.datasets.fashion_mnist
(train_images,train_labels),(test_images,test_labels)=fashion_mnist.load_data()
print(train_images,train_labels)
2.构建模型
在keras中,可以通过组合层来构建模型。模型通常是以层构建成图,最常见模型是层的推叠,keras.layers中就又许多模型:
from tensorflow.python.keras.layers import Dense
from tensorflow.python.keras.layers import DepthwiseConv2D
from tensorflow.python.keras.layers import Dot
from tensorflow.python.keras.layers import Dropout
from tensorflow.python.keras.layers import ELU
from tensorflow.python.keras.layers import Embedding
from tensorflow.python.keras.layers import Flatten
from tensorflow.python.keras.layers import GRU
from tensorflow.python.keras.layers import GRUCell
from tensorflow.python.keras.layers import LSTMCell
...
...
...
Flatten:将输入数据进行改变展开
Dense:添加一层神经元,Dense(units,activation=None,**kwargs)
units:神经元个数
activation:激活函数
**kwargs:输入上层输入的形状minput_shape=()
(其他方法看上一章)
model=keras.Sequential([
# 将输入的数据改变容易训练的形状
keras.layers.Flatten(input_shape=(28,28)),
# 设置第一个隐藏
keras.layers.Dense(128,activation=tf.nn.relu),
# 设置输出层
keras.layers.Dense(10,activation=tf.nn.softmax)
])
3.训练与评估
1.通过通过调用model的compile方法去配置该模型所需要的训练参数以及评估方法
2.model.compile(optimizer,loss=None,metrics=None)配置训练相关参数
optimizer:优化器,常用的优化器有:
from tensorflow.python.keras.optimizers import Adadelta
from tensorflow.python.keras.optimizers import Adagrad
from tensorflow.python.keras.optimizers import Adam
from tensorflow.python.keras.optimizers import Adamax
from tensorflow.python.keras.optimizers import Nadam
from tensorflow.python.keras.optimizers import Optimizer
from tensorflow.python.keras.optimizers import RMSprop
from tensorflow.python.keras.optimizers import SGD
from tensorflow.python.keras.optimizers import deserialize
from tensorflow.python.keras.optimizers import get
from tensorflow.python.keras.optimizers import serialize
from tensorflow.python.keras.optimizers import AdamOptimizer()
loss:损失类型,类型可以是字符串也可以是该损失函数:
from tensorflow.python.keras.losses import KLD
from tensorflow.python.keras.losses import KLD as kld
from tensorflow.python.keras.losses import KLD as kullback_leibler_divergence
from tensorflow.python.keras.losses import MAE
from tensorflow.python.keras.losses import MAE as mae
from tensorflow.python.keras.losses import MAE as mean_absolute_error
from tensorflow.python.keras.losses import MAPE
from tensorflow.python.keras.losses import MAPE as mape
from tensorflow.python.keras.losses import MAPE as mean_absolute_percentage_error
from tensorflow.python.keras.losses import MSE
from tensorflow.python.keras.losses import MSE as mean_squared_error
from tensorflow.python.keras.losses import MSE as mse
from tensorflow.python.keras.losses import MSLE
from tensorflow.python.keras.losses import MSLE as mean_squared_logarithmic_error
from tensorflow.python.keras.losses import MSLE as msle
from tensorflow.python.keras.losses import binary_crossentropy
from tensorflow.python.keras.losses import categorical_crossentropy
from tensorflow.python.keras.losses import categorical_hinge
from tensorflow.python.keras.losses import cosine
from tensorflow.python.keras.losses import cosine as cosine_proximity
from tensorflow.python.keras.losses import deserialize
from tensorflow.python.keras.losses import get
from tensorflow.python.keras.losses import hinge
from tensorflow.python.keras.losses import logcosh
from tensorflow.python.keras.losses import poisson
from tensorflow.python.keras.losses import serialize
from tensorflow.python.keras.losses import sparse_categorical_crossentropy
from tensorflow.python.keras.losses import squared_hinge
model.fit():进行训练
model.fit(x=None,y=None,batch_size=None,epochs=None,callbacks=None)
x:训练数据
y:目标值
batch_size:每次训练的样本数
epochs:训练多少次
callbacks:回调函数,比如tensorboard
model=keras.Sequential([
# 将输入的数据改变容易训练的形状
keras.layers.Flatten(input_shape=(28,28)),
# 设置第一个隐藏
keras.layers.Dense(128,activation=tf.nn.relu),
# 设置输出层
keras.layers.Dense(10,activation=tf.nn.softmax)
])
# 设置模型的优化器为Adam,损失为交叉熵损失,metrics为度量的依据,这里是准确率
model.compile(optimizer=tf.keras.optimizers.Adam(),
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
# 开始模型训练
model.fit(train_images,train_labels,epochs=1)
# 模型评估
model.evaluate(test_images,test_labels)
二.案例:实现多层神经网络进行时装分类
keras中的数据涵盖10个类别(裤子,衬衫,裙子......),70000张灰度图像
1.读取数据
from tensorflow import keras
import tensorflow as tf
class FashionClassification:
def __init__(self):
(self.train,self.train_label),(self.test,self.test_label)=keras.datasets.fashion_mnist.load_data()
2.建立模型
class FashionClassification:
model=keras.Sequential([
# 将输入的数据转换形状,图片一般使用[28,28]形状
keras.layers.Flatten(input_shape=(28,28)),
# 建立第一给隐藏,128个神经元
keras.layers.Dense(128,activation=tf.nn.relu),
# 建立输出层,十个输出类别,使用softmax分类
keras.layers.Dense(10,activation=tf.nn.softmax)
])
def __init__(self):
(self.train,self.train_label),(self.test,self.test_label)=keras.datasets.fashion_mnist.load_data()
3.设置模型参数,开始训练,评估模型
def compile(self):
# 设置模型使用的优化器,设置损失函数
FashionClassification.model.Compile(optimizer=tf.train.AdamOptimizer(),
loss=tf.keras.losses.sparse_categorical_crossentropy,
metrics=['accuracy'])
return None
def fit(self):
# 训练函数,训练五次
FashionClassification.model.fit(self.train,self.train_label,epochs=5)
return None
def evaluate(self):
# 模型评估,
test_loss,test_acc=FashionClassification.model.evaluate(self.test,self.test_label)
# 打印损失和准确率
print(test_loss,test_acc)
return None
4.保存和加载模型
model.save_weights('保存的路径')
model.load_weights('模型所在的路径')
if __name__ == '__main__':
# 创建对象
snn=FashionClassification()
# 开始训练
snn.compile()
snn.fit()
snn.evaluate()
# 保存模型
FashionClassification.model.save_weights("./ckpt/SingleNN.h5")
5.使用保存的模型进行预测
def predict(self):
# 查看是否已经有训练好的数据,有就直接用用
if os.path.exists('./data/checkpoint'):
FashionClassification.model.load_weights('./data/FashionClassification')
predictions=FashionClassification.predict(self.test)
# print(np.argmax(predictions,1))
return predictions
if __name__ == '__main__':
# # 创建对象
snn=FashionClassification()
# # 开始训练
# snn.compile()
# snn.fit()
# snn.evaluate()
# 保存模型
# FashionClassification.model.save_weights("./ckpt/SingleNN.h5")
# 进行模型预测
predictions = snn.predict()
# [10000, 10]
print(predictions)
print(np.argmax(predictions, axis=1))
6.添加tensorboard
def fit(self):
# 调用tensorboard回调函数
board = keras.callbacks.TensorBoard(log_dir='"./graph/', write_graph=True)
# 训练函数,训练五次
FashionClassification.model.fit(self.train, self.train, epochs=5,
batch_size=128,callbacks=[board])
return None
四.完整代码
from tensorflow import keras
import tensorflow as tf
import os
class FashionClassification:
model=keras.Sequential([
# 将输入的数据转换形状,图片一般使用[28,28]形状
keras.layers.Flatten(input_shape=(28,28)),
# 建立第一给隐藏,128个神经元
keras.layers.Dense(128,activation=tf.nn.relu),
# 建立输出层,十个输出类别,使用softmax分类
keras.layers.Dense(10,activation=tf.nn.softmax)
])
def __init__(self):
# 返回两个元组,测试集和训练集
# x_train(60000,784),y_train(60000,1)
(self.train,self.train_label),(self.test,self.test_label)=keras.datasets.fashion_mnist.load_data()
# 数据归一化,一般图片处理都要归一化,不然效果会很差
self.train = self.train / 255.0
self.test = self.test / 255.0
def compile(self):
# 设置模型使用的优化器,设置损失函数
FashionClassification.model.compile(optimizer=keras.optimizers.Adam(),
loss=tf.keras.losses.sparse_categorical_crossentropy,
metrics=['accuracy'])
return None
def fit(self):
# 调用tensorboard回调函数
board = keras.callbacks.TensorBoard(log_dir='"./graph/', write_graph=True)
# 训练函数,训练五次
FashionClassification.model.fit(self.train, self.train, epochs=5,
batch_size=128,callbacks=[board])
return None
def evaluate(self):
# 模型评估,
test_loss,test_acc=FashionClassification.model.evaluate(self.test,self.test_label)
# 打印损失和准确率
print(test_loss,test_acc)
return None
def predict(self):
# 查看是否已经有训练好的数据,有就直接用用
if os.path.exists('./data/checkpoint'):
FashionClassification.model.load_weights('./data/FashionClassification')
predictions=FashionClassification.predict(self.test)
# print(np.argmax(predictions,1))
return predictions
if __name__ == '__main__':
# 创建对象
snn=FashionClassification()
# 开始训练
snn.compile()
snn.fit()
snn.evaluate()
# 保存模型
# FashionClassification.model.save_weights("./ckpt/SingleNN.h5")
# 进行模型预测
# predictions = snn.predict()
# # [10000, 10]
# print(predictions)
# print(np.argmax(predictions, axis=1))