keras

构建简单的模型

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 a softmax layer with 10 output units:
model.add(layers.Dense(10, activation='softmax'))

配置层

我们可以使用很多 tf.keras.layers,它们具有一些相同的构造函数参数:

activation:设置层的激活函数。此参数由内置函数的名称指定,或指定为可调用对象。默认情况下,系统不会应用任何激活函数。
kernel_initializer 和 bias_initializer:创建层权重(核和偏差)的初始化方案。此参数是一个名称或可调用对象,默认为 “Glorot uniform” 初始化器。
kernel_regularizer 和 bias_regularizer:应用层权重(核和偏差)的正则化方案,例如 L1 或 L2 正则化。默认情况下,系统不会应用正则化函数。
以下代码使用构造函数参数实例化 tf.keras.layers. Dense 层:

# Create a sigmoid layer:
layers.Dense(64, activation='sigmoid')
# Or:
layers.Dense(64, activation=tf.sigmoid)

# 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))

创建一个使用sigmoid为激活函数的layerlayers.Dense(64, activation=‘sigmoid’)
也可以这样创建,效果一样layers.Dense(64, activation=tf.sigmoid)
一个kernel矩阵使用正则化因子为0.01的L1正则项的全连接层layers.Dense(64, kernel_regularizer=keras.regularizers.l1(0.01))
一个偏差向量使用正则化因子为0.01的L2正则项的全连接层
layers.Dense(64, bias_regularizer=keras.regularizers.l2(0.01))
一个使用随机正交矩阵初始化Kernel的全连接层layers.Dense(64, kernel_initializer=‘orthogonal’)
一个偏差初始化时全为2的全连接层layers.Dense(64, bias_initializer=keras.initializers.constant(2.0))

训练和评估

设置训练流程

构建好模型后,通过调用 compile 方法配置该模型的学习流程:
tf.keras.Model.compile 采用三个重要参数:

optimizer:此对象会指定训练过程。从 tf.train 模块向其传递优化器实例,例如 tf.train.AdamOptimizer、tf.train.RMSPropOptimizer 或 tf.train.GradientDescentOptimizer。
loss:要在优化期间最小化的函数。常见选择包括均方误差 (mse)、categorical_crossentropy 和 binary_crossentropy。损失函数由名称或通过从 tf.keras.losses 模块传递可调用对象来指定。
metrics:用于监控训练。它们是 tf.keras.metrics 模块中的字符串名称或可调用对象。

# Configure a model for mean-squared error regression.
model.compile(optimizer=tf.train.AdamOptimizer(0.01),
              loss='mse',       # mean squared error
              metrics=['mae'])  # mean absolute error

# Configure a model for categorical classification.
model.compile(optimizer=tf.train.RMSPropOptimizer(0.01),
              loss=tf.keras.losses.categorical_crossentropy,
              metrics=[tf.keras.metrics.categorical_accuracy])

binary_accuracy: 对二分类问题,计算在所有预测值上的平均正确率 categorical_accuracy:对多分类问题,计算再所有预测值上的平均正确率 sparse_categorical_accuracy:与categorical_accuracy相同,在对稀疏的目标值预测时有用 top_k_categorical_accracy: 计算top-k正确率,当预测值的前k个值中存在目标类别即认为预测正确 sparse_top_k_categorical_accuracy:与top_k_categorical_accracy作用相同,但适用于稀疏情况

作者:macair123
来源:CSDN
原文:https://blog.csdn.net/macair123/article/details/79511215
版权声明:本文为博主原创文章,转载请附上博文链接!

使用 fit 方法使模型与训练数据“拟合”

输入 NumPy 数据

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)

one epoch:所有的训练样本完成一次Forword运算以及一次BP运算

batch size:一次Forword运算以及BP运算中所需要的训练样本数目,其实深度学习每一次参数的更新所需要损失函数是由一组数据加权得到的,这一组数据的数量就是[batch size]。

iterations(迭代):每一次迭代都是一次权重更新,每一次权重更新需要batch size个数据进行Forward运算得到损失函数,再BP算法更新参数。
N = 训练样本的数量/batch size
one epoch = N iterations
比如,我们有1000个样本,batch size是500,其将会有2个Iterations。这两个Iteration完成一个Epoch

输入 tf.data 数据集

# Instantiates a toy dataset instance:
dataset = tf.data.Dataset.from_tensor_slices((data, labels))
dataset = dataset.batch(32)
dataset = dataset.repeat()

# Don't forget to specify `steps_per_epoch` when calling `fit` on a dataset.
model.fit(dataset, epochs=10, steps_per_epoch=30)

fit 方法使用了 steps_per_epoch 参数(表示模型在进入下一个周期之前运行的训练步数)。由于 Dataset 会生成批次数据,因此该代码段不需要 batch_size。

评估和预测

tf.keras.Model.evaluate 和 tf.keras.Model.predict 方法可以使用 NumPy 数据和 tf.data.Dataset。评估所提供数据的推理模式损失和指标

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值