如何在Numpy中完成这个棘手的细分:

2024-10-02 02:33:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我想知道如何在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.]]

包含输入-权重[0],输入-权重[1]的减法

我在寻找一种方法,用一个操作符来实现2d数组,比如:

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数组呢


Tags: numpyoutputnp数组floatarray向量权重
1条回答
网友
1楼 · 发布于 2024-10-02 02:33:16

您可以使用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.]]])

相关问题 更多 >

    热门问题