pytorch之---max()函数

本文详细解析了PyTorch中torch.max函数的使用方法,包括如何获取Tensor中的最大值及其索引,适用于一维或多维张量。通过实例展示了不同参数组合下torch.max的运行效果。

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

形式: torch.max(input) → Tensor
返回输入tensor中所有元素的最大值:

a = torch.randn(1, 3)
>>0.4729 -0.2266 -0.2085
torch.max(a) #也可以写成a.max()
>>0.4729

形式: torch.max(input, dim, keepdim=False, out=None) -> (Tensor, LongTensor)
按维度dim 返回最大值,并且返回索引。
torch.max(a,0)返回每一列中最大值的那个元素,且返回索引(返回最大元素在这一列的行索引)。返回的最大值和索引各是一个tensor,一起构成元组(Tensor, LongTensor)

a = torch.randn(3,3)
>>
0.2252 -0.0901  0.5663
-0.4694  0.8073  1.3596
 0.1073 -0.7757 -0.8649
 
torch.max(a,0)
>>
(
 0.2252
 0.8073
 1.3596
[torch.FloatTensor of size 3]
, 
 0
 1
 1
[torch.LongTensor of size 3]
)

torch.max(a,1)返回每一行中最大值的那个元素,且返回其索引(返回最大元素在这一行的列索引)

a = torch.randn(3,3)
>>
0.2252 -0.0901  0.5663
-0.4694  0.8073  1.3596
 0.1073 -0.7757 -0.8649
 
torch.max(a,1)
>>
(
 0.5663
 1.3596
 0.1073
[torch.FloatTensor of size 3]
, 
 2
 2
 0
[torch.LongTensor of size 3]
)

 

拓展:
torch.max()[0], 只返回最大值的每个数
troch.max()[1], 只返回最大值的每个索引
torch.max()[1].data 只返回variable中的数据部分(去掉Variable containing:)
torch.max()[1].data.numpy() 把数据转化成numpy ndarry
torch.max()[1].data.numpy().squeeze() 把数据条目中维度为1 的删除掉

转载:https://blog.youkuaiyun.com/Z_lbj/article/details/79766690

### 使用 PyTorch 实现 CNN-BiLSTM 模型进行回归任务 为了构建一个适用于回归问题的 CNN-BiLSTM 模型,在 PyTorch 中需要定义模型结构并配置训练流程。下面是一个详细的实现方案。 #### 定义 CNN-BiLSTM 模型类 ```python import torch from torch import nn class CNNBiLSTM(nn.Module): def __init__(self, input_dim, hidden_dim, output_dim, num_layers, dropout_prob): super(CNNBiLSTM, self).__init__() # Define the convolutional layer to extract spatial features from data self.conv_layer = nn.Sequential( nn.Conv1d(in_channels=input_dim, out_channels=hidden_dim, kernel_size=3), nn.ReLU(), nn.MaxPool1d(kernel_size=2) ) # Initialize BiLSTM layers with specified parameters self.lstm = nn.LSTM(input_size=hidden_dim, hidden_size=hidden_dim, num_layers=num_layers, bidirectional=True, batch_first=True) # Dropout layer for regularization and preventing overfitting self.dropout = nn.Dropout(dropout_prob) # Fully connected layer that maps LSTM outputs to regression predictions self.fc = nn.Linear(hidden_dim * 2, output_dim) def forward(self, x): conv_out = self.conv_layer(x.permute(0, 2, 1)) lstm_input = conv_out.permute(0, 2, 1) lstm_output, _ = self.lstm(lstm_input) last_hidden_state = lstm_output[:, -1, :] dropped_last_hidden_state = self.dropout(last_hidden_state) prediction = self.fc(dropped_last_hidden_state) return prediction ``` 此代码片段展示了如何创建一个继承自 `nn.Module` 的新类 `CNNBiLSTM`,其中包含了卷积层、双向 LSTM 层以及全连接层的设计[^2]。 #### 设置损失函数和优化器 对于回归问题而言,均方误差 (MSE Loss) 是一种常用的损失函数;Adam 则作为默认的选择之一被广泛应用于梯度下降法中: ```python criterion = nn.MSELoss() optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate) ``` #### 训练循环 接下来是完整的训练过程,包括前向传播、计算损失值、反向传播更新权重等操作: ```python for epoch in range(num_epochs): model.train() running_loss = 0.0 for i, (inputs, labels) in enumerate(train_loader): inputs = inputs.to(device).float() labels = labels.to(device).float().view(-1, 1) optimizer.zero_grad() outputs = model(inputs) loss = criterion(outputs, labels) loss.backward() optimizer.step() running_loss += loss.item() print(f'Epoch [{epoch+1}/{num_epochs}], Loss: {running_loss/len(train_loader):.4f}') ``` 上述代码实现了批量处理输入数据,并通过调用 `.to(device)` 方法确保所有张量都在同一设备上运行(CPU 或 GPU)。此外还加入了简单的进度条显示功能以便观察训练情况[^1]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值