二元交叉熵计算损失 python程序
时间: 2023-11-02 14:59:52 浏览: 215
交叉熵损失函数python实现源码
以下是二元交叉熵计算损失的Python程序:
```python
import numpy as np
def binary_cross_entropy_loss(y_true, y_pred):
# y_true: true labels (1 or 0)
# y_pred: predicted probabilities between 0 and 1
epsilon = 1e-7 # small value to prevent log(0)
loss = - (y_true * np.log(y_pred + epsilon) + (1 - y_true) * np.log(1 - y_pred + epsilon))
return loss.mean()
```
使用示例:
```python
# example usage
y_true = np.array([1, 0, 1, 0, 1])
y_pred = np.array([0.9, 0.2, 0.8, 0.4, 0.7])
loss = binary_cross_entropy_loss(y_true, y_pred)
print(loss) # 0.34219197077380723
```
阅读全文