使用Keras建立模型并训练等一系列操作方式


Posted in Python onJuly 02, 2020

由于Keras是一种建立在已有深度学习框架上的二次框架,其使用起来非常方便,其后端实现有两种方法,theano和tensorflow。由于自己平时用tensorflow,所以选择后端用tensorflow的Keras,代码写起来更加方便。

1、建立模型

Keras分为两种不同的建模方式,

Sequential models:这种方法用于实现一些简单的模型。你只需要向一些存在的模型中添加层就行了。

Functional API:Keras的API是非常强大的,你可以利用这些API来构造更加复杂的模型,比如多输出模型,有向无环图等等。

这里采用sequential models方法。

构建序列模型。

def define_model():

  model = Sequential()

  # setup first conv layer
  model.add(Conv2D(32, (3, 3), activation="relu",
           input_shape=(120, 120, 3), padding='same')) # [10, 120, 120, 32]

  # setup first maxpooling layer
  model.add(MaxPooling2D(pool_size=(2, 2))) # [10, 60, 60, 32]

  # setup second conv layer
  model.add(Conv2D(8, kernel_size=(3, 3), activation="relu",
           padding='same')) # [10, 60, 60, 8]

  # setup second maxpooling layer
  model.add(MaxPooling2D(pool_size=(3, 3))) # [10, 20, 20, 8]

  # add bianping layer, 3200 = 20 * 20 * 8
  model.add(Flatten()) # [10, 3200]

  # add first full connection layer
  model.add(Dense(512, activation='sigmoid')) # [10, 512]

  # add dropout layer
  model.add(Dropout(0.5))

  # add second full connection layer
  model.add(Dense(4, activation='softmax')) # [10, 4]

  return model

可以看到定义模型时输出的网络结构。

使用Keras建立模型并训练等一系列操作方式

2、准备数据

def load_data(resultpath):
  datapath = os.path.join(resultpath, "data10_4.npz")
  if os.path.exists(datapath):
    data = np.load(datapath)
    X, Y = data["X"], data["Y"]
  else:
    X = np.array(np.arange(432000)).reshape(10, 120, 120, 3)
    Y = [0, 0, 1, 1, 2, 2, 3, 3, 2, 0]
    X = X.astype('float32')
    Y = np_utils.to_categorical(Y, 4)
    np.savez(datapath, X=X, Y=Y)
    print('Saved dataset to dataset.npz.')
  print('X_shape:{}\nY_shape:{}'.format(X.shape, Y.shape))
  return X, Y

使用Keras建立模型并训练等一系列操作方式

3、训练模型

def train_model(resultpath):
  model = define_model()

  # if want to use SGD, first define sgd, then set optimizer=sgd
  sgd = SGD(lr=0.001, decay=1e-6, momentum=0, nesterov=True)

  # select loss\optimizer\
  model.compile(loss=categorical_crossentropy,
         optimizer=Adam(), metrics=['accuracy'])
  model.summary()

  # draw the model structure
  plot_model(model, show_shapes=True,
        to_file=os.path.join(resultpath, 'model.png'))

  # load data
  X, Y = load_data(resultpath)

  # split train and test data
  X_train, X_test, Y_train, Y_test = train_test_split(
    X, Y, test_size=0.2, random_state=2)

  # input data to model and train
  history = model.fit(X_train, Y_train, batch_size=2, epochs=10,
            validation_data=(X_test, Y_test), verbose=1, shuffle=True)

  # evaluate the model
  loss, acc = model.evaluate(X_test, Y_test, verbose=0)
  print('Test loss:', loss)
  print('Test accuracy:', acc)

可以看到训练时输出的日志。因为是随机数据,没有意义,这里训练的结果不必计较,只是练习而已。

使用Keras建立模型并训练等一系列操作方式

保存下来的模型结构:

使用Keras建立模型并训练等一系列操作方式

4、保存与加载模型并测试

有两种保存方式

4.1 直接保存模型h5

保存:

def my_save_model(resultpath):

  model = train_model(resultpath)

  # the first way to save model
  model.save(os.path.join(resultpath, 'my_model.h5'))

加载:

def my_load_model(resultpath):

  # test data
  X = np.array(np.arange(86400)).reshape(2, 120, 120, 3)
  Y = [0, 1]
  X = X.astype('float32')
  Y = np_utils.to_categorical(Y, 4)

  # the first way of load model
  model2 = load_model(os.path.join(resultpath, 'my_model.h5'))
  model2.compile(loss=categorical_crossentropy,
         optimizer=Adam(), metrics=['accuracy'])

  test_loss, test_acc = model2.evaluate(X, Y, verbose=0)
  print('Test loss:', test_loss)
  print('Test accuracy:', test_acc)

  y = model2.predict_classes(X)
  print("predicct is: ", y)

使用Keras建立模型并训练等一系列操作方式

4.2 分别保存网络结构和权重

保存:

def my_save_model(resultpath):

  model = train_model(resultpath)

  # the secon way : save trained network structure and weights
  model_json = model.to_json()
  open(os.path.join(resultpath, 'my_model_structure.json'), 'w').write(model_json)
  model.save_weights(os.path.join(resultpath, 'my_model_weights.hd5'))

