회귀 KNeighborsRegression

 

라이브러리 불러오기

import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split

 

변수 제거", "데이터 분리", "가변수화

# 변수 제거
del_cols = ['컬럼명']
data.drop(del_cols, axis=1, inplace = True)

# 데이터 분리
target = '타겟 컬럼'
x = data.drop(target, axis=1)
y = data.loc[:,target]

# 가변수화
dum_cols = ['컬럼명', '컬럼명', '컬럼명']
x = pd.get_dummies(x, columns = cols, drop_first = True)

 

학습용 평가용 데이터 분리, 정규화

# 학습용, 평가용 데이터 분리
from sklearn.model_selection import train_test_split
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size = 0.3, random_state = 1)

# 정규화
from sklearn.preprocessing import MinMaxScaler

scaler = MinMaxScaler()
scaler.fit(x_train)
x_train = scaler.transform(x_train)
x_test = scaler.transform(x_test)

 

성능 예측

from sklearn.neighbors import KNeighborsRegression

분류 - LogisticRegression

 

1. 라이브러리 불러오기

import pandas as 

impot numpy as np

import maplotlib.pyplot as plt

import seaborn as sns

 

2. 데이터 불러오기

data = pd.read_csv('데이터.csv')

 

3. 학습용 평가용 데이터

from sklearn.model_selectoin import train_test_split

x_train, x_test, y_train, y_test = train_test_split(x, y, test_size = 0.3, random_state=2023)

 

4. 모델링

# 1단계 : 불러오기

from sklearn.linear_model import LogisticRegression

from sklearn.metrics import confision_matrix, classification_report

# 2단계: 선언하기

model = LogisticRegression()

# 3단계 : 학습하기

model.fit(x_train, y_train)

 

학습 되었을 떄 출력

# 4단계 : 예측하기

y_pred = model.predict(x_test)

# 5단계 평가하기

print(confusion_maxtrix(y_test, y_pred))

print(classification_report(y_test, y_pred))

평가 데이터 출력 모습

 

필기

수업시간 필기 1

 

필기 2

수업시간 필기 2

 

XGBClassifier

  • XGBClassifier에 대한 GPT의 답변
  • params 대입 방법

 

XGBClassifier에 대한 GPT의 답변

 

 

params 대입 방법

 

# 라이브러리 불러오기

import numpy as np
import  pandas as pd
import matplotlib.pyplot as plt

from sklearn.model_selection import train_test_split

# 데이터 불러오기

data = pd.read_csv(path)

# target 확인
target = 'ADMIT'

# 데이터 분리
x = data.drop(target, axis=1)
y = data[target]

# 7:3으로 분리
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.3, random_state=1)

# 선언하기
model = XGBClassifier(max_depth=5, random_state=1)

# 학습하기
model.fit(x_train,y_train)



 

학습 결과 출력

 

# 예측하기

y_pred = model.predict(x_test)

 

# 평가하기

print(confusion_matrix(y_test, y_pred))
print(classification_report(y_test,y_pred))

평가물 출력

 

 

내용

  • model 저장하기 joblib

지도 학습 분류 문제

랜덤 포레스트 분류

  1. 환경 준비
  2. 데이터 준비
  3. 모델링
1. 환경준비
# 라이브러리 불러오기

from  sklearn.ensemble import RandomForestClassifier

2. 데이터 준비
data = pd.read_csv('데이터.csv')

target = 'medv'

# 데이터 분리
x = data.drop(target, axis=1)
y = data.loc[:,target]


# 학습용, 평가용 데이터 분리
from sklearn.model_selection import train_test_split

x_train, x_test, y_train, y_test = train_test_split(x,y, test_size = 0.3, random_state = 2023)
4. 모델링
#  선언하기

model = RandomForestClassifier(max_depth=5, random_state=1)

#  학습하기

model.fit(x_train_s, y_train)

# 예측하기

y_pred = model.predict(x_test)

# 평가하기

print(confusion_matrix(y_test, y_pred))
print(classification_report(y_test, y_pred))

모델 학습 시, 출력되는 결과

 

평가물 출력 모습

지도 학습 분류 문제

결정나무 분류

  1. 환경 준비
  2. 데이터 이해
  3. 데이터 준비
  4. 모델링
  5. 기타
  • graphviz
  • 변수 중요도
1. 환경준비
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import warnings

warnings.filterwarnings(action='ignore')
%config InlineBackend.figure_format = 'retina'

# 데이터 읽어오기
data = pd.read_csv(path)
 
2. 데이터 이해
data.head()
data.describe()
data['컬럼명'].value_counts()
data.corr()
 
3. 데이터 준비
1) x, y 분리
target = '타겟 컬럼'

x = data.drop(target, axis = 1)
y = data.loc[:, target]

2) 학습용, 평가용 데이터 분리
from sklearn.model_selection import train_test_split
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size = 0.3, random_state=1)
 
4. 모델링
# 1단계
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import confusion_matrix, classification_report

# 2단계 선언하기
model = DecisionTreeClassifier(max_depth=5, random_state=1

# 3단계 학습하기
model.fit(x_train, y_train)

# 4단계 예측하기
y_pred = model.predict(x_test)

# 5단계 평가하기
print( confusion_matrix(y_test, y_pred) )
print( classification_report(y_test, y_pred) )
 
graphviz
# 시각화 모듈
from sklearn.tree import export_graphviz
from IPython.display import Image

# 이미지 파일
export_graphviz( model,
                            out_file = 'tree.dot',
                            feature_names = x.columns,
                            class_names = ['No', 'Yes'],
                            rounded = True,
                            precision = 2,
                            filled = True)
# 파일 변환
!dot tree.dot -Tpng -otree.png -Gdpi=300

# 이미지 파일 표시
Images(filename = 'tree.png')
 
변수 중요도 시각화
plt.figure(figsize=(5,5))
plt.barh(list(x), model.feature_importances_ )
plt.show()

 

+ Recent posts