카테고리 없음

종속,독립변수 넣고 머신러닝

jaman 2025. 1. 14. 23:55

import pandas as pd
from sklearn.model_selection import train_test_split

# 예시 데이터프레임 로드
# transaction 데이터 로드
transaction_data = pd.read_csv("transaction.csv")

# 독립변수(X)와 종속변수(Y) 설정
X = transaction_data[['shippment_fee']]  # 독립변수
y = transaction_data['total_fee']       # 종속변수

# 학습 데이터와 테스트 데이터 분리
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

 

2. 트리 기반 모델 학습 (예: Random Forest)

 

from sklearn.ensemble import RandomForestRegressor

# 모델 초기화
model = RandomForestRegressor(n_estimators=100, random_state=42)

# 학습
model.fit(X_train, y_train)

 

3. 예측 및 평가

from sklearn.metrics import mean_squared_error, r2_score

# 테스트 데이터에 대한 예측
y_pred = model.predict(X_test)

# 평가 지표 계산
mse = mean_squared_error(y_test, y_pred)
r2 = r2_score(y_test, y_pred)

print(f"Mean Squared Error: {mse}")
print(f"R2 Score: {r2}")
 
 
(+)

4. 결과 시각화

결과를 시각적으로 확인하면 더 이해하기 쉬워

 

import matplotlib.pyplot as plt

plt.scatter(X_test, y_test, color='blue', label='Actual')
plt.scatter(X_test, y_pred, color='red', label='Predicted', alpha=0.5)
plt.xlabel("Shippment Fee")
plt.ylabel("Total Fee")
plt.legend()
plt.show()