GPUCodeForces/S1/wut0n_#8/bce_torchcode.py

44 lines
1.2 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import torch
import torch.nn as nn
class Model(nn.Module):
"""
合理优化的PyTorch BCE Loss实现
使用PyTorch内置函数避免重复的数值处理
"""
def __init__(self):
super(Model, self).__init__()
def forward(self, input: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
"""
使用PyTorch内置的binary_cross_entropy函数
让PyTorch自己处理数值稳定性
Args:
input (torch.Tensor): 预测概率 (0-1之间)
target (torch.Tensor): 真实标签 (0或1)
Returns:
torch.Tensor: BCE Loss标量值
"""
# 直接使用内置函数让PyTorch处理数值稳定性
return torch.nn.functional.binary_cross_entropy(
input,
target,
reduction='sum'
)
batch_size = 256
num_features = 2000
def get_inputs():
"""
生成合理的测试数据
"""
input_probs = torch.sigmoid(torch.randn(batch_size, num_features))
target_labels = torch.randint(0, 2, (batch_size, num_features)).float()
return [input_probs, target_labels]
def get_init_inputs():
return [] # 没有特殊的初始化输入需求