Pandas는 파이썬을 위한 데이터 조작 및 분석 라이브러리다.
특히, Dataframe이라는 구조를 사용하여
데이터를 엑셀 시트와 비슷하게 다룰 수 있게 지원한다.
import pandas as pd
Pandas는 CSV, Excel, SQL, Json 등의 포맷 데이터를 지원한다.
아래 예시는 csv 파일의 경로를 melbourne_file_path 변수에 저장하고,
melbourn_data 변수에서 Pandas csv 파일 읽기 함수를 통해 데이터를 읽어들이는 과정이다.
# save filepath to variable for easier access
melbourne_file_path = '../input/melbourne-housing-snapshot/melb_data.csv'
# read the data and store data in DataFrame titled melbourne_data
melbourne_data = pd.read_csv(melbourne_file_path)
# print a summary of the data in Melbourne data
melbourne_data.describe()
melbourne_data.dropna(...)는
pd.read_csv(...) 후에, dropna(...)를 실행하게 되므로, pd를 칠 필요가 없다.
melbourne_data.dropna( axis = 0 ) 는
axis =0 는 행 axis = 1 은 열을 기준으로 하는데,
즉, 행을 기준으로 Null 값이 포함되어 있는 행 데이터를 삭제하는 작업이다.
# The Melbourne data has some missing values (some houses for which some variables weren't recorded.)
# We'll learn to handle missing values in a later tutorial.
# Your Iowa data doesn't have missing values in the columns you use.
# So we will take the simplest option for now, and drop houses from our data.
# Don't worry about this much for now, though the code is:
# dropna drops missing values (think of na as "not available")
melbourne_data = melbourne_data.dropna(axis=0)
변수 y에 melbourne_data 중 Price에 해당하는 칼럼의 값을 저장한다.
y = melbourne_data.Price
melbourn_feature 변수에, 컬럼 str을 입력하고
아래 선언문으로, 변수 X에 여러개의 칼럼 값을 행렬로 받아올 수 있다.
melbourne_features = ['Rooms', 'Bathroom', 'Landsize', 'Lattitude', 'Longtitude']
X = melbourne_data[melbourne_features]
describe() 함수, head() 함수를 통해서
X에 올바른 칼럼 값이 입력되었는지 확인할 수 있다.
describe() 함수, head() 함수는 지금 뿐 아니라, 처음 데이터 read 하고 나서 파악할 때도 쓴다.
X.describe()
X.head()
데이터가 준비되었으니
Define > Fit > Predict > Evaluate 순서대로 모델을 준비한다.
sklearn 라이브러리에서 tree 모듈의 DecisionTreeRegressor 함수를 불러온다
melbourne_model 변수에 DecisionTreeRegressor를 저장한다
random_state를 설정함으로써, 데이터 분할 시, 동일한 훈련 세트와 테스트 세트로 고정할 수 있다.
melbourne_model.fit(X,y)을 통해 훈련 시킨다.
from sklearn.tree import DecisionTreeRegressor
# Define model. Specify a number for random_state to ensure same results each run
melbourne_model = DecisionTreeRegressor(random_state=1)
# Fit model
melbourne_model.fit(X, y)
predict() 함수에 X 인풋 데이터를 추가하여,
y값을 예측한다.
print("Making predictions for the following 5 houses:")
print(X.head())
print("The predictions are")
print(melbourne_model.predict(X.head()))
'IT 공부 > Machine Learning' 카테고리의 다른 글
머신 러닝 학습 5. 범주형 데이터 (Categorial Variable) (0) | 2024.07.01 |
---|---|
머신 러닝 학습_4 (0) | 2024.06.25 |
머신 러닝 학습_3 (0) | 2024.06.20 |
머신 러닝 학습_2 (0) | 2024.06.18 |
머신 러닝 공부 시작 (1) | 2024.06.16 |