【问题标题】:python-ValueError: setting an array element with a sequencepython-ValueError:使用序列设置数组元素
【发布时间】:2015-02-14 10:54:53
【问题描述】:

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


ValueError Traceback(最近一次调用最后一次) 在 () 25 # 做接受/拒绝比较 26 如果 x 27 个样本[接受] = x,y 28 接受 += 1 29

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()

【问题讨论】:

  • 请在您的问题中包含完整的错误信息。

标签: python


【解决方案1】:

这里的行:

samples[accepted] = x,y

是问题所在。 samples 是具有特定 dtype 的 np.ndarray 类型。可能是np.floatnumpy 期待一个数字,但得到一个 tuple(x,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 循环。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-04
    • 1970-01-01
    • 2011-06-08
    • 2018-08-04
    • 2019-08-04
    相关资源
    最近更新 更多