99999久久久久久亚洲,欧美人与禽猛交狂配,高清日韩av在线影院,一个人在线高清免费观看,啦啦啦在线视频免费观看www

熱線電話:13121318867

登錄
首頁(yè)大數(shù)據(jù)時(shí)代機(jī)器學(xué)習(xí)中感知機(jī)是什么?如何實(shí)現(xiàn)?
機(jī)器學(xué)習(xí)中感知機(jī)是什么?如何實(shí)現(xiàn)?
2020-07-10
收藏

感知機(jī)(Perceptron)或者叫做感知器,是Frank Rosenblatt在1957年就職于Cornell航空實(shí)驗(yàn)室(Cornell Aeronautical Laboratory)時(shí)所發(fā)明的一種人工神經(jīng)網(wǎng)絡(luò),是機(jī)器學(xué)習(xí)領(lǐng)域最基礎(chǔ)的模型,被譽(yù)為機(jī)器學(xué)習(xí)的敲門磚。

感知機(jī)是生物神經(jīng)細(xì)胞的簡(jiǎn)單抽象,可以說(shuō)是形式最簡(jiǎn)單的一種前饋神經(jīng)網(wǎng)絡(luò),是一種二元線性分類模型。感知機(jī)的輸入為實(shí)例的特征向量,輸出為實(shí)例的類別取+1和-1.雖然現(xiàn)在看來(lái)感知機(jī)的分類模型,大多數(shù)情況下的泛化能力不是很強(qiáng),但是感知機(jī)是最古老的分類方法之一,是神經(jīng)網(wǎng)絡(luò)的雛形,同時(shí)也是支持向量機(jī)的基礎(chǔ),如果能夠?qū)?a href='/map/ganzhiji/' style='color:#000;font-size:inherit;'>感知機(jī)研究透徹,對(duì)我們支持向量機(jī)、神經(jīng)網(wǎng)絡(luò)的學(xué)習(xí)也有很大幫助。

一、感知機(jī)模型

其中x為特征向量,w和b為感知機(jī)模型的參數(shù)。

感知機(jī)的幾何解釋:線性方程

二·、感知機(jī)算法

1.原始形式


from random import randint
import numpy as np
import matplotlib.pyplot as plt


class TrainDataLoader:
    def __init__(self):
        pass
    def GenerateRandomData(self, count, gradient, offset):
        x1 = np.linspace(1, 5, count)
        x2 = gradient*x1 + np.random.randint(-10,10,*x1.shape)+offset
        dataset = []
        y = []
        for i in range(*x1.shape):
            dataset.append([x1[i], x2[i]])
            real_value = gradient*x1[i]+offset
            if real_value > x2[i]:
                y.append(-1)
            else:
                y.append(1)
        return x1,x2,np.mat(y),np.mat(dataset)


class SimplePerceptron:
    def __init__(self, train_data = [], real_result = [], eta = 1):
        self.w   =   np.zeros([1, len(train_data.T)], int)
        self.b   =   0
        self.eta =   eta
        self.train_data   = train_data
        self.real_result  = real_result
    def nomalize(self, x):
        if x > 0 :
            return 1
        else :
            return -1
    def model(self, x):
        # Here are matrix dot multiply get one value
        y = np.dot(x, self.w.T) + self.b
        # Use sign to nomalize the result
        predict_v = self.nomalize(y)
        return predict_v, y
    def update(self, x, y):
        # w = w + n*y_i*x_i
        self.w = self.w + self.eta*y*x
        # b = b + n*y_i
        self.b = self.b + self.eta*y
    def loss(slef, fx, y):
        return fx.astype(int)*y

    def train(self, count):
        update_count = 0
        while count > 0:
            # count--
            count = count - 1

            if len(self.train_data) <= 0:
                print("exception exit")
                break
            # random select one train data
            index = randint(0,len(self.train_data)-1)
            x = self.train_data[index]
            y = self.real_result.T[index]
            # wx+b
            predict_v, linear_y_v = self.model(x)
            # y_i*(wx+b) > 0, the classify is correct, else it's error
            if self.loss(y, linear_y_v) > 0:
                continue
            update_count = update_count + 1
            self.update(x, y)
        print("update count: ", update_count)
        pass
    def verify(self, verify_data, verify_result):
        size = len(verify_data)
        failed_count = 0
        if size <= 0:
            pass
        for i in range(size):
            x = verify_data[i]
            y = verify_result.T[i]
            if self.loss(y, self.model(x)[1]) > 0:
                continue
            failed_count = failed_count + 1
        success_rate = (1.0 - (float(failed_count)/size))*100
        print("Success Rate: ", success_rate, "%")
        print("All input: ", size, " failed_count: ", failed_count)

    def predict(self, predict_data):
        size = len(predict_data)
        result = []
        if size <= 0:
            pass
        for i in range(size):
            x = verify_data[i]
            y = verify_result.T[i]
            result.append(self.model(x)[0])
        return result



