简体   繁体   中英

Python big matrix probability calculation

Assume given large matrix displays an inventory of products in a store:

在此处输入图片说明

The matrix is represented by the following data structure:

{'products': [['milk'],
  ['bread'],
  ['eggs'],
  ['tomatoes'],
  ['cucumbers'],
  ['nuts'],
  ['cheese'], ...],
 'store_a': {0: 40,
  1: 415,
  5: 55,
  6: 7},
 'store_b': {1: 45,
  3: 44,
  5: 451,
  6: 451},       
 'store_c': {0: 455, 4: 54}}

That is, each inventory of a product in a store is represented by by the index of products list. For example milk inventory in store_a is 40.

The goal is to find the probability of finding a particular product in the store. That is, get the following matrix:

在此处输入图片说明

Need to write a function that will get the data structure above and return the same structure, except that instead of the quantity, the probability calculation will display.

In the example above, the expected result is:

{'products': [['milk'],
  ['bread'],
  ['eggs'],
  ['tomatoes'],
  ['cucumbers'],
  ['nuts'],
  ['cheese'], ...],
 'store_a': {0: 0.0773694390715667,
  1: 0.802707930367505,
  5: 0.106382978723404,
  6: 0.0135396518375242},
 'store_b': {1: 0.0454086781029263,
  3: 0.0443995963673058,
  5: 0.455095862764884,
  6: 0.455095862764884},       
 'store_c': {0: 0.893909626719057, 
             4: 0.106090373280943}}

It should be borne in mind that this may be a very large matrix and therefore the calculation needs to be efficient.

Try that:

input={'products': [['milk'],
  ['bread'],
  ['eggs'],
  ['tomatoes'],
  ['cucumbers'],
  ['nuts'],
  ['cheese'], ...],
 'store_a': {0: 40,
  1: 415,
  5: 55,
  6: 7},
 'store_b': {1: 45,
  3: 44,
  5: 451,
  6: 451},       
 'store_c': {0: 455, 4: 54}}

for i in input:
    if i != "products":
        sum=0
        for j in input[i]:
            sum=sum+input[i][j]
        for j in input[i]:
            input[i][j]/=sum
print(input)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM