博客
关于我
Keras简单梳理
阅读量:360 次
发布时间:2019-03-04

本文共 4531 字,大约阅读时间需要 15 分钟。

Keras 实现基础

Keras 实现线性回归

Keras 的便捷性在于其代码简洁,以下是实现线性回归的示例:

import numpy as np
from keras.models import Sequential
from keras.layers import Dense
# 生成随机点
x_data = np.random.rand(100)
# 添加噪声
noise = np.random.normal(0, 0.01, x_data.shape)
y_data = x_data * 0.1 + 0.2 + noise
# 定义模型
model = Sequential()
model.add(Dense(units=1, input_dim=1))
# 编译模型
model.compile(optimizer='sgd', loss='mse')
# 训练过程
for step in range(3000):
cost = model.train_on_batch(x_data, y_data)
if step % 300 == 0:
print(f'step: {step}; cost: {cost}')
# 预测结果
y_pred = model.predict(x_data)

Keras 实现非线性回归

通过添加激活函数,可以实现非线性回归:

import numpy as np
from keras.models import Sequential
from keras.layers import Dense, Activation
from keras.optimizers import SGD
# 随机生成200个点
x_data = np.linspace(-0.5, 0.5, 200)
# 添加噪声
noise = np.random.normal(0, 0.02, x_data.shape)
y_data = np.square(x_data) + noise
# 定义模型
model = Sequential()
model.add(Dense(units=10, input_dim=1))
model.add(Activation('tanh'))
model.add(Dense(units=1, activation='tanh'))
# 编译模型
model.compile(optimizer=SGD(lr=0.1), loss='mse')
# 训练过程
for step in range(6000):
cost = model.train_on_batch(x_data, y_data)
if step % 300 == 0:
print(f'step: {step}; cost: {cost}')

MNIST 手写数字识别

使用 Keras 实现 MNIST 的手写数字分类:

from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense, Dropout
from keras.utils import np_utils
from keras.optimizers import SGD
from keras.regularizers import l2
# 加载数据集
(x_train, y_train), (x_test, y_test) = mnist.load_data()
# 数据预处理
x_train = x_train.reshape(x_train.shape[0], -1) / 255
x_test = x_test.reshape(x_test.shape[0], -1) / 255
# 将标签转换为 one-hot 编码
y_train = np_utils.to_categorical(y_train, num_classes=10)
y_test = np_utils.to_categorical(y_test, num_classes=10)
# 定义模型
model = Sequential([
Dense(units=200, input_dim=784, bias_initializer='one', activation='relu',
kernel_regularizer=l2(0.0003)),
Dropout(0.4),
Dense(units=100, bias_initializer='one', activation='relu'),
Dropout(0.4),
Dense(units=10, activation='softmax')
])
# 编译模型
adam = SGD(lr=0.2)
model.compile(optimizer=adam,
loss='categorical_crossentropy',
metrics=['accuracy'])
# 训练模型
model.fit(x_train, y_train, batch_size=32, epochs=10)

Keras 实现CNN

使用卷积层实现图像分类:

from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense, Convolution2D, MaxPool2D, Flatten, Dropout
from keras.utils import np_utils
from keras.optimizers import Adam
# 加载数据集
(x_train, y_train), (x_test, y_test) = mnist.load_data()
# 数据预处理
x_train = x_train.reshape(-1, 28, 28, 1) / 255
x_test = x_test.reshape(-1, 28, 28, 1) / 255
# 将标签转换为 one-hot 编码
y_train = np_utils.to_categorical(y_train, num_classes=10)
y_test = np_utils.to_categorical(y_test, num_classes=10)
# 定义模型
model = Sequential([
Convolution2D(filters=32, kernel_size=5, strides=1, padding='same', activation='relu'),
MaxPool2D(pool_size=2, strides=2, padding='same'),
Convolution2D(filters=64, kernel_size=5, strides=1, padding='same', activation='relu'),
MaxPool2D(pool_size=2, strides=2, padding='same'),
Flatten(),
Dense(1024, activation='relu'),
Dropout(0.5),
Dense(10, activation='softmax')
])
# 编译模型
adam = Adam(lr=0.001)
model.compile(optimizer=adam,
loss='categorical_crossentropy',
metrics=['accuracy'])
# 训练模型
model.fit(x_train, y_train, batch_size=64, epochs=4)

Keras 实现LSTM

实现时间序列预测:

from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense, LSTM
from keras.utils import np_utils
from keras.optimizers import Adam
# 加载数据集
(x_train, y_train), (x_test, y_test) = mnist.load_data()
# 数据预处理
time_steps = 28
input_size = 28
cell_size = 50
x_train = x_train / 255
x_test = x_test / 255
# 将标签转换为 one-hot 编码
y_train = np_utils.to_categorical(y_train, num_classes=10)
y_test = np_utils.to_categorical(y_test, num_classes=10)
# 定义模型
model = Sequential([
LSTM(units=cell_size, input_shape=(time_steps, input_size)),
Dense(10, activation='softmax')
])
# 编译模型
adam = Adam(lr=0.001)
model.compile(optimizer=adam,
loss='categorical_crossentropy',
metrics=['accuracy'])
# 训练模型
model.fit(x_train, y_train, batch_size=64, epochs=10)

模型的保存与载入

保存模型

使用 h5py 库保存模型:

model.save('lstm_mnist.h5')

加载模型

在需要时加载模型:

from keras.models import load_model
model = load_model('lstm_mnist.h5')

以上代码示例展示了 Keras 在多种任务中的实际应用,涵盖了线性回归、非线性回归、图像分类以及时间序列预测等。通过这些示例,可以清晰地看到 Keras 在机器学习模型开发中的强大优势。

转载地址:http://tzee.baihongyu.com/

你可能感兴趣的文章
MySQL 常用列类型
查看>>
mysql 常用命令
查看>>
Mysql 常见ALTER TABLE操作
查看>>
MySQL 常见的 9 种优化方法
查看>>
MySQL 常见的开放性问题
查看>>
Mysql 常见错误
查看>>
mysql 常见问题
查看>>
MYSQL 幻读(Phantom Problem)不可重复读
查看>>
mysql 往字段后面加字符串
查看>>
mysql 快速自增假数据, 新增假数据,mysql自增假数据
查看>>
Mysql 批量修改四种方式效率对比(一)
查看>>
Mysql 报错 Field 'id' doesn't have a default value
查看>>
MySQL 报错:Duplicate entry 'xxx' for key 'UNIQ_XXXX'
查看>>
Mysql 拼接多个字段作为查询条件查询方法
查看>>
mysql 排序id_mysql如何按特定id排序
查看>>
Mysql 提示:Communication link failure
查看>>
mysql 插入是否成功_PDO mysql:如何知道插入是否成功
查看>>
Mysql 数据库InnoDB存储引擎中主要组件的刷新清理条件:脏页、RedoLog重做日志、Insert Buffer或ChangeBuffer、Undo Log
查看>>
mysql 数据库中 count(*),count(1),count(列名)区别和效率问题
查看>>
mysql 数据库备份及ibdata1的瘦身
查看>>