当前位置: 首页 > news >正文

自组织映射Python实现

自组织映射(Self-organizing map)Python实现。仅供学习。

#!/usr/bin/env python3"""
Self-organizing map
"""from math import expimport toolzimport numpy as np
import numpy.linalg as LAfrom sklearn.base import ClusterMixin
from sklearn.preprocessing import MinMaxScaler
scaler = MinMaxScaler()class Node:"""NodeAttributes:location (np.ndarray): location of the nodeweight (np.ndarray): weight of the node, in the data sp."""def __init__(self, weight, location=None):self.weight = weightself.location = locationdef normalize(self):return self.weight / LA.norm(self.weight)def output(self, x):# similarity between the node and the input `x`return LA.norm(x - self.weight)def near(self, other, d=0.2):# judge the neighborhood of the nodes by locationsif self.location is not None and other.location is not None:return LA.norm(self.location - other.location) < delse:return 0def update(self, x, eta=0.1):"""update the weight of the nodew += r (x-w)"""self.weight += eta *(x - self.weight)@staticmethoddef random(n=2):weight = np.random.random(n)location = np.random.random(2)node = Node(weight, location)node.normalize()return nodedef plot(self, axes, i1=0, i2=1, *args, **kwargs):x1, x2 = self.weight[i1], self.weight[i2]axes.plot(x1, x2, *args, **kwargs)class Layer(ClusterMixin):"""Layer of SOMA Grid of nodes"""def __init__(self, nodes):self.nodes = list(nodes)@staticmethoddef random(n_nodes=100, *args, **kwargs):return Layer([Node.random(*args, **kwargs) for _ in range(n_nodes)])def output(self, x):# all outputs(similarity to x) of the nodesreturn [node.output(x) for node in self.nodes]def champer(self, x):"""champer node: best matching unit (BMU)"""return self.nodes[self.predict(x)]def predict(self, x):"""the index of best matching unit (BMU)"""return np.argmin(self.output(x))def update(self, x, eta=0.5, d=0.5):# update the nerighors of the best nodec = self.champer(x)for node in self.nodes:if node.near(c, d):node.update(x, eta)def plot(self, axes, i1=0, i2=1, *args, **kwargs):x1 = [node.weight[i1] for node in self.nodes]x2 = [node.weight[i2] for node in self.nodes]axes.scatter(x1, x2, *args, **kwargs)def fit(self, data, eta=0.2, d=0.2, max_iter=100):data = scaler.fit_transform(data)for t in range(max_iter):for x in data:self.update(x, eta=eta*exp(-t/10), d=d*exp(-t/10))if __name__ == '__main__':try:import pandas as pddf = pd.read_csv('heart.csv')  # input your dataexcept Exception as e:printe(e)raise Exception('Please input your data!')def _grid(size=(5, 5), *args, **kwargs):grid = []r, c = sizefor k in range(1,r):row = []for l in range(1,c):weight = np.array((k/r, l/c))# weight = np.random.random(kwargs['dim']) # for randomly generatinglocation = np.array((k/r, l/c))node = Node(weight=weight, location=location)row.append(node)grid.append(row)return griddf = df[['trestbps', 'chol']]N, p = df.shapeX = df.values.astype('float')import matplotlib.pyplot as pltfig = plt.figure()ax = fig.add_subplot(111)X_ = scaler.fit_transform(X)ax.plot(X_[:,0], X_[:,1], 'o')g = _grid(size=(5,5), dim=p)for row in g:x = [node.weight[0] for node in row]y = [node.weight[1] for node in row]ax.plot(x, y, 'g--')for col in zip(*g):x = [node.weight[0] for node in col]y = [node.weight[1] for node in col]ax.plot(x, y, 'g--')l = Layer(nodes=toolz.concat(g))l.plot(ax, marker='s', color='g', alpha=0.2)l.fit(X[:N//2,:], max_iter=50)l.plot(ax, marker='+', color='r')for row in g:x = [node.weight[0] for node in row]y = [node.weight[1] for node in row]ax.plot(x, y, 'r')for col in zip(*g):x = [node.weight[0] for node in col]y = [node.weight[1] for node in col]ax.plot(x, y, 'r')ax.set_title('Demo of SOM')ax.legend(('Data', 'Initial nodes', 'Terminal nodes'))plt.show()

在这里插入图片描述

相关文章:

自组织映射Python实现

自组织映射&#xff08;Self-organizing map&#xff09;Python实现。仅供学习。 #!/usr/bin/env python3""" Self-organizing map """from math import expimport toolzimport numpy as np import numpy.linalg as LAfrom sklearn.base import…...

如何避免阿里云对象储存OSS被盗刷

网站app图片的云端存储离不开对象存储oss,而最难为的问题就是app做的出名了&#xff0c;少不了同行的攻击&#xff0c;包含ddos&#xff0c;cc攻击以及oss外链被盗刷&#xff01; 防盗链功能通过设置Referer白名单以及是否允许空Referer&#xff0c;限制仅白名单中的域名可以访…...

产品研发团队协作神器!10款提效工具大盘点!

在如今科技驱动的时代&#xff0c;产品研发团队面临着前所未有的竞争压力和不断变化的市场需求。为了在这个激烈的环境中脱颖而出&#xff0c;团队需要高效协作并充分利用先进的工具来提高生产力和创新能力。 本文将为你盘点产品研发团队协作必备的10个提效工具&#xff0c;这…...

LSTM 与 GRU

RNN无法处理长距离依赖问题&#xff0c;通俗点就是不能处理一些较长的序列数据&#xff0c;那么今天就来介绍一下两个能处理长距离依赖问题地RNN变种结构&#xff0c;LSTM和GRU。 1. LSTM&#xff08;Long short-term memory&#xff09; 1.1 LSTM结构 上左图是普通RNN结构图…...

代码评审CheckList

代码评审CheckList Author: histonevonzohomail.com Date: 2023/10/24 此博客为笔者在工作中总结的经验&#xff0c;适用于笔者所在的工作&#xff0c;具体情况还需各位自己分析以下的分类并不规范&#xff0c;有好的建议可以给我Email值此1024祝全世界的开发者&#xff1a;天天…...

[尚硅谷React笔记]——第5章 React 路由

目录&#xff1a; 对SPA应用的理解对路由的理解前端路由原理路由的基本使用路由组件与一般组件NavLink的使用封装NavLink组件Switch的使用解决样式丢失问题路由的模糊匹配与严格匹配Redirect的使用嵌套路由向路由组件传递params参数向路由组件传递search参数.向路由组件传递st…...

如何去掉不够优雅的IF-ELSE

不够优雅的IF-ELSE&#xff1a; 在一个方法中根据两个参数的不同值组合来返回四种可能的类型&#xff0c;你可以使用条件语句&#xff0c;例如 if-else 语句或 switch 语句&#xff0c;来实现这个逻辑。以下是一个示例&#xff0c;假设你有两个参数 param1 和 param2&#xff…...

Python中defaultdict的使用

文章目录 Python 中的 defaultdict 与 dictPython 中的 defaultdict Python 中 defaultdict 的有用函数Python 中的 defaultdict.clear()Python 中的 defaultdict.copy()Python 中的 defaultdict.default_factory()Python 中的 defaultdict.get(key, default value) 今天的文章…...

【ccc3.8】虚拟列表

一个简单的虚拟列表&#xff0c;没有任何其他东西。 原理就是向上滚动时&#xff0c;将下面离开屏幕的那一个item塞到上侧来&#xff1a; 主代码仅有两个&#xff1a;ScrollList对应的滚动容器&#xff0c;ScrollListItem对应单项的预制体 当前支持两种&#xff1a;竖向滚动、…...

【23种设计模式】单一职责原则

个人主页&#xff1a;金鳞踏雨 个人简介&#xff1a;大家好&#xff0c;我是金鳞&#xff0c;一个初出茅庐的Java小白 目前状况&#xff1a;22届普通本科毕业生&#xff0c;几经波折了&#xff0c;现在任职于一家国内大型知名日化公司&#xff0c;从事Java开发工作 我的博客&am…...

DNS入门学习:什么是TTL值?如何设置合适的TTL值?

TTL值是域名解析中的一个重要参数&#xff0c;TTL值设置的合理与否对于域名解析的效率和准确性有着非常重要的影响&#xff0c;因此对于网站管理者而言&#xff0c;了解什么是TTL值以及如何设置合理的TTL值对于做好域名解析管理&#xff0c;确保网站的安全稳定运行至关重要。 …...

ilr normalize isometric log-ratio transformation

visium_heart/st_snRNAseq/05_colocalization/create_niches_ct.R at 5b30c7e497e06688a8448afd8d069d2fa70ebcd2 saezlab/visium_heart (github.com) 更多内容&#xff0c;关注微信&#xff1a;生信小博士 The ILR (Isometric Log-Ratio) transformation is used in the anal…...

el表单的简单查询方法

预期效果 实现表单页面根据groupid 、type 、errortype进行数据过滤 实现 第一步&#xff0c;在页面中添加输入或者是下拉框&#xff0c;并且用相应的v-model进行绑定 <div style"display: flex;flex-direction: row;"><el-input style"width: auto…...

【USRP】通信总的分支有哪些

概述 通信是一个广泛的领域&#xff0c;涵盖了许多不同的技术、应用和专业分支。以下是通信领域的一些主要分支&#xff1a; 有线通信&#xff1a;这涉及到利用物理媒介&#xff08;如电缆、光纤&#xff09;进行通信。 电信&#xff1a;包括电话、电报和传真服务。宽带&#…...

关于服务器网络代理解决方案(1024)

方法一、nginx代理 配置代理服务器 在能够访问外网的服务器上&#xff0c;安装和配置 Nginx。你可以使用包管理器来安装 Nginx&#xff0c;例如&#xff1a; csharpCopy codesudo apt-get install nginx # 对于基于 Debian/Ubuntu 的系统 sudo yum install nginx # 对于基于 C…...

Linux下 /etc/shadow内容详解

/etc/shadow 文件&#xff0c;用于存储 Linux 系统中用户的密码信息&#xff0c;又称为“影子文件”。 前面介绍了 /etc/passwd 文件&#xff0c;由于该文件允许所有用户读取&#xff0c;易导致用户密码泄露&#xff0c;因此 Linux 系统将用户的密码信息从 /etc/passwd 文件中…...

Go学习第二章——变量与数据类型

Go变量与数据类型 1 变量1.1 变量概念1.2 变量的使用步骤1.3 变量的注意事项1.4 ""的使用 2 数据类型介绍3 整数类型3.1 有符号整数类型3.2 无符号整数类型3.3 其他整数类型3.4 整型的使用细节 4 小数类型/浮点型4.1 浮点型的分类4.2 简单使用 5 字符类型5.1 字符类型…...

【剑指Offer】:循环有序列表的插入(涉及链表的知识)

给定循环单调非递减列表中的一个点&#xff0c;写一个函数向这个列表中插入一个新元素 insertVal &#xff0c;使这个列表仍然是循环升序的 给定的可以是这个列表中任意一个顶点的指针&#xff0c;并不一定是这个列表中最小元素的指针 如果有多个满足条件的插入位置&#xff0c…...

【Django 04】Django-DRF(ModelViewSet)

DRF是什么&#xff1f; ModelViewSet 是 Django REST framework 提供的一个视图集类&#xff0c;它封装了常见的模型操作方法。 模型类提供了默认的增删改查功能。 它继承自 GenericViewSet、ListModelMixin、RetrieveModelMixin、CreateModelMixin、UpdateModelMixin、Dest…...

ubuntu命令

一、 防火墙命令 1、安装防火墙 sudo sudo apt-get install ufw2、查看防火墙状态 sudo ufw status# 返回结果 # Status: inactive # 表示没有开启防火墙3、开启防火墙 sudo ufw enable# 返回结果 # Command may disrupt existing ssh connections. Proceed with operation…...

wordpress后台更新后 前端没变化的解决方法

使用siteground主机的wordpress网站&#xff0c;会出现更新了网站内容和修改了php模板文件、js文件、css文件、图片文件后&#xff0c;网站没有变化的情况。 不熟悉siteground主机的新手&#xff0c;遇到这个问题&#xff0c;就很抓狂&#xff0c;明明是哪都没操作错误&#x…...

Linux 文件类型,目录与路径,文件与目录管理

文件类型 后面的字符表示文件类型标志 普通文件&#xff1a;-&#xff08;纯文本文件&#xff0c;二进制文件&#xff0c;数据格式文件&#xff09; 如文本文件、图片、程序文件等。 目录文件&#xff1a;d&#xff08;directory&#xff09; 用来存放其他文件或子目录。 设备…...

【kafka】Golang实现分布式Masscan任务调度系统

要求&#xff1a; 输出两个程序&#xff0c;一个命令行程序&#xff08;命令行参数用flag&#xff09;和一个服务端程序。 命令行程序支持通过命令行参数配置下发IP或IP段、端口、扫描带宽&#xff0c;然后将消息推送到kafka里面。 服务端程序&#xff1a; 从kafka消费者接收…...

ES6从入门到精通:前言

ES6简介 ES6&#xff08;ECMAScript 2015&#xff09;是JavaScript语言的重大更新&#xff0c;引入了许多新特性&#xff0c;包括语法糖、新数据类型、模块化支持等&#xff0c;显著提升了开发效率和代码可维护性。 核心知识点概览 变量声明 let 和 const 取代 var&#xf…...

质量体系的重要

质量体系是为确保产品、服务或过程质量满足规定要求&#xff0c;由相互关联的要素构成的有机整体。其核心内容可归纳为以下五个方面&#xff1a; &#x1f3db;️ 一、组织架构与职责 质量体系明确组织内各部门、岗位的职责与权限&#xff0c;形成层级清晰的管理网络&#xf…...

C++中string流知识详解和示例

一、概览与类体系 C 提供三种基于内存字符串的流&#xff0c;定义在 <sstream> 中&#xff1a; std::istringstream&#xff1a;输入流&#xff0c;从已有字符串中读取并解析。std::ostringstream&#xff1a;输出流&#xff0c;向内部缓冲区写入内容&#xff0c;最终取…...

unix/linux,sudo,其发展历程详细时间线、由来、历史背景

sudo 的诞生和演化,本身就是一部 Unix/Linux 系统管理哲学变迁的微缩史。来,让我们拨开时间的迷雾,一同探寻 sudo 那波澜壮阔(也颇为实用主义)的发展历程。 历史背景:su的时代与困境 ( 20 世纪 70 年代 - 80 年代初) 在 sudo 出现之前,Unix 系统管理员和需要特权操作的…...

鱼香ros docker配置镜像报错:https://registry-1.docker.io/v2/

使用鱼香ros一件安装docker时的https://registry-1.docker.io/v2/问题 一键安装指令 wget http://fishros.com/install -O fishros && . fishros出现问题&#xff1a;docker pull 失败 网络不同&#xff0c;需要使用镜像源 按照如下步骤操作 sudo vi /etc/docker/dae…...

图表类系列各种样式PPT模版分享

图标图表系列PPT模版&#xff0c;柱状图PPT模版&#xff0c;线状图PPT模版&#xff0c;折线图PPT模版&#xff0c;饼状图PPT模版&#xff0c;雷达图PPT模版&#xff0c;树状图PPT模版 图表类系列各种样式PPT模版分享&#xff1a;图表系列PPT模板https://pan.quark.cn/s/20d40aa…...

SAP学习笔记 - 开发26 - 前端Fiori开发 OData V2 和 V4 的差异 (Deepseek整理)

上一章用到了V2 的概念&#xff0c;其实 Fiori当中还有 V4&#xff0c;咱们这一章来总结一下 V2 和 V4。 SAP学习笔记 - 开发25 - 前端Fiori开发 Remote OData Service(使用远端Odata服务)&#xff0c;代理中间件&#xff08;ui5-middleware-simpleproxy&#xff09;-CSDN博客…...