初学者python和montecarlo

问题描述

我在遵循所有montecarlo教程时遇到了麻烦,因为它们似乎已开始发展为我所遵循。我有几个月的python经验。到目前为止,我还无法找到任何基础知识。任何与montecarlo和python的基础知识有关的提示链接都很棒。

我正在寻找一个简单的蒙特卡洛模拟。一种模拟将涉及从分布中选择事件1的随机结果,然后分配分数。然后是事件2的另一个随机结果,依此类推。因此,运行1次SIM卡会给我3分。在此先感谢您的任何帮助

我将尝试在更大的数据集上朗读sim约10000次。我应该在numpy中尝试这样做吗?

概率分布

         outcome 1  outcome 2  outcome 3  outcome 4  outcome 5
event 1        0.1        0.2        0.5        0.6          1
event 2        0.1        0.3        0.4        0.7          1
event 3        0.1        0.5        0.6        0.7          1

得分

         outcome 1  outcome 2  outcome 3  outcome 4  outcome 5
score 1        100        400        200        600        100
score 2        200        600        300        700        500
score 3        400        100        500        300        200

解决方法

您正在寻找什么吗?

import numpy as np


if __name__ == "__main__":
    n_events = 3
    n_scores = 3
    n_outcomes = 5

    events = np.random.random((n_events,n_outcomes))
    scores = np.random.random((n_scores,n_outcomes))

    print("events",events.shape,events,"\n")
    print("scores",scores.shape,scores,"\n")

    run_scores = np.zeros(n_events)
    for run_idx in range(n_events):
        selected_idx = np.random.choice(n_outcomes,1)
        run_scores[run_idx] = scores[run_idx][selected_idx]

    print("run_scores",run_scores.shape,run_scores)
,

在处理随机仿真问题时,python中的random模块特别有用。您可以使用random.choices()函数来模拟上述实验。

通过choices()函数,您可以指定结果和相应的权重以及要运行的模拟次数。该函数返回结果列表。我们可以使用collections.Counter对象将结果制成表格并以字典形式获取。

from random import choices
from collections import Counter

"""
         outcome 1  outcome 2  outcome 3  outcome 4  outcome 5
event 1        0.1        0.2        0.5        0.6          1
"""
# outcomes and weights for event 1 as per the probability distribution you provided
outcomes = [1,2,3,4,5]
cumulative_weights = [0.1,0.2,0.5,0.6,1]
num_simulations = 10000

scores_list = choices(population=outcomes,cum_weights=cumulative_weights,k=num_simulations)

# Use a Counter to tabulate our results. This will give us a dict-like object
scores = Counter(scores_list)

for outcome in outcomes:
    print("Outcome {},Score: {}".format(outcome,scores[outcome]))

# Output ->>
# Outcome 1,Score: 1022
# Outcome 2,Score: 1009
# Outcome 3,Score: 2983
# Outcome 4,Score: 1045
# Outcome 5,Score: 3941

上面的代码示例演示了如何对一个事件运行10,000个模拟。根据需要使用多组结果/权重。