溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Python深度學(xué)習(xí)算法實(shí)例分析

發(fā)布時(shí)間:2022-01-18 15:47:17 來源:億速云 閱讀:426 作者:iii 欄目:編程語言

本篇內(nèi)容主要講解“Python深度學(xué)習(xí)算法實(shí)例分析”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實(shí)用性強(qiáng)。下面就讓小編來帶大家學(xué)習(xí)“Python深度學(xué)習(xí)算法實(shí)例分析”吧!

最小二乘法

所有的深度學(xué)習(xí)算法都始于下面這個(gè)數(shù)學(xué)公式(我已將其轉(zhuǎn)成 Python 代碼)

Python

# y = mx + b

# m is slope, b is y-intercept

 

def compute_error_for_line_given_points(b, m, coordinates):

    totalError = 0

    for i in range(0, len(coordinates)):

        x = coordinates[i][0]

        y = coordinates[i][1]

        totalError += (y - (m * x + b)) ** 2

    return totalError / float(len(coordinates))

# example

compute_error_for_line_given_points(1, 2, [[3,6],[6,9],[12,18]])

最小二乘法在 1805 年由 Adrien-Marie Legendre 首次提出(1805, Legendre),這位巴黎數(shù)學(xué)家也以測量儀器聞名。他極其癡迷于預(yù)測彗星的方位,堅(jiān)持不懈地尋找一種可以基于彗星方位歷史數(shù)據(jù)計(jì)算其軌跡的算法。

他嘗試了許多種算法,一遍遍試錯(cuò),終于找到了一個(gè)算法與結(jié)果相符。Legendre 的算法是首先預(yù)測彗星未來的方位,然后計(jì)算誤差的平方,最終目的是通過修改預(yù)測值以減少誤差平方和。而這也正是線性回歸的基本思想。

讀者可以在 Jupyter notebook 中運(yùn)行上述代碼來加深對這個(gè)算法的理解。m 是系數(shù),b 是預(yù)測的常數(shù)項(xiàng),coordinates 是彗星的位置。目標(biāo)是找到合適的 m 和 b 使其誤差盡可能小。

Python深度學(xué)習(xí)算法實(shí)例分析

這是深度學(xué)習(xí)的核心思想:給定輸入值和期望的輸出值,然后尋找兩者之間的相關(guān)性。

梯度下降

Legendre 這種通過手動(dòng)嘗試來降低錯(cuò)誤率的方法非常耗時(shí)。荷蘭的**獎(jiǎng)得主 Peter Debye 在一個(gè)世紀(jì)后(1909 年)正式提出了一種簡化這個(gè)過程的方法。

假設(shè) Legendre 的算法需要考慮一個(gè)參數(shù) —— 我們稱之為 X 。Y 軸表示每個(gè) X 的誤差值。Legendre 的算法是找到使得誤差最小的 X。在下圖中,我們可以看到當(dāng) X = 1.1 時(shí),誤差 Y 取到最小值。

Python深度學(xué)習(xí)算法實(shí)例分析

Peter Debye 注意到最低點(diǎn)左邊的斜率是負(fù)的,而另一邊則是正的。因此,如果知道了任意給定 X 的斜率值,就可以找到 Y 的最小值點(diǎn)。

這便是梯度下降算法的基本思想。幾乎所有的深度學(xué)習(xí)模型都會(huì)用到梯度下降算法。

要實(shí)現(xiàn)這個(gè)算法,我們假設(shè)誤差函數(shù)是 Error = x ^ 5 -2x ^ 3-2。要得到任意給定 X 的斜率,我們需要對其求導(dǎo),即 5x^4 – 6x^2:

如果您需要復(fù)習(xí)導(dǎo)數(shù)的相關(guān)知識(shí),請觀看 Khan Academy 的視頻

下面我們用 Python 實(shí)現(xiàn) Debye 的算法:

Python

current_x = 0.5 # the algorithm starts at x=0.5

learning_rate = 0.01 # step size multiplier

num_iterations = 60 # the number of times to train the function

 

#the derivative of the error function (x**4 = the power of 4 or x^4)

def slope_at_given_x_value(x):

   return 5 * x**4 - 6 * x**2

 

# Move X to the right or left depending on the slope of the error function

for i in range(num_iterations):

   previous_x = current_x

   current_x += -learning_rate * slope_at_given_x_value(previous_x)

   print(previous_x)

 

print("The local minimum occurs at %f" % current_x)

這里的竅門在于 learning_rate。我們通過沿斜率的相反方向行進(jìn)來逼近最低點(diǎn)。此外,越接近最低點(diǎn),斜率越小。因此當(dāng)斜率接近零時(shí),每一步下降的幅度會(huì)越來越小。

num_iterations 是你預(yù)計(jì)到達(dá)最小值之前所需的迭代次數(shù)??梢酝ㄟ^調(diào)試該參數(shù)訓(xùn)練自己關(guān)于梯度下降算法的直覺。

線性回歸

最小二乘法配合梯度下降算法,就是一個(gè)完整的線性回歸過程。在 20 世紀(jì) 50 年代和 60 年代,一批實(shí)驗(yàn)經(jīng)濟(jì)學(xué)家在早期的計(jì)算機(jī)上實(shí)現(xiàn)了這些想法。這個(gè)過程是通過實(shí)體打卡 —— 真正的手工軟件程序?qū)崿F(xiàn)的。準(zhǔn)備這些打孔卡就需要幾天的時(shí)間,而通過計(jì)算機(jī)進(jìn)行一次回歸分析最多需要 24 小時(shí)。

