Study/Error

[Error] [Pytorch] TypeError: '<' not supported between instances of 'Example' and 'Example' (Torchtext BucketIterator 사용때 마주한 에러)

후이 (hui) 2022. 3. 29. 08:11
반응형

Torchtext BucketIterator 를 쓸 때, trainset, valset , testset을 각각 iterator로 바꿔주는 부분에서 마주한 에러다 

 

 

1. 상황 

torchtext.legacy.data 안에 TabularDataset 으로 csv 파일을 불러온 뒤 

trainset, valset , testset 로 split 했다. 

확인해보면 모두 <torchtext.legacy.data.dataset.Dataset at ~~~~ > 객체로 되어있음 

 

각각의 trainset, valset , testset 이제 iterator로 만들기 위해서 BucketIterator.split()을 쓰는데 에러가 발생했다. 

train_iter는 문제없이 할당이 되었는데 

val_iter와 test_iter를 확인해봤을때 위와 같은 type error 가 발생했다 ;; 

 

 

2. 해결방법 

 

https://github.com/pytorch/text/issues/474

 

TypeError: '<' not supported between instances of 'Example' and 'Example' · Issue #474 · pytorch/text

Got the error when running the following code. Is there anything similar to an operator overloading for "<" needed here, or there is a go around way here? from torchtext.data import Ta...

github.com

train_iter, val_iter, test_iter = data.BucketIterator.splits( 
    (trainset, valset, testset), 
    batch_size=BATCH_SIZE, 
    device = DEVICE,
    shuffle=True, 
    repeat=False, 
    sort=False) #### 추가추가 !!!!

 

sort = False 부분을 추가하면 에러는 해결된다. 

이유를 파악하고 싶으나, document에는 파라미터 각각에 대해 상세히 설명되어있지 않고 

다른 코드 설명을 찾아보니 아래와 같이 적혀있었다. 

 

It is important to keep sort=False and 

sort_with_batch=True to only sort the examples in each batch

and not the examples in the whole dataset!

 

하나의 묶음 데이터를 iterator로 만들면서 이를 sort 하고 싶을때는 sort=True 여야하지만

위와 같이 각각의 데이터를  iterator로 만들면서 이를 sort 하고 싶을때는 sort=False 로 두고 sort_key=lambda x: len(x['text']),

로 해야한다고 한다...

 

참고 link : 

https://colab.research.google.com/github/gmihaila/ml_things/blob/master/notebooks/pytorch/pytorchtext_bucketiterator.ipynb#scrollTo=OKfYOod_LQrs

 

pytorchtext_bucketiterator.ipynb

Run, share, and edit Python notebooks

colab.research.google.com

 

 

 

728x90
반응형