加载:

def my_load_model(resultpath):

  # test data
  X = np.array(np.arange(86400)).reshape(2, 120, 120, 3)
  Y = [0, 1]
  X = X.astype('float32')
  Y = np_utils.to_categorical(Y, 4)

  # the second way : load model structure and weights
  model = model_from_json(open(os.path.join(resultpath, 'my_model_structure.json')).read())
  model.load_weights(os.path.join(resultpath, 'my_model_weights.hd5'))
  model.compile(loss=categorical_crossentropy,
         optimizer=Adam(), metrics=['accuracy']) 

  test_loss, test_acc = model.evaluate(X, Y, verbose=0)
  print('Test loss:', test_loss)
  print('Test accuracy:', test_acc)

  y = model.predict_classes(X)
  print("predicct is: ", y)

使用Keras建立模型并训练等一系列操作方式

可以看到,两次的结果是一样的。

5、完整代码

from keras.models import Sequential
from keras.layers import Dense, Conv2D, MaxPooling2D, Flatten, Dropout
from keras.losses import categorical_crossentropy
from keras.optimizers import Adam
from keras.utils.vis_utils import plot_model
from keras.optimizers import SGD
from keras.models import model_from_json
from keras.models import load_model
from keras.utils import np_utils
import numpy as np
import os
from sklearn.model_selection import train_test_split

def load_data(resultpath):
  datapath = os.path.join(resultpath, "data10_4.npz")
  if os.path.exists(datapath):
    data = np.load(datapath)
    X, Y = data["X"], data["Y"]
  else:
    X = np.array(np.arange(432000)).reshape(10, 120, 120, 3)
    Y = [0, 0, 1, 1, 2, 2, 3, 3, 2, 0]
    X = X.astype('float32')
    Y = np_utils.to_categorical(Y, 4)
    np.savez(datapath, X=X, Y=Y)
    print('Saved dataset to dataset.npz.')
  print('X_shape:{}\nY_shape:{}'.format(X.shape, Y.shape))
  return X, Y

def define_model():
  model = Sequential()

  # setup first conv layer
  model.add(Conv2D(32, (3, 3), activation="relu",
           input_shape=(120, 120, 3), padding='same')) # [10, 120, 120, 32]

  # setup first maxpooling layer
  model.add(MaxPooling2D(pool_size=(2, 2))) # [10, 60, 60, 32]

  # setup second conv layer
  model.add(Conv2D(8, kernel_size=(3, 3), activation="relu",
           padding='same')) # [10, 60, 60, 8]

  # setup second maxpooling layer
  model.add(MaxPooling2D(pool_size=(3, 3))) # [10, 20, 20, 8]

  # add bianping layer, 3200 = 20 * 20 * 8
  model.add(Flatten()) # [10, 3200]

  # add first full connection layer
  model.add(Dense(512, activation='sigmoid')) # [10, 512]

  # add dropout layer
  model.add(Dropout(0.5))

  # add second full connection layer
  model.add(Dense(4, activation='softmax')) # [10, 4]

  return model

def train_model(resultpath):
  model = define_model()

  # if want to use SGD, first define sgd, then set optimizer=sgd
  sgd = SGD(lr=0.001, decay=1e-6, momentum=0, nesterov=True)

  # select loss\optimizer\
  model.compile(loss=categorical_crossentropy,
         optimizer=Adam(), metrics=['accuracy'])
  model.summary()

  # draw the model structure
  plot_model(model, show_shapes=True,
        to_file=os.path.join(resultpath, 'model.png'))

  # load data
  X, Y = load_data(resultpath)

  # split train and test data
  X_train, X_test, Y_train, Y_test = train_test_split(
    X, Y, test_size=0.2, random_state=2)

  # input data to model and train
  history = model.fit(X_train, Y_train, batch_size=2, epochs=10,
            validation_data=(X_test, Y_test), verbose=1, shuffle=True)

  # evaluate the model
  loss, acc = model.evaluate(X_test, Y_test, verbose=0)
  print('Test loss:', loss)
  print('Test accuracy:', acc)

  return model

def my_save_model(resultpath):

  model = train_model(resultpath)

  # the first way to save model
  model.save(os.path.join(resultpath, 'my_model.h5'))

  # the secon way : save trained network structure and weights
  model_json = model.to_json()
  open(os.path.join(resultpath, 'my_model_structure.json'), 'w').write(model_json)
  model.save_weights(os.path.join(resultpath, 'my_model_weights.hd5'))