下面是用 Python 實(shí)現(xiàn)線性回歸的一個(gè)示例(我們不需要在打卡機(jī)上完成這個(gè)操作):

Python

#Price of wheat/kg and the average price of bread

wheat_and_bread = [[0.5,5],[0.6,5.5],[0.8,6],[1.1,6.8],[1.4,7]]

 

def step_gradient(b_current, m_current, points, learningRate):

    b_gradient = 0

    m_gradient = 0

    N = float(len(points))

    for i in range(0, len(points)):

        x = points[i][0]

        y = points[i][1]

        b_gradient += -(2/N) * (y - ((m_current * x) + b_current))

        m_gradient += -(2/N) * x * (y - ((m_current * x) + b_current))

    new_b = b_current - (learningRate * b_gradient)

    new_m = m_current - (learningRate * m_gradient)

    return [new_b, new_m]

 

def gradient_descent_runner(points, starting_b, starting_m, learning_rate, num_iterations):

    b = starting_b

    m = starting_m

    for i in range(num_iterations):

        b, m = step_gradient(b, m, points, learning_rate)

    return [b, m]

 

gradient_descent_runner(wheat_and_bread, 1, 1, 0.01, 100)

線性回歸本身并沒有引入什么新的內(nèi)容。但是,如何將梯度下降算法運(yùn)用到誤差函數(shù)上就需要?jiǎng)觿?dòng)腦子了。運(yùn)行代碼并使用這個(gè)線性回歸模擬器來加深你的理解吧。

感知機(jī)

接下來讓我們來認(rèn)識(shí)一下 Frank Rosenblatt。這是一個(gè)白天解剖老鼠大腦,晚上尋找外星生命跡象的家伙。1958年,他發(fā)明了一個(gè)模仿神經(jīng)元的機(jī)器(1958, Rosenblatt),并因此登上《紐約時(shí)報(bào)》的頭條:“New Navy Device Learns By Doing”。

如果向 Rosenblatt 的機(jī)器展示 50 組分別在左右兩側(cè)有標(biāo)記的圖像,它可以在沒有預(yù)先編程的情況下分辨出兩張圖像(標(biāo)記的位置)。大眾被這個(gè)可能真正擁有學(xué)習(xí)能力的機(jī)器震驚了。

Python深度學(xué)習(xí)算法實(shí)例分析

如上圖所示,每個(gè)訓(xùn)練周期都是從左側(cè)輸入數(shù)據(jù)開始。給所有輸入數(shù)據(jù)添加一個(gè)初始的隨機(jī)權(quán)重。然后將它們相加。如果總和為負(fù),將其輸出為 0,否則輸出為 1。

如果預(yù)測結(jié)果是正確的,就不改變循環(huán)中的權(quán)重。如果預(yù)測結(jié)果是錯(cuò)誤的,可以用誤差乘以學(xué)習(xí)率來相應(yīng)地調(diào)整權(quán)重。

我們用經(jīng)典的“或”邏輯來運(yùn)行感知機(jī)。

<td class="crayon-code" ">

from __future__ import division, print_function, absolute_import

import tflearn

from tflearn.layers.core import dropout, fully_connected

from tensorflow.examples.tutorials.mnist import input_data

from tflearn.layers.conv import conv_2d, max_pool_2d

from tflearn.layers.normalization import local_response_normalization

from tflearn.layers.estimator import regression

# Data loading and preprocessing

mnist = input_data.read_data_sets("/data/", one_hot=True)

X, Y, testX, testY = mnist.train.images, mnist.train.labels, mnist.test.images, mnist.test.labels

X = X.reshape([-1, 28, 28, 1])

testX = testX.reshape([-1, 28, 28, 1])

# Building convolutional network

network = tflearn.input_data(shape=[None, 28, 28, 1], name='input')

network = conv_2d(network, 32, 3, activation='relu', regularizer="L2")

network = max_pool_2d(network, 2)

network = local_response_normalization(network)

network = conv_2d(network, 64, 3, activation='relu', regularizer="L2")

network = max_pool_2d(network, 2)

network = local_response_normalization(network)

network = fully_connected(network, 128, activation='tanh')

network = dropout(network, 0.8)

network = fully_connected(network, 256, activation='tanh')

network = dropout(network, 0.8)

network = fully_connected(network, 10, activation='softmax')

network = regression(network, optimizer='adam', learning_rate=0.01,

                        loss='categorical_crossentropy', name='target')

# Training

model = tflearn.DNN(network, tensorboard_verbose=0)

model.fit({'input': X}, {'target': Y}, n_epoch=20,

            validation_set=({'input': testX}, {'target': testY}),

            snapshot_step=100, show_metric=True, run_id='convnet_mnist')

到此,相信大家對“Python深度學(xué)習(xí)算法實(shí)例分析”有了更深的了解,不妨來實(shí)際操作一番吧!這里是億速云網(wǎng)站,更多相關(guān)內(nèi)容可以進(jìn)入相關(guān)頻道進(jìn)行查詢,關(guān)注我們,繼續(xù)學(xué)習(xí)!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI