python自定义线性回归损失函数
时间: 2024-10-28 19:10:02 浏览: 63
在Python中,如果你想要自定义线性回归的损失函数,通常我们会选择均方误差(Mean Squared Error, MSE)作为标准损失,因为它直观且易于优化。MSE计算公式是预测值和真实值之间差的平方的平均值:
```python
def mean_squared_error(y_true, y_pred):
return np.mean((y_true - y_pred) ** 2)
```
如果你想自定义其他损失函数,比如对数似然损失(log likelihood loss)适合二分类问题,或者Huber损失(Huber Loss)对于异常值更鲁棒,你可以这样做:
```python
import numpy as np
# 对数似然损失(二分类)
def log_loss(y_true, y_pred):
epsilon = 1e-7 # 防止除以0
return -(y_true * np.log(np.clip(y_pred, epsilon, 1 - epsilon)) + (1 - y_true) * np.log(np.clip(1 - y_pred, epsilon, 1 - epsilon))).mean()
# Huber损失
def huber_loss(y_true, y_pred, delta=1):
diff = np.abs(y_true - y_pred)
quadratic = diff < delta
linear = diff >= delta
return 0.5 * (diff[quadratic]**2).sum() + delta*(diff[linear] - 0.5*delta**2)[linear].sum()
```
阅读全文