David의 개발 이야기!

[파트2 섹션6] 단순회귀 Simple Regression 본문

Udemy Python Machine Learning A-Z

[파트2 섹션6] 단순회귀 Simple Regression

david.kim2028 2022. 9. 11. 22:13
반응형

Simple Linear Regression

단순회귀를 적용하는 방법을 알아보고, 연차별 임금 예측 모형을 만들어보자! 

 

1. 라이브러리 호출하기 

Importing the libraries

 

2. 데이터셋 불러오기 

Importing the dataset

 

3. 훈련세트와 테스트 세트로 나누기

Splitting the dataset into the Training set and Test set

 

4. 단순선형회귀모델에 학습시키기

Training the Simple Linear Regression model on the Training Set

 

5. 테스트 세트 결과 예측하기 

Predicting the Test set results

 

6. 결과 시각화하기 

Visualizing the Training set and the Test set Results

 


각각 단계에 맞는 코드를 확인해보자 

 

1. Importing the libraries

import numpy as np
import pandas as pd
import matplotlib as plt

 

2. Importing the dataset

dataset = pd.read_csv("----")

x = dataset.iloc[:,:-1].values
y = dataset.iloc[:,-1].values

 

연차별 임금 데이터

 

3. Splitting the dataset into the Training set and Test set

from sklearn.model_selection import train_test_split
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=1)

 

4. Training the Simple Linear Regression model on the Training set

from sklearn.linear_model import LinearRegression
regressor = LinearRegression()
regressor.fit(x_train, y_train)

regression.fit 이 부분에서 x_train, y_train 훈련데이터로 모델 학습이 이뤄진다! 

 

 

5. Predicting the Test set results

y_pred = regressor.predict(x_test)

 

6. Visualizing the Training set and the Test set Results

 

6-1 Visualizing the Training set

plt.scatter(x_train, y_train, color='red')
plt.plot(x_train, regressor.predict(x_train), color='blue')
plt.title('Salary VS Experience(Train set)')
plt.xlabel('Years of Experiece')
plt.ylabel('Salary')
plt.show()

 

plt.scatter : 점을 찍어줌 

plt.plot : 그래프를 그려줌

plt.title : 제목을 적게 해줌

plt.xlable : x축명을 적을 수 있음 

plt.ylabel : y축명을 적을 수 있음

 

 

 

 

6-2 Visualizing the Test set

plt.scatter(x_test, y_test, color='red')
plt.plot(x_train, regressor.predict(x_train), color='blue')
#여기에 x_train 이 들어간건, 훈련데이터를 통해 모델을 학습시켰기 때문이다! 
plt.xlabel('Years of Experience')
plt.ylabel('Salary')
plt.show()

 

 

 

반응형
Comments