pytorch中tf.nn.functional.softmax(x,dim = -1)对参数dim的理解

本文深入解析PyTorch中softmax函数的dim参数作用,通过实例演示不同维度下softmax运算的具体效果,帮助读者掌握softmax在神经网络中的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

torch.nn.functional.Softmax(input,dim=None)

tf.nn.functional.softmax(x,dim = -1)中的参数dim是指维度的意思,设置这个参数时会遇到0,1,2,-1等情况,特别是对2和-1不熟悉,细究了一下这个问题
查了一下API手册,是指最后一行的意思。原文:
dim (python:int) – A dimension along which Softmax will be computed (so every slice along dim will sum to 1).

softmax的公式为:
Softmax(xi)=exp(xi)∑jxiSoftmax(x_i)=\frac{exp(x_i)}{\sum_{j}x_i}Softmax(xi)=jxiexp(xi)

一般会有设置成dim=0,1,2,-1的情况

准备工作:先随机生成一个(2,2,3)的矩阵,两个维度的(2,3)矩阵。

import torch
import torch.nn.functional as F
input = torch.randn(2,2,3)
print(input)

输出为:

tensor([[[-3.9332,  0.7909,  0.8927],
         [-1.7991,  0.2505,  0.7695]],

        [[ 0.1946,  0.1878,  1.2713],
         [ 0.9536,  1.0525, -0.7081]]])
  • 要注意的是当dim=0时, 是对每一维度相同位置的数值进行softmax运算,举个栗子:
m = F.softmax(input,dim=0)
print(m)

输出为:

tensor([[[0.0159, 0.6464, 0.4065],
         [0.0599, 0.3096, 0.8142]],

        [[0.9841, 0.3536, 0.5935],
         [0.9401, 0.6904, 0.1858]]])

从输出结果可以看出,一共2个维度
每一个维度(2,3)对应的数值相加为1,例如:

[0][0][0]+[1][0][0]=0.0159+0.9841=1
[0][0][1]+[1][0][1]=0.6464+0.3536=1

  • 要注意的是当dim=1时, 是对某一维度的列进行softmax运算:
m = F.softmax(input,dim=1)
print(m)

输出为:

tensor([[[0.1058, 0.6319, 0.5308],
         [0.8942, 0.3681, 0.4692]],

        [[0.3189, 0.2964, 0.8786],
         [0.6811, 0.7036, 0.1214]]])

从输出结果可以看出,计算的是某一维度中的列,例如:
在第1维度中:
[0][0][0]+[0][1][0]=0.1058+0.8942=1
在第2维度中:
[1][0][0]+[1][1][0]=0.3189+0.6811=1

  • 要注意的是当dim=2时, 是对某一维度的行进行softmax运算:
m = F.softmax(input,dim=2)
print(m)

输出为:

tensor([[[0.0042, 0.4726, 0.5232],
         [0.0458, 0.3560, 0.5982]],

        [[0.2029, 0.2015, 0.5955],
         [0.4360, 0.4813, 0.0828]]])

从输出结果可以看出,计算的是某一维度中的行,例如:
在第1维度中:
[0][0][0]+[0][0][1]+[0][0][2]=0.0042+0.4726+0.5232=1
在第2维度中:
[1][0][0]+[1][0][1]+[1][0][2]=0.2029+0.2015+0.5955=0.9999=1(是等于1的,只是后面还有很多位小数省略了)

  • 要注意的是当dim=-1时, 是对某一维度的行进行softmax运算:
m = F.softmax(input,dim=-1)
print(m)

输出为:

tensor([[[0.0042, 0.4726, 0.5232],
         [0.0458, 0.3560, 0.5982]],

        [[0.2029, 0.2015, 0.5955],
         [0.4360, 0.4813, 0.0828]]])

从这里可以发现,dim=-1dim=2的结果是一样的。
其实这些结果,拿个计算器,自己算都行,可以加深对公式的印象:
input数值第一维第一行为例:
[-3.9332, 0.7909, 0.8927]怎么求得上面的结果[0.0042, 0.4726, 0.5232]
Softmax(x1)=exp(x1)∑jxi=exp(−3.9332)exp(−3.9332)+exp(0.7909)+exp(0.8927)=0.0041959Softmax(x_1)=\frac{exp(x_1)}{\sum_{j}x_i}=\frac{exp(-3.9332)}{exp(-3.9332)+exp(0.7909)+exp(0.8927)}=0.0041959Softmax(x1)=jxiexp(x1)=exp(3.9332)+exp(0.7909)+exp(0.8927)exp(3.9332)=0.0041959
Softmax(x2)=exp(x2)∑jxi=exp(0.7909)exp(−3.9332)+exp(0.7909)+exp(0.8927)=0.4725807Softmax(x_2)=\frac{exp(x_2)}{\sum_{j}x_i}=\frac{exp(0.7909)}{exp(-3.9332)+exp(0.7909)+exp(0.8927)}=0.4725807Softmax(x2)=jxiexp(x2)=exp(3.9332)+exp(0.7909)+exp(0.8927)exp(0.7909)=0.4725807
Softmax(x3)=exp(x3)∑jxi=exp(0.8927)exp(−3.9332)+exp(0.7909)+exp(0.8927)=0.5232234Softmax(x_3)=\frac{exp(x_3)}{\sum_{j}x_i}=\frac{exp(0.8927)}{exp(-3.9332)+exp(0.7909)+exp(0.8927)}=0.5232234Softmax(x3)=jxiexp(x3)=exp(3.9332)+exp(0.7909)+exp(0.8927)exp(0.8927)=0.5232234

