梯度下降求損失函數(shù)Minimizing cost functions with gradient descent

損失函數(shù)與梯度,從上圖可以看出梯度向下,
偏導(dǎo)數(shù)

可以看出計(jì)算樣本y誤差向量乘以樣本x列向量,算出w需要使用所有的樣本,然后再次迭代
import pandas as pd
import numpy as np
import matplotlib
import matplotlib.pyplot as plt

df = pd.read_csv('https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data', header=None)
y = df.iloc[0:100, 4].values
y = np.where(y=='Iris-setosa',1,-1)
x = df.iloc[0:100, [0,2]].values

class Perceptron():
    def __init__(self, eta, X, Y, N):
        self.eta = eta
        self.X = X
        self.Y = Y
        self.N = N
        self.w = [0]*len(X[0])
        self.w0 = 0
        self.m = len(X)
        self.n = len(X[0])
    def output_y(self, x):
        return np.dot(x,self.w)+self.w0
    def training(self):
        self.errors = []
        for times in xrange(self.N):
            delta_y = self.Y-self.output_y(self.X)
            error = (delta_y**2).sum()/2.0
            self.w0 += self.eta*delta_y.sum()
            self.w += self.eta*np.dot(delta_y,self.X)
            self.errors.append(error)

per = Perceptron(0.0001, x, y, 300)

per.training()

print per.w0,per.w

def f(x, y):
    z = per.w0+np.dot(per.w,zip(x,y))
    z = np.where(z>0,1,-1)
    return z

n = 200

mx = np.linspace(4, 7.5, n)
my = np.linspace(0, 6, n)
# 生成網(wǎng)格數(shù)據(jù)
X, Y = np.meshgrid(mx, my)
fig, axes = plt.subplots(1,2)
axes0, axes1 = axes.flatten()
axes0.plot(per.errors, marker='o')
axes0.set_title('errors')
axes1.contourf(X, Y, f(X, Y), 2, alpha = 0.75, cmap = plt.cm.RdBu)
axes1.scatter(x[:,0][0:50], x[:, 1][0:50],s=80,edgecolors='r', marker='o')
axes1.scatter(x[:,0][50:100], x[:, 1][50:100], marker='x', color='g')
axes1.annotate(r'versicolor',xy=(5.5,4.5),xytext=(4.5,5.5),arrowprops=dict(arrowstyle='->', facecolor='blue'))
axes1.annotate(r'setosa',xy=(5.8,2),xytext=(6.5,3),arrowprops=dict(arrowstyle='->', facecolor='blue'))
fig.set_size_inches(15.5, 10.5)

plt.subplots_adjust(left=0.1, right= 0.9, bottom=0.1, top=0.5)
plt.show()
數(shù)據(jù)標(biāo)準(zhǔn)化,收斂更快
x_std = np.copy(x)
x_std[:, 0] = (x[:,0]-x[:,0].mean())/x[:,0].std()
x_std[:, 1] = (x[:,1]-x[:,1].mean())/x[:,1].std()
圖形如下:
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容