if __name__ == "__main__":
    # Init some parameters
    gradient = 2
    offset   = 10
    point_num = 1000
    train_num = 50000
    loader = TrainDataLoader()
    x, y, result, train_data =  loader.GenerateRandomData(point_num, gradient, offset)
    x_t, y_t, test_real_result, test_data =  loader.GenerateRandomData(100, gradient, offset)

    # First training
    perceptron = SimplePerceptron(train_data, result)
    perceptron.train(train_num)
    perceptron.verify(test_data, test_real_result)
    print("T1: w:", perceptron.w," b:", perceptron.b)

    # Draw the figure
    # 1. draw the (x,y) points
    plt.plot(x, y, "*", color='gray')
    plt.plot(x_t, y_t, "+")
    # 2. draw y=gradient*x+offset line
    plt.plot(x,x.dot(gradient)+offset, color="red")
    # 3. draw the line w_1*x_1 + w_2*x_2 + b = 0
    plt.plot(x, -(x.dot(float(perceptron.w.T[0]))+float(perceptron.b))/float(perceptron.w.T[1])
             , color='green')
    plt.show()
2.對(duì)偶形式



from random import randint
import numpy as np
import matplotlib.pyplot as plt


class TrainDataLoader:
    def __init__(self):
        pass
    def GenerateRandomData(self, count, gradient, offset):
        x1 = np.linspace(1, 5, count)
        x2 = gradient*x1 + np.random.randint(-10,10,*x1.shape)+offset
        dataset = []
        y = []
        for i in range(*x1.shape):
            dataset.append([x1[i], x2[i]])
            real_value = gradient*x1[i]+offset
            if real_value > x2[i]:
                y.append(-1)
            else:
                y.append(1)
        return x1,x2,np.mat(y),np.mat(dataset)


class SimplePerceptron:
    def __init__(self, train_data = [], real_result = [], eta = 1):
        self.alpha   =   np.zeros([train_data.shape[0], 1], int)
        self.w   =   np.zeros([1, train_data.shape[1]], int)
        self.b   =   0
        self.eta =   eta
        self.train_data   = train_data
        self.real_result  = real_result
        self.gram         = np.matmul(train_data[0:train_data.shape[0]], train_data[0:train_data.shape[0]].T)
    def nomalize(self, x):
        if x > 0 :
            return 1
        else :
            return -1
    def train_model(self, index):
        temp = 0
        y = self.real_result.T
        # Here are matrix dot multiply get one value
        for i in range(len(self.alpha)):
            alpha      = self.alpha[i]
            if alpha == 0:
                continue
            gram_value = self.gram[index].T[i]
            temp = temp + alpha*y[i]*gram_value
        y = temp + self.b
        # Use sign to nomalize the result
        predict_v = self.nomalize(y)
        return predict_v, y
    def verify_model(self, x):
        # Here are matrix dot multiply get one value
        y = np.dot(x, self.w.T) + self.b
        # Use sign to nomalize the result
        predict_v = self.nomalize(y)
        return predict_v, y
    def update(self, index, x, y):
        # alpha = alpha + 1
        self.alpha[index] = self.alpha[index] + 1
        # b = b + n*y_i
        self.b = self.b + self.eta*y
    def loss(slef, fx, y):
        return fx.astype(int)*y

    def train(self, count):
        update_count = 0
        train_data_num = self.train_data.shape[0]
        print("train_data:", self.train_data)
        print("Gram:",self.gram)
        while count > 0:
            # count--
            count = count - 1

            if train_data_num <= 0:
                print("exception exit")
                break
            # random select one train data
            index = randint(0, train_data_num-1)
            if index >= train_data_num:
                print("exceptrion get the index")
                break;
            x = self.train_data[index]
            y = self.real_result.T[index]
            # w = \sum_{i=1}^{N}\alpha_iy_iGram[i]
            # wx+b
            predict_v, linear_y_v = self.train_model(index)
            # y_i*(wx+b) > 0, the classify is correct, else it's error
            if self.loss(y, linear_y_v) > 0:
                continue
            update_count = update_count + 1
            self.update(index, x, y)

        for i in range(len(self.alpha)):
            x = self.train_data[i]
            y = self.real_result.T[i]
            self.w = self.w + float(self.alpha[i])*x*float(y)
        print("update count: ", update_count)
        pass
    def verify(self, verify_data, verify_result):
        size = len(verify_data)
        failed_count = 0
        if size <= 0:
            pass
        for i in range(size-1):
            x = verify_data[i]
            y = verify_result.T[i]
            if self.loss(y, self.verify_model(x)[1]) > 0:
                continue
            failed_count = failed_count + 1
        success_rate = (1.0 - (float(failed_count)/size))*100
        print("Success Rate: ", success_rate, "%")
        print("All input: ", size, " failed_count: ", failed_count)

    def predict(self, predict_data):
        size = len(predict_data)
        result = []
        if size <= 0:
            pass
        for i in range(size):
            x = verify_data[i]
            y = verify_result.T[i]
            result.append(self.model(x)[0])
        return result



