Python矩陣回歸並視覺化

2021-10-03 21:43:47 字數 2194 閱讀 2771

from matplotlib import pyplot as plt

import numpy as np

from mpl_toolkits.mplot3d import axes3d

fig = plt.figure(figsize=(10

,6))

ax = axes3d(fig)

#列出實驗資料

point=[[

2,3,

48],[

4,5,

50],[

5,7,

51],[

8,9,

55],[

9,12,

56]]plt.xlabel(

"x1"

)plt.ylabel(

"x2"

)#表示矩陣中的值

isum =

0.0x1sum =

0.0x2sum =

0.0x1_2sum =

0.0x1x2sum =

0.0x2_2sum =

0.0ysum =

0.0x1ysum =

0.0x2ysum =

0.0#在圖中顯示各點的位置

for i in

range(0

,len

(point)):

x1i=point[i][0

] x2i=point[i][1

] yi=point[i][2

] ax.scatter(x1i, x2i, yi, color=

"red"

) show_point =

"["+

str(x1i)

+","

+str

(x2i)

+","

+str

(yi)

+"]"

ax.text(x1i,x2i,yi,show_point)

isum = isum+

1 x1sum = x1sum+x1i

x2sum = x2sum+x2i

x1_2sum = x1_2sum+x1i**

2 x1x2sum = x1x2sum+x1i*x2i

x2_2sum = x2_2sum+x2i**

2 ysum = ysum+yi

x1ysum = x1ysum+x1i*yi

x2ysum = x2ysum+x2i*yi

# 進行矩陣運算

# _mat1 設為 mat1 的逆矩陣

m1=[

[isum,x1sum,x2sum]

,[x1sum,x1_2sum,x1x2sum]

,[x2sum,x1x2sum,x2_2sum]

]mat1 = np.matrix(m1)

m2=[

[ysum]

,[x1ysum]

,[x2ysum]

]mat2 = np.matrix(m2)

_mat1 =mat1.geti(

)mat3 = _mat1*mat2

# 用list來提取矩陣資料

m3=mat3.tolist(

)a0 = m3[0]

[0]a1 = m3[1]

[0]a2 = m3[2]

[0]# 繪製回歸線

x1 = np.linspace(0,

9)x2 = np.linspace(0,

12)y = a0+a1*x1+a2*x2

ax.plot(x1,x2,y)

show_line =

"y="

+str

(a0)

+"+"

+str

(a1)

+"x1"

+"+"

+str

(a2)

+"x2"

plt.title(show_line)

plt.show(

)

執行效果如下:

歡迎**:620139909

python隨機漫步資料,並視覺化

randow walk.py內的 隨機漫步 from random import choice class randomwalk 乙個生成隨機漫步資料的類 def init self,num points 5000 初始化隨機漫步的屬性 self.num points num points 所有隨機...

python爬蟲(4) 統計並視覺化資料

爬取資料的三字真言 整理清洗資料 更新資料庫 資料的視覺化 下面我幾句我這幾天所的視覺化資料統計的知識,來簡單總結一下知識點 我們上 引入我們所需要的庫檔案 import pymongo from string import punctuation import charts 連線資料庫 clien...

python讀取excel資料,並視覺化展現

coding utf 8 import pandas as pda import matplotlib.pyplot as pyl import matplotlib.font manager from collections import counter 配置變數區 start zhibanfil...