【numpy】axis 维度 是什么 Softmax中dim方向是什么

1 对于numpy.ndarray,可以使用shape查看形状

下图形状是(3,2, 1),如何得到的? 第一层 [ ] 中含有3个元素, 单拿一个元素出来, 有2个元素, blabla…
【numpy】axis 维度 是什么 Softmax中dim方向是什么

2 axis是如何定义?

从shape上理解更快。

axis=0,相当于拆除第1层 [ ] ,剩下元素shape会是 (2, 1)。下图中红框叠加sum起来就是这个形状。
【numpy】axis 维度 是什么 Softmax中dim方向是什么
axis=1,相当于拆除第2层 [ ] ,剩下元素shape会是 (3, 1)。
【numpy】axis 维度 是什么 Softmax中dim方向是什么

axis=2,相当于拆除第3层 [ ] ,剩下元素shape会是 (3, 2)。
【numpy】axis 维度 是什么 Softmax中dim方向是什么

代码:

import numpy as np

kl = [2, 2, 3, 3, 7, 7]
npa = np.asarray(kl).reshape((3, 2, 1))
print(npa)
print("--------")
print(np.sum(npa, axis=0))
print("--------")
print(np.sum(npa, axis=1))
print("--------")
print(np.sum(npa, axis=2))

3 方向的含义

Axis or axes along which a sum is performed.

这里的along 很关键,在很多库包里,无论叫 Axis 、axes 、dim , 都是指沿着哪一个dim去计算, 如果用shape去理解,会快一些。

比如在Softmax中:

import torch
from torch import nn

m = nn.Softmax(dim=1)
input = torch.randn(2, 3)
print(input)
output = m(input)
print(output)

得到:

tensor([[-0.6087, -0.5550, -0.2106],
        [-0.4120,  0.7185, -1.3630]])
tensor([[0.2822, 0.2977, 0.4201],
        [0.2230, 0.6908, 0.0862]])

Softmax的那个方向的数字加起来会是1,代码里面是(dim=1),也就是想形成的shape是(2,),去掉3。
所以是用 [-0.6087, -0.5550, -0.2106] 和 [-0.4120, 0.7185, -1.3630] 在算 Softmax。
结果也正是如此,[0.2822, 0.2977, 0.4201]或者 [0.2230, 0.6908, 0.0862] 加起来就是1 。

文章出处登录后可见!

已经登录?立即刷新

共计人评分,平均

到目前为止还没有投票!成为第一位评论此文章。

(0)
社会演员多的头像社会演员多普通用户
上一篇 2022年4月1日 下午7:15
下一篇 2022年4月1日 下午7:25

相关推荐