머신러닝
[키홈] Python Machine Learning Cheat Sheet
키홈
2023. 7. 22. 18:07
1. 환경 세팅
[1-1] 파이썬 kaggle 기본 세팅
# This Python 3 environment comes with many helpful analytics libraries installed
# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python
# For example, here's several helpful packages to load
import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
pd.set_option('max_columns',130, 'max_rows', 130)
# Input data files are available in the read-only "../input/" directory
# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory
import os
for dirname, _, filenames in os.walk('/kaggle/input'):
for filename in filenames:
print(os.path.join(dirname, filename))
# You can write up to 5GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using "Save & Run All"
# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session
[1-2] 데이터 불러오기
train = pd.read_csv('/kaggle/input/house-prices-advanced-regression-techniques/train.csv')
train
2. 데이터 시각화
[2-1] DataFrame 상위/하위 5개만 출력
train_df.head()
# train_df dataframe의 상위 5개를 출력한다
train_df.tail()
# train_df dataframe의 하위 5개를 출력한다
[2-2] DataFrame (행,열)의 개수를 출력
train_df.shape
# train_df의 (행,열)을 출력한다
[2-3] DataFrame 특정 column 통계값 출력
train_df['Fare'].mean()
# train_df의 Fare column의 평균값 출력
train_df['Fare'].max()
# train_df의 Fare column의 최대값 출력
train_df['Fare'].min()
# train_df의 Fare column의 최소값 출력
train_df['Fare'].std()
# train_df의 Fare column의 표준편차값 출력
train_df['Fare'].describe()
# train_df의 Fare column의 통계값 출력
[2-3] DataFrame Null/Nan값 확인
train_df.isnull()
# train_df 데이터의 빈값(NaN, Null)을 확인
train_df.isnull().sum()
# train_df의 각 column별 null값의 개수를 확인
train_df['Age'] = train_df['Age'].fillna(train_df['Age'].mean())
# train_df의 age column의 Nan값에 train_df['Age']의 평균값을 넣어준다
# 이렇게 만들어진 column을 train_df['Age']에 할당해준다
[2-4] DataFrame filtering
train_df[train_df['Pclass'] == 3]
# train_df의 pclass가 3인것들만 출력 (Filtering)
train_df[train_df['Fare'] > 10]
# train_df의 Fare가 10보다 큰것들만 출력 (Filtering)
train_df[train_df['Embarked'] == 'C']
# train_df의 Embarked가 C인 것들만 출력 (Filtering)
train_df2 = train_df[train_df['Embarked'] == 'C']
# train_df의 Embarked가 C인 것들만 출력 (Filtering)
# 이걸 train_df2로 할당
3. 데이터 전처리
[3-1] DataFrame에서 특정 column 삭제
train = train.drop(['MSZoning'],1)
# train dataframe에서 MSZoning column을 삭제
train = train.drop(['MSZoning', 'Street', 'Alley', 'LotShape', 'LandContour', 'Utilities',
'LotConfig', 'LandSlope', 'Neighborhood', 'Condition1', 'Condition2',
'BldgType', 'HouseStyle', 'RoofStyle', 'RoofMatl', 'Exterior1st',
'Exterior2nd', 'MasVnrType', 'ExterQual', 'ExterCond', 'Foundation',
'BsmtQual', 'BsmtCond', 'BsmtExposure', 'BsmtFinType1', 'BsmtFinType2',
'Heating', 'HeatingQC', 'CentralAir', 'Electrical', 'KitchenQual',
'Functional', 'FireplaceQu', 'GarageType', 'GarageFinish', 'GarageQual',
'GarageCond', 'PavedDrive', 'PoolQC', 'Fence', 'MiscFeature',
'SaleType', 'SaleCondition'],1)
# train dataframe에서 여러 column을 삭제
[3-2] 두개의 DataFrame을 합쳐줌 (단순히 좌우로 or 위아래로 합침)
total_df = pd.concat([temp_df1, temp_df2] 0)
# 위아래로 합쳐줌
# temp_df1 (100행,10열) + temp_df2 (200행, 10열) -> total_df (300행, 10열)
total_df = pd.concat([temp_df1, temp_df2] 1)
# 좌우로 합쳐줌
# temp_df1 (100행,10열) + temp_df2 (100행, 20열) -> total_df (100행, 30열)
[3-2] OHE(One Hot Encoding) 특정 column의 값들을 개별 column으로 바꿔서 만들어줌
train_embarked_df = pd.get_dummies(train_df['Embarked'], prefix='Embarked')
# train_df의 Embarked column의 값들을 개별 column으로 만들어줌
# 새롭게 만들어진 column 앞에 Embarked_ prefix를 만들어줌
train_df2 = pd.concat([train_df, train_embarked_df],1)
# 개별 column으로 만든 train_embarked_df를 train_df의 오른쪽에 붙혀줌
# ex. train_df (300행, 20열), train_embarked_df (300행, 3열) -> train_df2 (300행 23열)
train_df2 = train_df2.drop(['Embarked'],1)
기존에 있던 Embarked 지워줌