def my_load_model(resultpath):

  # test data
  X = np.array(np.arange(86400)).reshape(2, 120, 120, 3)
  Y = [0, 1]
  X = X.astype('float32')
  Y = np_utils.to_categorical(Y, 4)

  # the first way of load model
  model2 = load_model(os.path.join(resultpath, 'my_model.h5'))
  model2.compile(loss=categorical_crossentropy,
          optimizer=Adam(), metrics=['accuracy'])

  test_loss, test_acc = model2.evaluate(X, Y, verbose=0)
  print('Test loss:', test_loss)
  print('Test accuracy:', test_acc)

  y = model2.predict_classes(X)
  print("predicct is: ", y)

  # the second way : load model structure and weights
  model = model_from_json(open(os.path.join(resultpath, 'my_model_structure.json')).read())
  model.load_weights(os.path.join(resultpath, 'my_model_weights.hd5'))
  model.compile(loss=categorical_crossentropy,
         optimizer=Adam(), metrics=['accuracy'])

  test_loss, test_acc = model.evaluate(X, Y, verbose=0)
  print('Test loss:', test_loss)
  print('Test accuracy:', test_acc)

  y = model.predict_classes(X)
  print("predicct is: ", y)

def main():
  resultpath = "result"
  #train_model(resultpath)
  #my_save_model(resultpath)
  my_load_model(resultpath)


if __name__ == "__main__":
  main()

以上这篇使用Keras建立模型并训练等一系列操作方式就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Python 相关文章推荐
python实现的一个火车票转让信息采集器
Jul 09 Python
python抽象基类用法实例分析
Jun 04 Python
python中enumerate函数遍历元素用法分析
Mar 11 Python
python绘制直线的方法
Jun 30 Python
使用Python如何测试InnoDB与MyISAM的读写性能
Sep 18 Python
Python2和Python3中urllib库中urlencode的使用注意事项
Nov 26 Python
基于MSELoss()与CrossEntropyLoss()的区别详解
Jan 02 Python
python模拟实现斗地主发牌
Jan 07 Python
python-docx文件定位读取过程(尝试替换)
Feb 13 Python
python中threading和queue库实现多线程编程
Feb 06 Python
python爬虫scrapy基本使用超详细教程
Feb 20 Python
如何Python使用re模块实现okenizer
Apr 30 Python
python解释器安装教程的方法步骤
Jul 02 #Python
Python分析最近大火的网剧《隐秘的角落》
Jul 02 #Python
keras训练浅层卷积网络并保存和加载模型实例
Jul 02 #Python
Python RabbitMQ实现简单的进程间通信示例
Jul 02 #Python
利用scikitlearn画ROC曲线实例
Jul 02 #Python
Python使用文件操作实现一个XX信息管理系统的示例
Jul 02 #Python
keras用auc做metrics以及早停实例
Jul 02 #Python
You might like
开启CURL扩展,让服务器支持PHP curl函数(远程采集)
2011/03/19 PHP
将时间以距今多久的形式表示,PHP,js双版本
2012/09/25 PHP
PHP实现创建微信自定义菜单的方法示例
2017/07/14 PHP
基于Jquery 解决Ajax请求的页面 浏览器后退前进功能,页面刷新功能实效问题
2010/12/11 Javascript
js bind 函数 使用闭包保存执行上下文
2011/12/26 Javascript
Javscript删除数组中指定元素并返回新数组
2014/03/06 Javascript
javascript实现博客园页面右下角返回顶部按钮
2015/02/22 Javascript
JS自定义混合Mixin函数示例
2016/11/26 Javascript
node.js入门学习之url模块
2017/02/25 Javascript
Angular 5.0 来了! 有这些大变化
2017/11/15 Javascript
js判断节假日实例代码
2017/12/27 Javascript
JavaScript:ES2019 的新特性(译)
2019/08/08 Javascript
浅谈Vue 自动化部署打包上线
2020/06/14 Javascript
[47:36]Optic vs Newbee 2018国际邀请赛小组赛BO2 第二场 8.17
2018/08/18 DOTA
通过代码实例展示Python中列表生成式的用法
2015/03/31 Python
python抓取最新博客内容并生成Rss
2015/05/17 Python
Python常用知识点汇总
2016/05/08 Python
python数据结构之列表和元组的详解
2017/09/23 Python
django中的setting最佳配置小结
2017/11/21 Python
python 发送和接收ActiveMQ消息的实例
2019/01/30 Python
详解pyinstaller selenium python3 chrome打包问题
2019/10/18 Python
wxPython实现列表增删改查功能
2019/11/19 Python
python tqdm 实现滚动条不上下滚动代码(保持一行内滚动)
2020/02/19 Python
Windows下Pycharm远程连接虚拟机中Centos下的Python环境(图文教程详解)
2020/03/19 Python
python七种方法判断字符串是否包含子串
2020/08/18 Python
Python3中小括号()、中括号[]、花括号{}的区别详解
2020/11/15 Python
日语专业个人求职信范文
2014/02/02 职场文书
内刊编辑求职自荐书范文
2014/02/19 职场文书
国际会计专业求职信
2014/08/04 职场文书
高中生学习计划书
2014/09/15 职场文书
学院党的群众路线教育实践活动整改方案
2014/10/04 职场文书
护士个人年终总结
2015/02/13 职场文书
2016年优秀班主任先进事迹材料
2016/02/26 职场文书
Nginx防盗链与服务优化配置的全过程
2022/01/18 Servers
口袋妖怪冰系十大最强精灵,几何雪花排第七,第六类似北极熊
2022/03/18 日漫
国产动画《万圣街》日语配音版制作决定!
2022/03/20 国漫