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

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

Keras 实现基础

Keras 实现线性回归

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

import numpy as npfrom keras.models import Sequentialfrom 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 npfrom keras.models import Sequentialfrom keras.layers import Dense, Activationfrom 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 mnistfrom keras.models import Sequentialfrom keras.layers import Dense, Dropoutfrom keras.utils import np_utilsfrom keras.optimizers import SGDfrom 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) / 255x_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 mnistfrom keras.models import Sequentialfrom keras.layers import Dense, Convolution2D, MaxPool2D, Flatten, Dropoutfrom keras.utils import np_utilsfrom keras.optimizers import Adam# 加载数据集(x_train, y_train), (x_test, y_test) = mnist.load_data()# 数据预处理x_train = x_train.reshape(-1, 28, 28, 1) / 255x_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 mnistfrom keras.models import Sequentialfrom keras.layers import Dense, LSTMfrom keras.utils import np_utilsfrom keras.optimizers import Adam# 加载数据集(x_train, y_train), (x_test, y_test) = mnist.load_data()# 数据预处理time_steps = 28input_size = 28cell_size = 50x_train = x_train / 255x_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_modelmodel = load_model('lstm_mnist.h5')

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

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

你可能感兴趣的文章
MySQL 添加索引,删除索引及其用法
查看>>
mysql 状态检查,备份,修复
查看>>
MySQL 用 limit 为什么会影响性能?
查看>>
MySQL 用 limit 为什么会影响性能?有什么优化方案?
查看>>
MySQL 用户权限管理:授权、撤销、密码更新和用户删除(图文解析)
查看>>
mysql 用户管理和权限设置
查看>>
MySQL 的 varchar 水真的太深了!
查看>>
mysql 的GROUP_CONCAT函数的使用(group_by 如何显示分组之前的数据)
查看>>
MySQL 的instr函数
查看>>
MySQL 的mysql_secure_installation安全脚本执行过程介绍
查看>>
MySQL 的Rename Table语句
查看>>
MySQL 的全局锁、表锁和行锁
查看>>
mysql 的存储引擎介绍
查看>>
MySQL 的存储引擎有哪些?为什么常用InnoDB?
查看>>
Mysql 知识回顾总结-索引
查看>>
Mysql 笔记
查看>>
MySQL 精选 60 道面试题(含答案)
查看>>
mysql 索引
查看>>
MySQL 索引失效的 15 种场景!
查看>>
MySQL 索引深入解析及优化策略
查看>>