
感知机(Perceptron)或者叫做感知器,是Frank Rosenblatt在1957年就职于Cornell航空实验室(Cornell Aeronautical Laboratory)时所发明的一种人工神经网络,是机器学习领域最基础的模型,被誉为机器学习的敲门砖。
感知机是生物神经细胞的简单抽象,可以说是形式最简单的一种前馈神经网络,是一种二元线性分类模型。感知机的输入为实例的特征向量,输出为实例的类别取+1和-1.虽然现在看来感知机的分类模型,大多数情况下的泛化能力不是很强,但是感知机是最古老的分类方法之一,是神经网络的雏形,同时也是支持向量机的基础,如果能够将感知机研究透彻,对我们支持向量机、神经网络的学习也有很大帮助。
一、感知机模型
感知机的几何解释:线性方程
二·、感知机算法
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.对偶形式
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()
数据分析咨询请扫描二维码
若不方便扫码,搜微信号:CDAshujufenxi
在手游行业,“次日留存率” 是衡量一款游戏生死的 “第一道关卡”—— 它不仅反映了玩家对游戏的初始接受度,更直接决定了后续 ...
2025-10-13分库分表,为何而生? 在信息技术发展的早期阶段,数据量相对较小,业务逻辑也较为简单,单库单表的数据库架构就能够满足大多数 ...
2025-10-13在企业数字化转型过程中,“数据孤岛” 是普遍面临的痛点:用户数据散落在 APP 日志、注册系统、客服记录中,订单数据分散在交易 ...
2025-10-13在数字化时代,用户的每一次行为 —— 从电商平台的 “浏览→加购→购买”,到视频 APP 的 “打开→搜索→观看→收藏”,再到银 ...
2025-10-11在机器学习建模流程中,“特征重要性分析” 是连接 “数据” 与 “业务” 的关键桥梁 —— 它不仅能帮我们筛选冗余特征、提升模 ...
2025-10-11在企业的数据体系中,未经分类的数据如同 “杂乱无章的仓库”—— 用户行为日志、订单记录、商品信息混杂存储,CDA(Certified D ...
2025-10-11在 SQL Server 数据库操作中,“数据类型转换” 是高频需求 —— 无论是将字符串格式的日期转为datetime用于筛选,还是将数值转 ...
2025-10-10在科研攻关、工业优化、产品开发中,正交试验(Orthogonal Experiment)因 “用少量试验覆盖多因素多水平组合” 的高效性,成为 ...
2025-10-10在企业数据量从 “GB 级” 迈向 “PB 级” 的过程中,“数据混乱” 的痛点逐渐从 “隐性问题” 变为 “显性瓶颈”:各部门数据口 ...
2025-10-10在深度学习中,“模型如何从错误中学习” 是最关键的问题 —— 而损失函数与反向传播正是回答这一问题的核心技术:损失函数负责 ...
2025-10-09本文将从 “检验本质” 切入,拆解两种方法的核心适用条件、场景边界与实战选择逻辑,结合医学、工业、教育领域的案例,让你明确 ...
2025-10-09在 CDA 数据分析师的日常工作中,常会遇到这样的困惑:某电商平台 11 月 GMV 同比增长 20%,但究竟是 “长期趋势自然增长”,还 ...
2025-10-09Pandas 选取特定值所在行:6 类核心方法与实战指南 在使用 pandas 处理结构化数据时,“选取特定值所在的行” 是最高频的操作之 ...
2025-09-30球面卷积神经网络(SCNN) 为解决这一痛点,球面卷积神经网络(Spherical Convolutional Neural Network, SCNN) 应运而生。它通 ...
2025-09-30在企业日常运营中,“未来会怎样” 是决策者最关心的问题 —— 电商平台想知道 “下月销量能否达标”,金融机构想预判 “下周股 ...
2025-09-30Excel 能做聚类分析吗?基础方法、进阶技巧与场景边界 在数据分析领域,聚类分析是 “无监督学习” 的核心技术 —— 无需预设分 ...
2025-09-29XGBoost 决策树:原理、优化与工业级实战指南 在机器学习领域,决策树因 “可解释性强、处理非线性关系能力突出” 成为基础模型 ...
2025-09-29在标签体系的落地链路中,“设计标签逻辑” 只是第一步,真正让标签从 “纸上定义” 变为 “业务可用资产” 的关键,在于标签加 ...
2025-09-29在使用 Excel 数据透视表进行多维度数据汇总时,折叠功能是梳理数据层级的核心工具 —— 通过点击 “+/-” 符号可展开明细数据或 ...
2025-09-28在使用 Pandas 处理 CSV、TSV 等文本文件时,“引号” 是最容易引发格式混乱的 “隐形杀手”—— 比如字段中包含逗号(如 “北京 ...
2025-09-28