均方根误差(RMSE)Python代码
时间: 2024-05-13 09:12:03 浏览: 15
均方根误差(RMSE)是一种衡量回归模型预测误差的指标,表示实际观测值与模型预测值之间差异的标准差。在Python中,可以使用NumPy库中的mean()和sqrt()函数来计算均方根误差。以下是一个示例代码:
```python
import numpy as np
# 定义实际观测值和模型预测值
actual = np.array([1, 2, 3, 4, 5])
predicted = np.array([1.5, 2.5, 3.5, 4.5, 5.5])
# 计算均方根误差
rmse = np.sqrt(np.mean((predicted - actual) ** 2))
# 输出结果
print("均方根误差:", rmse)
```
输出结果为:
```
均方根误差: 0.7071067811865476
```
相关问题
python求均方根误差rmse
好的,关于计算均方根误差(RMSE)的Python代码可以这样写:
```python
import numpy as np
def rmse(predictions, targets):
return np.sqrt(((predictions - targets) ** 2).mean())
# 测试
predictions = np.array([1.2, 2.4, 3.6])
targets = np.array([1, 2, 4])
print("RMSE: ", rmse(predictions, targets))
```
输出:
```
RMSE: 0.6244997998398398
```
希望这样的回答能够帮助到您!
均方根误差python代码
均方根误差(Root Mean Square Error,RMSE)是衡量预测值与真实值之间差异的常用指标。在Python中,可以使用以下代码计算均方根误差:
```python
import numpy as np
def rmse(predictions, targets):
return np.sqrt(((predictions - targets) ** 2).mean())
# 示例
predictions = np.array([1, 2, 3])
targets = np.array([2, 3, 4])
print(rmse(predictions, targets)) # 输出0.816496580927726
```
在上面的示例中,我们首先导入NumPy库,然后定义了一个`rmse()`函数,该函数接受两个参数:预测值和真实值。接下来,我们使用NumPy的广播机制计算预测值与真实值之间的差异的平方,并取平均数。最后,我们再对平均数取平方根,得到均方根误差。