0

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!

Loading Zone
  • 177
  • 2
  • 12
  • X and theta1 are not compatible shapes. One is (50,), the other (400,). The product X*theta1 in your function makes no sense. – Ryan Walker Aug 17 '17 at 01:01
  • `T1` and `T2`, as produced by `meshgrid` are 2d arrays, (400,400). How do you expect them to interact with the 1d `X` and `Y` (of length 50). You have tell us what you expect. – hpaulj Aug 17 '17 at 02:01
  • Thank you for your comments. 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). Does that make sense? Thank you! – Loading Zone Aug 17 '17 at 13:54

1 Answers1

0

For anyone who might come here from a Google search (as I did), there is a way to actually solve this using numpy vectorize() method:

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)
vJ = np.vectorize(J)   #Just add this
Z = vJ(T1,T2)

However, as it says in the documentation, it's essentially a for loop, so I would doubt its performance on large data.

bukovskiy
  • 16
  • 3