当前位置: 首页 > 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…...

业务系统对接大模型的基础方案:架构设计与关键步骤

业务系统对接大模型&#xff1a;架构设计与关键步骤 在当今数字化转型的浪潮中&#xff0c;大语言模型&#xff08;LLM&#xff09;已成为企业提升业务效率和创新能力的关键技术之一。将大模型集成到业务系统中&#xff0c;不仅可以优化用户体验&#xff0c;还能为业务决策提供…...

conda相比python好处

Conda 作为 Python 的环境和包管理工具&#xff0c;相比原生 Python 生态&#xff08;如 pip 虚拟环境&#xff09;有许多独特优势&#xff0c;尤其在多项目管理、依赖处理和跨平台兼容性等方面表现更优。以下是 Conda 的核心好处&#xff1a; 一、一站式环境管理&#xff1a…...

【杂谈】-递归进化:人工智能的自我改进与监管挑战

递归进化&#xff1a;人工智能的自我改进与监管挑战 文章目录 递归进化&#xff1a;人工智能的自我改进与监管挑战1、自我改进型人工智能的崛起2、人工智能如何挑战人类监管&#xff1f;3、确保人工智能受控的策略4、人类在人工智能发展中的角色5、平衡自主性与控制力6、总结与…...

工业安全零事故的智能守护者:一体化AI智能安防平台

前言&#xff1a; 通过AI视觉技术&#xff0c;为船厂提供全面的安全监控解决方案&#xff0c;涵盖交通违规检测、起重机轨道安全、非法入侵检测、盗窃防范、安全规范执行监控等多个方面&#xff0c;能够实现对应负责人反馈机制&#xff0c;并最终实现数据的统计报表。提升船厂…...

解决Ubuntu22.04 VMware失败的问题 ubuntu入门之二十八

现象1 打开VMware失败 Ubuntu升级之后打开VMware上报需要安装vmmon和vmnet&#xff0c;点击确认后如下提示 最终上报fail 解决方法 内核升级导致&#xff0c;需要在新内核下重新下载编译安装 查看版本 $ vmware -v VMware Workstation 17.5.1 build-23298084$ lsb_release…...

UDP(Echoserver)

网络命令 Ping 命令 检测网络是否连通 使用方法: ping -c 次数 网址ping -c 3 www.baidu.comnetstat 命令 netstat 是一个用来查看网络状态的重要工具. 语法&#xff1a;netstat [选项] 功能&#xff1a;查看网络状态 常用选项&#xff1a; n 拒绝显示别名&#…...

Leetcode 3577. Count the Number of Computer Unlocking Permutations

Leetcode 3577. Count the Number of Computer Unlocking Permutations 1. 解题思路2. 代码实现 题目链接&#xff1a;3577. Count the Number of Computer Unlocking Permutations 1. 解题思路 这一题其实就是一个脑筋急转弯&#xff0c;要想要能够将所有的电脑解锁&#x…...

第一篇:Agent2Agent (A2A) 协议——协作式人工智能的黎明

AI 领域的快速发展正在催生一个新时代&#xff0c;智能代理&#xff08;agents&#xff09;不再是孤立的个体&#xff0c;而是能够像一个数字团队一样协作。然而&#xff0c;当前 AI 生态系统的碎片化阻碍了这一愿景的实现&#xff0c;导致了“AI 巴别塔问题”——不同代理之间…...

Ascend NPU上适配Step-Audio模型

1 概述 1.1 简述 Step-Audio 是业界首个集语音理解与生成控制一体化的产品级开源实时语音对话系统&#xff0c;支持多语言对话&#xff08;如 中文&#xff0c;英文&#xff0c;日语&#xff09;&#xff0c;语音情感&#xff08;如 开心&#xff0c;悲伤&#xff09;&#x…...

Element Plus 表单(el-form)中关于正整数输入的校验规则

目录 1 单个正整数输入1.1 模板1.2 校验规则 2 两个正整数输入&#xff08;联动&#xff09;2.1 模板2.2 校验规则2.3 CSS 1 单个正整数输入 1.1 模板 <el-formref"formRef":model"formData":rules"formRules"label-width"150px"…...