I am working on this code.
I understand what the problem is which is indicated clearly by the ValueError. I want to know if there is a good way around my problem. That is to design a function that can take a (400,400) array and for each single element (t1,t2) in that 2d array, I want to perform the J(t1,t2) function, which involves a 1d array of length 50. Does that make sense? Thank you!
import numpy as np
import matplotlib.pylab as plt
X = np.linspace(0,10)
a = 1
b = 2
Y = a + b * X + np.random.normal(1,0.1,X.shape)*np.random.normal(20,0.1,X.shape)
def J(theta0, theta1):
return np.sum((theta0 + X*theta1 - Y)**2)
delta = 0.025
theta0 = np.arange(-5,5,delta)
theta1 = np.arange(-5,5,delta)
T1, T2 = np.meshgrid(theta0, theta1)
Z = J(T1,T2)
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-28-9956753b05ce> in <module>()
6 theta1 = np.arange(-5,5,delta)
7 T1, T2 = np.meshgrid(theta0, theta1)
----> 8 Z = J(T1,T2)
9
<ipython-input-28-9956753b05ce> in J(theta0, theta1)
1 def J(theta0, theta1):
----> 2 return np.sum((theta0 + X*theta1 - Y)**2)
3
4 delta = 0.025
5 theta0 = np.arange(-5,5,delta)
ValueError: operands could not be broadcast together with shapes (50,) (400,400)
I can definitely calculate Z by writing a loop. But I was wondering if there is a good way around it. Thanks!