Product between scalar and array

Asked

Viewed 529 times

3

I have a vector:

a = [0.4850045, 0.45512111]

and a vector of an element:

b = [-0.03116616]

I’m trying to multiply the vector content b, that is to say, b[0], by vector a, but instead of getting :

b[0] * a == [-0.01511573, -0.01418438]

I’m getting:

b[0] * a == [[-0.01511573, -0.01418438]
             [-0.01511573, -0.01418438]]

Here’s a full example of the problem I’m facing:

import numpy as np

a = np.array([[0.3], [-0.1]])
b = np.zeros(a.shape)
c = np.array([0.5249765])
d = np.array([0.4850045, 0.45512111])
y = np.array([0.4])
error = y - c 
f = error * c * (1 - c)

b += f[0] * d.T

The result is the following error:

Valueerror: non-broadcastable output operand with Shape (2,1) doesn’t match the broadcast Shape (2,2)

  • Is using some library, like Numpy?

  • Have you tried it b = b + f[0]*d.T ?

  • Already Isac, it works but the result is a matrix (2,2) and precise that is (2,1)

  • You say that b[0] * a does not return the result you expect, but the return is expected, your problem is not where you say it is, but rather elsewhere in your complete example (that should be a [mcve]).

3 answers

2

You can use a loop to perform the operation, for example, follows an algorithm with for loop and with the application of enumerate method:

a = [ 0.4850045, 0.45512111]
b = [-0.03116616]

for i, j in enumerate(a):
    a[i] = j*b[0]

0

If you wish to resolve this issue using the library numpy, can use the following algorithm...

import numpy as np

a = np.array([0.4850045, 0.45512111])
b = np.array([-0.03116616])

prod = (a * b)

print(f'O produto escalar é: {prod}')

When running this algorithm the result will be...

[-0.01511573 -0.01418438]

0

If you do not want to use numpy you can solve with list comprehension:

a = [0.4850045, 0.45512111]
b = [-0.03116616]

[(x * y) for x in a for y in b]

Exit:

[-0.015115727847719999, -0.0141843773336376]

Browser other questions tagged

You are not signed in. Login or sign up in order to post.