我有一个值数组
数据= [1,2,3,4,5]
我想生成一个20000个条目的样本,以使其随时间变化遵循数字趋势,因此最初有5个可用,并且随时间减少到1。
我正试图通过以下方式实现这一目标:
def random_iti(start, end, starting_prob = 1.0, ending_prob = 0.1, num_samples = 20000):
start = start
end = end
# Get days between `start` and `end`
num = (end - start)
linear_probabilities = expon.cdf(np.linspace(starting_prob, ending_prob, num), scale = 0.3)
# normalize probabilities so they add up to 1
linear_probabilities /= np.sum(linear_probabilities)
rand_days = np.random.choice(num, size = num_samples, replace = True,
p = linear_probabilities)
rand = [(start + int(rand_days))]
# return list of date strings
return rand
num_iti = random_iti(1, 5, starting_prob = 1.0, ending_prob = 0.1, num_samples=sample_count)
但是,运行这段代码给了我:
TypeError:只有大小为1的数组可以转换为Python标量
任何人都可以就这里的问题以及为实现此目标需要做什么而提出建议。
答案 0 :(得分:0)
我很确定您将需要循环并分别做出每个随机选择; np.random.choice
将对每个样本使用相同的权重。
无论如何,都会发生错误,因为rand_days
是20000个值的数组。调用int
毫无意义。使用.astype
方法完成整个数组的转换-但它们应该已经是整数,因为它们是从np.arange(num)
采样的。 (顺便说一句:这也是一个错误-我们有start = 1
和end = 5
,所以num = 4
-这意味着可能的值将是{{1} }和不是 [0, 1, 2, 3]
。)
您在这里4
想要的转换只是:rand = [(start + int(rand_days))]
。但是我们可以改用更简洁的方法:不传递数字作为rand = start + rand_days
的第一个参数,而是传递实际的样本集:np.random.choice
(同样,范围不包含第二个端点)。或者,而不是传递np.arange(start, end+1)
和start
参数,而是直接传递该范围并直接在函数中使用-这样可以为您提供更多的自定义功能,因此您可以从喜欢的任何数据集中进行采样。