from sklearn.datasets import make_regression
import matplotlib.pyplot as plt
X, y = make_regression(n_samples=250, n_features=1, noise=50, random_state=2)
plt.scatter(X,y, s=2)
plt.show()
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
# 한글 깨짐 없이 나오게 설정
from matplotlib import rcParams # 인코딩 폰트 설정
rcParams['font.family'] = 'New Gulim'
rcParams['font.size'] = 10
x_train, x_test, y_train, y_test = train_test_split(X,y, test_size=.20, random_state=0)
x_train.shape, x_test.shape, y_train.shape, y_test.shape
# 모델 생성
model = LinearRegression()
# 학습하기
model.fit(x_train, y_train)
# 가중치, 편향치 구하기
model.coef_, model.intercept_ # (array([90.11061494]), 2.4224269924448585)
# 결정 계수
model.score(x_train, y_train) # 0.789267454050733
# 추정
pred = model.predict(x_test)
# 산점도
plt.scatter(x_test,y_test)
plt.plot(x_test, pred, 'r-')
plt.show()
# 추정
model.predict([[3.0]]) # 학습할 때 주는 데이터의 형식을 따른다
# x의 최소값, 최대값을 계수와 절편을 사용하여 y값을 계산한다
# ymin = model.coef_ * xmin + model.intercept_
# ymax = model.coef_ * xmax + model.intercept_
ymin = model.coef_ * X.min() + model.intercept_
ymax = model.coef_ * X.max() + model.intercept_
X.min(), ymin, X.max(), ymax
(-2.6594494563834883, array([-237.22219892]), 4.108692623805201, array([372.65924592]))
plt.scatter(X, y, s=3)
plt.plot([X.min(),X.max()], [ymin,ymax], "r-")
plt.show()