keras 的使用例子

keras 搭建简单模型

扁平化model.add(Flatten()) 可以用  全局平均池化代替 model.add(GlobalAveragePooling2D())

方法1

# 序列模型
# 序列模型属于通用模型的一种,因为很常见,所以这里单独列出来进行介绍,这种模型各层之间
# 是依次顺序的线性关系,在第k层和第k+1层之间可以加上各种元素来构造神经网络
# 这些元素可以通过一个列表来制定,然后作为参数传递给序列模型来生成相应的模型

from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Activation

# Dense相当于构建一个全连接层,32指的是全连接层上面神经元的个数
layers = [Dense(32, input_shape=(784,)),
          Activation('relu'),
          Dense(10),
          Activation('softmax')]
model = Sequential(layers)
#输出模型结构 model.summary()

方法2 

效果同方法1一样

from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Activation

model = Sequential()
model.add(Dense(32, input_shape=(784,)))
model.add(Activation('relu'))
model.add(Dense(10))
model.add(Activation('softmax'))
model.summary()

一个稍复杂的例子

# 通用模型
# 通用模型可以用来设计非常复杂、任意拓扑结构的神经网络,例如有向无环图网络
# 类似于序列模型,通用模型通过函数化的应用接口来定义模型
# 使用函数化的应用接口有好多好处,比如:决定函数执行结果的唯一要素是其返回值,而决定
# 返回值的唯一要素则是其参数,这大大减轻了代码测试的工作量

# 在通用模型中,定义的时候,从输入的多维矩阵开始,然后定义各层及其要素,最后定义输出层
# 将输入层和输出层作为参数纳入通用模型中就可以定义一个模型对象

from keras.layers import Input
from keras.layers import Dense
from keras.models import Model

# 定义输入层
input = Input(shape=(784,))
# 定义各个连接层,假设从输入层开始,定义两个隐含层,都有64个神经元,都使用relu激活函数
x = Dense(64, activation='relu')(input)
x = Dense(64, activation='relu')(x)
# 定义输出层,使用最近的隐含层作为参数
y = Dense(10, activation='softmax')(x)

# 所有要素都齐备以后,就可以定义模型对象了,参数很简单,分别是输入和输出,其中包含了
# 中间的各种信息
model = Model(inputs=input, outputs=y)

# 当模型对象定义完成之后,就可以进行编译了,并对数据进行拟合,拟合的时候也有两个参数
# 分别对应于输入和输出
model.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy'])
model.fit(data, labels)

一个更加复杂的例子

import numpy as np
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Dropout
from keras.layers import Flatten
from keras.layers.convolutional import Conv2D
from keras.layers.convolutional import MaxPooling2D


# 先读入数据
(X_train, y_train), (X_test, y_test) = mnist.load_data("../test_data_home")
# 看一下数据集的样子
print(X_train[0].shape)
print(y_train[0])

# 下面把训练集中的手写黑白字体变成标准的四维张量形式,即(样本数量,长,宽,1)
# 并把像素值变成浮点格式
X_train = X_train.reshape(X_train.shape[0], 28, 28, 1).astype('float32')
X_test = X_test.reshape(X_test.shape[0], 28, 28, 1).astype('float32')

# 由于每个像素值都介于0到255,所以这里统一除以255,把像素值控制在0-1范围
X_train /= 255
X_test /= 255


# 由于输入层需要10个节点,所以最好把目标数字0-9做成One Hot编码的形式
def tran_y(y):
    y_ohe = np.zeros(10)
    y_ohe[y] = 1
    return y_ohe


# 把标签用One Hot编码重新表示一下
y_train_ohe = np.array([tran_y(y_train[i]) for i in range(len(y_train))])
y_test_ohe = np.array([tran_y(y_test[i]) for i in range(len(y_test))])

# 搭建卷积神经网络
model = Sequential()
# 添加一层卷积层,构造64个过滤器,每个过滤器覆盖范围是3*3*1
# 过滤器步长为1,图像四周补一圈0,并用relu进行非线性变化
model.add(Conv2D(filters=64, kernel_size=(3, 3), strides=(1, 1), padding='same',
                 input_shape=(28, 28, 1), activation='relu'))
# 添加一层最大池化层
model.add(MaxPooling2D(pool_size=(2, 2)))
# 设立Dropout层,Dropout的概率为0.5
model.add(Dropout(0.5))

# 重复构造,搭建深度网络
model.add(Conv2D(128, kernel_size=(3, 3), strides=(1, 1), padding='same',
                 activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.5))
model.add(Conv2D(256, kernel_size=(3, 3), strides=(1, 1), padding='same',
                 activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.5))

# 把当前层节点展平
model.add(Flatten())

# 构造全连接层神经网络层
model.add(Dense(128, activation='relu'))
model.add(Dense(64, activation='relu'))
model.add(Dense(32, activation='relu'))
model.add(Dense(10, activation='softmax'))

# 定义损失函数,一般来说分类问题的损失函数都选择采用交叉熵
model.compile(loss='categorical_crossentropy', optimizer='adagrad', metrics=['accuracy'])

