【TensorFlow】Keras介绍与入门


tensorflow中文官网

Keras简介

Keras 是一个高级神经网络API,它以简单性和快速实验设计为目标。Keras 既可以作为独立工具使用,也可以作为 TensorFlow、Microsoft Cognitive Toolkit (CNTK) 和 Theano 等后端的接口。自2017年起,Keras 成为了 TensorFlow 的官方高级 API,并且是推荐给初学者和专家的主要界面。

Keras 的主要特点

  • 用户友好:Keras 提供了一个一致且简洁的API,减少了常见用例所需的代码量,同时提供清晰且有用的错误消息。
  • 模块化和可组合:模型可以理解为由可配置构建块(如层、损失函数、优化器等)组成的有向无环图,这些构建块可以任意连接,只要数据形状匹配即可。
  • 易于扩展:你很容易编写新的层、损失函数和开发复杂的模型,比如多输入/输出模型、共享层模型或非序列模型。
  • 与Python兼容:Keras 没有单独的模型配置格式,所有的模型都是纯 Python 构建的,这使得它可以利用 Python 工具进行调试和检查。

Keras 的核心组件

模型(Model)

Keras 中有两种类型的模型:

  • Sequential:线性堆叠的层,适合简单的模型结构。
  • Functional API:更灵活,允许创建具有多个输入、输出或复杂拓扑的模型。

层(Layer)

层是构成模型的基本单元,它们接收输入张量并输出其他张量。常见的层类型包括:

  • Dense:全连接层
  • Conv2D:二维卷积层,常用于图像处理
  • LSTM:长短期记忆层,适用于序列数据
  • Embedding:将整数索引转换为密集向量

损失函数(Loss Function)

损失函数用于评估模型预测与实际标签之间的误差。常用的损失函数有:

  • binary_crossentropy:二分类问题
  • categorical_crossentropy:多分类问题
  • mse(均方误差):回归问题

优化器(Optimizer)

优化器决定了如何根据损失函数的梯度更新模型参数。常见的优化器有:

  • SGD:随机梯度下降
  • Adam:自适应矩估计
  • RMSprop:均方根传播

回调(Callback)

回调是在训练过程中的不同阶段执行的操作,例如:

  • ModelCheckpoint:定期保存模型
  • EarlyStopping:当验证集性能不再改善时提前停止训练
  • TensorBoard:可视化训练过程

中文官方文档

Keras使用

最简单的使用方式是使用Keras Sequential, 中文叫做顺序模型, 可以用来表示多个网络层的线性堆叠.

使用的时候可以通过讲网络层实例的列表传递给Sequential, 比如:

python 复制代码
from keras.models import Sequential
from keras.layers import Dense, Activation

model = Sequential([
    Dense(32, input_shape=(784,)),
    Activation('relu'),
    Dense(10),
    Activation('softmax'),
])

也可以简单的使用.add()方法将各层添加到模型中:

python 复制代码
model = Sequential()
model.add(Dense(32, input_dim=784))
model.add(Activation('relu'))

对于输入层,需要指定输入数据的尺寸,通过Dense对象中的input_shape属性.注意无需写batch的大小.

input_shape=(784,) 等价于我们在神经网络中定义的shape为(None, 784)的Tensor.

模型创建成功之后,需要进行编译.使用.compile()方法对创建的模型进行编译.compile()方法主要需要指定一下几个参数:

  • 优化器 optimizer: 可以是Keras定义好的优化器的字符串名字,比如'rmsprop'也可以是Optimizer类的实例对象.常见的优化器有: SGD, RMSprop, Adagrad, Adadelta等.

  • 损失函数 loss: 模型视图最小化的目标函数, 它可以是现有损失函数的字符串形式, 比如:categorical_crossentropy, 也可以是一个目标函数.

  • 评估标准 metrics. 评估算法性能的衡量指标.对于分类问题, 建议设置为metrics = ['accuracy'].评估标准可以是现有的标准的字符串标识符,也可以是自定义的评估标准函数。

    以下为compile的常见写法:

    python 复制代码
    # 多分类问题
    model.compile(optimizer='rmsprop',
                  loss='categorical_crossentropy',
                  metrics=['accuracy'])
    
    # 二分类问题
    model.compile(optimizer='rmsprop',
                  loss='binary_crossentropy',
                  metrics=['accuracy'])
    
    # 均方误差回归问题
    model.compile(optimizer='rmsprop',
                  loss='mse')
    
    # 自定义评估标准函数
    import keras.backend as K
    
    def mean_pred(y_true, y_pred):
        return K.mean(y_pred)
    
    model.compile(optimizer='rmsprop',
                  loss='binary_crossentropy',
                  metrics=['accuracy', mean_pred])

训练模型: 使用.fit()方法,将训练数据,训练次数(epoch), 批次尺寸(batch_size)传递给fit()方法即可.

