用户定义函数:操作数不能一起广播

User defined function: operands could not be broadcast together

我正在处理这段代码。

我明白 ValueError 清楚地指出了问题所在。我想知道是否有解决我的问题的好方法。那就是设计一个可以采用 (400,400) 数组的函数,并且对于该二维数组中的每个单个元素 (t1,t2),我想执行 J(t1,t2) 函数,它涉及一个长度为 50 的一维数组。 那有意义吗?谢谢!

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) 

写个循环肯定能算出Z。但我想知道是否有解决它的好方法。谢谢!

对于可能通过 Google 搜索来到这里的任何人(就像我一样),有一种方法可以使用 numpy vectorize() 方法实际解决这个问题:

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)

但是,正如文档中所说,它本质上是一个for循环,所以我怀疑它在大数据上的性能。