下面的for循环用于为15 varuabel创建所有可能的权重组合,但是,我只需要总变量=1的组合,但是,循环太大了,它运行了11个小时,仍然没有完成,因此代码可以在循环后执行行,并获得总和=1的组合,有没有办法在循环中设置条件
import pandas as pd, numpy, itertools
w1, w2, w3, w4, w5, w6, w7, w8, w9, w10, w11, w12, w13, w14, w15 = (
list(
numpy.arange(0, 11, 1)/10
) for i in range(15)
)
comb_list = [w1, w2, w3, w4, w5, w6, w7, w8, w9, w10, w11, w12, w13, w14, w15]
weights_df = pd.DataFrame(
columns = ['w1', 'w2', 'w3', 'w4', 'w5', 'w6', 'w7', 'w8', 'w9', 'w10', 'w11', 'w12', 'w13', 'w14', 'w15']
)
for weights in itertools.product(*comb_list):
weights_df.loc[len(weights_df)] = weights
weights_df.loc[:,'total_weight'] = (weights_df['w1']
+ weights_df['w2'] + weights_df['w3']
+ weights_df['w4'] + weights_df['w5']
+ weights_df['w6'] + weights_df['w7']
+ weights_df['w8'] + weights_df['w9']
+ weights_df['10'] + weights_df['w11']
+ weights_df['w12'] + weights_df['w13']
+ weights_df['w14'] + weights_df['w15'])
weights_df = weights_df[weights_df['total_weight'] == 1]
索赔
此问题可以在25秒内解决,而不是在11小时内解决,如下所示
代码
测试
输出
发电机版本
在这种情况下,我们为权重创建了一个生成器,它消除了存储所有1.9M权重向量的必要性,如下所示
用法
共有十五个列表,每个列表包含十一个(0-10个)元素。你得到的是所有这些的笛卡尔积
这是您迭代的11^15项。大约4千5百万。
当然,您可以在for循环中移动测试,但我认为这不足以使这个脚本实用
你也可以把你的循环分解成一个15倍的嵌套循环,每个级别都有一个过滤器;我希望这能在运行时给您带来一个数量级的改进。但我认为这还不够
你需要重新思考并抽象地考虑这个问题,找出一些计算你正在计算的东西的方法。p>相关问题 更多 >
编程相关推荐