微调HuggingFace ViT模型预测时遇输入尺寸不匹配错误求助
问题描述
用户微调HuggingFace的ViT模型后进行预测,相关代码如下:
获取测试图像代码:
# Get test image from the web test_image_url = 'something.jpg' response = requests.get(test_image_url) test_image = Image.open(BytesIO(response.content)) # Resize and display the image aspect_ratio = test_image.size[0] / test_image.size[1] max_height = 250 resized_width = int(max_height * aspect_ratio) resized_img = test_image.resize((resized_width, max_height)) display(resized_img)
预测代码:
# Predict the top k classes for the test image inputs = feature_extractor(images=test_image, return_tensors="pt").to("cuda") outputs = model(**inputs) logits = outputs.logits top_classes = torch.topk(outputs.logits, k_for_top_acc).indices.flatten().tolist() for i, class_idx in enumerate(top_classes): print(str(i + 1), "- Predicted class:", model.config.id2label[class_idx])
运行后持续报错:
ValueError: Input image size (256*256) doesn't match model (224*224).
解决方法
对齐Feature Extractor的图像尺寸配置
ViT模型(如默认的vit-base-patch16-224)要求输入尺寸为224x224,问题根源是你的feature_extractor使用的尺寸和模型要求不匹配。可以通过两种方式修正:- 初始化Feature Extractor时明确指定尺寸:
from transformers import ViTFeatureExtractor # 替换为你的微调模型路径或名称 feature_extractor = ViTFeatureExtractor.from_pretrained("your-finetuned-vit-model", size=(224, 224)) - 调用Feature Extractor时临时指定尺寸:
inputs = feature_extractor(images=test_image, return_tensors="pt", size=(224, 224)).to("cuda")
注意:代码中手动resize的
resized_img仅用于显示,预测时使用的是原始的test_image,无需手动修改其尺寸,交给Feature Extractor自动处理即可。- 初始化Feature Extractor时明确指定尺寸:
确保微调与预测的输入尺寸一致
如果你微调模型时使用的是256x256的输入尺寸,那预测时也需保持统一:将Feature Extractor的size参数设为(256, 256),同时确认模型的patch尺寸(如16)能整除该输入尺寸(256是16的整数倍,符合ViT要求)。
内容的提问来源于stack exchange,提问作者inter galactic
相关产品推荐
相关产品推荐

