딥러닝 모델에서 input 입력값으로는 항상 numpy array를 사용합니다.

반응형

이미지의 경로를 numpy array로 저장하는 코드와 target 값으로 사용될 라벨링 데이터(json)의 소분류 카테고리만 뽑아서 numpy array로 저장하는 과정에서 문제 발생.

문제 상황 : VIT , Deit 모델을 실행하다가 마지막 훈련 과정에서

TypeError: default_collate: batch must contain tensors, numpy arrays, numbers, dicts or lists; found object

에러를 마주쳤다. input 값으로 tensor array number 등이 들어와야 한다고 알려주는거 같다.

아무리봐도 모델 코드 자체에는 에러가 없었다.

model에 들어가려면 웬만하면 전부 numpy array로 변환해야 한다.

🌟 딥러닝 모델에서 input 값으로 numpy array를 사용하는 이유?

Numpy는 파이썬에서 과학 계산을 위한 패키지이며, 다차원 배열을 다루는 데 강점이 있다.

따라서 Numpy array는 대규모 데이터를 다룰 때 매우 효율적이며, 이러한 이유로 인공지능 모델에서 입력값으로 Numpy array를 사용한다.

또한, 인공지능 모델에서는 주로 행렬 연산을 수행하며, Numpy는 행렬 연산에 최적화되어 있어서 인공지능 모델에서 Numpy array를 사용하면 행렬 연산이 빠르고 효율적으로 수행될 수 있다. 이는 딥러닝 모델에서 특히 중요한데, 딥 러닝 모델은 매우 복잡하고 대규모의 데이터셋을 다루기 때문에 행렬 연산의 속도와 효율성이 매우 중요하다.

또한 많은 머신러닝 라이브러리들은 입력데이터를 numpy array 형태로 받아들인다. 따라서 numpy array는 인공지능 모델에서 입력값으로 사용되는 이유는 다차원 배열을 다루기 효율적이며 행렬 연산에 최적화 되어 있기 때문.

 

import os
import json
import pandas as pd

# define the root directory where your folders are located
root_dir = '/home/minyoungxi/project/training_labels_L1_4/'

# initialize an empty list to store the category information
category_list = []

# iterate through each subdirectory in the root directory
for dir1 in os.listdir(root_dir):
    for dir2 in os.listdir(os.path.join(root_dir, dir1)):
        for dir3 in os.listdir(os.path.join(root_dir, dir1, dir2)):
            # check if the file is a json file
            if dir3.endswith('.json'):
                # load the json file
                with open(os.path.join(root_dir, dir1, dir2, dir3), encoding='utf-8-sig') as f:
                    data = json.load(f)
                # extract the category information
                category = data['category']['ctg_nm_level3']
                # add the category information to the list
                category_list.append(category)

# convert the list to a pandas DataFrame
df = pd.DataFrame({'category': category_list})

df


Output :
민영님이 저장한 target 배열의 차원 :  2
[['소라']
 ['소라']
 ['소라']
 ['소라']
 ['소라']]

 

당연히 target 값은 1차원이어야 한다. 위 코드의 결과는 2차원 배열이다.

 

target_1dim = [ target[0]for target in target_encoded]
print("1차원 타겟 배열  : ", target_1dim[:5])

print("\n\n# 이전 타겟 배열: " , target_encoded[:5], "\n# 이후 타겟 배열 : ", target_1dim[:5])


Output:
1차원 타겟 배열  :  ['소라', '소라', '소라', '소라', '소라']


# 이전 타겟 배열:  [['소라']
 ['소라']
 ['소라']
 ['소라']
 ['소라']] 
# 이후 타겟 배열 :  ['소라', '소라', '소라', '소라', '소라']

 

위의 코드를 통해서 target 값들을 1차원으로 평평하게 저장할 수 있다.

이후 넘파이 배열로 저장.

 

target_np = np.array(target_1dim)
print(target_np[:5], "  > 타입 : ", type(target_np))

['소라' '소라' '소라' '소라' '소라']   > 타입 :  <class 'numpy.ndarray'>

 

정리

위에서 이미지의 라벨링 json 파일들의 소분류만 추출하여 저장하는 코드까지 작성하였지만, 그 이후에 numpy array로 변환하는 과정에서 1차원 배열로 변환해주어야 한다는 점을 생각하지 못했다.

 

당연히 모델로 들어갔을 때 2차원 배열로 input 되기 때문에 안돌아가지.. 바보

반응형