PyTorch NLP开发报错:Variable需传入张量却得到int值求助
Hey there! Let's break down why you're hitting this error—especially since it works fine in interactive mode, which means there's a subtle difference in how abstract is being handled in your script vs. your test session.
Common Causes & Fixes
The core issue here is clear: when you run abstract = Variable(abstract), the abstract variable at that line isn't a LongTensor anymore—it's a plain Python integer. Here's how that might happen and how to fix it:
Accidental scalar extraction in your code flow
In interactive mode, you probably created aLongTensorand wrapped it immediately. But in your script, there might be a step where you're pulling a single value from the tensor (likeabstract = abstract[0]or a similar index operation) that converts it to a Python int instead of keeping it as a tensor.To confirm this, add debug prints right before the problematic line:
print("Current abstract type:", type(abstract)) print("Current abstract value:", abstract) abstract = Variable(abstract)If the output shows
<class 'int'>, trace back through your code to find whereabstractloses its tensor type.Data loading/preprocessing glitches
For NLP tasks, it's common for data preprocessing to accidentally turn a tensor into a scalar int—especially if you're handling batches of text and one sample has unexpected formatting. Double-check your data loading pipeline to ensure every instance ofabstractstays aLongTensor.Quick note on PyTorch version
If you're using a newer PyTorch version (v0.4+),Variablehas been merged into tensors—you can just usetensor.requires_grad = Trueinstead of wrapping withVariable. But if you're stuck on an older version, make sure you're always passing a tensor (not a Python scalar) toVariable.
Temporary Fix for Testing
If you confirm abstract is a Python int and need to keep it that way temporarily, convert it back to a LongTensor first:
import torch from torch.autograd import Variable # Convert int to LongTensor before wrapping abstract_tensor = torch.LongTensor([abstract]) abstract = Variable(abstract_tensor)
This is a band-aid though—you'll want to fix the root cause so abstract stays a tensor throughout your pipeline.
Key Takeaway
The gap between your interactive success and script failure is the state of abstract right before wrapping. Use debug prints to check its type and value, then trace back to see where it's being converted to an int.
内容的提问来源于stack exchange,提问作者Shiloh_C

