我正在使用來自Towards Data Science的現有代碼來微調 BERT 模型。我面臨的問題屬于代碼的這一部分,它嘗試將我們的資料格式化為 PyTorchdata.Dataset物件:
class MeditationsDataset(torch.utils.data.Dataset):
def _init_(self, encodings, *args, **kwargs):
self.encodings = encodings
def _getitem_(self, idx):
return {key: torch.tensor(val[idx]) for key, val in self.encodings.items()}
def _len_(self):
return len(self.encodings.input_ids)
dataset = MeditationsDataset(inputs)
當我運行代碼時,我遇到了這個錯誤:
TypeError Traceback (most recent call last)
<ipython-input-144-41fc3213bc25> in <module>()
----> 1 dataset = MeditationsDataset(inputs)
/usr/lib/python3.7/typing.py in __new__(cls, *args, **kwds)
819 obj = super().__new__(cls)
820 else:
--> 821 obj = super().__new__(cls, *args, **kwds)
822 return obj
823
TypeError: object.__new__() takes exactly one argument (the type to instantiate)
我已經搜索過這個錯誤,但這里的問題是我不熟悉 PyTorch 或 OOP,所以我無法解決這個問題。您能否讓我知道我應該從該代碼中添加或洗掉什么以便我可以運行它?提前非常感謝。
此外,如果需要,我們的資料如下:
{'input_ids': tensor([[ 2, 1021, 1005, ..., 0, 0, 0],
[ 2, 1021, 1005, ..., 0, 0, 0],
[ 2, 1021, 1005, ..., 0, 0, 0],
...,
[ 2, 1021, 1005, ..., 0, 0, 0],
[ 2, 103, 1005, ..., 0, 0, 0],
[ 2, 4, 0, ..., 0, 0, 0]]),
'token_type_ids': tensor([[0, 0, 0, ..., 0, 0, 0],
[0, 0, 0, ..., 0, 0, 0],
[0, 0, 0, ..., 0, 0, 0],
...,
[0, 0, 0, ..., 0, 0, 0],
[0, 0, 0, ..., 0, 0, 0],
[0, 0, 0, ..., 0, 0, 0]]),
'attention_mask': tensor([[1, 1, 1, ..., 0, 0, 0],
[1, 1, 1, ..., 0, 0, 0],
[1, 1, 1, ..., 0, 0, 0],
...,
[1, 1, 1, ..., 0, 0, 0],
[1, 1, 1, ..., 0, 0, 0],
[1, 1, 0, ..., 0, 0, 0]]),
'labels': tensor([[ 2, 1021, 1005, ..., 0, 0, 0],
[ 2, 1021, 1005, ..., 0, 0, 0],
[ 2, 1021, 1005, ..., 0, 0, 0],
...,
[ 2, 1021, 1005, ..., 0, 0, 0],
[ 2, 1021, 1005, ..., 0, 0, 0],
[ 2, 4, 0, ..., 0, 0, 0]])}
uj5u.com熱心網友回復:
Python 中的特殊函式使用雙下劃線前綴和后綴。在您的情況下,要實作 a data.Dataset,您必須具有__init__、__getitem__和__len__:
class MeditationsDataset(torch.utils.data.Dataset):
def __init__(self, encodings, *args, **kwargs):
self.encodings = encodings
def __getitem__(self, idx):
return {key: torch.tensor(val[idx]) for key, val in self.encodings.items()}
def __len__(self):
return len(self.encodings.input_ids)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/496383.html
下一篇:如何在另一個類方法中參考類屬性?