比如 :

python 复制代码
# 对于具有 2 个类的单输入模型(二进制分类):

model = Sequential()
model.add(Dense(32, activation='relu', input_dim=100))
model.add(Dense(1, activation='sigmoid'))
model.compile(optimizer='rmsprop',
              loss='binary_crossentropy',
              metrics=['accuracy'])

# 生成虚拟数据
import numpy as np
data = np.random.random((1000, 100))
labels = np.random.randint(2, size=(1000, 1))

# 训练模型,以 32 个样本为一个 batch 进行迭代
model.fit(data, labels, epochs=10, batch_size=32)

下面用一个完整的例子来说明Keras的使用.

以下为使用神经网络来进行手写数字识别:

python 复制代码
import keras
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense, Dropout
from keras.optimizers import RMSprop

batch_size = 128
num_classes = 10
epochs = 20

# 导入手写数字数据集
(x_train, y_train), (x_test, y_test) = mnist.load_data()

# 对数据进行初步处理
x_train = x_train.reshape(60000, 784)
x_test = x_test.reshape(10000, 784)
x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
x_train /= 255
x_test /= 255
print(x_train.shape[0], 'train samples')
print(x_test.shape[0], 'test samples')

# 将标记结果转化为独热编码
y_train = keras.utils.to_categorical(y_train, num_classes)
y_test = keras.utils.to_categorical(y_test, num_classes)

# 创建顺序模型
model = Sequential()
# 添加第一层网络, 512个神经元, 激活函数为relu
model.add(Dense(512, activation='relu', input_shape=(784,)))
# 添加Dropout
model.add(Dropout(0.2))
# 第二层网络
model.add(Dense(512, activation='relu'))
model.add(Dropout(0.2))
# 输出层
model.add(Dense(num_classes, activation='softmax'))

# 打印神经网络参数情况
model.summary()

# 编译
model.compile(loss='categorical_crossentropy',
              optimizer=RMSprop(),
              metrics=['accuracy'])

# 训练并打印中间过程
history = model.fit(x_train, y_train,
                    batch_size=batch_size,
                    epochs=epochs,
                    verbose=1,
                    validation_data=(x_test, y_test))
# 计算预测数据的准确率
score = model.evaluate(x_test, y_test, verbose=0)
print('Test loss:', score[0])
print('Test accuracy:', score[1])

Keras函数式API

Sequential 顺序模型封装了太多东西,不够灵活,如果你想定义复杂模型可以使用Keras的函数式API.

以下是一个全连接网络的例子:

python 复制代码
from keras.layers import Input, Dense
from keras.models import Model

# 这部分返回一个张量
inputs = Input(shape=(784,))

# 层的实例是可调用的,它以张量为参数,并且返回一个张量
output_1 = Dense(64, activation='relu')(inputs)
output_2 = Dense(64, activation='relu')(output_1)
predictions = Dense(10, activation='softmax')(output_2)

# 这部分创建了一个包含输入层和三个全连接层的模型
model = Model(inputs=inputs, outputs=predictions)
model.compile(optimizer='rmsprop',
              loss='categorical_crossentropy',
              metrics=['accuracy'])
model.fit(data, labels)  # 开始训练

