欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Keras-多輸入多輸出實(shí)例(多任務(wù))

 更新時(shí)間:2020年06月22日 09:26:27   作者:happyprince  
這篇文章主要介紹了Keras-多輸入多輸出實(shí)例(多任務(wù)),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧

1、模型結(jié)果設(shè)計(jì)

2、代碼

from keras import Input, Model
from keras.layers import Dense, Concatenate
import numpy as np
from keras.utils import plot_model
from numpy import random as rd

samples_n = 3000
samples_dim_01 = 2
samples_dim_02 = 2
# 樣本數(shù)據(jù)
x1 = rd.rand(samples_n, samples_dim_01)
x2 = rd.rand(samples_n, samples_dim_02)
y_1 = []
y_2 = []
y_3 = []
for x11, x22 in zip(x1, x2):
  y_1.append(np.sum(x11) + np.sum(x22))
  y_2.append(np.max([np.max(x11), np.max(x22)]))
  y_3.append(np.min([np.min(x11), np.min(x22)]))
y_1 = np.array(y_1)
y_1 = np.expand_dims(y_1, axis=1)
y_2 = np.array(y_2)
y_2 = np.expand_dims(y_2, axis=1)
y_3 = np.array(y_3)
y_3 = np.expand_dims(y_3, axis=1)

# 輸入層
inputs_01 = Input((samples_dim_01,), name='input_1')
inputs_02 = Input((samples_dim_02,), name='input_2')
# 全連接層
dense_01 = Dense(units=3, name="dense_01", activation='softmax')(inputs_01)
dense_011 = Dense(units=3, name="dense_011", activation='softmax')(dense_01)
dense_02 = Dense(units=6, name="dense_02", activation='softmax')(inputs_02)
# 加入合并層
merge = Concatenate()([dense_011, dense_02])
# 分成兩類輸出 --- 輸出01
output_01 = Dense(units=6, activation="relu", name='output01')(merge)
output_011 = Dense(units=1, activation=None, name='output011')(output_01)
# 分成兩類輸出 --- 輸出02
output_02 = Dense(units=1, activation=None, name='output02')(merge)
# 分成兩類輸出 --- 輸出03
output_03 = Dense(units=1, activation=None, name='output03')(merge)
# 構(gòu)造一個(gè)新模型
model = Model(inputs=[inputs_01, inputs_02], outputs=[output_011,
                           output_02,
                           output_03
                           ])
# 顯示模型情況
plot_model(model, show_shapes=True)
print(model.summary())
# # 編譯
# model.compile(optimizer="adam", loss='mean_squared_error', loss_weights=[1,
#                                     0.8,
#                                     0.8
#                                     ])
# # 訓(xùn)練
# model.fit([x1, x2], [y_1,
#           y_2,
#           y_3
#           ], epochs=50, batch_size=32, validation_split=0.1)

# 以下的方法可靈活設(shè)置
model.compile(optimizer='adam',
       loss={'output011': 'mean_squared_error',
          'output02': 'mean_squared_error',
          'output03': 'mean_squared_error'},
       loss_weights={'output011': 1,
              'output02': 0.8,
              'output03': 0.8})
model.fit({'input_1': x1,
      'input_2': x2},
     {'output011': y_1,
      'output02': y_2,
      'output03': y_3},
     epochs=50, batch_size=32, validation_split=0.1)

# 預(yù)測(cè)
test_x1 = rd.rand(1, 2)
test_x2 = rd.rand(1, 2)
test_y = model.predict(x=[test_x1, test_x2])
# 測(cè)試
print("測(cè)試結(jié)果:")
print("test_x1:", test_x1, "test_x2:", test_x2, "y:", test_y, np.sum(test_x1) + np.sum(test_x2))

補(bǔ)充知識(shí):Keras多輸出(多任務(wù))如何設(shè)置fit_generator

在使用Keras的時(shí)候,因?yàn)樾枰紤]到效率問題,需要修改fit_generator來適應(yīng)多輸出

# create model
model = Model(inputs=x_inp, outputs=[main_pred, aux_pred])
# complie model
model.compile(
  optimizer=optimizers.Adam(lr=learning_rate),
  loss={"main": weighted_binary_crossentropy(weights), "auxiliary":weighted_binary_crossentropy(weights)},
  loss_weights={"main": 0.5, "auxiliary": 0.5},
  metrics=[metrics.binary_accuracy],
)
# Train model
model.fit_generator(
  train_gen, epochs=num_epochs, verbose=0, shuffle=True
)

Keras官方文檔:

generator: A generator or an instance of Sequence (keras.utils.Sequence) object in order to avoid duplicate data when using multiprocessing. The output of the generator must be either

a tuple (inputs, targets)

a tuple (inputs, targets, sample_weights).

Keras設(shè)計(jì)多輸出(多任務(wù))使用fit_generator的步驟如下:

根據(jù)官方文檔,定義一個(gè)generator或者一個(gè)class繼承Sequence

