Keras-多输入多输出实例(多任务)

1、模型结果设计

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
# 样本数据
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)
# 构造一个新模型
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
#                                     ])
# # 训练
# model.fit([x1, x2], [y_1,
#           y_2,
#           y_3
#           ], epochs=50, batch_size=32, validation_split=0.1)

# 以下的方法可灵活设置
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)

# 预测
test_x1 = rd.rand(1, 2)
test_x2 = rd.rand(1, 2)
test_y = model.predict(x=[test_x1, test_x2])
# 测试
print("测试结果:")
print("test_x1:", test_x1, "test_x2:", test_x2, "y:", test_y, np.sum(test_x1) + np.sum(test_x2))

补充知识:Keras多输出(多任务)如何设置fit_generator

在使用Keras的时候,因为需要考虑到效率问题,需要修改fit_generator来适应多输出

# 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设计多输出(多任务)使用fit_generator的步骤如下:

根据官方文档,定义一个generator或者一个class继承Sequence

class Batch_generator(Sequence):
 """
 用于产生batch_1, batch_2(记住是numpy.array格式转换)
 """
 y_batch = {'main':batch_1,'auxiliary':batch_2}
 return X_batch, y_batch

# or in another way
def batch_generator():
 """
 用于产生batch_1, batch_2(记住是numpy.array格式转换)
 """
 yield X_batch, {'main': batch_1,'auxiliary':batch_2}

重要的事情说三遍(亲自采坑,搜了一大圈才发现滴):

如果是多输出(多任务)的时候,这里的target是字典类型

如果是多输出(多任务)的时候,这里的target是字典类型

如果是多输出(多任务)的时候,这里的target是字典类型

以上这篇Keras-多输入多输出实例(多任务)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持我们。

(0)

