ValueError: Sample larger than population selecting samples from graph

自作多情 提交于 2021-02-07 18:43:21

问题


I am trying to randomly select n samples from a graph. In order to do so I create a list called X using the random.sample function like the following:

X= random.sample(range(graph.ecount()), numPosSamples)

The problem is that when numPosSamples is equal to graph.ecount() I receive the following error:

ValueError: Sample larger than population

Any help will be much appreciated. Thanks


回答1:


I'm not sure how numPosSamples is getting its value, but because random.sample does sampling without replacement, what is probably happening here is that numPosSamples is greater than the number of edges in your graph. As a result, Python raises the ValueError that you are seeing.

Either reduce the number of samples to less than the number of edges, or use a method of sampling that allows for sampling with replacement, such as a list comprehension with random.choice.




回答2:


You can add some logic that detects if your list if shorter than the number of samples you want.

For example:

a = list(range(10))
num_samples = 20
sample(a, num_samples if len(a) > num_samples else len(a))


来源:https://stackoverflow.com/questions/29760394/valueerror-sample-larger-than-population-selecting-samples-from-graph

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!