TensorFlow 学习笔记
Tensorflow 是谷歌开发的一款机器学习软件包。2019 年,谷歌将 Keras 集成到 Tensorflow 中,并发布了 Tensorflow 2.0。Keras 是 François Chollet 独立开发的一个框架,为 Tensorflow 创建了一个简单的、以层为中心的接口。
张量(Tensor)是数组的另一个名称。
注意 TensorFlow 对数据的处理方式和 NumPy 有所不同。你可以使用 NumPy 加载数据,当你把 NumPy 对象作为参数传给 TensorFlow 时,TensorFlow 会自动将其转换为内部的 Tensor 格式。计算完成后,你可以使用 tensor.numpy() 获取其 NumPy 版本。
导入包:
import tensorflow as tf
from tensorflow.keras import Sequential
from tensorflow.keras.layers import Dense, Input
from tensorflow.keras.losses import MeanSquaredError, BinaryCrossentropy
from tensorflow.keras.activations import sigmoid
创建一个只有一个神经元的 layer,使用 linear 激活函数(\(g(z) = z\)):
Module: tf.keras.layers | TensorFlow
linear_layer = Dense(units=1, activation='linear') # Dense 是神经网络中的 layer 的别名,而 unit 是神经元的别名
w, b = linear_layer.get_weights() # 获取权重
linear_layer.set_weights([set_w, set_b]) # 设置权重
activation = linear_layer(X_train[0].reshape(1,1)) # 使用 layer 进行计算
Tensorflow 最常用于创建多层模型。Sequential 模型是构建这些模型的便捷方法:
model = Sequential([
Dense(1, input_dim=1, activation='sigmoid', name='L1')
])
一个更大的模型:
import tensorflow.keras.layers as tfl
model = Sequential([
tfl.ZeroPadding2D(padding=3, input_shape=(64, 64, 3)), # 第一层要指定输入数据集形状,后面的会自动推导
tfl.Conv2D(32, 7),
tfl.BatchNormalization(axis=3),
tfl.ReLU(),
tfl.MaxPool2D(),
tfl.Flatten(),
tfl.Dense(1, activation='sigmoid')
])
查看模型的层数和参数个数:
model.summary()
获取模型中的 layer:
logistic_layer = model.get_layer('L1') # 获取一个 layer
[layer1, layer2, layer3] = model.layers # 获取全部 layer
model.layers[2].weights # 获取一个 layer 的信息
归一化训练数据:
norm_l = tf.keras.layers.Normalization(axis=-1) # 此 layer 非神经网络中的 layer
norm_l.adapt(X) # 学习均值和方差
Xn = norm_l(X) # 使用训练好的 layer 计算归一化的数据
训练模型:
# 定义损失函数,指定编译优化
model.compile(
loss = tf.keras.losses.BinaryCrossentropy(),
optimizer = tf.keras.optimizers.Adam(learning_rate=0.01),
)
# 运行梯度下降,并根据数据拟合权重。
model.fit(X, y, epochs=10)
使用模型进行预测:
prediction = model.predict(X_train[0].reshape(1,1))
通过概率进行决策:
yhat = (predictions >= 0.5).astype(int)
获取错误决策实例:
errors = np.where(y != Yhat)
实例
使用 Functional API 构造任意数据流的模型。
def convolutional_model(input_shape):
"""
Implements the forward propagation for the model:
CONV2D -> RELU -> MAXPOOL -> CONV2D -> RELU -> MAXPOOL -> FLATTEN -> DENSE
Note that for simplicity and grading purposes, you'll hard-code some values
such as the stride and kernel (filter) sizes.
Normally, functions should take these values as function parameters.
Arguments:
input_img -- input dataset, of shape (input_shape)
Returns:
model -- TF Keras model (object containing the information for the entire training process)
"""
input_img = tf.keras.Input(shape=input_shape)
## CONV2D: 8 filters 4x4, stride of 1, padding 'SAME'
Z1 = tfl.Conv2D(8, 4, 1, padding="same")(input_img)
## RELU
A1 = tfl.ReLU()(Z1)
## MAXPOOL: window 8x8, stride 8, padding 'SAME'
P1 = tfl.MaxPool2D(8, 8, padding="same")(A1)
## CONV2D: 16 filters 2x2, stride 1, padding 'SAME'
Z2 = tfl.Conv2D(16, 2, 1, padding="same")(P1)
## RELU
A2 = tfl.ReLU()(Z2)
## MAXPOOL: window 4x4, stride 4, padding 'SAME'
P2 = tfl.MaxPool2D(4, 4, padding="same")(A2)
## FLATTEN
F = tfl.Flatten()(P2)
## Dense layer
## 6 neurons in output layer. Hint: one of the arguments should be "activation='softmax'"
outputs = tfl.Dense(6, activation="softmax")(F)
model = tf.keras.Model(inputs=input_img, outputs=outputs)
return model

浙公网安备 33010602011771号