1. 사이킷런(sklearn)라이브러리
# 선형 회귀 모델을 제공하는 서브라이브러리
from sklearn.linear_model import LinearRegression
# 데이터 분리 기능을 제공하는 서브라이브러리
from sklearn.model_selection import train_test_split
# train_test_split은 sklearn.model_selection 서브라이브러리 안에 있는 모듈
from sklearn.model_selection import train_test_split
# LinearRegression은 sklearn.linear_model 서브라이브러리 안에 있는 모듈
from sklearn.linear_model import LinearRegression
# 데이터 분리 기능을 사용해보기
# sklearn의 model_selection 서브라이브러리에서 train_test_split 모듈을 가져옵니다.
from sklearn.model_selection import train_test_split
# 선형 회귀 모델을 사용해보기
# sklearn의 linear_model 서브라이브러리에서 LinearRegression 모듈을 가져옵니다.
from sklearn.linear_model import LinearRegression
# 데이터 평가 기능을 사용해보기
# sklearn의 metrics 서브라이브러리에서 mean_squared_error 모듈을 가져옵니다.
from sklearn.metrics import mean_squared_error
# 데이터 생성
# pandas 라이브러리를 사용해 데이터프레임 형태의 데이터를 만듭니다.
import pandas as pd # pandas는 데이터를 다루기 위한 라이브러리입니다.
# 간단한 데이터셋을 만듭니다. Feature는 입력 데이터, Target은 정답 값입니다.
data = {'Feature': [1, 2, 3, 4, 5], 'Target': [3, 6, 9, 12, 15]}
df = pd.DataFrame(data) # 데이터프레임 생성
# 입력 데이터(X)와 출력 데이터(y)로 분리
# Feature 열은 입력으로 사용하고, Target 열은 출력 값으로 사용합니다.
X = df[['Feature']] # 입력 데이터 (2차원 배열로 만들어야 합니다)
y = df['Target'] # 출력 데이터 (1차원 배열로 저장)
# 데이터를 학습용 데이터와 테스트용 데이터로 나눕니다.
# train_test_split 함수는 데이터를 랜덤하게 분리하는 기능을 제공합니다.
X_train, X_test, y_train, y_test = train_test_split(
X, y, # 입력 데이터(X)와 출력 데이터(y)를 넣습니다.
test_size=0.2, # 전체 데이터의 20%를 테스트용 데이터로 사용합니다.
random_state=42 # 결과 재현을 위해 랜덤 시드를 고정합니다.
)
# 선형 회귀 모델 생성 및 학습
# LinearRegression 클래스는 선형 회귀 모델을 제공합니다.
model = LinearRegression() # 모델 객체 생성
model.fit(X_train, y_train) # 모델을 학습용 데이터로 학습시킵니다.
# 학습된 모델로 테스트 데이터를 예측
# 학습된 모델을 사용해 X_test의 출력 값을 예측합니다.
predictions = model.predict(X_test)
# 모델 성능 평가
# mean_squared_error 함수로 실제 값(y_test)과 예측 값(predictions) 간의 차이를 계산합니다.
mse = mean_squared_error(y_test, predictions) # 평균 제곱 오차 계산
print("Mean Squared Error:", mse) # 평가 결과 출력
2. 선형회귀
# 필요한 라이브러리 불러오기
import pandas as pd # 데이터 처리
from sklearn.model_selection import train_test_split # 데이터 분리
from sklearn.linear_model import LinearRegression # 선형 회귀 모델
from sklearn.metrics import mean_squared_error, r2_score # 평가 지표
# 1. 데이터 로드
# 'winequality-white.csv' 파일을 읽어와 데이터프레임 생성
data = pd.read_csv('datasets/winequality-white.csv')
# 2. 입력(X)과 출력(y) 분리
# 독립 변수(X): 'quality'를 제외한 나머지 특성
# 종속 변수(y): 'quality' 열
X = data.drop(['quality','alcohol'], axis=1) # 입력 데이터 (와인의 특성들)
y = data['quality'] # 출력 데이터 (와인의 품질 점수)
# 3. 데이터를 학습용과 테스트용으로 나누기
# 학습 데이터: 80%, 테스트 데이터: 20%
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 4. 모델 생성 및 학습
model = LinearRegression() # 선형 회귀 모델 생성
model.fit(X_train, y_train) # 학습 데이터로 모델 학습
# 5. 테스트 데이터로 예측 수행
y_pred = model.predict(X_test)
# 6. 모델 평가
mse = mean_squared_error(y_test, y_pred) # 평균 제곱 오차 계산
r2 = r2_score(y_test, y_pred) # 결정 계수 계산
# 결과 출력
print("Mean Squared Error:", mse)
print("R² Score:", r2)
모델평가코드
import numpy as np
# 평가 지표 계산
mse = mean_squared_error(y_test, y_pred) # 평균 제곱 오차
rmse = np.sqrt(mse) # 루트 평균 제곱 오차
r2 = r2_score(y_test, y_pred) # 결정 계수
# 평가 결과 출력
print("Mean Squared Error (MSE):", mse)
print("Root Mean Squared Error (RMSE):", rmse)
print("R² Score:", r2)
import matplotlib.pyplot as plt
# 실제 값 vs 예측 값 비교
plt.figure(figsize=(8, 6))
plt.scatter(y_test, y_pred, alpha=0.6, color='blue', label='Predicted vs Actual')
plt.plot([y_test.min(), y_test.max()], [y_test.min(), y_test.max()], 'r--', lw=2, label='Ideal Line')
plt.xlabel("Actual Values")
plt.ylabel("Predicted Values")
plt.title("Actual vs Predicted Values")
plt.legend()
plt.grid()
plt.show()
# 잔차(Residual) 시각화
residuals = y_test - y_pred # 잔차 계산
plt.figure(figsize=(8, 6))
plt.scatter(y_pred, residuals, alpha=0.6, color='purple')
plt.axhline(y=0, color='r', linestyle='--', lw=2)
plt.xlabel("Predicted Values")
plt.ylabel("Residuals")
plt.title("Residual Plot")
plt.grid()
plt.show()
로지스틱 선형회귀 모델
import numpy as np
import matplotlib.pyplot as plt
# 시그모이드 함수 정의
def sigmoid(z):
return 1 / (1 + np.exp(-z))
# 값 생성
z = np.linspace(-10, 10, 100) # -10부터 10까지 100개 점 생성
sigmoid_values = sigmoid(z)
# 그래프 그리기
plt.plot(z, sigmoid_values)
plt.title('Sigmoid Function')
plt.xlabel('z')
plt.ylabel('Sigmoid(z)')
plt.grid()
plt.show()
# 필요한 라이브러리 불러오기
import pandas as pd # 데이터 처리
from sklearn.model_selection import train_test_split # 데이터 분리
from sklearn.linear_model import LogisticRegression # 로지스틱 회귀 모델
from sklearn.metrics import accuracy_score, confusion_matrix # 평가 지표
# 1. 데이터 로드
# 'heart.csv' 파일을 읽어와 데이터프레임 생성
data = pd.read_csv('datasets/heart.csv')
# 2. 입력(X)과 출력(y) 분리
# 'target' 열이 심장병 여부 (1: 있음, 0: 없음)
X = data.drop('output', axis=1) # 독립 변수: 'output'을 제외한 모든 열
y = data['output'] # 종속 변수: 'output'
# 3. 데이터를 학습용과 테스트용으로 나누기
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42) # 학습 80%, 테스트 20%
# 4. 모델 생성 및 학습
model = LogisticRegression(max_iter=1000) # 로지스틱 회귀 모델 생성 (반복 횟수 1000으로 설정)
model.fit(X_train, y_train) # 학습 데이터로 모델 학습
# 5. 테스트 데이터로 예측 수행
y_pred = model.predict(X_test) # 학습된 모델로 테스트 데이터 예측
# 6. 모델 평가
accuracy = accuracy_score(y_test, y_pred) # 정확도 계산
conf_matrix = confusion_matrix(y_test, y_pred) # 혼동 행렬 계산
# 결과 출력
print("Accuracy:", accuracy) # 정확도 출력
print("Confusion Matrix:\n", conf_matrix) # 혼동 행렬 출력
# 정밀도, 재현율, F1 스코어 출력
print("Classification Report:\n", classification_report(y_test, y_pred))
4. 의사결정나무모델
import pandas as pd
df = pd.read_csv("datasets/heart.csv")
df.head()
# 필요한 라이브러리 불러오기
import pandas as pd # 데이터 처리
from sklearn.model_selection import train_test_split # 데이터 분리
from sklearn.tree import DecisionTreeClassifier # 의사결정 나무 모델
from sklearn.metrics import accuracy_score, confusion_matrix, classification_report
# 평가 지표
import matplotlib.pyplot as plt # 시각화
from sklearn.tree import plot_tree # 의사결정 나무 시각화
# 1. 데이터 로드
data = pd.read_csv('datasets/heart.csv')
# 2. 입력(X)과 출력(y) 분리
X = data.drop('output', axis=1) # 'output'을 제외한 모든 열
y = data['output'] # 심장병 여부 (1: 있음, 0: 없음)
# 3. 데이터를 학습용과 테스트용으로 나누기
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 4. 모델 생성 및 학습
model = DecisionTreeClassifier(max_depth=4, random_state=42) # 트리 깊이 제한
model.fit(X_train, y_train)
# 5. 테스트 데이터로 예측
y_pred = model.predict(X_test)
# 6. 모델 평가
accuracy = accuracy_score(y_test, y_pred) # 정확도 계산
conf_matrix = confusion_matrix(y_test, y_pred) # 혼동 행렬 계산
report = classification_report(y_test, y_pred) # 정밀도, 재현율, F1 스코어 계산
# 평가 결과 출력
print("Accuracy:", accuracy)
print("Confusion Matrix:\n", conf_matrix)
print("Classification Report:\n", report)
# 7. 의사결정 나무 시각화
plt.figure(figsize=(20, 10))
plot_tree(model, feature_names=X.columns, class_names=["No Disease", "Disease"], filled=True, rounded=True)
plt.title("Decision Tree Visualization")
plt.show()
5. 앙상블(Emsemble)모델
# 필요한 라이브러리 불러오기
import pandas as pd
from sklearn.model_selection import train_test_split # 데이터 분리
from sklearn.ensemble import VotingClassifier, BaggingClassifier, AdaBoostClassifier # 앙상블 모델
from sklearn.linear_model import LogisticRegression # 로지스틱 회귀
from sklearn.tree import DecisionTreeClassifier # 의사결정 나무
from sklearn.svm import SVC # 서포트 벡터 머신
from sklearn.metrics import accuracy_score, classification_report # 평가 지표
# 1. 데이터 로드 및 분리
data = pd.read_csv('datasets/heart.csv') # 데이터 로드
X = data.drop('output', axis=1) # 독립 변수
y = data['output'] # 종속 변수
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) # 데이터 분리
# 2. 보팅 앙상블
# 개별 모델 생성
model1 = LogisticRegression(max_iter=1000) # 로지스틱 회귀
model2 = DecisionTreeClassifier(max_depth=4) # 의사결정 나무
model3 = SVC(probability=True) # 서포트 벡터 머신 (확률 계산 가능)
# 보팅 모델 생성 (소프트 보팅)
voting_clf = VotingClassifier(
estimators=[('lr', model1), ('dt', model2), ('svc', model3)],
voting='soft'
)
voting_clf.fit(X_train, y_train) # 모델 학습
y_pred_voting = voting_clf.predict(X_test) # 예측
accuracy_voting = accuracy_score(y_test, y_pred_voting) # 정확도 계산
# 3. 배깅 앙상블
# 배깅 모델 생성
bagging_clf = BaggingClassifier(
estimator=DecisionTreeClassifier(),
n_estimators=10, # 10개의 의사결정 나무
random_state=42
)
bagging_clf.fit(X_train, y_train) # 모델 학습
y_pred_bagging = bagging_clf.predict(X_test) # 예측
accuracy_bagging = accuracy_score(y_test, y_pred_bagging) # 정확도 계산
# 4. 부스팅 앙상블
# 부스팅 모델 생성
boosting_clf = AdaBoostClassifier(
estimator=DecisionTreeClassifier(max_depth=2),
n_estimators=50, # 50개의 약한 학습기
random_state=42
)
boosting_clf.fit(X_train, y_train) # 모델 학습
y_pred_boosting = boosting_clf.predict(X_test) # 예측
accuracy_boosting = accuracy_score(y_test, y_pred_boosting) # 정확도 계산
# 5. 결과 출력
print("Voting Classifier Accuracy:", accuracy_voting)
print("Bagging Classifier Accuracy:", accuracy_bagging)
print("Boosting Classifier Accuracy:", accuracy_boosting)
print("\nClassification Report (Voting):\n", classification_report(y_test, y_pred_voting))
print("\nClassification Report (Bagging):\n", classification_report(y_test, y_pred_bagging))
print("\nClassification Report (Boosting):\n", classification_report(y_test, y_pred_boosting))
6. 랜덤포레스트 모델
# 필요한 라이브러리 불러오기
import pandas as pd # 데이터 처리
from sklearn.model_selection import train_test_split # 데이터 분리
from sklearn.ensemble import RandomForestClassifier # 랜덤 포레스트 모델
from sklearn.metrics import accuracy_score, classification_report # 평가 지표
import matplotlib.pyplot as plt # 시각화
# 1. 데이터 로드 및 분리
data = pd.read_csv('datasets/heart.csv') # 데이터 로드
X = data.drop('output', axis=1) # 입력 변수
y = data['output'] # 출력 변수 (심장병 여부)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) # 데이터 분리
# 2. 랜덤 포레스트 모델 생성 및 학습
rf_model = RandomForestClassifier(
n_estimators=100, # 100개의 의사결정 나무
max_depth=5, # 트리의 최대 깊이 제한
random_state=42 # 결과 재현성 유지
)
rf_model.fit(X_train, y_train) # 모델 학습
# 3. 테스트 데이터로 예측
y_pred = rf_model.predict(X_test)
# 4. 모델 평가
accuracy = accuracy_score(y_test, y_pred) # 정확도 계산
report = classification_report(y_test, y_pred) # 정밀도, 재현율, F1-스코어
print("Random Forest Accuracy:", accuracy)
print("\nClassification Report:\n", report)
# 5. 특성 중요도 시각화
feature_importances = rf_model.feature_importances_ # 특성 중요도 계산
features = X.columns
# 시각화
plt.figure(figsize=(10, 6))
plt.barh(features, feature_importances, color='skyblue')
plt.title("Feature Importance")
plt.xlabel("Importance Score")
plt.ylabel("Features")
plt.show()
# 특성 중요도 계산 및 정렬
import numpy as np
feature_importances = rf_model.feature_importances_ # 특성 중요도 계산
features = X.columns
# 정렬
sorted_idx = np.argsort(feature_importances)[::-1] # 중요도 내림차순 정렬
sorted_features = features[sorted_idx]
sorted_importances = feature_importances[sorted_idx]
# 표 형태로 출력
print("Feature Importances (Descending Order):")
for feature, importance in zip(sorted_features, sorted_importances):
print(f"{feature}: {importance:.4f}")
# 시각화
plt.figure(figsize=(10, 6))
plt.barh(sorted_features, sorted_importances, color='skyblue')
plt.title("Feature Importance")
plt.xlabel("Importance Score")
plt.ylabel("Features")
plt.gca().invert_yaxis() # 가장 중요한 특성이 위로 오도록 설정
plt.show()
'파이썬' 카테고리의 다른 글
이패스 신성진 김용재 와 함께하는 AI모델링 (0) | 2025.03.18 |
---|---|
12-4. 머신러닝 회귀모델 총정리 (이패스 신성진 김용재 와 함께하는 AI모델링) (0) | 2025.03.18 |
12-3. 머신러닝 분류모델 총정리(이패스 신성진 김용재 와 함께하는 AI모델링) (0) | 2025.03.18 |
13. 모델평가 (모델성능비교) (0) | 2025.03.18 |
12-1 데이터분할(분할, k-fold) (0) | 2025.03.18 |