前言:
前面用自寫函數解決了多元問題,現在用sklearn庫來解決多元線性問題
正文:
#老朋友,不介紹了
import numpy as np
from numpy import genfromtxt
#把線性回歸模型庫單獨導出來
from sklearn import linear_model
#把畫圖工具庫導出來
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
#讀入你的數據
data = genfromtxt(r"Delivery.csv",delimiter = ',')
print(data)
數據圖片:
#切割數據,和原先一樣的方法
#需要什么就切什么
x_data = data[:,:-1]
y_data = data[:,-1]
print(x_data)
print(y_data)
切分后的數據:
#創建回歸模型
#帶入切分好的數據
model = linear_model.LinearRegression()
model.fit(x_data,y_data)
#系數
print("model.coef:",model.coef_)
#截距
print("model.intercept:",model.intercept_)
#測試一下
x_test = [[102,4]]
predict = model.predict(x_test)
print("predict:",predict)
測試結果如下:
#使用add_subplot函數來創建3d面
ax = plt.figure().add_subplot(111,projection = '3d')
#描點並設置參數(函數介紹在上一篇內容中)
ax.scatter(x_data[:,0],x_data[:,1],y_data,c='r',marker = 'o',s=100)
x0 = x_data[:,0]
x1 = x_data[:,1]
#使用meshgrid函數生成網格矩陣
x0,x1 = np.meshgrid(x0,x1)
z = model.intercept_ + x0*model.coef_[0]+x1*model.coef_[1]
#畫3d圖
ax.plot_surface(x0,x1,z)
#設置坐標軸名稱
ax.set_xlabel('miles')
ax.set_ylabel('num of delivers')
ax.set_zlabel('time')
#顯示圖像
plt.show()
總結:
效果還是不錯的,而且這個圖可以移動,方便查看!