Vega
Vega

Reputation: 2930

How to calculate RMSE without numpy?

Just did a coding challenge for a job.

One task was to calculate the Root Mean Square Error between predicted and observed values.

Predicted:

[4, 25, 0.75, 11]

Observed:

[3, 21, -1.25, 13]

Result would be 2.5.

numpy was not available. I failed that task but I wonder how one can do this with pure Python 3?

Upvotes: 0

Views: 1508

Answers (2)

Theo
Theo

Reputation: 91

Here is how I would do it:

pred = [4, 25, 0.75, 11]
observed = [3, 21, -1.25, 13]
error = [(p - o) for p, o in zip(pred, observed)]
square_error = [e**2 for e in error]
mean_square_error = sum(square_error)/len(square_error)
root_mean_square_error = mean_square_error**0.5

Upvotes: 4

Talha Anwar
Talha Anwar

Reputation: 2959

a=[4, 25, 0.75, 11]
b=[3, 21, -1.25, 13]
c=[]

First loop both list and subtract them element wise and take square. Append it to another list

for l1, l2 in zip(b,a):
     c.append((l1-l2)**2)

take sum of that list and divided by the length of the list. Then take the square root.

(sum(c)/len(c))**(1/2)

Upvotes: 0

Related Questions