相关推荐

  • Keras—embedding嵌入层的用法详解

    最近在工作中进行了NLP的内容,使用的还是Keras中embedding的词嵌入来做的. Keras中embedding层做一下介绍. 中文文档地址:https://keras.io/zh/layers/embeddings/ 参数如下: 其中参数重点有input_dim,output_dim,非必选参数input_length. 初始化方法参数设置后面会单独总结一下. demo使用预训练(使用百度百科(word2vec)的语料库)参考 embedding使用的demo参考: def creat

  • 浅谈Keras参数 input_shape、input_dim和input_length用法

    在keras中,数据是以张量的形式表示的,不考虑动态特性,仅考虑shape的时候,可以把张量用类似矩阵的方式来理解. 例如 [[1],[2],[3]] 这个张量的shape为(3,1) [[[1,2],[3,4]],[[5,6],[7,8]],[[9,10],[11,12]]]这个张量的shape为(3,2,2), [1,2,3,4]这个张量的shape为(4,) input_shape:即张量的shape.从前往后对应由外向内的维度. input_length:代表序列长度,可以理解成有多少个

  • keras 自定义loss层+接受输入实例

    loss函数如何接受输入值 keras封装的比较厉害,官网给的例子写的云里雾里, 在stackoverflow找到了答案 You can wrap the loss function as a inner function and pass your input tensor to it (as commonly done when passing additional arguments to the loss function). def custom_loss_wrapper(input_

  • 使用keras实现BiLSTM+CNN+CRF文字标记NER

    我就废话不多说了,大家还是直接看代码吧~ import keras from sklearn.model_selection import train_test_split import tensorflow as tf from keras.callbacks import ModelCheckpoint,Callback # import keras.backend as K from keras.layers import * from keras.models import Model

  • Keras-多输入多输出实例(多任务)

    1.模型结果设计 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 # 样本数据 x1 = rd.rand(s

  • Keras 数据增强ImageDataGenerator多输入多输出实例

    我就废话不多说了,大家还是直接看代码吧~ import os os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID" os.environ["CUDA_VISIBLE_DEVICES"]="" import sys import gc import time import cv2 import random import numpy as np import pandas as pd impo

  • C语言数据输入与输出实例详解

    C语言数据输入与输出实例详解 1 概论 C语言提供了跨平台的数据输入输出函数scanf()和printf()函数,它们可以按照指定的格式来解析常见的数据类型,例如整数,浮点数,字符和字符串等等.数据输入的来源可以是文件,控制台以及网络,而输出的终端可以是控制台,文件甚至是网页. 2 数据输出 从第一个c语言程序中,就使用了跨平台的库函数printf实现将一段文字输出到控制台,而实际上,printf()不仅可以将数据按照指定的格式输出到控制台,还可以是网页或者是指定的文件中,printf()函数执

  • Python3基础之输入和输出实例分析

    通常来说,一个Python程序可以从键盘读取输入,也可以从文件读取输入:而程序的结果可以输出到屏幕上,也可以保存到文件中便于以后使用.本文就来介绍Python中最基本的I/O函数. 一.控制台I/O 1.读取键盘输入 内置函数input([prompt]),用于从标准输入读取一个行,并返回一个字符串(去掉结尾的换行符): s = input("Enter your input:") 注:在Python 3.x版本中取消了 raw_input() 函数. 2.打印到屏幕 最简单的输出方法

  • keras 获取某层输出 获取复用层的多次输出实例

    官方文档很全面,搜索功能也很好.但是如果你想单独实现某个功能,根本无从搜寻.于是我写了这个笔记.从功能出发. 两个tensor经过一个layer实例会产生两个输出. a = Input(shape=(280, 256)) b = Input(shape=(280, 256)) lstm = LSTM(32) encoded_a = lstm(a) encoded_b = lstm(b) lstm.output 这个代码有错误,因为最后一行没有指定lstm这个layer实例的那个输出. >> A

  • keras获得某一层或者某层权重的输出实例

    一个例子: print("Loading vgg19 weights...") vgg_model = VGG19(include_top=False, weights='imagenet') from_vgg = dict() # 因为模型定义中的layer的名字与原始vgg名字不同,所以需要调整 from_vgg['conv1_1'] = 'block1_conv1' from_vgg['conv1_2'] = 'block1_conv2' from_vgg['conv2_1']

  • Python3基本输入与输出操作实例分析

    本文实例讲述了Python3基本输入与输出操作.分享给大家供大家参考,具体如下: 数据的输入和输出操作是计算机最基本的操作,本节只研究基本的输入与输出,基本输入是指从键盘上输入数据的操作,基本输出是指屏幕上显示输出结果的操作. 2.1基本输入和输出 常用的输入与输出设备有很多,如摄像机.扫描仪.话筒.键盘等都是输入设备,然后经过计算机解码后在显示器或打印机等终端上输出显示. 2.2使用print()函数输出 ----基本语法: print(输出内容) #其中输出内容可以是数字和字符串 print

  • Java学习笔记:基本输入、输出数据操作实例分析

    本文实例讲述了Java学习笔记:基本输入.输出数据操作.分享给大家供大家参考,具体如下: 相关内容: 输出数据: print println printf 输入数据: Scanner 首发时间:2018-03-16 16:30 输出数据: JAVA中在屏幕中打印数据可以使用: System.out.print(x):x可以是一个变量.表达式.字符串. System.out.println(x):x可以是一个变量.表达式.字符串.与print不同的是打印完后会换行 System.out.print

  • java输入数字,输出倒序的实例

    我就废话不多说了,大家还是直接看代码吧~ package c10; import java.util.Scanner; public class zhengzhengshu { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("输入一个正整数:"); int num = input.nextInt(); while (num != 0)

  • 在QT5中实现求两个输入值的和并输出(实例)

    1.在UI设计界面放置两个输入lineEdit.一个输出TextBrowser和一个PushButton(用以按键求和), 如图 2.打开.h文件,在类里面添加槽函数的声明代码,如图  : 3.打开.cpp文件,在文件最下面编写槽函数代码,如图 : 由于需要用到QString类型转基本数据类型(int),因此在头文件添加#include <QString> 4.点击运行,在弹出的程序窗口中输入两个数值并点击求和即可,如图 以上这篇在QT5中实现求两个输入值的和并输出(实例)就是小编分享给大家的

随机推荐