多變數線性回歸

2021-10-10 07:40:13 字數 2909 閱讀 7138

python**

推理部分

1 損失函式

注意,那個第一列為1的值是插入的,不是原始資料,為了彌補theta 0 這個引數。

2 特徵歸一化

3 損失函式

特徵歸一化處理

:param data:特徵值

:return: 特徵歸一化處理後的特徵值

'''return

(data - data.mean())

/ data.std(

)data = normalize_feature(data)

print

(data.head())

data.plot.scatter(

'size'

,'price'

, label=

'size'

)plt.show(

)data.plot.scatter(

'bedrooms'

,'price'

, label=

'bedrooms'

)plt.show(

)data.insert(0,

'ones',1

)x = data.iloc[:,

0:-1

]y = data.iloc[:,

-1]x = x.values

y = y.values

y = y.reshape(

(len

(y),1)

)def

costfunction

(x, y, theta)

:'''

:param x:特徵值

:param y: 標籤

:param theta: 引數

:return: 損失值

'''inner = np.power(x.dot(theta)

- y,2)

return np.

sum(inner)/(

2*len(x)

)theta = np.zeros((3

,1))

cost_init = costfunction(x, y, theta)

print

(cost_init)

defgradientdescent

(x, y, theta, alpha, iters, isprint=

false):

''' 梯度下降方法

:param x:特徵值

:param y: 標籤

:param theta: 引數

:param alpha: 步長

:param iters: 迭代次數

:param isprint: 是否列印

:return: 每次迭代產生的損失,和最終的擬合引數

'''costs =

for i in

range

(iters)

: theta = theta -

(x.t.dot(x.dot(theta)

- y)

* alpha /

len(x)

) cost = costfunction(x, y, theta)

if i %

100==0:

if isprint:

print

(cost)

return theta, costs

candidata_alpha =

[0.0003

,0.003

,0.03

,0.0001

,0.001

,0.01

]# 候選的步長

iters =

2000

# 迭代次數

fig, ax = plt.subplots(

)for alpha in candidata_alpha:

_, costs = gradientdescent(x, y, theta, alpha, iters)

ax.plot(np.arange(iters)

, costs, label=alpha)

ax.legend(

)ax.

set(xlabel=

'iters'

, ylabel=

'cost'

, title=

'cost vs iters'

)plt.show(

)

最終的效果圖

多變數線性回歸

import numpy as np import pandas as pd import matplotlib.pyplot as plt import cost function import gd function path ex1data2.txt data2 pd.read csv pat...

多變數線性回歸

固定隨機數 x1 numpy.random.random 50 x2 numpy.random.random 50 y 3 0.7 x1 2.3 x2 x numpy.c x1,x2 x numpy.c numpy.ones len x x y numpy.c y m,n x.shape alpha...

C 實現線性回歸(多變數)

本文主要介紹c 實現線性回歸問題,實現房價的 可以有多個變數 1 單變數 2 多變數 1 測試資料 房價的估計 2 開發工具 vim gnu linux make gdb 3 執行環境 linux,g 4.9.2 4 動態庫 libmatrix.so 自己寫的矩陣包 libmyaxis.so 自己用...