簡單的線性回歸程序
我們將展示一個簡單線性回歸程序的例子。公式如下: y = b0 + b1 * x1 - y = 因變量 (DV) b0 = 常數
在本文中,我們將展示一個簡單線性回歸程序的示例。
[sc_fs_faq html='true'headline='h2″ img='' question='Simple Linear Regression Program' img_alt='' css_class=''] 導入庫
導入數據集
將數據集拆分成訓練集和測試集
訓練訓練集上的簡單線性回歸模型
預測測試集結果
可視化訓練集結果
可視化測試集結果
[/sc_fs_faq]
公式如下:
y = b0 + b1 * x1
y = 因變量 (DV)
b0 = 常數
b1 = 係數
x1 = 自變量 (IV)
這是該程序的一個示例:
導入庫
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
導入數據集
dataset = pd.read_csv('dataset-file.csv')
x = dataset.iloc[:, :-1].values
x = dataset.iloc[:, -1].values
用您的文件替換dataset-file.csv文件並提及文件的完整路徑。
將數據集拆分為訓練集和測試集
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)
在訓練集上訓練簡單線性回歸模型
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.predit(x_train), color = 'blue')
plt.title('Name of the graph')
plt.xlabel('Name of the x label')
plt.ylabel('name of the y label')
plt.show()
可視化測試集結果
plt.scatter(x_test, y_test, color = 'red')
plt.plot(x_train, regressor.predit(x_train), color = 'blue')
plt.title('Name of the graph')
plt.xlabel('Name of the x label')
plt.ylabel('name of the y label')
plt.show()
我們已經展示了簡單的線性回歸程序。