激活函数softmax
- 处理多分类问题,将多分类的结果以概率的形式展出,且所有的分类的概率和为1,且选择概率最大的分类作为结果
- torch.softmax()
- 如下图这样求一个输入特征x的概率


概率和为1


激活函数的选择建议
- 隐藏层优先建议使用ReLU
- 输出层,二分类就使用sigmoid,多分类建议softmax

测试代码
import torch
t1 = torch.tensor([0.1,0.3, 0.3, 0.4,0.8])
p = torch.softmax(t1, dim=0)
print(p)
t2 = torch.tensor([0.1, 0.1, 0.1, 0.1, 0.1])
p2 = torch.softmax(t2, dim=0)
print(p2)
测试结果
D:\software\python.exe -X pycache_prefix=C:\Users\HONOR\AppData\Local\JetBrains\PyCharm2025.2\cpython-cache "D:/software/PyCharm 2025.2.4/plugins/python-ce/helpers/pydev/pydevd.py" --multiprocess --qt-support=auto --client 127.0.0.1 --port 51824 --file C:\Users\HONOR\Desktop\python\test17_softmax.py
Connected to: <socket.socket fd=968, family=2, type=1, proto=0, laddr=('127.0.0.1', 51827), raddr=('127.0.0.1', 51824)>.
Connected to pydev debugger (build 252.27397.106)
tensor([0.1469, 0.1794, 0.1794, 0.1983, 0.2959])
tensor([0.2000, 0.2000, 0.2000, 0.2000, 0.2000])
Process finished with exit code 0