【问题标题】:How to calculate RMSE using IPython/NumPy?如何使用 IPython/NumPy 计算 RMSE?
【发布时间】:2014-03-22 11:18:30
【问题描述】:

我在尝试使用 NumPy 在 IPython 中计算均方根误差时遇到问题。我很确定这个函数是正确的,但是当我尝试输入值时,它给了我以下 TypeError 消息:

TypeError: unsupported operand type(s) for -: 'tuple' and 'tuple'

这是我的代码:

import numpy as np

def rmse(predictions, targets):
    return np.sqrt(((predictions - targets) ** 2).mean())

print rmse((2,2,3),(0,2,6))

显然我的输入有问题。放入rmse():行之前需要建立数组吗?

【问题讨论】:

标签: python numpy jupyter-notebook


【解决方案1】:

在rmse函数中,试试:

return np.sqrt(np.mean((predictions-targets)**2))

【讨论】:

    【解决方案2】:

    它说没有为元组定义减法。

    试试

    print rmse(np.array([2,2,3]), np.array([0,2,6]))
    

    改为。

    【讨论】:

      【解决方案3】:

      Google formulas 开始,RMSD 或 RSME 是根据测量数据和每次测量的预测数据或地面实况数据计算得出的。

      RMSD      = root-mean-square deviation (error)
      i         = variable i
      N         = number of non-missing data points
      x_i       = actual observations time series
      \hat{x}_i = estimated time series
      

      这是它使用快速范数函数的 numpy 实现:

      rmse = np.linalg.norm(measured - truth) / np.sqrt(len(thruth))
      

      measuredtruth 必须具有相同的形状。

      【讨论】:

      • 应该是/sqrt(len(thruth))
      • 已修复。谢谢。
      • 遗憾的是,如果使用numba,它并不是最快的。请参阅my answer 进行基准测试
      【解决方案4】:

      正如@miladiouss 所说,np.linalg.norm(y1 - y2) / np.sqrt(len(y1)) 是纯 numpy 最快的。

      但是,如果你也使用numba,那已经不是最快的了。使用小型时间序列数据(大约 8 个数据点)进行基准测试。

      import numba
      import numpy as np
      
      @jit(nopython=True)
      def rmse(y1, y2):
          return np.sqrt(((y1-y2)**2).mean())
      # 851 ns ± 1.05 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
      
      @jit(nopython=True)
      def rmse_norm(y1, y2):
          return np.linalg.norm(y1 - y2) / np.sqrt(len(y1))
      # 1.17 µs ± 3.44 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-10-26
        • 1970-01-01
        • 2019-07-03
        • 1970-01-01
        • 2018-08-22
        • 2016-06-25
        • 1970-01-01
        • 2018-10-20
        相关资源
        最近更新 更多