if __name__ == "__main__":
    # Init some parameters
    gradient = 2
    offset   = 10
    point_num = 1000
    train_num = 1000
    loader = TrainDataLoader()
    x, y, result, train_data =  loader.GenerateRandomData(point_num, gradient, offset)
    x_t, y_t, test_real_result, test_data =  loader.GenerateRandomData(100, gradient, offset)
    # train_data = np.mat([[3,3],[4,3],[1,1]])
    # First training
    perceptron = SimplePerceptron(train_data, result)
    perceptron.train(train_num)
    perceptron.verify(test_data, test_real_result)
    print("T1: w:", perceptron.w," b:", perceptron.b)

    # Draw the figure
    # 1. draw the (x,y) points
    plt.plot(x, y, "*", color='gray')
    plt.plot(x_t, y_t, "+")
    # 2. draw y=gradient*x+offset line
    plt.plot(x,x.dot(gradient)+offset, color="red")
    # 3. draw the line w_1*x_1 + w_2*x_2 + b = 0
    plt.plot(x, -(x.dot(float(perceptron.w.T[0]))+float(perceptron.b))/float(perceptron.w.T[1])
             , color='green')
    plt.show()



數(shù)據(jù)分析咨詢請(qǐng)掃描二維碼

若不方便掃碼,搜微信號(hào):CDAshujufenxi

數(shù)據(jù)分析師資訊
更多

OK
客服在線
立即咨詢
客服在線
立即咨詢
') } function initGt() { var handler = function (captchaObj) { captchaObj.appendTo('#captcha'); captchaObj.onReady(function () { $("#wait").hide(); }).onSuccess(function(){ $('.getcheckcode').removeClass('dis'); $('.getcheckcode').trigger('click'); }); window.captchaObj = captchaObj; }; $('#captcha').show(); $.ajax({ url: "/login/gtstart?t=" + (new Date()).getTime(), // 加隨機(jī)數(shù)防止緩存 type: "get", dataType: "json", success: function (data) { $('#text').hide(); $('#wait').show(); // 調(diào)用 initGeetest 進(jìn)行初始化 // 參數(shù)1:配置參數(shù) // 參數(shù)2:回調(diào),回調(diào)的第一個(gè)參數(shù)驗(yàn)證碼對(duì)象,之后可以使用它調(diào)用相應(yīng)的接口 initGeetest({ // 以下 4 個(gè)配置參數(shù)為必須,不能缺少 gt: data.gt, challenge: data.challenge, offline: !data.success, // 表示用戶后臺(tái)檢測(cè)極驗(yàn)服務(wù)器是否宕機(jī) new_captcha: data.new_captcha, // 用于宕機(jī)時(shí)表示是新驗(yàn)證碼的宕機(jī) product: "float", // 產(chǎn)品形式,包括:float,popup width: "280px", https: true // 更多配置參數(shù)說(shuō)明請(qǐng)參見:http://docs.geetest.com/install/client/web-front/ }, handler); } }); } function codeCutdown() { if(_wait == 0){ //倒計(jì)時(shí)完成 $(".getcheckcode").removeClass('dis').html("重新獲取"); }else{ $(".getcheckcode").addClass('dis').html("重新獲取("+_wait+"s)"); _wait--; setTimeout(function () { codeCutdown(); },1000); } } function inputValidate(ele,telInput) { var oInput = ele; var inputVal = oInput.val(); var oType = ele.attr('data-type'); var oEtag = $('#etag').val(); var oErr = oInput.closest('.form_box').next('.err_txt'); var empTxt = '請(qǐng)輸入'+oInput.attr('placeholder')+'!'; var errTxt = '請(qǐng)輸入正確的'+oInput.attr('placeholder')+'!'; var pattern; if(inputVal==""){ if(!telInput){ errFun(oErr,empTxt); } return false; }else { switch (oType){ case 'login_mobile': pattern = /^1[3456789]\d{9}$/; if(inputVal.length==11) { $.ajax({ url: '/login/checkmobile', type: "post", dataType: "json", data: { mobile: inputVal, etag: oEtag, page_ur: window.location.href, page_referer: document.referrer }, success: function (data) { } }); } break; case 'login_yzm': pattern = /^\d{6}$/; break; } if(oType=='login_mobile'){ } if(!!validateFun(pattern,inputVal)){ errFun(oErr,'') if(telInput){ $('.getcheckcode').removeClass('dis'); } }else { if(!telInput) { errFun(oErr, errTxt); }else { $('.getcheckcode').addClass('dis'); } return false; } } return true; } function errFun(obj,msg) { obj.html(msg); if(msg==''){ $('.login_submit').removeClass('dis'); }else { $('.login_submit').addClass('dis'); } } function validateFun(pat,val) { return pat.test(val); }