constrained_nn6.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. import torch
  2. import torch.nn as nn
  3. # 定义神经网络模型
  4. class ConstrainedNN(nn.Module):
  5. def __init__(self, input_size):
  6. super(ConstrainedNN, self).__init__()
  7. self.fc1 = nn.Linear(input_size, 128)
  8. self.fc2 = nn.Linear(128, 64)
  9. self.fc3 = nn.Linear(64, 16)
  10. #self.fc4 = nn.Linear(32, 16)
  11. self.fc5 = nn.Linear(16, 1)
  12. # 嵌入一元一次线性函数的参数
  13. self.a = nn.Parameter(torch.randn(1))
  14. self.b = nn.Parameter(torch.randn(1))
  15. def forward(self, x, original_x, special_feature_index):
  16. x = torch.relu(self.fc1(x))
  17. x = torch.relu(self.fc2(x))
  18. x = torch.relu(self.fc3(x))
  19. #x = torch.relu(self.fc4(x))
  20. x = self.fc5(x)
  21. # 嵌入一元一次线性函数
  22. special_feature = original_x[:, special_feature_index].unsqueeze(1)
  23. x = x + self.a * special_feature + self.b
  24. return x
  25. # 自定义损失函数
  26. def custom_loss(y_pred, y_true, X, monotonic_feature_index, mean_X_special, mean_y):
  27. y_true = y_true
  28. mse_loss = nn.MSELoss()(y_pred, y_true)
  29. # 惩罚项
  30. X_special = X[:, monotonic_feature_index]
  31. punishment = torch.mean((torch.sign(X_special - mean_X_special) - torch.sign(y_pred - mean_y)) ** 2)
  32. # 惩罚项
  33. # 对于所有样本,计算它们的预测值之间的差值
  34. # 如果某个样本的特定变量大于另一个样本的特定变量,但预测值却不大于另一个样本的预测值,则增加惩罚
  35. sorted_indices = torch.argsort(X[:, monotonic_feature_index]) # 按特定变量排序
  36. sorted_outputs = y_pred[sorted_indices]
  37. sorted_targets = y_true[sorted_indices]
  38. # 计算相邻样本之间的差值
  39. output_diff = sorted_outputs[1:] - sorted_outputs[:-1]
  40. target_diff = sorted_targets[1:] - sorted_targets[:-1]
  41. # 惩罚项:如果输出差值与目标差值的符号不一致,则增加惩罚
  42. penalty = torch.relu(-output_diff * target_diff).mean()
  43. return mse_loss + 2*punishment + penalty # 权衡 mse_loss 和惩罚项的权重