python ValueError:使用序列设置数组元素

python ValueError:使用序列设置数组元素,python,Python,我从二维分布生成了一个随机样本,但是我得到了这个运行时错误。有人能告诉我如何修复这个错误吗? 这是错误消息: ValueError回溯最近一次呼叫last 在里面 25是否进行接受/拒绝比较 26如果x27个样品[已接受]=x,y 28接受+=1 二十九 ValueError:使用序列设置数组元素 P = lambda x, y: np.exp(-x**2-y**2-x**2*y**2) # domain limits xmin = -2 # the lower limit of our do

我从二维分布生成了一个随机样本,但是我得到了这个运行时错误。有人能告诉我如何修复这个错误吗? 这是错误消息:

ValueError回溯最近一次呼叫last 在里面 25是否进行接受/拒绝比较 26如果x27个样品[已接受]=x,y 28接受+=1 二十九

ValueError:使用序列设置数组元素

P = lambda x, y: np.exp(-x**2-y**2-x**2*y**2)

# domain limits
xmin = -2 # the lower limit of our domain
xmax = 2 # the upper limit of our domain

# range limit (supremum) for y
ymin = -2
ymax = 2

N = 10000 # the total of samples we wish to generate
accepted = 0 # the number of accepted samples
samples = np.zeros(N)
count = 0 # the total count of proposals

# generation loop
while (accepted < N):

    # pick a uniform number on [xmin, xmax) (e.g. 0...10)
    x = np.random.uniform(xmin, xmax)

    # pick a uniform number on [0, ymax)
    y = np.random.uniform(ymin,ymax)

    # Do the accept/reject comparison
    if x < P(x,y):
        samples[accepted] = x,y
        accepted += 1

    count +=1

print count, accepted

# get the histogram info
hinfo = np.histogram(samples,30)

# plot the histogram
plt.hist(samples,bins=30, label=u'Samples', alpha=0.5);

# plot our (normalized) function
xvals=np.linspace(xmin, xmax, 1000)
plt.plot(xvals, hinfo[0][0]*P(xvals), 'r', label=u'P(x)')

# turn on the legend
plt.legend()
这里的台词是:

samples[accepted] = x,y
这就是问题所在。样本类型为np.ndarray,具有特定的数据类型。可能是np.float。numpy期望一个数字,但得到一个元组,y。您可能打算创建一个二维阵列:

samples = np.zeros((N,2))
那么你的代码应该可以工作了,尽管我还没有深入了解它到底在做什么

旁白 我看到你在N上循环,同时生成数字。这是从另一种编程语言学习numpy/scipy的典型例子。我想敦促你们以阵列的方式思考。这更优雅,速度更快:

x = np.random.uniform(xmin,xmax,(N,2))
y = np.random.uniform(ymin,ymax,(N,2))
accepted = x < P(x,y)
samples[accepted] = x[accepted]

上述代码将替换整个while循环。

请在问题中包含完整的错误消息。