I recommend you use numpy arrays for this, that will be the easiest way. Either convert your tuples to arrays or just store them as arrays.
If you subtract numpy arrays, they will be subtracted elementwise. The same statement is true for squaring (which, btw, in Python is not ^2
but **2
). You will then have a list containg all the (y_t – f_t)**2. From there, you can just use numpys product to multiply all of these elements with each other, take the root and you’re done.
import numpy as np
def grmse(ft, yt):
N = len(ft)
prod = np.product( (ft-yt)**2 ) # do the product
return prod**(1/(2*N)) # return the (2N)th root
if __name__ == '__main__':
ft=np.array([2,3,4.5,6,4,3,2])
yt=np.array([2.1,4.2,4.5,7,3,2,2])
print(grmse(ft,yt))
Technically, if it doesn’t confuse you, you can actually rephrase this into one line:
def grmse(ft, yt):
return (np.product( (ft-yt)**2 ))**(1/(2*len(ft)))
Edit To say a little more, you could also use reduce together with a lambda expression, that would also work with lists without converting them. You would zip up your values (i.e. creating a list of the tuples (y_t, f_t)) and then do a list comprehension to get to the same point as before. Then take the product of the lists elements (with reduce). Reduce applies the operation, i.e. the multiplication we’re going to feed it, to the elements of the lists sequentially.
from functools import reduce
def grmse2(ft,yt):
prod_terms = [(x-y)**2 for x,y in zip(ft,yt)]
prod = reduce(lambda x, y: x * y, prod_terms, 1)
N = len(ft)
return prod**(1/(2*N))
Or again, in one line (maybe don’t do this, it’s just for show how awesome python is)
def grmse2(ft,yt):
return (reduce(lambda x,y:x*y, [(x-y)**2 for x,y in zip(ft,yt)], 1))**(1/(2*len(ft)))
I recommend you also try solving this only with basic python, i.e. no libraries, for learning purposes. Cheers!
3
solved geometric root mean squared error in python