class Batch_generator(Sequence):
 """
 用于產(chǎn)生batch_1, batch_2(記住是numpy.array格式轉(zhuǎn)換)
 """
 y_batch = {'main':batch_1,'auxiliary':batch_2}
 return X_batch, y_batch

# or in another way
def batch_generator():
 """
 用于產(chǎn)生batch_1, batch_2(記住是numpy.array格式轉(zhuǎn)換)
 """
 yield X_batch, {'main': batch_1,'auxiliary':batch_2}

重要的事情說三遍(親自采坑,搜了一大圈才發(fā)現(xiàn)滴):

如果是多輸出(多任務(wù))的時(shí)候,這里的target是字典類型

如果是多輸出(多任務(wù))的時(shí)候,這里的target是字典類型

如果是多輸出(多任務(wù))的時(shí)候,這里的target是字典類型

以上這篇Keras-多輸入多輸出實(shí)例(多任務(wù))就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • python實(shí)現(xiàn)電子詞典

    python實(shí)現(xiàn)電子詞典

    這篇文章主要為大家詳細(xì)介紹了python實(shí)現(xiàn)電子詞典,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2014-01-01
  • Python實(shí)現(xiàn)TCP協(xié)議下的端口映射功能的腳本程序示例

    Python實(shí)現(xiàn)TCP協(xié)議下的端口映射功能的腳本程序示例

    端口映射一個(gè)最基本的運(yùn)作形態(tài)就是通過一個(gè)中間端口將一個(gè)端口發(fā)送的數(shù)據(jù)全部轉(zhuǎn)給另一個(gè)端口,well,這里我們就來看一下Python實(shí)現(xiàn)TCP協(xié)議下的端口映射功能的腳本程序示例
    2016-06-06
  • pytorch?cuda安裝報(bào)錯(cuò)的解決方法

    pytorch?cuda安裝報(bào)錯(cuò)的解決方法

    這篇文章主要給大家介紹了關(guān)于pytorch?cuda安裝報(bào)錯(cuò)的解決方法,文中通過圖文介紹的非常詳細(xì),對(duì)大家學(xué)習(xí)或者使用Pytorch具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2023-01-01
  • 如何用python獲取EXCEL文件內(nèi)容并保存到DBC

    如何用python獲取EXCEL文件內(nèi)容并保存到DBC

    很多時(shí)候,使用python進(jìn)行數(shù)據(jù)分析的第一步就是讀取excel文件,下面這篇文章主要給大家介紹了關(guān)于如何用python獲取EXCEL文件內(nèi)容并保存到DBC的相關(guān)資料,需要的朋友可以參考
    2023-12-12
  • PyTorch讀取Cifar數(shù)據(jù)集并顯示圖片的實(shí)例講解

    PyTorch讀取Cifar數(shù)據(jù)集并顯示圖片的實(shí)例講解

    今天小編就為大家分享一篇PyTorch讀取Cifar數(shù)據(jù)集并顯示圖片的實(shí)例講解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2018-07-07
  • Python的Flask項(xiàng)目中獲取請(qǐng)求用戶IP地址 addr問題

    Python的Flask項(xiàng)目中獲取請(qǐng)求用戶IP地址 addr問題

    這篇文章主要介紹了Python的Flask項(xiàng)目中獲取請(qǐng)求用戶IP地址 addr問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-01-01
  • 在Python中使用mechanize模塊模擬瀏覽器功能

    在Python中使用mechanize模塊模擬瀏覽器功能

    這篇文章主要介紹了在Python中使用mechanize模塊模擬瀏覽器功能,包括使用cookie和設(shè)置代理等功能的實(shí)現(xiàn),需要的朋友可以參考下
    2015-05-05
  • NumPy中掩碼數(shù)組的操作

    NumPy中掩碼數(shù)組的操作

    本文主要介紹了NumPy中掩碼數(shù)組的操作,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2023-03-03
  • python實(shí)現(xiàn)數(shù)據(jù)清洗(缺失值與異常值處理)

    python實(shí)現(xiàn)數(shù)據(jù)清洗(缺失值與異常值處理)

    今天小編就為大家分享一篇python實(shí)現(xiàn)數(shù)據(jù)清洗(缺失值與異常值處理),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2019-12-12
  • PyTorch零基礎(chǔ)入門之構(gòu)建模型基礎(chǔ)

    PyTorch零基礎(chǔ)入門之構(gòu)建模型基礎(chǔ)

    PyTorch是一個(gè)開源的Python機(jī)器學(xué)習(xí)庫(kù),基于Torch,用于自然語言處理等應(yīng)用程序,它是一個(gè)可續(xù)計(jì)算包,提供兩個(gè)高級(jí)功能:1、具有強(qiáng)大的GPU加速的張量計(jì)算(如NumPy)。2、包含自動(dòng)求導(dǎo)系統(tǒng)的深度神經(jīng)網(wǎng)絡(luò)
    2021-10-10

最新評(píng)論