【问题标题】:Multiple outputs in Pytorch, Keras stylePytorch、Keras 风格的多个输出
【发布时间】:2020-01-05 07:10:12
【问题描述】:

您如何在Pytorch 中实现这两个Keras 模型(灵感来自Datacamp 课程'Advanced Deep Learning with Keras in Python'):

1 个输入,2 个输出的分类:

from keras.layers import Input, Concatenate, Dense
from keras.models import Model

input_tensor = Input(shape=(1,))
output_tensor = Dense(2)(input_tensor)

model = Model(input_tensor, output_tensor)
model.compile(optimizer='adam', loss='categorical_crossentropy')
X = ... # e.g. a pandas series
y = ... # e.g. a pandas df with 2 columns
model.fit(X, y, epochs=100)

具有分类和回归的模型:

from keras.layers import Input, Dense
from keras.models import Model

input_tensor = Input(shape=(1,))
output_tensor_reg = Dense(1)(input_tensor)
output_tensor_class = Dense(1, activation='sigmoid')(output_tensor_reg)

model.compile(loss=['mean_absolute_error','binary_crossentropy']
X = ...
y_reg = ...
y_class = ...
model.fit(X, [y_reg, y_class], epochs=100)

【问题讨论】:

  • 关于第一个模型,我发现这个资源很有用:discuss.pytorch.org/t/a-model-with-multiple-outputs/10440/9 但我不知道这是否是 Keras 在后台所做的,以及它是否真的是编写方式。 . 到底为什么要加上loss??
  • 关于 Keras 模型的 Keras 功能 API 的这一部分非常有趣:keras.io/getting-started/functional-api-guide/… 它表明您可以明确写出必须在每个输出损失之间分配多少全局损失:model.compile(optimizer='rmsprop', loss={'main_output': 'binary_crossentropy', 'aux_output': 'binary_crossentropy'} loss_weights={'main_output': 1., 'aux_output': 0.2}

标签: python keras deep-learning pytorch


【解决方案1】:

This ressource 特别有帮助。

基本上,这个想法是,与 Keras 不同,您必须明确说明要在前向函数中计算每个输出的位置以及如何从中计算全局损失。

例如,关于第一个例子:

def __init__(self, ...):
    ... # define your model elements

def forward(self, x):
    # Do your stuff here
    ...
    x1 = F.sigmoid(x) # class probabilities
    x2 = F.sigmoid(x) # bounding box calculation
    return x1, x2

然后你计算损失:

out1, out2 = model(data)
loss1 = criterion1(out1, target1)
loss2 = criterion2(out2, targt2)
alpha = ... # define the weights of each sub-loss in the global loss
loss = alpha * loss1 + (1-alpha) * loss2
loss.backward()

对于第二个,它几乎相同,但您计算前向传递中不同点的损失:

def __init__(self, ...):
    ... # define your model elements

def forward(self, main_input, aux_input):
    aux = F.relu(self.dense_1(main_input))
    x = F.relu(self.input_layer(aux))
    x = F.sigmoid(x)
    return x, aux

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-17
    • 2018-01-16
    • 2018-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-08
    • 2018-09-14
    相关资源
    最近更新 更多