全连接层
net=tf.keras.layers.Dense(units,activation)
net.build( input_shape=() ) 完成网络参数的创建
net.kernel 获取权值矩阵
net.bias 获取偏置向量
net.trainable_variables 获取待优化参数列表
net.variables 获取所有参数列表
model=tf.keras.Sequential([ ])
model.summary() 获取网络信息
激活函数
tf.nn.sigmoid Sigmoid函数
tf.nn.ranh tanh函数
tf.nn.relu ReLU函数 对应网络层类 tf.keras.layers.ReLU()
tf.nn.leaky_relu LeakyReLU函数 类 tf.keras.layers.LeakyReLU()
tf.nn.softmax softmax函数 类 tf.keras.layers.Softmax()
误差计算
均方差误差函数MSE
tf.reduce_mean( tf.keras.losses.MSE(y , out) )
层方法实现
tf.keras.losses.MeanSquaredError()
交叉熵误差函数
tf.keras.losses.categorical_crossentropy()
反向传播算法
自动求梯度
x=tf.random.normal([1,3])
w=tf.ones([3,2])
b=tf.ones([2])
y = tf.constant([0, 1])
with tf.GradientTape() as tape: # 构建梯度记录器
tape.watch([w, b]) # 非tf.Variable类型张量需人为设置记录梯度信息
logits = tf.sigmoid(x@w+b)
loss = tf.reduce_mean(tf.losses.MSE(y, logits))
grads = tape.gradient(loss, [w, b])
print('w grad:', grads[0])
print('b grad:', grads[1])
Keras高层接口
自定义网络
net=tf.keras.Sequential( [Layer] )
net.add(Layer) 追加新的网络层
net.build(input_shape=)
net.summary() 网络结构
net.trainable_variables 待优化张量列表
net.variables 全部张量列表
模型装配、训练与测试
tf.keras.Model类 网络的母类
tf.keras.layers.Layer类 网络层的母类
net.compile( optimizer=,loss=,metrics=['accuracy'] ) 装配模型
history=net.fit(Dataset , epochs=, validation_data=,......) 模型训练
history.history 训练记录
net.evaluate 模型测试
net.predict 模型预测
模型保存与加载
net.save_weights('weights.ckpt') 保存模型所有张量数据
net.load_weights('weights.ckpt') 读取数据并写入当前网络
net.save('model.h5') 保存模型结构与参数
net=tf.keras.model.load_model('model.h5') 读取网络
tf.saved_model.save(net, 'model_savedmodel') 保存模型结构与参数
net=tf.saved_model.load('model_savedmodel') 读取网络
测量工具
tf.keras.metrics 如:统计平均值Mean类,准确率Accuracy类
loss_metre=metrics.Mean() 新建测量器
loss_meter.updata_state(float()) 写入数据
loss_meter.result() 读取统计信息
loss_meter.reset_states() 清除状态
Fashion MNIST Dense 实战
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import datasets, layers, optimizers, Sequential, metrics
def preprocess(x, y):
x = tf.cast(x, dtype=tf.float32) / 255.
y = tf.cast(y, dtype=tf.int32)
return x,y
(x, y), (x_test, y_test) = datasets.fashion_mnist.load_data()
batchsz = 128
db = tf.data.Dataset.from_tensor_slices((x,y))
db = db.map(preprocess).shuffle(10000).batch(batchsz)
db_test = tf.data.Dataset.from_tensor_slices((x_test,y_test))
db_test = db_test.map(preprocess).batch(batchsz)
model = Sequential([
layers.Dense(256, activation=tf.nn.relu), # [b, 784] => [b, 256]
layers.Dense(128, activation=tf.nn.relu), # [b, 256] => [b, 128]
layers.Dense(64, activation=tf.nn.relu), # [b, 128] => [b, 64]
layers.Dense(32, activation=tf.nn.relu), # [b, 64] => [b, 32]
layers.Dense(10) # [b, 32] => [b, 10], 330 = 32*10 + 10
])
model.build(input_shape=[None, 28*28])
model.summary()
# w = w - lr*grad
optimizer = optimizers.Adam(lr=1e-3)
def main():
loss_ce_list=[]
loss_mse_list=[]
acc_list=[]
for epoch in range(30):
for step, (x,y) in enumerate(db):
# x: [b, 28, 28] => [b, 784]
# y: [b]
x = tf.reshape(x, [-1, 28*28])
with tf.GradientTape() as tape:
# [b, 784] => [b, 10]
logits = model(x)
y_onehot = tf.one_hot(y, depth=10)
# [b]
loss_mse = tf.reduce_mean(tf.losses.MSE(y_onehot, logits))
loss_ce = tf.losses.categorical_crossentropy(y_onehot, logits, from_logits=True)
loss_ce = tf.reduce_mean(loss_ce)
grads = tape.gradient(loss_ce, model.trainable_variables)
optimizer.apply_gradients(zip(grads, model.trainable_variables))
if step % 100 == 0:
print(epoch, step, 'loss:', float(loss_ce), float(loss_mse))
loss_ce_list.append(float(loss_ce))
loss_mse_list.append(float(loss_mse))
# test
total_correct = 0
total_num = 0
for x,y in db_test:
# x: [b, 28, 28] => [b, 784]
# y: [b]
x = tf.reshape(x, [-1, 28*28])
# [b, 10]
logits = model(x)
# logits => prob, [b, 10]
prob = tf.nn.softmax(logits, axis=1)
# [b, 10] => [b], int64
pred = tf.argmax(prob, axis=1)
pred = tf.cast(pred, dtype=tf.int32)
# pred:[b]
# y: [b]
# correct: [b], True: equal, False: not equal
correct = tf.equal(pred, y)
correct = tf.reduce_sum(tf.cast(correct, dtype=tf.int32))
total_correct += int(correct)
total_num += x.shape[0]
acc = total_correct / total_num
print(epoch, 'test acc:', acc)
acc_list.append(acc)
return loss_ce_list,loss_mse_list,acc_list
ce,mse,acc=main()
import matplotlib.pyplot as plt
%matplotlib inline
epochs1=range(1, len(ce)+1)
epochs2=range(1,len(mse)+1)
plt.plot(epochs1, ce, 'b', label='ce',color='coral')
plt.plot(epochs2, mse, 'b', label='mse')
plt.ylim(0,1)
plt.title('loss')
plt.legend()
plt.figure()
epochs3=range(1, len(acc)+1)
plt.plot(epochs3, acc, 'b', label='acc',color='coral')
plt.ylim(0,1)
plt.title('acc')
plt.legend()
plt.show()
自定义网络实战
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import datasets, layers, optimizers
# 预处理
def preprocess(x, y):
x = tf.cast(x, dtype=tf.float32) / 255. #标准化
x = tf.reshape(x, [-1, 28*28]) #打平
y = tf.cast(y, dtype=tf.int32) #转出整型张量
y = tf.one_hot(y, depth=10) #one_hot编码
return x,y
(x, y), (x_test, y_test) = datasets.mnist.load_data() #加载数据
print('x:', x.shape, 'y:', y.shape, 'x test:', x_test.shape, 'y test:', y_test.shape)
train_db = tf.data.Dataset.from_tensor_slices((x, y)) #构建Dataset对象
train_db = train_db.shuffle(60000).batch(128).map(preprocess) #随机打散和进行批量处理
test_db = tf.data.Dataset.from_tensor_slices((x_test, y_test))
test_db = test_db.shuffle(10000).batch(128).map(preprocess)
x,y = next(iter(train_db))
print('train sample:', x.shape, y.shape)
class MyDense(layers.Layer):
def __init__(self, in_dim, out_dim):
super(MyDense, self).__init__()
self.kernel = self.add_variable('w', [in_dim, out_dim])
def call(self, inputs, training=None):
x = inputs @ self.kernel
x = tf.nn.relu(x)
return x
class MyModel(tf.keras.Model):
def __init__(self):
super(MyModel, self).__init__()
self.fc1 = MyDense(28 * 28, 256)
self.fc2 = MyDense(256, 128)
self.fc3 = MyDense(128, 64)
self.fc4 = MyDense(64, 32)
self.fc5 = MyDense(32, 10)
def call(self, inputs, training=None):
x = self.fc1(inputs)
x = self.fc2(x)
x = self.fc3(x)
x = self.fc4(x)
x = self.fc5(x)
return x
model = MyModel()
model.compile(
optimizer=optimizers.Adam(),
loss=tf.losses.CategoricalCrossentropy(from_logits=True),
metrics=['accuracy']
)
model.fit(train_db, epochs=10, validation_data=test_db)
扫一扫 获得更多内容