###### tags: `machine learning`|`python` # 機器學習 - 簡單線性回歸(Simple Linear Regression) ## 介紹 <font color="#3355FF">**一個**</font>應變數($Y$)和<font color="#3355FF">**一個**</font>自變數($X$)之<font color="#008000">線性關係</font>(皆為<font color="#f00">連續型數</font>) > 目的: > * 解釋data過去現象 > * 利用自變數($X$)來預測應變數($Y$)的未來可能數值 --- 方程式:$y = b_0 + b_1x_1$ ![](https://i.imgur.com/UdcuOxs.png) ![](https://i.imgur.com/SGt2WSp.png) ![](https://i.imgur.com/oKXNeyk.png) --- ## 練習 機器學習-作業4 ![](https://i.imgur.com/x89UbMk.png) ```python= # Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # Importing the dataset dataset = pd.read_csv("Salary_Data.csv") x = dataset.iloc[:, :-1].values y = dataset.iloc[:, 1].values ''' # Missing Data # Categorical Data ''' # 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=0) ''' # Feature Scaling ''' # Simple Linear Regression from sklearn.linear_model import LinearRegression regressor = LinearRegression() regressor.fit(x_train, y_train) y_pred = regressor.predict(x_test) plt.scatter(x_train, y_train, color = 'red') plt.plot(x_train, regressor.predict(x_train), color = 'blue') plt.title("Salary vs Experience (training set)") plt.xlabel("Years of Experience") plt.ylabel("Salary") plt.show() plt.scatter(x_test, y_test, color = 'red') plt.plot(x_train, regressor.predict(x_train), color = 'blue') plt.title("Salary vs Experience (testing set)") plt.xlabel("Years of Experience") plt.ylabel("Salary") plt.show() ```