日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

Keras —— 序贯模型和函数式模型

發布時間:2024/1/1 编程问答 31 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Keras —— 序贯模型和函数式模型 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

序貫模型

序貫模型是多個網絡層的線性堆疊,是函數式模型的簡略版,為最簡單的線性、從頭到尾的結構順序,不發生分叉。

1、應用序貫模型的基本步驟

  • model.add,添加層;
  • model.compile,模型訓練的BP模式設置;
  • model.fit,模型訓練參數設置 + 訓練;
  • 模型評估
  • 模型預測
  • 2、創建

    1、可以通過向Sequential模型傳遞一個layer的list來構造該模型:

    from keras.models import Sequential from keras.layers import Dense, Activationmodel = Sequential([ Dense(32, units=784), Activation('relu'), Dense(10), Activation('softmax'), ])

    2、也可以通過.add()方法一個個的將layer加入模型中:

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

    3、指定輸入數據的shape

    模型需要知道輸入數據的shape,因此,Sequential的第一層需要接受一個關于輸入數據shape的參數,后面的各個層則可以自動的推導出中間數據的shape,因此不需要為每個層都指定這個參數。有幾種方法來為第一層指定輸入數據的shape

    1、傳遞一個input_shape的關鍵字參數給第一層,input_shape是一個tuple類型的數據

    model = Sequential() model.add(Dense(64, input_shape=(20,), activation='relu'))

    2、有些2D層,如Dense,支持通過指定其輸入維度input_dim來隱含的指定輸入數據shape,是一個Int類型的數據。一些3D的時域層支持通過參數input_dim和input_length來指定輸入shape。

    model = Sequential() model.add(Dense(64, input_dim=20, activation='relu'))

    4、編譯

    在訓練模型之前,我們需要通過compile來對學習過程進行配置。compile接收三個參數:優化器optimizer,損失函數loss,指標列表metrics

    model.compile(loss='binary_crossentropy',optimizer='rmsprop',metrics=['accuracy'])

    5、訓練

    訓練模型一般使用fit函數

    model.fit(x_train, y_train,epochs=20,batch_size=128)

    6、評估

    根據驗證集評估模型的好壞

    score = model.evaluate(x_val, y_val, batch_size=128) print('val score:', score[0]) print('val accuracy:', score[1])

    7、預測

    對已訓練完成的模型,輸入特征值x會預測得到標簽y

    x=1 y=model.predict(x,verbose=0) print(y)

    8、示例

    import numpy as np from keras.models import Sequential from keras.layers import Dense, Dropout# 準備訓練集和驗證集 x_train = np.random.random((1000, 20)) y_train = np.random.randint(2, size=(1000, 1)) x_val = np.random.random((100, 20)) y_val = np.random.randint(2, size=(100, 1))model = Sequential() model.add(Dense(64, input_dim=20, activation='relu')) # 或 model.add(Dense(64, input_shape=(20,), activation='relu')) model.add(Dropout(0.5)) model.add(Dense(64, activation='relu')) model.add(Dropout(0.5)) model.add(Dense(1, activation='sigmoid'))model.compile(loss='binary_crossentropy',optimizer='rmsprop',metrics=['accuracy']) model.fit(x_train, y_train,epochs=20,batch_size=128)score = model.evaluate(x_val, y_val, batch_size=128) print('val score:', score[0]) print('val accuracy:', score[1])x=1 y=model.predict(x,verbose=0) print(y)

    函數式模型

    比序貫模型要復雜,可以同時/分階段輸入變量,分階段輸出想要的模型

    1、應用函數式模型的基本步驟

  • model.layers,添加層;
  • model.compile,模型訓練的BP模式設置;
  • model.fit,模型訓練參數設置 + 訓練;
  • 模型評估
  • 模型預測
  • 2、創建

    model=Model(inputs=, outputs=)

    3、指定輸入數據的shape

    inputs = Input(shape=(20,))

    4、編譯,訓練,評估,預測等步驟與序貫式模型相同,這里不再贅述

    5、示例一

    基于上文序貫式模型進行改造

    import numpy as np from keras.models import Model from keras.layers import Dense, Dropout# 準備訓練集和驗證集 x_train = np.random.random((1000, 20)) y_train = np.random.randint(2, size=(1000, 1)) x_val = np.random.random((100, 20)) y_val = np.random.randint(2, size=(100, 1))inputs = Input(shape=(20,)) x=Dense(64,activation='relu')(inputs) x=Dropout(0.5)(x) x=Dense(64,activation='relu')(x) x=Dropout(0.5)(x) predictions=Dense(1, activation='sigmoid')(x)model=Model(inputs=inputs, outputs=predictions) model.compile(loss='binary_crossentropy', optimizer='rmsprop', metrics=['accuracy']) model.fit(x_train, y_train,epochs=20,batch_size=128)score = model.evaluate(x_val, y_val, batch_size=128) print('val score:', score[0]) print('val accuracy:', score[1])x=1 y=model.predict(x,verbose=0) print(y)

    6、示例二

    多輸入多輸出模型

    from keras.layers import Input, Embedding, LSTM, Dense from keras.models import Modelmain_input = Input(shape=(100,), dtype='int32', name='main_input') x = Embedding(output_dim=512, input_dim=10000, input_length=100)(main_input) lstm_out = LSTM(32)(x) auxiliary_output = Dense(1, activation='sigmoid', name='aux_output')(lstm_out) auxiliary_input = Input(shape=(5,), name='aux_input') x = keras.layers.concatenate([lstm_out, auxiliary_input])# We stack a deep densely-connected network on top x = Dense(64, activation='relu')(x) x = Dense(64, activation='relu')(x) x = Dense(64, activation='relu')(x)# And finally we add the main logistic regression layer main_output = Dense(1, activation='sigmoid', name='main_output')(x)model = Model(inputs=[main_input, auxiliary_input], outputs=[main_output, auxiliary_output]) model.compile(optimizer='rmsprop',loss={'main_output': 'binary_crossentropy', 'aux_output': 'binary_crossentropy'},loss_weights={'main_output': 1., 'aux_output': 0.2})# And trained it via: model.fit({'main_input': headline_data, 'aux_input': additional_data},{'main_output': labels, 'aux_output': labels},epochs=50, batch_size=32)

    總結

    以上是生活随笔為你收集整理的Keras —— 序贯模型和函数式模型的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。