总结:
用一张图片会更好理解这个参数数值变化代表的意思:
softmax

mport numpy as np import pandas as pd import torch import torch.nn as nn import matplotlib.pyplot as plt from sklearn.preprocessing import StandardScaler from torch.utils.data import DataLoader, TensorDataset 设备配置 device = torch.device(‘cuda’ if torch.cuda.is_available() else ‘cpu’) 数据预处理模块 def preprocess_data(file_path): # 读取原始数据 df = pd.read_excel(file_path) # 计算年平均值 annual_data = df.groupby(['站号', '纬度', '经度', '年']).agg({ '日平均气温': 'mean', '日降水量': 'sum', '日平均相对湿度': 'mean', '日日照时数': 'sum', '日平均0cm地温': 'mean', '日平均40cm地温': 'mean' }).reset_index() # 选择特征列 features = ['日平均气温', '日降水量', '日平均相对湿度', '日日照时数', '日平均0cm地温', '日平均40cm地温'] # 标准化处理 scaler = StandardScaler() annual_data[features] = scaler.fit_transform(annual_data[features]) return annual_data, scaler, features 自注意力评分模型 class ClimateAttention(nn.Module): def init(self, input_dim): super().init() self.query = nn.Linear(input_dim, input_dim) self.key = nn.Linear(input_dim, input_dim) self.value = nn.Linear(input_dim, input_dim) self.softmax = nn.Softmax(dim=2) def forward(self, x): Q = self.query(x) K = self.key(x) V = self.value(x) attention_scores = torch.bmm(Q, K.transpose(1,2)) / np.sqrt(x.size(2)) attention_weights = self.softmax(attention_scores) weighted_values = torch.bmm(attention_weights, V) return weighted_values.mean(dim=1) # 聚合特征维度 完整模型 class EvaluationModel(nn.Module): def init(self, input_dim): super().init() self.attention = ClimateAttention(input_dim) self.regressor = nn.Sequential( nn.Linear(input_dim, 32), nn.ReLU(), nn.Linear(32, 1), nn.Sigmoid() ) def forward(self, x): x = self.attention(x) return self.regressor(x) 训练函数 def train_model(data_loader): model = EvaluationModel(input_dim=6).to(device) criterion = nn.MSELoss() optimizer = torch.optim.Adam(model.parameters(), lr=0.001) for epoch in range(50): for inputs in data_loader: inputs = inputs.to(device) outputs = model(inputs) # 这里可以加入专家评分作为监督信号 # 示例使用自动生成评分规则(需根据实际需求修改) synthetic_scores = 0.3*inputs[:,0] + 0.2*inputs[:,1] + 0.15*inputs[:,2] + 0.15*inputs[:,3] + 0.1*inputs[:,4] + 0.1*inputs[:,5] synthetic_scores = synthetic_scores.unsqueeze(1) loss = criterion(outputs, synthetic_scores) optimizer.zero_grad() loss.backward() optimizer.step() return model 可视化模块 def visualize_results(df, scores): plt.figure(figsize=(12, 8)) sc = plt.scatter(df[‘经度’], df[‘纬度’], c=scores, cmap=‘YlGn’, s=100, edgecolor=‘k’) plt.colorbar(sc, label=‘适宜性评分’) plt.title(‘云南省除虫菊种植气候适宜性分布’) plt.xlabel(‘经度’) plt.ylabel(‘纬度’) plt.grid(True) plt.show() 主程序 if name == “main”: # 数据预处理 data, scaler, features = preprocess_data(r"C:\Users\Administrator\Desktop\data.xlsx") # 转换为张量 tensor_data = torch.FloatTensor(data[features].values).unsqueeze(1) dataset = TensorDataset(tensor_data) loader = DataLoader(dataset, batch_size=32, shuffle=True) # 训练模型 trained_model = train_model(loader) # 生成预测评分 with torch.no_grad(): inputs = tensor_data.to(device) predictions = trained_model(inputs).cpu().numpy().flatten() # 结果可视化 visualize_results(data, predictions) 请修改代码 我不想使用PyTorch
03-31
评论 29
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值