0
回答
Python3使用累计概率抽签出现死循环的问题
滴滴云服务器,限时包月0.9元,为开发者而生>>>   

问题描述如下:从5×9的二维矩阵中根据各自元素的不同概率p进行随机抽样,共抽取N=15个不重复的下标值,概率p的二维数组已经进行硬编码,和为1,但在一些情况下会陷入while的elif的语句内的死循环,我检查、修改了好几次,以为是随机数种子问题,但是尝试每次进行随机取值时候都重置随机数种子为random.seed(time.time())依旧会出现问题,经多次更正无果,来向大家请教一下问题出在哪里?并且为什么会这样,原因是什么?
 

import random
import time


def pick_pisotions(how_many):
    result_positions = []
    p = [[0, 0, 0, 0, 0, 0, 0, 0, 0],
         [0, 0, 0.09200879765395895, 0.10227272727272728, 0.0988514173998045, 0.010019550342130987, 0, 0, 0],
         [0, 0, 0.0024437927663734115, 0.17424242424242423, 0.44477028347996095, 0.07539100684261975, 0, 0, 0],
         [0, 0, 0, 0, 0, 0, 0, 0, 0],
         [0, 0, 0, 0, 0, 0, 0, 0, 0]]
    temp_position_list = []  # tiff子图的二维坐标
    temp_p_list = []  # tiff子图的被选中概率
    for row in range(5):
        for col in range(9):
            temp_position_list.append((row, col))
            temp_p_list.append(p[row][col])
    print("sum =", sum(temp_p_list))

    seed_index = 0
    while True:  # 选取N个不重复数据
        seed_index += 1
        # random.seed(time.time())
        random.seed(seed_index)
        length_of_result = len(result_positions)
        if length_of_result == how_many:  # 选够了
            return result_positions
        elif 0 <= length_of_result < how_many:  # 还不够
            random_number = random.uniform(0, 1)
            cumulative_probability = 0.0
            for item_position, item_probability in zip(temp_position_list, temp_p_list):
                cumulative_probability += item_probability  #
                print("测试random_number = ", random_number)
                print("测试cumulative_probability = ", cumulative_probability)

                if random_number <= cumulative_probability:
                    result_positions.append(item_position)
                    result_positions = list(set(result_positions))  #
                    break
                else:
                    print("测试random_number > cumulative_probability")
                    # pass
        else:
            print("错误:pick_tiffs()")


pick_pisotions(15)

 

<无标签>
举报
HiJacker
发帖于5个月前 0回/24阅
顶部