from torch.utils import data def load_data_nmt(batch_size, num_steps, num_examples=600): """返回翻译数据集的迭代器和词表""" with open(d2l.download('cmn-eng'), 'r') as f: lines = f.readlines() return lines num_lines = min(num_examples, len(raw_text.split('\n'))) text = raw_text.split('\n')[:num_lines] src_vocab, tgt_vocab = d2l.load_vocab('cmn-eng') src_iter= d2l.build_data_iter(text, src_vocab, tgt_vocab, batch_size, num_steps) return src_iter, src_vocab, tgt_vocab train_iter, src_vocab, tgt_vocab = load_data_nmt(batch_size=2, num_steps=8) for X, X_valid_len, Y, Y_valid_len in train_iter: print('X:', X.type(torch.int32)) print('X的有效长度:', X_valid_len) print('Y:', Y.type(torch.int32)) print('Y的有效长度:', Y_valid_len) break 报这个错误ValueError: not enough values to unpack (expected 3, got 2)
时间: 2024-03-01 18:55:11 浏览: 235
问题出在这一行代码上:
```
src_iter= d2l.build_data_iter(text, src_vocab, tgt_vocab, batch_size, num_steps)
```
这个函数返回的是一个迭代器对象,但是在你的 load_data_nmt 函数中却没有将其打包到元组中一起返回,导致在使用元组解包时数量不足的错误。你需要修改 load_data_nmt 函数,将 src_iter 也添加到返回的元组中,如下所示:
```
def load_data_nmt(batch_size, num_steps, num_examples=600):
"""返回翻译数据集的迭代器和词表"""
with open(d2l.download('cmn-eng'), 'r') as f:
lines = f.readlines()
num_lines = min(num_examples, len(lines))
lines = lines[:num_lines]
src_vocab, tgt_vocab = d2l.load_vocab('cmn-eng')
src_iter, tgt_iter = d2l.build_data_iter(lines, src_vocab, tgt_vocab,
batch_size, num_steps)
return src_iter, tgt_iter, src_vocab, tgt_vocab
```
这样修改后,你的代码就可以正确运行了。
阅读全文