본문 바로가기
IT 공부/Machine Learning

머신 러닝 학습_4

by 랜턴K 2024. 6. 25.
반응형

이전 글에서 본 데이터 전처리 내용이다. 
결측치를 포함한 열을 제거하고,

머신러닝 시키기 간편한 숫자 데이터만 남기기 위해서, str 데이터를 드롭했다. 


X_full.dropna(axis=0, subset=['SalePrice'], inplace=True)
- dropna() : 결측치를 포함한 행 또는 열을 날려버린다.
- axis = 0 : 0은 행 / 1은 열을 날리게 설정한다는 뜻

- subset= ['SalePrice'] : SalePrice 열에 대해서 결측치 여부를 판단한다는 뜻 
- inplace = True : True 면 실 데이터에도 결측치 제거를 반영
                           / False면 실 데이터는 내비두고, 결측치 제거 데이터의 사본을 전달한다

X_full.drop(['SalePrice'], axis=1, inplace=True)
- drop() : 행 또는 열을 날려버린다

X = X_full.select_dtypes(exclude=['object'])
- select_dtypes() : 데이터 타입을 감지하여 select 한다. 
- exclude = ['object'] : object 타입에 해당하는 타입을 제거하는 조건 
(조건으로 include도 사용할 수 있다 

import pandas as pd
from sklearn.model_selection import train_test_split

# Read the data
X_full = pd.read_csv('../input/train.csv', index_col='Id')
X_test_full = pd.read_csv('../input/test.csv', index_col='Id')

# Remove rows with missing target, separate target from predictors
X_full.dropna(axis=0, subset=['SalePrice'], inplace=True)
y = X_full.SalePrice
X_full.drop(['SalePrice'], axis=1, inplace=True)

# To keep things simple, we'll use only numerical predictors
X = X_full.select_dtypes(exclude=['object'])
X_test = X_test_full.select_dtypes(exclude=['object'])

# Break off validation set from training data
X_train, X_valid, y_train, y_valid = train_test_split(X, y, train_size=0.8, test_size=0.2,
                                                      random_state=0)

 

X_train 데이터에 대한 개괄적 정보를 파악해본다.

몇 개의 열과 행이 학습 데이터로 남았는지 알 수 있다. 

아까는 SalePrice에 결측치가 존재하는 지만 확인했는데,

(y값이 결측치면, 모델 학습을 시킬 수 없을 뿐더러, validation도 못하므로)

지금은 학습 과정에서 방해가 될 수 있는 나머지 열에 대해서도 결측치를 확인해본다. 

 

isnull() : 결측치가 있으면 True / 없으면 False -> 동일한 크기의 DataFrame으로 반환한다 

sum() : True를 전부 산술합으로 더해, 몇개의 결측치가 있는 지 확인한다 
             기본적으로 각 열에 대해 산술합을 실행한다. -> pandas Series로 반환한다 

 

 

 

# Shape of training data (num_rows, num_columns)
print(X_train.shape)

# Number of missing values in each column of training data
missing_val_count_by_column = (X_train.isnull().sum())

 

pandas series는 인덱스-값의 구조로 되어있다.

dictionary와 비슷한 자료 구조라 볼 수 있다. 

 

결측치 갯수가 0개 이상이면 -> True 
True인 인덱스만 별도 추출하고 -> pandas index 타입으로 저장되어 다른 함수나 메서드 적용이 안된다. 

tolist() 메서드를 통해, list로 다시 변환한다 

이제 다른 일반적인 문법 적용이 된다!! 

 

결측치가 있는 열을 drop시켜서 전처리를 진행한다. 

# Fill in the line below: get names of columns with missing values
index_col = missing_val_count_by_column[missing_val_count_by_column > 0].index 
print(index_col)
list_col = index_col.tolist()
print(list_col)
# Your code here

# Fill in the lines below: drop columns in training and validation data
reduced_X_train = X_train.drop(list_col, axis =1)
reduced_X_valid = X_valid.drop(list_col, axis = 1 )

# Check your answers
step_2.check()

 

위의 과정을 솔루션은 아래처럼 한 줄에 작성했다. 

X_train.columns 에 속한 모든 col에 대해서 

만약, 해당 column에 Null값이(isnull()결과가 True) 하나라도 있다면 (any())

col_with_missing에 해당 col을 저장한다. 

# Get names of columns with missing values
cols_with_missing = [col for col in X_train.columns
                     if X_train[col].isnull().any()]

# Drop columns in training and validation data
reduced_X_train = X_train.drop(cols_with_missing, axis=1)
reduced_X_valid = X_valid.drop(cols_with_missing, axis=1)

 

여기까지 결측치를 제거하는 방법으로 데이터 전처리 및 학습을 진행하는 내용이다.


임퓨테이션을 시킨다면 어떻게 해야 할까? 

sklearn에서 SimpleImputer 함수를 끌어온다.

이 함수는 여러가지 조건을 주고 임퓨테이션을 시킬 수 있게 도와준다. 

 

임퓨테이션도 모델 학습 -> 예측과 비슷하게 진행된다. 

fit -> transform 

fit 임퓨테이션 과정을 학습하는 것이고,

transform은 실제 임퓨테이션한 데이터를 반환한다. 

 

트레인 데이터를 기준으로 먼저 fit -> transform을 진행하고,

테스트 데이터는, 트레인 데이터와 동등하게 fit해진 대로, transform만 진행한다 

simpleimputer는 Numpy의 array를 반환하므로

다시 pd.DataFrame으로 변환시켜준다. 

그래야... model 학습을 시키니까..

from sklearn.impute import SimpleImputer

# Fill in the lines below: imputation
imputor = SimpleImputer()# Your code here
imputed_X_train = pd.DataFrame(imputor.fit_transform(X_train))
imputed_X_valid = pd.DataFrame(imputor.transform(X_valid))

# Fill in the lines below: imputation removed column names; put them back
imputed_X_train.columns = X_train.columns
imputed_X_valid.columns = X_valid.columns
반응형

'IT 공부 > Machine Learning' 카테고리의 다른 글

머신 러닝 학습 5. 범주형 데이터 (Categorial Variable)  (0) 2024.07.01
머신 러닝 학습_3  (0) 2024.06.20
머신 러닝 학습_2  (0) 2024.06.18
머신러닝 학습_1  (0) 2024.06.17
머신 러닝 공부 시작  (1) 2024.06.16