在 Python 中實現(xiàn)線性回歸算法有多種方式,以下是一種常用的方法:
1. 數(shù)據(jù)準備:將數(shù)據(jù)集劃分為訓練集和測試集,并進行特征縮放(將數(shù)據(jù)標準化)。
2. 導入必要的庫: NumPy 和 Pandas 用于數(shù)據(jù)操作, Matplotlib 用于可視化。
3. 引入線性回歸模型:引入 Scikit-Learn 中的線性回歸模型,如下所示:
from sklearn.linear_model import LinearRegression
4. 創(chuàng)建線性回歸對象:創(chuàng)建 LinearRegression() 對象。
lin_reg = LinearRegression()
5. 訓練模型:使用訓練集進行訓練。
lin_reg.fit(X_train, y_train)
其中,X_train 是訓練集特征,y_train 是訓練集標簽。
6. 預測結果:使用測試集進行預測。
y_pred = lin_reg.predict(X_test)
其中,y_pred 是測試集的預測標簽。
7. 可視化:使用 Matplotlib 可視化結果。
plt.scatter(X_test, y_test, color='red')
plt.plot(X_test, y_pred, color='blue')
plt.title('Linear Regression')
plt.xlabel('Independent Variable')
plt.ylabel('Dependent Variable')
plt.show()
完整代碼示例:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
# 讀取數(shù)據(jù)
dataset = pd.read_csv('data.csv')
# 準備數(shù)據(jù)
X = dataset.iloc[:, :-1].values
y = dataset.iloc[:, 1].values
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=1/3, random_state=None)
# 特征縮放
from sklearn.preprocessing import StandardScaler
sc_X = StandardScaler()
X_train = sc_X.fit_transform(X_train)
X_test = sc_X.transform(X_test)
# 創(chuàng)建線性回歸對象
lin_reg = LinearRegression()
# 訓練模型
lin_reg.fit(X_train, y_train)
# 預測結果
y_pred = lin_reg.predict(X_test)
# 可視化
plt.scatter(X_test, y_test, color='red')
plt.plot(X_test, y_pred, color='blue')
plt.title('Linear Regression')
plt.xlabel('Independent Variable')
plt.ylabel('Dependent Variable')
plt.show()
注:data.csv 數(shù)據(jù)集應該包含兩列數(shù)據(jù),第一列為特征,第二列為標簽。