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

基于Flask实现的医疗保险欺诈识别监测模型

基于Flask实现的医疗保险欺诈识别监测模型 项目截图 项目简介 社会医疗保险是国家通过立法形式强制实施&#xff0c;由雇主和个人按一定比例缴纳保险费&#xff0c;建立社会医疗保险基金&#xff0c;支付雇员医疗费用的一种医疗保险制度&#xff0c; 它是促进社会文明和进步的…...

Robots.txt 文件

什么是robots.txt&#xff1f; robots.txt 是一个位于网站根目录下的文本文件&#xff08;如&#xff1a;https://example.com/robots.txt&#xff09;&#xff0c;它用于指导网络爬虫&#xff08;如搜索引擎的蜘蛛程序&#xff09;如何抓取该网站的内容。这个文件遵循 Robots…...

鱼香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…...

GC1808高性能24位立体声音频ADC芯片解析

1. 芯片概述 GC1808是一款24位立体声音频模数转换器&#xff08;ADC&#xff09;&#xff0c;支持8kHz~96kHz采样率&#xff0c;集成Δ-Σ调制器、数字抗混叠滤波器和高通滤波器&#xff0c;适用于高保真音频采集场景。 2. 核心特性 高精度&#xff1a;24位分辨率&#xff0c…...

C++课设:简易日历程序(支持传统节假日 + 二十四节气 + 个人纪念日管理)

名人说:路漫漫其修远兮,吾将上下而求索。—— 屈原《离骚》 创作者:Code_流苏(CSDN)(一个喜欢古诗词和编程的Coder😊) 专栏介绍:《编程项目实战》 目录 一、为什么要开发一个日历程序?1. 深入理解时间算法2. 练习面向对象设计3. 学习数据结构应用二、核心算法深度解析…...

Spring AI Chat Memory 实战指南:Local 与 JDBC 存储集成

一个面向 Java 开发者的 Sring-Ai 示例工程项目&#xff0c;该项目是一个 Spring AI 快速入门的样例工程项目&#xff0c;旨在通过一些小的案例展示 Spring AI 框架的核心功能和使用方法。 项目采用模块化设计&#xff0c;每个模块都专注于特定的功能领域&#xff0c;便于学习和…...

ZYNQ学习记录FPGA(一)ZYNQ简介

一、知识准备 1.一些术语,缩写和概念&#xff1a; 1&#xff09;ZYNQ全称&#xff1a;ZYNQ7000 All Pgrammable SoC 2&#xff09;SoC:system on chips(片上系统)&#xff0c;对比集成电路的SoB&#xff08;system on board&#xff09; 3&#xff09;ARM&#xff1a;处理器…...

AD学习(3)

1 PCB封装元素组成及简单的PCB封装创建 封装的组成部分&#xff1a; &#xff08;1&#xff09;PCB焊盘&#xff1a;表层的铜 &#xff0c;top层的铜 &#xff08;2&#xff09;管脚序号&#xff1a;用来关联原理图中的管脚的序号&#xff0c;原理图的序号需要和PCB封装一一…...

2025-05-08-deepseek本地化部署

title: 2025-05-08-deepseek 本地化部署 tags: 深度学习 程序开发 2025-05-08-deepseek 本地化部署 参考博客 本地部署 DeepSeek&#xff1a;小白也能轻松搞定&#xff01; 如何给本地部署的 DeepSeek 投喂数据&#xff0c;让他更懂你 [实验目的]&#xff1a;理解系统架构与原…...

break 语句和 continue 语句

break语句和continue语句都具有跳转作用&#xff0c;可以让代码不按既有的顺序执行 break break语句用于跳出代码块或循环 1 2 3 4 5 6 for (var i 0; i < 5; i) { if (i 3){ break; } console.log(i); } continue continue语句用于立即终…...