= +
: 실제값
: 예측값
: 평균값
: 가중치(기울기)
: 편향(y절편)

coef_ : 회귀계수(가중치)intercept_ : 편향Linear Regression은 회귀모델에서만 사용 가능함
# 회귀모델 불러오기
from sklearn.linear_model import LinearRegression
# 회귀모델 평가지표 불러오기
from sklearn.metrics import mean_absolute_error, r2_score
k 최근접 이웃
학습용 데이터에서 k개의 최근접 이웃을 찾아 그 값들로 새로운 값을 예측함
k 값에 따라 예측 값이 달라져서 적절한 k 값 찾아야함
k를 1로 설정안함
k를 홀수로 설정
회귀와 분류에 모두에 사용된다.
# 정규화 전
plt.figure(figsize=(8, 2))
plt.boxplot(x_train, vert=False, labels=list(x))
plt.show()

# 정규화 방법 1
# 최댓값, 최솟값 구하기
x_max = x_train.max()
x_min = x_train.min()
# 정규화
x_train = (x_train - x_min) / (x_max - x_min)
x_test = (x_test - x_min) / (x_max - x_min)
# 정규화 방법 2
# 모듈 불러오기
from sklearn.preprocessing import MinMaxScaler
# 정규화
scaler = MinMaxScaler()
# scaler.fit(x_train)
x_train = scaler.fit_transform(x_train)
x_test = scaler.transform(x_test)
# 정규화 후
plt.figure(figsize=(8, 2))
plt.boxplot(x_train, vert=False, labels=list(x))
plt.show()

# 1단계: 불러오기
from sklearn.neighbors import KNeighborsRegressor
from sklearn.metrics import mean_absolute_error, r2_score
# 2단계: 선언하기
model = KNeighborsRegressor(n_neighbors=5)
# 3단계: 학습하기
model.fit(x_train, y_train)
# 4단계 예측하기
y_pred = model.predict(x_test)
# 5단계: 평가하기
print('Mae: ', mean_absolute_error(y_test, y_pred))
print('R2: ', r2_score(y_test, y_pred))
# 예측값, 실젯값 시각화
plt.plot(y_test.values, label='Actual')
plt.plot(y_pred, label='Predicted')
plt.legend()
plt.ylabel('Ozone')
plt.show()

# 1단계: 불러오기
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import confusion_matrix, classification_report
# 2단계: 선언하기
model = KNeighborsClassifier()
# 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))
분류의 경우 시각화가 어려움
데이터프레임에서 x와 y 데이터를 분리하고 난 뒤
가변수화를 진행한다.
# 가변수화 대상: Gender, JobSatisfaction, MaritalStatus, OverTime
dum = ['Gender', 'JobSatisfaction', 'MaritalStatus', 'OverTime']
# 가변수화
x = pd.get_dummies(x, columns=dum, drop_first=True, dtype=int)
# 확인
x.head()

max_depth, min_samples_leaf, min_samples_splitexpot_graphviz# 시각화 모듈 불러오기
from sklearn.tree import export_graphviz
from IPython.display import Image
# 이미지 파일 만들기
export_graphviz(model, # 모델 이름
out_file='tree.dot', # 파일 이름
feature_names=list(x), # Feature 이름
class_names=['die', 'survived'], # Target Class 이름
rounded=True, # 둥근 테두리
precision=2, # 불순도 소숫점 자리수
max_depth=3, # 표시할 트리 깊이
filled=True) # 박스 내부 채우기
# 파일 변환
!dot tree.dot -Tpng -otree.png -Gdpi=300
# 이미지 파일 표시
Image(filename='tree.png')
feature_importances_# 변수 중요도
plt.figure(figsize=(5, 5))
plt.barh(list(x), model.feature_importances_)
# plt.barh(list(x), model.best_estimator_.feature_importances_)
plt.show()

# 데이터프레임 만들기
df = pd.DataFrame()
df['feature'] = list(x)
df['importance'] = model.feature_importances_
df.sort_values(by='importance', ascending=True, inplace=True)
# 시각화
plt.figure(figsize=(5, 5))
plt.barh(df['feature'], df['importance'])
plt.show()

# 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))
# 1단계: 불러오기
from sklearn.tree import DecisionTreeRegressor
from sklearn.metrics import mean_absolute_error, r2_score
# 2단계: 선언하기
model = DecisionTreeClassifier(max_depth=5)
# 3단계: 학습하기
model.fit(x_train, y_train)
# 4단계: 예측하기
y_pred = model.predict(x_test)
# 5단계 평가하기
print(mean_absolute_error(y_test, y_pred))
print(r2_score(y_test, y_pred))