Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
553 views
in Technique[技术] by (71.8m points)

python - Multiply list of arrays by list of scalars and sum elements

I have a list of arrays (factors) that I want to first multiply by a list of scalars (weights) and then sum the elements of the product of each array. I have tried the following but I get an error. Any suggestion would be highly appreciated.

factors = np.array([[f1], [f2], [f3]])
weights = np.array([0.333, 0.333, 0.333])
prod = np.sum(factors.transpose()*weights)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Consider the following inputs

factors = np.array([[1, 2], [3, 4], [5, 6]])
weights = np.array([[2, 1, 0]]) # notice how this is a 2d array

First convert weights into a 2D "Vector" so that you can multiply each term

weights = weights.T # [[2], [1], [0]]

Then you can just simply multiply by using the __mul__ dunder

new_factors = weights * factors # [[2, 4],[3, 4],[0, 0]]

Then you can just use np.array.sum to sum each row

new_factors.sum(axis=1) 

The output is

array([6, 7, 0])

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...