原始数据:
(1)导入库
import pandas as pd
import numpy as np
(2)导入数据集:数据中存在值为0的丢失数据情况
dataset = pd.read_csv('50_Startups.csv')
X = dataset.iloc[ : , :-1].values
Y = dataset.iloc[ : , 4 ].values
(3)数据预处理:
1:将丢失数据0使用平均值代替
from sklearn.preprocessing import Imputer
imputer = Imputer(missing_values = 0, strategy = "mean", axis = 0)
imputer = imputer.fit(X[:,0:3])
X[:,0:3] = imputer.transform(X[:,0:3])
2:将类别数据数字化
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
labelencoder = LabelEncoder()
X[: , 3] = labelencoder.fit_transform(X[ : , 3])
3:将类别数字转换为onehot类型
onehotencoder = OneHotEncoder(categorical_features = [3])
X = onehotencoder.fit_transform(X).toarray()
(4)躲避虚拟变量陷阱:丢弃第一列数据,他可以被其他属性预测
X = X[: , 1:]
(5)拆分数据集为训练集和测试集
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)
(6)在训练集上训练多元线性回归模型
from sklearn.linear_model import LinearRegression
regressor = LinearRegression()
regressor = regressor.fit(X_train, Y_train)
(7)在测试集上预测结果
y_pred = regressor.predict(X_test)
多元线性回归: