在 tensorflow 和numpy 中矩阵的加法
A m × n × . . × k m \times n \times ..\times k m×n×..×k 和B 1 × k 1\times k 1×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]]]
A m × n × . . × p × k m \times n \times ..\times p\times k m×n×..×p×k 和B p × k p\times k p×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]]]
A 2 × 3 × 4 2 \times 3\times 4 2×3×4 和B 2 × 1 × 4 2 \times 1\times 4 2×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]]]
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)