在 tensorflow 和numpy 中矩阵的加法

本文通过Python的NumPy库展示了不同形状的矩阵相加操作。从简单的二维矩阵到多维张量,再到特定维度上的分块相加,详细阐述了矩阵在不同情况下的加法实现,包括一维向量与矩阵的逐元素相加,以及不同大小矩阵的对应元素相加。实例清晰地揭示了矩阵运算的规则和灵活性。
Am×n×..×km \times n \times ..\times km×n×..×k 和B1×k1\times k1×k 矩阵相加
相当于在最后一个维度上map 依次相加A[-s:] for s in rang(k)
import numpy as np 

a=np.array(range(3*4)).reshape([3,4])
b=np.array([0.2]*4)

print('a.shape=',a.shape)
print('b.shape=',b.shape)

print(a+b)

print('-'*20+'我是分割线'+'-'*20)
a=np.array(range(2*3*4)).reshape([2,3,4])
b=np.array([0.2]*4)

print('a.shape=',a.shape)
print('b.shape=',b.shape)

print(a+b)

输出

a.shape= (3, 4)
b.shape= (1, 4)
[[ 0.2  1.2  2.2  3.2]
 [ 4.2  5.2  6.2  7.2]
 [ 8.2  9.2 10.2 11.2]]
--------------------我是分割线--------------------
a.shape= (2, 3, 4)
b.shape= (1, 4)
[[[ 0.2  1.2  2.2  3.2]
  [ 4.2  5.2  6.2  7.2]
  [ 8.2  9.2 10.2 11.2]]

 [[12.2 13.2 14.2 15.2]
  [16.2 17.2 18.2 19.2]
  [20.2 21.2 22.2 23.2]]]
Am×n×..×p×km \times n \times ..\times p\times km×n×..×p×k 和Bp×kp\times kp×k 矩阵相加
相当于在最后两个维度的分块加上B,A[-s:] for s in rang(p*k)
a=np.array(range(2*3*4)).reshape([2,3,4])
b=np.array(range(3*4)).reshape([3,4])*0.1

print('a.shape=',a.shape)
print('b.shape=',b.shape)
print(a+b)
a.shape= (2, 3, 4)
b.shape= (3, 4)
[[[ 0.   1.1  2.2  3.3]
  [ 4.4  5.5  6.6  7.7]
  [ 8.8  9.9 11.  12.1]]

 [[12.  13.1 14.2 15.3]
  [16.4 17.5 18.6 19.7]
  [20.8 21.9 23.  24.1]]]
A2×3×42 \times 3\times 42×3×4 和B2×1×42 \times 1\times 42×1×4 矩阵相加
c[0]=a[0]+b[0],c[1]=a[1]+b[1]
a=np.array(range(2*3*4)).reshape([2,3,4])
b=np.array([[[9,9,9,9]],[[2,3,5,9]]])
c=a+b
print('a.shape=',a.shape)
print('b.shape=',b.shape)

print(c)

a.shape= (2, 3, 4)
b.shape= (2, 1, 4)
[[[ 9 10 11 12]
  [13 14 15 16]
  [17 18 19 20]]

 [[14 16 19 24]
  [18 20 23 28]
  [22 24 27 32]]]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值