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

问题描述 投票:0回答:1

我正在研究此代码。

我了解ValueError明确指出的问题所在。我想知道是否有解决我问题的好方法。那就是设计一个函数,该函数可以采用(400,400)数组,对于该2d数组中的每个单个元素(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。但是我想知道是否有一个好的方法。谢谢!

python numpy numpy-broadcasting
1个回答
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循环,所以我会怀疑它在大数据上的性能。

© www.soinside.com 2019 - 2024. All rights reserved.