Pytorch、Keras和sty中的多个输出

2024-04-19 11:37:18 发布

您现在位置:Python中文网/ 问答频道 /正文

如何在Pytorch中实现这些2Keras模型(受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)

Tags: from模型importinputoutputmodelwith分类
1条回答
网友
1楼 · 发布于 2024-04-19 11:37:18

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

相关问题 更多 >