用户定义的功能:操作数无法一起广播

时间:2017-08-17 00:50:21

标签: python numpy numpy-broadcasting

我正在研究这段代码。

我理解ValueError清楚地表明问题是什么。我想知道我的问题是否有好的方法。那就是设计一个可以采用(400,400)数组的函数,对于那个2d数组中的每个单元素(t1,t2),我想执行J(t1,t2)函数,它涉及一个长度为50的1d数组。 那有意义吗?谢谢!

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.但我想知道是否有一个好方法。谢谢!

1 个答案:

答案 0 :(得分:0)

对于任何可能通过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循环,因此我会怀疑其在大数据上的性能。

相关问题