Programming/troubleshooting
[Python][NLP] ValueError: setting an array element with a sequence. The requested array has an inhomogeneous shape after 1 dimensions
brad.min
2022. 8. 16. 23:06
반응형
자연어처리에서 텍스트를 토크나이징 하여 리스트 형식의 input_ids 를 numpy 배열 형태로 변경하는 코드에서 이와 같은 에러가 발생하였다.
에러 문구
ValueError: setting an array element with a sequence. The requested array has an inhomogeneous shape after 1 dimensions
문제 발생 코드
input_ids = np.array(input_ids, dtype=int)
이러한 문제는 배열의 요소들의 길이가 일정하지 않아 발생하는 것 같다. 예를 들어 [[0,0], [0,0,0], [0,0]] 이렇게 2차원 배열에서 1차원 배열들의 길이가 달라 발생하는 것으로 보인다. [[0,0], [0,0], [0,0]] 이렇게 모두 동일한 길이를 갖도록 하면 이러한 에러가 발생하지 않는다.
아래의 코드에서 pad_to_max_length를 설정하지 않아 input_ids의 길이가 전부 달랐던 것이다.
encoded_dict = tokenizer.encode_plus(sent1, sent2,
add_special_tokens=True,
max_length = MAX_LEN,
pad_to_max_length=True,
return_attention_mask=True,
truncation=True)
반응형