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

Tol*_*oly 6 python random indexing numpy 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()
Run Code Online (Sandbox Code Playgroud)

这是错误:

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)
Run Code Online (Sandbox Code Playgroud)

我找到了几个过去的引用,其中这样的错误据说通过改变导入顺序来解决,就像我上面的情况一样(随机,在numpy之前).据说随机模块在导入过程中会以某种方式被覆盖,而我无法想象为什么会出现在高级语言中.但在我的情况下它没有用.我尝试了所有可能的变化,但没有解决方案

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

我很困惑,特别是因为应该工作的解决方案没有.我有Python 2.7

请帮忙

Ana*_*mar 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) - 返回从种群序列中选择的独特元素的长度列表.用于无需更换的随机抽样.

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

randIndex = random.sample(dRange, 30)
Run Code Online (Sandbox Code Playgroud)


Jef*_*f G 4

您试图将两个参数 --dRange30-- 传递给该sample函数,但sample只允许一个参数。 以下是一些文档,其中提到了这一点:

random_sample(size=None)

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

Parameters
----------
size : int or tuple of ints, optional
Run Code Online (Sandbox Code Playgroud)

您的导入顺序应该不成问题。

要从数组中随机抽取 30 个样本,也许您需要numpy.choice

np.random.choice(dRange, 30)
Run Code Online (Sandbox Code Playgroud)