아래는 sklearn을 사용한 회귀 분석의 예시 코드입니다.
python
from sklearn.linear_model import LinearRegression
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# 데이터 불러오기
df = pd.read_csv("heights.csv")
# 데이터 시각화
X = df["height"]
y = df["weight"]
plt.plot(X, y, 'o')
plt.show()
# 모델 생성 및 학습
line_fitter = LinearRegression()
line_fitter.fit(X.values.reshape(-1,1), y)
# 예측
y_predicted = line_fitter.predict(X.values.reshape(-1,1))
# 기울기와 절편 출력
print("기울기:", line_fitter.coef_)
print("절편:", line_fitter.intercept_)
# 예측 결과 시각화
plt.plot(X, y, 'o')
plt.plot(X, y_predicted)
plt.show()
위 코드는 "heights.csv"라는 파일에서 키와 몸무게 데이터를 불러와 선형 회귀 분석을 수행하는 예시입니다. 데이터를 시각화하고, LinearRegression 모델을 생성하고 학습시킨 후, 예측 결과를 시각화합니다. 마지막으로 기울기와 절편을 출력합니다.