import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers
model = tf.keras.Sequential() # Adds a densely-connected layer with 64 units to the model: model.add(layers.Dense(64, activation='relu')) # Add another: model.add(layers.Dense(64, activation='relu')) # Add an output layer with 10 output units: model.add(layers.Dense(10))
# A linear layer with L1 regularization of factor 0.01 applied to the kernel matrix: layers.Dense(64, kernel_regularizer=tf.keras.regularizers.l1(0.01))
# A linear layer with L2 regularization of factor 0.01 applied to the bias vector: layers.Dense(64, bias_regularizer=tf.keras.regularizers.l2(0.01))
# A linear layer with a kernel initialized to a random orthogonal matrix: layers.Dense(64, kernel_initializer='orthogonal')
# A linear layer with a bias vector initialized to 2.0s: layers.Dense(64, bias_initializer=tf.keras.initializers.Constant(2.0))
训练和评估
训练时的设置
当模型被构建后,我们可以通过调用compile方法来调整学习过程:
1 2 3 4 5 6 7 8 9 10 11
model = tf.keras.Sequential([ # Adds a densely-connected layer with 64 units to the model: layers.Dense(64, activation='relu', input_shape=(32,)), # Add another: layers.Dense(64, activation='relu'), # Add an output layer with 10 output units: layers.Dense(10)])
# Configure a model for mean-squared error regression. model.compile(optimizer=tf.keras.optimizers.Adam(0.01), loss='mse', # mean squared error metrics=['mae']) # mean absolute error
# Configure a model for categorical classification. model.compile(optimizer=tf.keras.optimizers.RMSprop(0.01), loss=tf.keras.losses.CategoricalCrossentropy(from_logits=True), metrics=['accuracy'])
从NumPy数据训练
对于小型的数据集,我们可以用如下方法训练:
1 2 3 4 5 6
import numpy as np
data = np.random.random((1000, 32)) labels = np.random.random((1000, 10))
model.fit(data, labels, epochs=10, batch_size=32)
fit方法有以下重要的参数:
epochs:训练的迭代次数
batch_size:每个批次的样本数量
validation_data:用于定义验证集
1 2 3 4 5 6 7 8 9 10
import numpy as np
data = np.random.random((1000, 32)) labels = np.random.random((1000, 10))
inputs = tf.keras.Input(shape=(32,)) # Returns an input placeholder
# A layer instance is callable on a tensor, and returns a tensor. x = layers.Dense(64, activation='relu')(inputs) x = layers.Dense(64, activation='relu')(x) predictions = layers.Dense(10)(x)
接下来实例化模型:
1 2 3 4 5 6 7 8 9
model = tf.keras.Model(inputs=inputs, outputs=predictions)
# The compile step specifies the training configuration. model.compile(optimizer=tf.keras.optimizers.RMSprop(0.001), loss=tf.keras.losses.CategoricalCrossentropy(from_logits=True), metrics=['accuracy'])
# Trains for 5 epochs model.fit(data, labels, batch_size=32, epochs=5)
defcall(self, inputs): # Define your forward pass here, # using layers you previously defined (in `__init__`). x = self.dense_1(inputs) return self.dense_2(x)
接下来定义新的模型子类:
1 2 3 4 5 6 7 8 9
model = MyModel(num_classes=10)
# The compile step specifies the training configuration. model.compile(optimizer=tf.keras.optimizers.RMSprop(0.001), loss=tf.keras.losses.CategoricalCrossentropy(from_logits=True), metrics=['accuracy'])
# Trains for 5 epochs. model.fit(data, labels, batch_size=32, epochs=5)
# The compile step specifies the training configuration model.compile(optimizer=tf.keras.optimizers.RMSprop(0.001), loss=tf.keras.losses.CategoricalCrossentropy(from_logits=True), metrics=['accuracy'])
# Trains for 5 epochs. model.fit(data, labels, batch_size=32, epochs=5)