Pytorch 网络对输入图像要求固定大小的处理方法 记录

本文介绍了如何使用PyTorch处理输入图像大小不一致的问题。通过读取图像,转换尺寸,应用预定义的转换(如ToTensor),并调整张量维度以匹配预训练模型的要求(如ImageNet上的模型),可以将任意大小的图像输入到模型进行分类。这种方法确保了网络能够正确处理非标准尺寸的测试图像。

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

对一些在ImageNet数据集上预训练的model,在分类的时候往往是使用的Fully Connected Layer,且往往是Linear(2048,1000)。而我们的测试图像往往不同于训练时候的2242243 ,那么经过以下方法的处理,可以经过网络处理。

import torch
from torchvision import datasets, transforms
import numpy as np
from PIL import Image
 
filename='hotpot.jpg'
image=Image.open(filename).convert('RGB') #读取图像,转换为三维矩阵
image=image.resize((224,224),Image.ANTIALIAS) #将其转换为要求的输入大小224*224
transform=transforms.Compose([transforms.ToTensor()])
img = transform(image) #转为Tensor
img=img.resize(1,3,224,224) #如果存在要求输入图像为4维的情况,使用resize函数增加一维
 
 
output =model(img) #执行即可

转载自:Pytorch 网络对输入图像要求固定大小的处理方法

### 使用LSTM层处理图像PyTorch中使用LSTM层进行图像处理通常涉及将二维图像转换成适合序列建模的形式。一种常见的方法是将图像展平为一维向量或将图像分割成多个区域作为时间步输入到LSTM网络中[^1]。 对于非时序图片分类任务,可以考虑以下几种方式来准备数据: - **像素级展开**:直接将整张图片按行或列顺序排列成为单一长向量; - **局部特征提取**:通过滑动窗口机制获取局部patch并依次送入LSTM单元; 下面给出一段简单的代码示例用于说明如何定义一个基于LSTM的图像分类器结构,在此例子中假设每幅图像固定大小(例如28x28),并且被划分为7×4=28个连续的时间片段喂给LSTM细胞[^4]。 ```python import torch from torch import nn class ImageLSTM(nn.Module): def __init__(self, input_dim, hidden_dim, layer_num, output_dim): super(ImageLSTM, self).__init__() # 定义多层LSTM self.lstm = nn.LSTM(input_dim, hidden_dim, num_layers=layer_num, batch_first=True) # 输出全连接层 self.fc = nn.Linear(hidden_dim, output_dim) def forward(self, x): # 输入形状 (batch_size, seq_len, feature_dim) out, _ = self.lstm(x) # LSTM输出 # 取最后一个时间步的结果做预测 out = self.fc(out[:, -1, :]) return out # 初始化模型参数 input_dim = 28 # 如果原图为28*28,则此处代表每一行作为一个time step的数据长度 hidden_dim = 50 # 隐藏状态维度 layer_num = 2 # LSTM层数 output_dim = 10 # 类别数(比如MNIST有十个类别) model = ImageLSTM(input_dim=input_dim, hidden_dim=hidden_dim, layer_num=layer_num, output_dim=output_dim).cuda() ``` 这段代码展示了创建一个多层LSTM架构的过程,并指定了最终线性变换以适应特定数量的目标类目。值得注意的是,这里并没有像某些案例那样预先应用卷积操作而是单纯依赖于LSTM本身来进行学习。 为了更好地理解训练过程中的表现情况,还可以绘制损失变化曲线以便观察收敛趋势[^2]: ```python with torch.no_grad(): timeseries = ... # 时间序列或其他形式的一维数组表示整个样本集的情况 train_plot = np.ones_like(timeseries) * np.nan y_pred = model(X_train.cuda()).cpu().numpy() # 记录下训练部分的真实位置处对应的预测值 train_plot[lookback:train_size] = y_pred[:len(y_pred)-test_size] plt.figure(figsize=(10,6)) plt.title('Training Loss Over Time') plt.xlabel('Time Steps') plt.ylabel('Loss Value') plt.plot(timeseries, label='True Values', color='blue') plt.plot(train_plot, 'o-', markersize=3, linewidth=1, alpha=.7, label='Predictions on Train Set', color='red') if X_test is not None and y_test is not None: test_plot = np.ones_like(timeseries) * np.nan y_pred_test = model(X_test.cuda()).cpu().numpy() # 同样记录测试集中对应的位置及其预测结果 test_plot[train_size+lookback:] = y_pred_test plt.plot(test_plot, '*-', markersize=3, linewidth=1, alpha=.7, label='Predictions on Test Set', color='green') plt.legend(loc="best") plt.grid(True); plt.show(); ``` 上述绘图脚本可以帮助直观地评估模型性能以及调整超参的效果。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值