본문 바로가기
Computer Science/Machine Learning

Linear Regression : Logistic Regression [수면시간에 따른 우울증 예측] (6)

by BaekDaBang 2024. 3. 24.
# 필요한 라이브러리를 임포트
import random
import os

import numpy as np
import pandas as pd

from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score, confusion_matrix


# 랜덤시드 고정
seed = 42

random.seed(seed)
np.random.seed(seed)
os.environ["PYTHONHASHSEED"] = str(seed)


# 데이터 폴더(Input) 내 경로 확인
for dirname, _, filenames in os.walk('/kaggle/input'):
    for filename in filenames:
        print(os.path.join(dirname, filename))

 

1. Dataset

# 학습용 데이터 셋(trainX, trainY)과 평가용 데이터 셋(testX), 제출 포맷(submit) 로드
trainX = pd.read_csv('/kaggle/input/2023-ml-w5p2/trainX.csv')
trainY = pd.read_csv('/kaggle/input/2023-ml-w5p2/trainY.csv')
testX  = pd.read_csv('/kaggle/input/2023-ml-w5p2/testX.csv')

submit = pd.read_csv('/kaggle/input/2023-ml-w5p2/submit.csv')
# 학습용 데이터 셋 (trainX)을 확인
print(f'shape of train data: {trainX.shape}')	# shape of train data: (23, 14)
trainX.head()
# 학습용 라벨 (label) 데이터 셋 (trainY)를 확인
print(f'columns: {trainY.columns}')			# columns: Index(['label'], dtype='object')
print(f'labels : {trainY.label.unique()}')	# labels : [0 1]

trainY.head()

 

2. Preprocessing

# 학습용 라벨 데이터 셋 (trainY)을 numpy 형태로 저장
labels = trainY['label'].values.ravel()

# 학습용 데이터를 토대로 검증하고자, 학습용 데이터를 다시 검증을 위한 학습 데이터와 검증 데이터로 분리 (최종 모델 최적화에는 전체 학습용 데이터 (trainX)를 사용해야 함)
x_train, x_val, y_train, y_val = train_test_split(trainX, labels, test_size=0.25, random_state=seed, stratify=labels)

print(f'shape of train data, x_train: {x_train.shape}, y_train: {y_train.shape}')
print(f'shape of test  data, x_val  : {x_val.shape}, y_val  : {y_val.shape}')

 

3. Model Learning (Logistic Regression) & Evaluation: Validation Data

# 학습 모델을 정의
clf = LogisticRegression(random_state=seed)

# 학습 데이터 (x_train)에 따라 최적화
clf.fit(x_train, y_train)

# 검증용 데이터 (x_val)에 대해 예측
pred_val = clf.predict(x_val)
# 검증용 데이터 라벨 (y_test)로 모델 성능의 경향성 살펴보기
# 현재 사용하는 데이터 셋은 학습 데이터의 표본이 적으므로 신뢰도가 떨어질 수 있음
print(f'accuracy for validation data accuracy: {accuracy_score(y_val, pred_val)}')

print('confusion matrix:')
print(confusion_matrix(y_val, pred_val))

 

4. Model Learning (Logistic Regression) & Prediction: Train Data

# 전체 데이터 (trainX)에 대해 최적화
clf.fit(trainX, labels)

# 평가용 데이터 (testX)에 대해 예측
pred_result = clf.predict(testX)

# 예측 데이터 확인
pred_result	# array([0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0])

 

5. Submit

# 제출 데이터 포맷 확인
submit.head()

# 제출 포맷에 맞춰 예측 데이터를 삽입 후 저장
submit['label'] = pred_result

submit.to_csv('Baseline.csv', index=False)