错误:random_sample()最多接受1个位置参数(给定2个)

2024-04-20 06:13:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我对random.sample函数有问题。代码如下:

import random
import numpy as np


simulateData = np.random.normal(30, 2, 10000)

meanValues = np.zeros(1000)

for i in range(1000):


    dRange = range(0, len(simulateData))
    randIndex = np.random.sample(dRange, 30)
    randIndex.sort()
    rand = [simulateData[j] for j in randIndex]
    meanValues[i] = rand.mean()

这是错误:

TypeError                                 Traceback (most recent call last)
<ipython-input-368-92c8d9b7ecb0> in <module>()
 20 
 21     dRange = range(0, len(simulateData))
---> 22     randIndex = np.random.sample(dRange, 30)
 23     randIndex.sort()
 24     rand = [simulateData[i] for i in randIndex]

mtrand.pyx in mtrand.RandomState.random_sample   (numpy\random\mtrand\mtrand.c:10022)()

TypeError: random_sample() takes at most 1 positional argument (2 given)

我发现了一些过去的参考资料,其中这样的错误被认为是通过改变导入顺序来解决的,就像我上面的例子(随机的,在numpy之前)。假设在导入过程中,随机模块会以某种方式被覆盖,而我无法想象为什么在高级语言中会这样。然而,在我的情况下,它没有工作。我尝试了所有可能的变化,但没有找到解决办法

问题本身就是试图引导:从初始分布中获取随机样本(大小相等),并测量平均值和标准差

我很困惑,尤其是因为本该有效的解决方案没有成功。我有Python 2.7

求求你,救命


Tags: sampleinimportnumpyforlennprange
2条回答

问题是你使用了错误的模块。出于您的目的,您需要使用random.sample()而不是np.random.sample()。同时,在代码的最后一行中,您正在使用mean函数和一个应该更正的列表。

更正代码:

import random
import numpy as np


simulateData = np.random.normal(30, 2, 10000)

meanValues = np.zeros(1000)

for i in range(1000):


    dRange = range(0, len(simulateData))
    randIndex = random.sample(dRange, 30)
    randIndex.sort()
    rand = [simulateData[j] for j in randIndex]
    meanValues[i] = np.asarray(rand).mean()

我猜你把^{}^{}搞混了-

np.random.sample(size=None) - Return random floats in the half-open interval [0.0, 1.0).
size : int or tuple of ints, optional Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are drawn. Default is None, in which case a single value is returned.

random.sample(population, k) - Return a k length list of unique elements chosen from the population sequence. Used for random sampling without replacement.

您正在使用np.random.sample,但试图将参数作为random.sample传递给它。我想你想用random.sample,如果是这样的话,你应该像-

randIndex = random.sample(dRange, 30)

相关问题 更多 >