【PyTorch】UserWarning: Implicit dimension choice for softmax has been deprecated.

部署运行你感兴趣的模型镜像

错误描述

UserWarning: Implicit dimension choice for softmax has been deprecated. Change the call to include dim=X as an argument.

这个警告提示了 softmax 函数在没有显式指定维度时的使用方式已经被弃用。过去,softmax 默认会对最后一个维度(通常是类别维度)执行,而在未来的 PyTorch 版本中,这种隐式的维度选择将被移除。为了避免这个警告,应该显式指定 softmax 的 dim 参数。

解决方案

修改前

attn_weights = F.softmax(self.attn(x))  

修改后

attn_weights = F.softmax(self.attn(x), dim=1)  # 显式指定 dim=1,假设对特征维度应用 softmax

如何确定 dim 的值?

1.查看输入张量的形状: 首先,你需要知道 x 或 self.attn(x) 的形状。你可以通过打印张量的形状来了解它的结构。例如:

print(x.shape)

假设 x 的形状是 (batch_size, num_features),那么:

  • dim=0:会对 batch_size 维度(即每个样本)进行归一化,通常不适用于 softmax,因为这样会在每个样本之间进行对比。
  • dim=1:会对 num_features 维度(即特征维度)进行归一化。通常在神经网络中的 softmax 用于对每个样本的特征进行归一化,这通常是你想要的操作。

2.根据模型的目的: 在注意力机制中,通常 softmax 是用来对特征维度进行归一化的,这意味着你希望在每个样本的特征之间应用 softmax,所以 dim=1 是最常见的选择。

您可能感兴趣的与本文相关的镜像

PyTorch 2.6

PyTorch 2.6

PyTorch
Cuda

PyTorch 是一个开源的 Python 机器学习库,基于 Torch 库,底层由 C++ 实现,应用于人工智能领域,如计算机视觉和自然语言处理

import matplotlib.pyplot as plt import torch import torch.nn as nn import torch.nn.functional as F from sklearn import datasets import numpy as np from torch.utils.data import TensorDataset,DataLoader import matplotlib.pyplot #数据读入从sklearn包datastets读入数据 x_data=datasets.load_iris().data#.data返回iris数据集所有输入特征 y_data=datasets.load_iris().target#.target返回iris数据集所有标签 #打乱 np.random.seed(116)#相同的随机种子 np.random.shuffle(x_data)#所有元素随机排序 np.random.seed(116) np.random.shuffle(y_data)#所有元素随机排序 torch.manual_seed(116) torch.cuda.manual_seed(116)#设置torch随机种子 #将数据集分割为训练集和测试集,训练集为前120行,测试集为后30行 x_train = x_data[:-30] y_train = y_data[:-30] x_test = x_data[-30:] y_test = y_data[-30:] #转化数据类型 train_x = torch.from_numpy(x_train) .type(torch.float32) train_y = torch.from_numpy(y_train) .type (torch.int64) test_x = torch.from_numpy(x_test).type(torch.float32) test_y = torch.from_numpy(y_test) .type (torch.int64) #TensorDataset()可以对tensor进行打包即合并 train_ds = TensorDataset(train_x, train_y) test_ds = TensorDataset(test_x, test_y) #数据打包 train_dl = DataLoader(train_ds, batch_size=32) test_dl = DataLoader(test_ds, batch_size=32) lr=0.1#学习率为0.1 train_loss_results=[]#将每轮的loss记录在此列表中,为后续画loss曲线提供数据 test_acc=[]#将每轮的acc记录在此列表中,为后续画acc曲线提供数据 epoch=5000#循环500轮 loss_all=0#每轮分4个step,loss_all记录四个step生成的4个loss的和 # wl = tf.Variable(tf.random.truncated _normal([4, 3], stddev=0.1, seed=l)) # bl = tf.Variable(tf.random.truncated_normal([3], stddev=0.1, seed=1)) w1 = torch.randn([4, 3], requires_grad=True) b1 = torch.randn([3], requires_grad=True) w2 = torch.randn([3, 3], requires_grad=True) b2 = torch.randn([3], requires_grad=True) #便于随着训练的进行观察数值的变化 test_loss = [] test_acc = [] for epoch in range(epoch): # Compute the predicted outputs and the loss for step, (train_x, train_y) in enumerate(train_dl): y_pred = torch.matmul(train_x,w1)+b1 y_pred = F.softmax(y_pred) y_pred = torch.matmul (y_pred,w2)+b2 y_pred = F.softmax(y_pred) train_y_one_hot = F.one_hot (train_y, num_classes=3) .float() #loss = F.cross_entropy(y_pred, train_y_one_hot) loss = F.mse_loss (y_pred, train_y_one_hot) loss_all += loss.detach().numpy() # Compute the gradients and update the weights loss.backward() with torch.no_grad(): w1 -= lr * w1 .grad b1 -= lr * b1 .grad w2 -= lr * w2 .grad b2 -= lr * b2 .grad w1 .grad .zero_() b1.grad.zero_() w2.grad.zero_() b2.grad.zero_() #每个epoch,打印1oss信息 print("Epoch {1, loss: {}".format(epoch, loss_all / 4)) train_loss_results.append(loss_all/4)#将4个step的loss求平均记录在此变量中 loss_all=0#loss_al1归零,为记录下一个epoch的1oss做准备 # Compute the accuracy on the test set for step, (test_x, test_y) in enumerate(test_dl): with torch.no_grad(): y_test_pred = torch.matmul(test_x, w1) + b1 y_test_pred = F.softmax(y_test_pred) y_test_pred = torch.matmul(y_test_pred,w2) + b2 y_test_pred = F.softmax(y_test_pred) # train_y = F.one_hot (test_Y, num_classes=3) # print(train_y) # loss = F.mse_loss(y_test_pred, train_y) acc = (y_pred == test_y) .float () .mean()#计算正确率 # test_loss.append(acc) test_acc.append(acc) # 绘制1038曲线 plt.title('LOSS Function Curve') plt.xlabel('Epoch') plt.ylabel('Loss') plt.plot(train_loss_results,lable="$Loss")#画出train_loss_results的值,并连线。 plt.legend()#画出曲线坐标 plt.show() #绘制Accuracy曲线 plt.title('Acc Curve') plt.xlabel('Epoch') plt.ylabel('Acc') plt.plot(test_acc, label="$Accuracy$") plt.legend () plt.show()这段代码运行结果为D:\xiazai\envs\pytorch\python.exe D:\pycharm项目\pythonProject1\神经网络计算.py D:\pycharm项目\pythonProject1\神经网络计算.py:53: UserWarning: Implicit dimension choice for softmax has been deprecated. Change the call to include dim=X as an argument. y_pred = F.softmax(y_pred) D:\pycharm项目\pythonProject1\神经网络计算.py:55: UserWarning: Implicit dimension choice for softmax has been deprecated. Change the call to include dim=X as an argument. y_pred = F.softmax(y_pred) Traceback (most recent call last): File "D:\pycharm项目\pythonProject1\神经网络计算.py", line 72, in <module> print("Epoch {1, loss: {}".format(epoch, loss_all / 4)) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ValueError: unmatched '{' in format spec 进程已结束,退出代码为 1 请指出错误原因并改正,最后给出改完后的完整代码
10-13
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值