我希望在Numpy中使用一个lile /一个操作员来完成此操作。 一维向量和矩阵之间的常规numpy减法将像这样工作:
weights = np.array([[2,3,0], [10,11,12], [1,2,4] , [10,11,12]], dtype = np.float)
inputs = np.array([1,2,3] , dtype = np.float)
print(inputs - weights)
结果是:
[[-1. -1. 3.]
[-9. -9. -9.]
[ 0. 0. -1.]
[-9. -9. -9.]]
包含输入-weights [0]和输入-weights [1]的减法
我正在寻找一种方法来使用像二维数组这样的运算符:
inputs = np.array([[1,2,3],[2,3,4],[7,8,9],[4,5,4]] , dtype = np.float)
weights = np.array([[2,3,0], [10,11,12], [1,2,4] , [10,11,12]], dtype = np.float)
#inputs - weights would be elementwise substraction
output = [i - weights for i in inputs]
print(output)
但这会在Python中创建一个循环,如何使用numpy数组正确地做到这一点?
答案 0 :(得分:2)
您可以使用np.expand_dims(inputs, axis=1)
扩展输入,使其具有(4, 1, 3)
的形状,因此当您广播减法时,它将按照您想要的方式工作:
import numpy as np
inputs = np.array([[1,2,3], [2,3,4], [7,8,9], [4,5,4]] , dtype = np.float)
weights = np.array([[2,3,0], [10,11,12], [1,2,4], [10,11,12]], dtype = np.float)
np.expand_dims(inputs, axis=1) - weights
结果
array([[[-1., -1., 3.],
[-9., -9., -9.],
[ 0., 0., -1.],
[-9., -9., -9.]],
[[ 0., 0., 4.],
[-8., -8., -8.],
[ 1., 1., 0.],
[-8., -8., -8.]],
[[ 5., 5., 9.],
[-3., -3., -3.],
[ 6., 6., 5.],
[-3., -3., -3.]],
[[ 2., 2., 4.],
[-6., -6., -8.],
[ 3., 3., 0.],
[-6., -6., -8.]]])