这个例子能够帮助我们进行一些简单的理解。

  • 网络层的实例是可调用的,它以张量为参数,并且返回一个张量
  • 输入和输出均为张量,它们都可以用来定义一个模型(Model
  • 这样的模型同 Keras 的 Sequential 模型一样,都可以被训练

TensorFlow中使用Keras

keras集成在tf.keras中.

创建模型

创建一个简单的模型,使用tf.keras.sequential.

python 复制代码
model = tf.keras.Sequential()
# 创建一层有64个神经元的网络:
model.add(layers.Dense(64, activation='relu'))
# 添加另一层网络:
model.add(layers.Dense(64, activation='relu'))
# 输出层:
model.add(layers.Dense(10, activation='softmax'))

配置layers

layers包含以下三组重要参数:

  • activation: 激活函数, 'relu', 'sigmoid', 'tanh'.
  • kernel_initializer 和 bias_initializer: 权重和偏差的初始化器. Glorot uniform是默认的初始化器.一般不用改.
  • kernel_regularizerbias_regularizer: 权重和偏差的正则化.L1, L2.

以下是配置模型的例子:

python 复制代码
# 激活函数为sigmoid:
layers.Dense(64, activation='sigmoid')
# Or:
layers.Dense(64, activation=tf.sigmoid)

# 权重加了L1正则:
layers.Dense(64, kernel_regularizer=tf.keras.regularizers.l1(0.01))

# 给偏差加了L2正则
layers.Dense(64, bias_regularizer=tf.keras.regularizers.l2(0.01))

# 随机正交矩阵初始化器:
layers.Dense(64, kernel_initializer='orthogonal')

# 偏差加了常数初始化器
layers.Dense(64, bias_initializer=tf.keras.initializers.constant(2.0))

训练和评估

配置模型

使用compile配置模型, 主要有以下几组重要参数.

  • optimizer: 优化器, 主要有:tf.train.AdamOptimizer, tf.train.RMSPropOptimizer, or tf.train.GradientDescentOptimizer.
  • loss: 损失函数. 主要有:mean square error (mse, 回归), categorical_crossentropy(多分类), and binary_crossentropy(二分类).
  • metrics: 算法的评估标准, 一般分类用accuracy.

以下是compile的 实例:

python 复制代码
# 配置均方误差的回归.
model.compile(optimizer=tf.train.AdamOptimizer(0.01),
              loss='mse',       # mean squared error
              metrics=['mae'])  # mean absolute error

# 配置多分类的模型.
model.compile(optimizer=tf.train.RMSPropOptimizer(0.01),
              loss=tf.keras.losses.categorical_crossentropy,
              metrics=[tf.keras.metrics.categorical_accuracy])

训练

使用model的fit方法进行训练, 主要有以下参数:

  • epochs: 训练次数
  • batch_size: 每批数据多少
  • validation_data: 测试数据

对于小数量级的数据,可以直接把训练数据传入fit.

python 复制代码
import numpy as np

data = np.random.random((1000, 32))
labels = random_one_hot_labels((1000, 10))

val_data = np.random.random((100, 32))
val_labels = random_one_hot_labels((100, 10))

model.fit(data, labels, epochs=10, batch_size=32,
          validation_data=(val_data, val_labels))

对于大数量级的训练数据,使用tensorflow中dataset.

python 复制代码
# 把数据变成dataset
dataset = tf.data.Dataset.from_tensor_slices((data, labels))
# 指定一批数据是32, 并且可以无限重复
dataset = dataset.batch(32).repeat()

val_dataset = tf.data.Dataset.from_tensor_slices((val_data, val_labels))
val_dataset = val_dataset.batch(32).repeat()

# 别忘了steps_per_epoch, 表示执行完全部数据的steps
model.fit(dataset, epochs=10, steps_per_epoch=30)

model.fit(dataset, epochs=10, steps_per_epoch=30,
          validation_data=val_dataset,
          validation_steps=3)

评估和预测

使用tf.keras.Model.evaluateandtf.keras.Model.predict进行评估和预测. 评估会打印算法的损失和得分.

python 复制代码
data = np.random.random((1000, 32))
labels = random_one_hot_labels((1000, 10))
#  普通numpy数据
model.evaluate(data, labels, batch_size=32)
# tensorflow dataset数据
model.evaluate(dataset, steps=30)

预测:

python 复制代码
result = model.predict(data, batch_size=32)
print(result.shape)

使用函数式API

函数式API,主要是需要自己把各个组件的对象定义出来,并且手动传递.

python 复制代码
inputs = tf.keras.Input(shape=(32,))  # 返回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, activation='softmax')(x)

model = tf.keras.Model(inputs=inputs, outputs=predictions)

# The compile step specifies the training configuration.
model.compile(optimizer=tf.train.RMSPropOptimizer(0.001),
              loss='categorical_crossentropy',
              metrics=['accuracy'])

# Trains for 5 epochs
model.fit(data, labels, batch_size=32, epochs=5)

保存和恢复

使用model.save把整个模型保存为HDF5文件

python 复制代码
model.save('my_model.h5')

恢复使用tf.keras.models.load_model即可.

python 复制代码
model = tf.keras.models.load_model('my_model.h5')

注意: 如果使用的tensorflow的optimizer, 那么保存的model中没有model配置信息, 恢复以后需要重新配置.推荐用keras的optimizer.

相关推荐
不惑_1 小时前
通俗理解卷积神经网络
人工智能·windows·python·深度学习·机器学习
rayufo1 小时前
自定义数据在深度学习中的应用方法
人工智能·深度学习
人工智能培训1 小时前
DNN案例一步步构建深层神经网络(3)
人工智能·深度学习·神经网络·大模型·dnn·具身智能·智能体
youngfengying2 小时前
先验知识融入深度学习
人工智能·深度学习·先验知识
A林玖2 小时前
【深度学习】目标检测
人工智能·深度学习·目标检测
代码洲学长2 小时前
一、RNN基本概念与数学原理
人工智能·rnn·深度学习
A林玖2 小时前
【深度学习】 循环神经网络
人工智能·rnn·深度学习
肥猪猪爸4 小时前
计算机视觉中的Mask是干啥的
图像处理·人工智能·深度学习·神经网络·目标检测·计算机视觉·视觉检测
All The Way North-4 小时前
PyTorch ExponentialLR:按指数学习率衰减原理、API、参数详解、实战
pytorch·深度学习·学习率优化算法·按指数学习率衰减