Jun's Blog
다중 회귀 분석 및 활용 예시 본문
회귀분석 및 활용 예시의 데이터들을 이어서 활용하여 다중 회귀 분석을 진행하였습니다.
print('multidf.columns')
print(multidf.columns)
# 독립 변수와 종속 변수를 분리
independent_variable = ['cylinders', 'horsepower', 'weight']
x = multidf[independent_variable]
y = multidf['mpg']
# 훈련용 데이터와 테스트용 데이터 분리
x_train, x_test, y_train, y_test = \
train_test_split(x, y, test_size=0.3, random_state=10)
print(f'훈련용 데이터 형상 : {x_train.shape}')
print(f'테스트용 데이터 형상 : {x_test.shape}')
# 다중 회귀 분석을 위한 모델 생성
multi_model = LinearRegression()
multi_model.fit(x_train, y_train)
r_square = multi_model.score(x_test, y_test)
print(f'R^2 결정 계수 : {x_train.shape}')
slope = multi_model.coef_.tolist()
print(f'기울기 : {slope}')
print(f'y절편 : {multi_model.intercept_}')
# 막대 그래프 그리기
plt.bar(independent_variable, slope)
plt.title('회귀식의 기울기')
plt.xlabel('변수')
plt.ylabel('기울기')
plt.savefig(dataOut + 'independent_variable_slope.png')
# 학습 후, 테스트 수행
prediction = multi_model.predict(x_test)
fig, axes = plt.subplots(1, 3, figsize=(12, 5))
for i, col in enumerate(x_test.columns): # ['cylinders', 'horsepower', 'weight']
axes[i].plot(x_train[col], y_train, 'o', label='훈련 데이터')
axes[i].plot(x_test[col], prediction, 'r+', label='예측값')
axes[i].set_xlabel(col)
axes[i].set_ylabel('mpg')
# 범례 위치는 데이터의 분포를 보시고, 적정 위치에 두세요.
axes[i].legend(loc='best')
plt.suptitle(f'독립 변수에 따른 종속 변수 산점도', size=15)
plt.savefig(dataOut + 'multivariance_regression.png')
'Python > 머신 러닝' 카테고리의 다른 글
클래스 분류와 KNN의 활용 예시 (0) | 2025.03.21 |
---|---|
클래스 분류의 정의와 SVM의 활용 예시 - (2) (0) | 2025.03.20 |
클래스 분류의 정의와 SVM의 활용 예시 - (1) (0) | 2025.03.20 |
기본 용어 간단 정리 및 실습 -(2) (0) | 2025.03.19 |
기본 용어 간단 정리 및 실습 -(1) (0) | 2025.03.18 |