最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

使用Keras建立模型并訓(xùn)練等一系列操作方式

 更新時(shí)間:2020年07月02日 12:03:24   作者:夏洛的網(wǎng)  
這篇文章主要介紹了使用Keras建立模型并訓(xùn)練等一系列操作方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧

由于Keras是一種建立在已有深度學(xué)習(xí)框架上的二次框架,其使用起來非常方便,其后端實(shí)現(xiàn)有兩種方法,theano和tensorflow。由于自己平時(shí)用tensorflow,所以選擇后端用tensorflow的Keras,代碼寫起來更加方便。

1、建立模型

Keras分為兩種不同的建模方式,

Sequential models:這種方法用于實(shí)現(xiàn)一些簡(jiǎn)單的模型。你只需要向一些存在的模型中添加層就行了。

Functional API:Keras的API是非常強(qiáng)大的,你可以利用這些API來構(gòu)造更加復(fù)雜的模型,比如多輸出模型,有向無環(huán)圖等等。

這里采用sequential models方法。

構(gòu)建序列模型。

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

可以看到定義模型時(shí)輸出的網(wǎng)絡(luò)結(jié)構(gòu)。

2、準(zhǔn)備數(shù)據(jù)

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

3、訓(xùn)練模型

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)

可以看到訓(xùn)練時(shí)輸出的日志。因?yàn)槭请S機(jī)數(shù)據(jù),沒有意義,這里訓(xùn)練的結(jié)果不必計(jì)較,只是練習(xí)而已。

保存下來的模型結(jié)構(gòu):

4、保存與加載模型并測(cè)試

有兩種保存方式

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)

4.2 分別保存網(wǎng)絡(luò)結(jié)構(gòu)和權(quán)重

保存:

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)

可以看到,兩次的結(jié)果是一樣的。

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建立模型并訓(xùn)練等一系列操作方式就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • python繪制圓柱體的方法

    python繪制圓柱體的方法

    這篇文章主要為大家詳細(xì)介紹了python繪制圓柱體的方法,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2018-07-07
  • Python基于SciPy庫(kù)實(shí)現(xiàn)統(tǒng)計(jì)分析與建模

    Python基于SciPy庫(kù)實(shí)現(xiàn)統(tǒng)計(jì)分析與建模

    SciPy是一個(gè)強(qiáng)大的Python庫(kù),提供了豐富的科學(xué)計(jì)算和數(shù)據(jù)分析工具,本文我們將探討如何使用Python和SciPy庫(kù)進(jìn)行統(tǒng)計(jì)分析和建模,感興趣的可以學(xué)習(xí)一下
    2023-06-06
  • 使用Pandas對(duì)列名和索引進(jìn)行重命名的幾種常見方法

    使用Pandas對(duì)列名和索引進(jìn)行重命名的幾種常見方法

    在數(shù)據(jù)分析和處理中,Pandas是一個(gè)非常強(qiáng)大的工具,它提供了靈活的數(shù)據(jù)結(jié)構(gòu)和豐富的操作方法,使得數(shù)據(jù)處理變得更加簡(jiǎn)單高效,其中,對(duì)數(shù)據(jù)的列名和索引進(jìn)行重命名是常見的需求之一,本文將從基礎(chǔ)概念出發(fā),逐步深入探討如何使用Pandas對(duì)列名和索引進(jìn)行重命名
    2024-12-12
  • python 中的int()函數(shù)怎么用

    python 中的int()函數(shù)怎么用

    int() 函數(shù)用于將一個(gè)字符串會(huì)數(shù)字轉(zhuǎn)換為整型。接下來通過本文給大家介紹python 中的int()函數(shù)的相關(guān)知識(shí),感興趣的朋友一起看看吧
    2017-10-10
  • Python 3.x對(duì).CSV數(shù)據(jù)按任意行、列讀取的過程

    Python 3.x對(duì).CSV數(shù)據(jù)按任意行、列讀取的過程

    這篇文章主要介紹了Python 3.x對(duì).CSV數(shù)據(jù)按任意行、列讀取的過程,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。
    2022-05-05
  • matlab中二維插值函數(shù)interp2的使用詳解

    matlab中二維插值函數(shù)interp2的使用詳解

    這篇文章主要介紹了matlab中二維插值函數(shù)interp2的使用詳解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2020-04-04
  • Python內(nèi)置函數(shù)詳談

    Python內(nèi)置函數(shù)詳談

    本篇文章主要介紹了Python內(nèi)置函數(shù)的使用方法,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2021-10-10
  • Python實(shí)戰(zhàn)之生成有關(guān)聯(lián)單選問卷

    Python實(shí)戰(zhàn)之生成有關(guān)聯(lián)單選問卷

    這篇文章主要為大家分享了一個(gè)Python實(shí)戰(zhàn)小案例——生成有關(guān)聯(lián)單選問卷,并且能根據(jù)問卷總分?jǐn)?shù)生成對(duì)應(yīng)判斷文案結(jié)果,感興趣的可以了解一下
    2023-04-04
  • Python實(shí)現(xiàn)實(shí)時(shí)顯示進(jìn)度條的6種方法

    Python實(shí)現(xiàn)實(shí)時(shí)顯示進(jìn)度條的6種方法

    相信大家對(duì)進(jìn)度條一定不陌生了,很多安裝或者下載都會(huì)出現(xiàn)進(jìn)度條,本文主要介紹了Python實(shí)現(xiàn)實(shí)時(shí)顯示進(jìn)度條的6種方法,具有一定的參考價(jià)值,感興趣的可以了解一下
    2021-12-12
  • pandas loc與iloc用法及區(qū)別

    pandas loc與iloc用法及區(qū)別

    本文主要介紹了pandas loc與iloc用法及區(qū)別,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2023-05-05

最新評(píng)論

通江县| 云阳县| 通化市| 炉霍县| 介休市| 林口县| 介休市| 始兴县| 邵阳市| 石台县| 于田县| 利津县| 满城县| 汕尾市| 吕梁市| 怀集县| 鄂托克旗| 南京市| 乐清市| 茂名市| 台江县| 高密市| 巴塘县| 麻栗坡县| 长丰县| 雷山县| 汤阴县| 邵阳县| 塔河县| 广德县| 米林县| 萨嘎县| 陆丰市| 海原县| 水富县| 神木县| 湖北省| 舞钢市| 扎赉特旗| 汕尾市| 庆城县|