Yi=[1,2,3,4,5,6]
Yi_hat=[1.2,2.1,2.9,4.3,5,6.5]
n=[1,2,3,4,5,6]
z=0
for i in n:
z+=((Yi[i]-Yi_hat[i])**2)
MSE=1/len(n)*(z)
Asked
Active
Viewed 49 times
-5

Dani Mesejo
- 61,499
- 6
- 49
- 76

ringoban
- 5
- 1
-
`Yi[6]` does not exist. – timgeb Nov 08 '18 at 22:00
-
1Python iterators are 0 indexed. As your code is currently, `i` takes values in the list `n`. So, in the first iter of the for loop, `i` is 1, in the second iter `i` is 2 and so on. But since you want to use `i` to index into other lists, you should probably just define `n = 6` instead of the list, and change the loop to `for i in range(n): ...` – Sanyam Mehra Nov 08 '18 at 22:05
-
1also convert `len(n)` to `float(len(n))` otherwise you will keep getting zero as a result – mad_ Nov 08 '18 at 22:08
2 Answers
0
In Python indexing starts from 0. So list with 6 elements has no index of 6 as the for loop get n[5]. With the list:
n=[0,1,2,3,4,5]
it should work.
Yi = [1, 2, 3, 4, 5, 6]
Yi_hat = [1.2, 2.1, 2.9, 4.3, 5, 6.5]
n = [0, 1, 2, 3, 4, 5]
z = 0
for i in n:
z += (Yi[i] - Yi_hat[i]) ** 2
MSE= 1. / len(n) * z
Note 1: 1., which means treats 1 as float, so you get the required float result in Python.
Note 2.:
I would prefer to use:
for i in range(len(Yi)):
instead of n.
Yi = [1, 2, 3, 4, 5, 6]
Yi_hat = [1.2, 2.1, 2.9, 4.3, 5, 6.5]
z = 0
for i in range(len(Yi)):
z += (Yi[i] - Yi_hat[i]) ** 2
MSE= 1. / len(Yi) * z
Yet another way of for looping:
Yis = [1, 2, 3, 4, 5, 6]
Yi_hats = [1.2, 2.1, 2.9, 4.3, 5, 6.5]
z = 0
for Yi, Yi_hat in zip(Yis, Yi_hats):
z += (Yi - Yi_hat) ** 2
MSE= 1. / len(Yis) * z

Geeocode
- 5,705
- 3
- 20
- 34
-
-
@mad_ Of course you can but you can do as op wanted to as well and I don't wanted to alter the object of his question too much. – Geeocode Nov 08 '18 at 22:17
-
I would recommend using range which has greater performance and does NOT alter the object of the problem in any case. If you have make an effort posting it as an answer rather than comment then you can easily post an answer which can be useful for future readers as well – mad_ Nov 08 '18 at 22:20
-
@mad_ I made effort posting, because he was brand new here and I wanted to get some answer he can understand, if he wanted to learn and it was not for the future era. Anyway thanks for the comments, though I was in editing most time. – Geeocode Nov 08 '18 at 22:34
0
You can use numpy as well
import numpy as np
(1/float(len(Yi)))*sum(np.square(np.array(Yi) - np.array(Yi_hat)))

mad_
- 8,121
- 2
- 25
- 40
-
Use np.sum() as it much faster as sum() if you are using numpy arrays – Geeocode Nov 08 '18 at 22:38