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

时间:2015-09-15 03:50:43

标签: python numpy random indexing random-sample

我有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

请帮助

5 个答案:

答案 0 :(得分:5)

我想你会random.samplenp.random.sample()混淆 -

  

np.random.sample(size=None) - 在半开区间[0.0, 1.0)中返回随机浮点数   size:int或int的元组,可选             输出形状。如果给定的形状是例如(m,n,k),则绘制m * n * k个样本。默认值为None,在这种情况下返回单个值。

     

random.sample(population, k) - 返回从群体序列中选择的k个长度的唯一元素列表。用于无需替换的随机抽样。

您正在使用np.random.sample,但尝试将其作为random.sample传递。我想你想使用random.sample,如果是这样你应该像 -

那样使用它
randIndex = random.sample(dRange, 30)

答案 1 :(得分:3)

您正尝试将两个参数 - dRange30 - 传递给sample函数,但sample只允许一个参数。 Here's some of the documentation它说的是:

random_sample(size=None)

Return random floats in the half-open interval [0.0, 1.0).

Parameters
----------
size : int or tuple of ints, optional

导入的顺序应该不是问题。

要从数组中获取30个随机样本,可能需要numpy.choice代替:

np.random.choice(dRange, 30)

答案 2 :(得分:1)

问题是您使用的是错误的模块。出于您的目的,您需要使用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()

答案 3 :(得分:0)

你必须使用

&#13;
&#13;
np.random.randint(a,b)
&#13;
&#13;
&#13; 你正在使用错误的模块

答案 4 :(得分:0)

size参数可以是一个元组,所以我想您想要实现的是:

randIndex = np.random.random(size=(dRange, 30))
相关问题