본문 바로가기
Data Projects/사용자 나이 추정 프로젝트

[사용자 나이 추정] 프로젝트 refactor 하기 (3)

by 천뿌니 2021. 12. 2.
728x90

프로젝트 : 키오스크 UIUX 개인화를 위한 사용자 나이 추정

데이터 읽기/결합/분포/라벨링/결합 과정

 

- zip파일로 된 데이터 파일을 풀어서 입력 받는다.

Combined_data_final_path = "/content/drive/My Drive/age_detection/zipped_dataset/Combined_data_final.zip"
try:
    os.mkdir("combined")
    os.remove("combined")
except OSError:
    pass

with ZipFile(Combined_data_final_path, 'r') as myzip:
    myzip.extractall("combined")
    print('Done unzipping Combined_data_final_path.zip')
    
Combined_data_path = '/content/combined'
Combined_data_image_names = os.listdir(Combined_data_path)

 

- 데이터 이미지 이름이 나이_데이터종류_번호 양식이므로 중요한 데이터인 나이와 데이터 종류를 입력 받아

combined_age_labels와 combined_kind_labels 배열에 저장한다.
# combined 데이터셋을 나이, 종류(0 - facial_age, 1 - utk,  2- all-ages-face, 3 - meag)

def age_kind_split(image_name):
    image_labels = image_name.split('_')
    age = image_labels[0]
    kind = image_labels[1]

    return (age, kind)
    
combined_age_labels = np.array([])
combined_kind_labels = np.array([])

for image in Combined_data_image_names:
    age, kind = age_kind_split(image)
    combined_age_labels = np.append(combined_age_labels, age)
    combined_kind_labels = np.append(combined_kind_labels, kind)

 

- 각 나이별 데이터 개수를 combined_images에 저장한다.

combined_ages_counts = pd.Series(combined_age_labels).value_counts()

combined_images = {}

for age, counts in combined_ages_counts.items():
    combined_images[int(age)] = counts

 

- Series 데이터를 표로 나타내기 위해 DataFrame형식으로 저장하고, 공백값을 0으로 변경해준다음 값들을 int로 변환한다.

images_df = pd.DataFrame(combined_images.values(), index=combined_images.keys(), columns=['combined_images'])

images_df.fillna(0, inplace=True)
images_df = images_df.astype(int)

 

- 전체 데이터의 분포를 표로 보기위해 저장한다.

plt.figure(figsize=(30, 10))

ax = sns.barplot(x=images_df.index, y=images_df['combined_images'], color='royalblue')

ax.tick_params(axis='both', labelsize=12)
ax.tick_params(axis='x', labelrotation=45)

plt.xlabel("Age", fontsize=16)
plt.ylabel("No. of Images", fontsize=16)

plt.title("Barplot showing No. of images in combined dataset by Age", fontsize=18)

# png로 저장
plt.savefig('/content/drive/My Drive/age_detection/plot_images/barplot_combined_images.png', bbox_inches='tight');

 

- 라벨링에 맞게 데이터들을 분배해주고, 분배해준 데이터들을 딥러닝 학습할때 input으로 사용하기 위해 csv파일로 저장한다.

def class_labels(age):
    if 10 <= age <= 29:
        return 0
    elif 30 <= age <= 59:
        return 1 
    else:
        return 2
        
master_df = pd.DataFrame()
master_df['filename'] = Combined_data_image_names
master_df['age'] = master_df['filename'].map(lambda img_name : np.uint8(img_name.split("_")[0]))
master_df['target'] = master_df['age'].map(class_labels)

master_df = shuffle(master_df, random_state=42).reset_index(drop=True)

temp_master = master_df.copy()

combined_path = "/content/combined"

def append_path_to_filename(filename):
    return os.path.join(combined_path, filename)

temp_master['filename'] = master_df['filename'].map(append_path_to_filename)
temp_master.to_csv("/content/drive/My Drive/age_detection/input_output/images_filenames_labels.csv", index=False)

 

 

* 댓글은 언제나 환영입니다. 다음 포스팅은 어떤 딥러닝 모델을 사용했는지, 딥러닝 모델 코드, 결과로 찾아 뵙겠습니다. 아래의 github도 많이 놀러와주세요!!

https://github.com/JunSeokCheon

 

JunSeokCheon - Overview

JunSeokCheon has 6 repositories available. Follow their code on GitHub.

github.com

 

댓글