# 放入批量样本,进行训练
model.fit(X_train, y_train_ohe, validation_data=(X_test, y_test_ohe)
          , epochs=20, batch_size=128)

# 在测试集上评价模型的准确率
# verbose : 进度表示方式。0表示不显示数据,1表示显示进度条
scores = model.evaluate(X_test, y_test_ohe, verbose=0)

迁移学习的例子

# 使用迁移学习的思想,以VGG16作为模板搭建模型,训练识别手写字体
# 引入VGG16模块
from keras.applications.vgg16 import VGG16

# 其次加载其他模块
from keras.layers import Input
from keras.layers import Flatten
from keras.layers import Dense
from keras.layers import Dropout
from keras.models import Model
from keras.optimizers import SGD

# 加载字体库作为训练样本
from keras.datasets import mnist

# 加载OpenCV(在命令行中窗口中输入pip install opencv-python),这里为了后期对图像的处理,
# 大家使用pip install C:Users28542Downloadsopencv_python-3.4.1+contrib-cp35-cp35m-win_amd64.whl
# 比如尺寸变化和Channel变化。这些变化是为了使图像满足VGG16所需要的输入格式
import cv2
import h5py as h5py
import numpy as np

# 建立一个模型,其类型是Keras的Model类对象,我们构建的模型会将VGG16顶层去掉,只保留其余的网络
# 结构。这里用include_top = False表明我们迁移除顶层以外的其余网络结构到自己的模型中(意思是顶层不用)
# weights='imagenet'使用imagenet大赛第一名的参数。
# VGG模型对于输入图像数据要求高宽至少为48个像素点,由于硬件配置限制,我们选用48个像素点而不是原来
# VGG16所采用的224个像素点。即使这样仍然需要24GB以上的内存,或者使用数据生成器
model_vgg = VGG16(include_top=False, weights='imagenet', input_shape=(48, 48, 3))
for layer in model_vgg.layers:#遍历vgg模型的每一层
    layer.trainable = False  #每层的,参数都设置为不可变更的,使用初始参数
model = Flatten(name='flatten')(model_vgg.output) # 扁平化,将vgg模型的输出。当做自己模型的输入
model = Dense(4096, activation='relu', name='fc1')(model)
model = Dense(4096, activation='relu', name='fc2')(model)
model = Dropout(0.5)(model)
model = Dense(10, activation='softmax')(model)
model_vgg_mnist = Model(inputs=model_vgg.input, outputs=model, name='vgg16')

# 打印模型结构,包括所需要的参数
model_vgg_mnist.summary()

model_vgg = VGG16(include_top=False, weights='imagenet', input_shape=(224, 224, 3))
for layer in model_vgg.layers:
    layer.trainable = False
model = Flatten()(model_vgg.output)
model = Dense(4096, activation='relu', name='fc1')(model)
model = Dense(4096, activation='relu', name='fc2')(model)
model = Dropout(0.5)(model)
model = Dense(10, activation='softmax', name='prediction')(model)
model_vgg_mnist_pretrain = Model(model_vgg.input, model, name='vgg16_pretrain')

model_vgg_mnist_pretrain.summary()

# 新的模型不需要训练原有卷积结构里面的1471万个参数,但是注意参数还是来自于最后输出层前的两个
# 全连接层,一共有1.2亿个参数需要训练
sgd = SGD(lr=0.05, decay=1e-5) #sgd 随机梯度下降法,作为优化器
model_vgg_mnist.compile(loss='categorical_crossentropy',
                                 optimizer=sgd, metrics=['accuracy'])

# 因为VGG16对网络输入层的要求,我们用OpenCV把图像从32*32变成48*48,函数cv2.COLOR_GRAY2RGB 把黑白图像转成RGB图像
# 并把训练数据转化成张量形式,供keras输入
(X_train, y_train), (X_test, y_test) = mnist.load_data("../test_data_home")
X_train, y_train = X_train[:10000], y_train[:10000]
X_test, y_test = X_test[:1000], y_test[:1000]
X_train = [cv2.cvtColor(cv2.resize(i, (48, 48)), cv2.COLOR_GRAY2RGB)
           for i in X_train]
X_train = np.concatenate([arr[np.newaxis] for arr in X_train]).astype('float32')
X_test = [cv2.cvtColor(cv2.resize(i, (48, 48)), cv2.COLOR_GRAY2RGB)
          for i in X_test]
X_test = np.concatenate([arr[np.newaxis] for arr in X_test]).astype('float32')



print(X_train.shape)
print(X_test.shape)

X_train = X_train / 255
X_test = X_test / 255


def tran_y(y):
    y_ohe = np.zeros(10)
    y_ohe[y] = 1
    return y_ohe


y_train_ohe = np.array([tran_y(y_train[i]) for i in range(len(y_train))])
y_test_ohe = np.array([tran_y(y_test[i]) for i in range(len(y_test))])

model_vgg_mnist.fit(X_train, y_train_ohe, validation_data=(X_test, y_test_ohe),
                             epochs=100, batch_size=50)
原文地址:https://www.cnblogs.com/HL-blog/p/9437461.html