【发布时间】:2019-03-13 08:11:06
【问题描述】:
以下代码模拟了一个可以随时采样 3 个不同状态的系统,这些状态之间的恒定转移概率由矩阵 prob_nor 给出。因此,trace 中的每个点都依赖于之前的状态。
n_states, n_frames = 3, 1000
state_val = np.linspace(0, 1, n_states)
prob = np.random.randint(1, 10, size=(n_states,)*2)
prob[np.diag_indices(n_states)] += 50
prob_nor = prob/prob.sum(1)[:,None] # transition probability matrix,
# row sum normalized to 1.0
state_idx = range(n_states) # states is a list of integers 0, 1, 2...
current_state = np.random.choice(state_idx)
trace = []
sigma = 0.1
for _ in range(n_frames):
trace.append(np.random.normal(loc=state_val[current_state], scale=sigma))
current_state = np.random.choice(state_idx, p=prob_nor[current_state, :])
上面代码中的循环使它运行得很慢,特别是当我必须对数百万个数据点进行建模时。有没有办法对其进行矢量化/加速?
【问题讨论】:
-
'vectorize' 在最严格的
numpy意义上意味着在编译代码中对整个数组进行操作。它将迭代移动到编译级别,不受 Python 代码的控制。所以一个固有的顺序、迭代的问题不能被“向量化”。一次为一个值重复调用这些np.random函数比为多个值调用一次要慢得多。 -
最近有人问为什么 Python
random.random函数比np.random函数快。一次用于一个值时,它们会更快。 -
@hpaulj 我想你指的是stackoverflow.com/a/50790263/8033585
-
"...我必须对数百万个数据点进行建模" 对于您感兴趣的问题,
n_states和n_frames的典型值是多少? -
@WarrenWeckesser
n_states大约是 2-10,但偶尔转移概率矩阵 (prob_nor) 是稀疏的,在这种情况下n_states是 10-100。n_frames1e3-1e6。trace必须生成 1000 次
标签: python numpy vectorization