python - Pytorch、Keras 风格的多个输出
问题描述
您如何在以下位置实现这 2 个Keras
模型(受 Datacamp 课程“使用 Python 中的 Keras 进行高级深度学习”的启发)Pytorch
:
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)
解决方案
这个资源特别有用。
基本上,这个想法是,与 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
推荐阅读
- html - 如何防止此表格行出现在表格标题后面?
- amazon-web-services - AWS 上的 docker-compose
- python - sqlite3.OperationalError:没有这样的表:kupuvac
- json - JSON 不会在 Unix 中用 jq 转换
- javascript - 如何扩展已经在使用的 React 组件?
- microsoft-graph-api - Access to Microsoft eDiscovery with Microsoft Graph API
- java - 忽略正则表达式的字符串过滤器
- python - QSplitter、QWidget 调整大小、setSizes()、setStretchFactor() 和 sizeHint() - 如何让它们一起工作?
- python - OpenAI "gym" Library throws a NoneType error on env.render()
- python - Is there a way for pytest to check if a log entry was made at Error level or higher?