To sum vectors by weighing them with scalars
Use the variable number and chain to
I wrote the following code.
import numpy as np
from chain import Variable
import chain.functions as F
a=np.array([10],[100],[1000]], dtype=np.float32)# set of weights
x = np.array([1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype = np.float32)# collection of vectors
print sum(a*x)# weighted sum of vectors
a = Variable(a)
x = Variable(x)
print F.sum(a*x)
If it's Numpy, it's calculated correctly. If you convert it to Variable, you will get in trouble if it doesn't fit.
What code should I write?
Can you return the same result for numpy and chain?
Thank you for your cooperation.
python chainer
Use chain.functions.batch_matmul
.
>>print(a*x)
[[ 10. 20. 30.]
[ 400. 500. 600.]
[ 7000. 8000. 9000.]]
>>print(sum(a*x))
[ 7410. 8520. 9630.]
>> print (F.batch_matmul(a,x,transb=True).data)
[[[ 10. 20. 30.]]
[[ 400. 500. 600.]]
[[ 7000. 8000. 9000.]]]
>>print(sum(F.batch_matmul(a,x,transb=True).data))
[[ 7410. 8520. 9630.]]
>>print(F.sum(F.batch_matmul(a,x,transb=True).data),axis=0).data)#sum is also required on the chain side
[[ 7410. 8520. 9630.]]
You can see that the a*x and sum vectors have been calculated.
© 2024 OneMinuteCode. All rights reserved.