簡體   English   中英

線性回歸中成本函數的實現

[英]Implementation of cost function in linear regression

我正在嘗試在一個簡單的訓練數據集上實現成本函數並在 3D 中可視化成本函數。

我的成本函數的形狀不像它應該的那樣。

這是我的代碼:

import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d.axes3d import Axes3D
import pandas as pd
from scipy.interpolate import griddata

def create_array(start, end, resolution):
    return np.linspace(start, end, int((end - start)/resolution + 1))

def f(x,a,b):
    x = np.array(x)
    return a*x+b # or Theta_1 * x + Theta_0

def get_J(x, y, a, b):
    x = np.array(x)
    y = np.array(y)
    # return 1/(2*len(y)) * sum(pow(f(x,a,b) - y, 2))
    # Simple implementation
    sum = 0
    for i in range(0, len(x)):
        sum+= (f(x[i],a,b) - y[i])**2
    return 1/(2*len(y))*sum
    
# Training set
x = np.array([0,1,2,3])
y = np.array([0,1,2,3])

Theta_0 = create_array(-20, 10, 0.5)
Theta_1 = create_array(-20, 10, 0.5)
X,Y = np.meshgrid(Theta_0, Theta_1)
X=X.flatten()
Y=Y.flatten()
J = [get_J(x, y, X[i], Y[i]) for i in range(0,len(X))]

# simple set to verify 3D plotting is doing as expetected - OK
# X = [10, 0, -10,-20, 10, 0, -10,-20, 10, 0,-10, -20, 10, 0, -10,-20]
# Y = [-20, -20, -20, -20, -10, -10, -10, -10, 0, 0, 0, 0, 10, 10, 10, 10]
# J = [50, 25, 26, 60, 24, 10, 11, 26, 10, 0, 2, 11, 52, 26, 27, 63]

# Create the graphing elements
xyz = {'x': X, 'y': Y, 'z': J}
# put the data into a pandas DataFrame (this is what my data looks like)
df = pd.DataFrame(xyz, index=range(len(xyz['x']))) 
# re-create the 2D-arrays
x1 = np.linspace(df['x'].min(), df['x'].max(), len(df['x'].unique()))
y1 = np.linspace(df['y'].min(), df['y'].max(), len(df['y'].unique()))
x2, y2 = np.meshgrid(x1, y1)
z2 = griddata((df['x'], df['y']), df['z'], (x2, y2), method='cubic')

fig = plt.figure(figsize =(14, 9))
ax = Axes3D(fig)
surf = ax.plot_surface(x2, y2, z2, rstride=1, cstride=1, cmap=plt.get_cmap('coolwarm'),linewidth=0, antialiased=False)
plt.gca().invert_xaxis()
ax.set_xlabel('\u03B81', fontweight ='bold')  
ax.set_ylabel('\u03B80', fontweight ='bold')  
ax.set_zlabel('J (\u03B81, \u03B80)', fontweight ='bold') 
fig.colorbar(surf, shrink=0.5, aspect=5)
plt.show()

3D 繪圖具有以下形狀: 在此處輸入圖片說明

當它應該具有這種形狀時: 在此處輸入圖片說明

如果你拿起紙和筆,分析得出你已經實現的J ,你會得到這樣的結果:

a = theta_1: -20 ... 10
b = theta_0: -20 ... 10
J(a,b) ~ b^2 + (a+b-1)^2 + (2a+b-2)^2 + (3a+b-3)^2

這基本上意味着aba+b一樣耦合。 a+b類的項是平方的, (a+b)^2看起來像這樣(用 gnuplot 制作):

耦合

參考圖有另一種形式,看起來更像是ab是獨立的,如a^2 + b^2 ,讓我們繪制這個: 獨立的

因此,如果J具有以下形式,我們應該能夠重現參考圖

J(a, b) ~ a^2 + b^2 + (other terms except a*b)

J的形式由訓練集xy 我留給你分析表明x中的值建立了ab之間的耦合。 對於y ,我使用這些值並得出:

x = np.array([-1, 1])
y = np.array([1, -4])

這是我能想到的最簡單的設置。 還有更多的可能性。

我對機器學習和這些價值觀的意義不是很深入。 我的知識基本上來自這里 所以如果我錯了,請告訴我。

現在我得到了以下圖像,我認為它與參考圖像非常接近,至少是形狀:

最后

作為總結:我認為您的實現中沒有錯誤。 我認為,您繪制了不同的數據。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM