Home > Net >  Vector product of a list of array, array by array
Vector product of a list of array, array by array

Time:11-23

I've a list of array and each array contains 5 softmax arrays. I want, as an output, a final list with only one element per array, which is the product of all the 5 arrays.

 vals_pred = [res.iloc[i]['y_pred'][0:5] for i in range(len(res))
             if len(res.iloc[i]['y_pred']) > lookahead]

res is a dataframe. This is an example of what is found within the list.

array([[1.34866089e-01, 5.28018773e-02, 2.23537564e-01, 4.62821350e-02,
    8.76934379e-02, 4.26145524e-01, 5.53494925e-03, 2.31384877e-02],
   [1.10163569e-01, 7.80740231e-02, 5.52961051e-01, 4.57449956e-03,
    4.64441329e-02, 2.07768157e-01, 1.45530776e-05, 4.66483916e-18],
   [1.82191223e-01, 1.10042050e-01, 3.27700675e-01, 3.38860601e-03,
    1.07456036e-01, 2.69037366e-01, 1.84074364e-04, 3.74613562e-13],
   [1.80145595e-02, 7.61333853e-03, 8.86637151e-01, 1.02691650e-02,
    2.46689599e-02, 5.27242124e-02, 7.26214203e-05, 2.64242381e-19],
   [5.62842265e-02, 1.42695876e-02, 8.42117667e-01, 1.62272118e-02,
    4.17451970e-02, 2.88727339e-02, 4.83323034e-04, 2.92075066e-13]],
  dtype=float32), array([[5.4129714e-04, 3.6672730e-02, 4.8940146e-06, 8.3479950e-05,
    6.5760143e-02, 1.6968355e-02, 8.7981069e-01, 1.5837120e-04],
   [2.1086331e-07, 1.4350067e-03, 1.6849227e-16, 8.4671612e-08,
    2.4794264e-07, 3.8307374e-03, 9.9473369e-01, 6.4219920e-24],
   [1.7740911e-04, 2.1856705e-02, 1.5427456e-11, 1.2592359e-08,
    2.0797092e-03, 3.5571402e-01, 6.2017220e-01, 3.4836909e-20],
   [1.7687974e-07, 4.4844073e-05, 9.6608031e-14, 4.5008356e-08,
    1.0638499e-03, 1.0105613e-04, 9.9878997e-01, 4.8578437e-24],
   [6.6033276e-11, 5.1952496e-09, 5.8398927e-21, 4.5752773e-13,
    5.2611317e-06, 2.4885111e-07, 9.9999452e-01, 2.5868782e-10]],
  dtype=float32)

The desired output is a list similarly composed of 2 arrays (in this example case), but each array is the multiplication of the 5 arrays (element by element) that contains the list element. Next I need to get the argmax.

Any ideas on how I could do this? I can use any Python library

CodePudding user response:

Assuming your list is named array_list, you can use a list comprehension and numpy.prod:

import numpy as np
[np.prod(a) for a in array_list]

output: [1.2981583896975622e-116, 2.2208998715549213e-267]

Or maybe you want the product only on the fist axis per array:

[np.prod(a, axis=0) for a in array_list]

output:

[array([2.74459685e-06, 4.92834563e-08, 3.02441299e-02, 1.19552067e-10,
        4.50698513e-07, 3.62616474e-05, 5.20432043e-19, 3.12070056e-63]),
 array([2.36512231e-31, 2.67974413e-19, 7.17724310e-66, 1.83289538e-39,
        1.89791218e-19, 5.81467373e-16, 5.42100925e-01, 4.45251202e-80])]

And to get the argmax:

[np.argmax(np.prod(a, axis=0)) for a in array_list]

output: [2, 6]

  • Related