自组织映射Python实现

news2024/10/3 4:42:00

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

#!/usr/bin/env python3

"""
Self-organizing map
"""

from math import exp

import toolz

import numpy as np
import numpy.linalg as LA

from sklearn.base import ClusterMixin
from sklearn.preprocessing import MinMaxScaler
scaler = MinMaxScaler()


class Node:
    """Node
    
    Attributes:
        location (np.ndarray): location of the node
        weight (np.ndarray): weight of the node, in the data sp.
    
    """
    def __init__(self, weight, location=None):
        self.weight = weight
        self.location = location

    def 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 locations
        if self.location is not None and other.location is not None:
            return LA.norm(self.location - other.location) < d
        else:
            return 0

    def update(self, x, eta=0.1):
        """update the weight of the node
        w += r (x-w)
        """
        self.weight += eta *(x - self.weight)

    @staticmethod
    def random(n=2):
        weight = np.random.random(n)
        location = np.random.random(2)
        node = Node(weight, location)
        node.normalize()
        return node

    def 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 SOM

    A Grid of nodes
    """

    def __init__(self, nodes):
        self.nodes = list(nodes)

    @staticmethod
    def 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 nodes
        return [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 node
        c = 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 pd
        df = pd.read_csv('heart.csv')  # input your data
    except Exception as e:
        printe(e)
        raise Exception('Please input your data!')

    def _grid(size=(5, 5), *args, **kwargs):
        grid = []
        r, c = size
        for 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 generating
                location = np.array((k/r, l/c))
                node = Node(weight=weight, location=location)
                row.append(node)
            grid.append(row)
        return grid

    df = df[['trestbps', 'chol']]
    N, p = df.shape
    X = df.values.astype('float')
    
    import matplotlib.pyplot as plt
    fig = 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()

在这里插入图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1128511.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Elasticsearch快速入门及结合Next.js案例使用

文章目录 什么是Elasticsearch安装Elasticsearch索引文档节点分片 使用Elasticsearch进行全文搜索连接到Elasticsearch创建索引和插入数据创建全文搜索页面测试全文搜索 结语 &#x1f389;欢迎来到Java学习路线专栏~Elasticsearch快速入门及结合Next.js案例使用 ☆* o(≧▽≦)…

Hbuilder打包安卓H5-APP,APP与程序分离,更新无需重新打包

一、目标 使用Hbuilder打包H5-APP 两个方式&#xff1a; 1、将自己的H5页面以及js全部打包进apk程序&#xff0c;后续如果更新&#xff0c;只能迭代apk版本&#xff0c;来进行APP更新升级。 2、使用HBuilder打个空包&#xff0c;修改应用入口页面(首页)地址&#xff0c;这里默…

Centos使用tomcat部署jenkins

jenkins的最新版本已经不在支持jdk8&#xff0c;支持的jdk环境如下&#xff1a; 安装jdk环境 yum -y install java-11-openjdk.x86_64 java-11-openjdk-devel.x86_64安装tomcat tomcat官网 cd /optwget https://dlcdn.apache.org/tomcat/tomcat-9/v9.0.82/bin/apache-tomcat…

HarmonyOS DevEso环境搭建

DevEco Studio 3.1配套支持HarmonyOS 3.1版本及以上的应用及服务开发&#xff0c;提供了代码智能编辑、低代码开发、双向预览等功能&#xff0c;以及轻量构建工具DevEco Hvigor 、本地模拟器&#xff0c;持续提升应用及服务开发效率。 1.下载 官方网站&#xff1a; HUAWEI De…

基于Java的校园论坛管理系统设计与实现(源码+lw+部署文档+讲解等)

文章目录 前言具体实现截图论文参考详细视频演示为什么选择我自己的网站自己的小程序&#xff08;小蔡coding&#xff09; 代码参考数据库参考源码获取 前言 &#x1f497;博主介绍&#xff1a;✌全网粉丝10W,CSDN特邀作者、博客专家、CSDN新星计划导师、全栈领域优质创作者&am…

【Docker从入门到入土 5】 使用Docker-compose一键部署Wordpress平台

Docker-compose 一、YAML 文件格式及编写注意事项&#xff08;重要&#xff09;1.1 简介1.2 yaml语法特性1.3 yaml文件格式1.4 json格式简介 二、Docker-compose2.1 简介2.2 docker-compose的三大概念2.3 docker-compose配置模板文件常用的字段2.4 docker-compose 常用命令 三、…

Java游戏修炼手册:2023 最新学习线路图

前言 有没有一种令人兴奋的学习方法&#xff1f;当然有&#xff01;绝对有&#xff01;而且我要告诉你&#xff0c;学习的快乐可以媲美游戏的刺激。 小学时代&#xff0c;我曾深陷于一款名为"八百万勇士的梦"的游戏。每当放学&#xff0c;我总是迫不及待地打开电脑&a…

【C刷题】day6

一、选择题 1、以下叙述中正确的是&#xff08; &#xff09; A: 只能在循环体内和switch语句体内使用break语句 B: 当break出现在循环体中的switch语句体内时&#xff0c;其作用是跳出该switch语句体&#xff0c;并中止循环体的执行 C: continue语句的作用是&#xff1a;在…

党建展馆vr仿真解说员具有高质量的表现力和互动性

随着虚拟数字人应用渐成趋势&#xff0c;以虚拟数字人为核心的营销远比其他更能加速品牌年轻化进程和认识&#xff0c;助力企业在激烈的市场竞争中脱颖而出&#xff0c;那么企业虚拟IP代言人解决了哪些痛点? 解决品牌与代言人之间的风险问题 传统代言人在代言品牌时&#xff0…

使用SecScanC2构建P2P去中心化网络实现反溯源

个人博客: xzajyjs.cn 前言 这款工具是为了帮助安全研究人员在渗透测试过程中防止扫描被封禁、保护自己免溯源的一种新思路。其利用到了区块链中的p2p点对点去中心化技术构建以来构建代理池。 工具链接&#xff1a;https://github.com/xzajyjs/SecScanC2 实验过程 该工具分为…

前端跨域相关

注&#xff1a;前端配置跨域后服务器端&#xff08;Nginx&#xff09;也需要配置&#xff0c;否则接口无法访问 vue跨域 配置文件 /vue.config.js devServer: { port: 7100, proxy: { /api: { target: http://域名, changeOrigin: true, logLevel: debug, pathRewrite: { ^/…

提升MODBUS-RTU通信数据刷新速度的常用方法

SMART PLC的MODBUS-RTU通信请参考下面文章链接: 【精选】PLC MODBUS通信优化、提高通信效率避免权限冲突(程序+算法描述)-CSDN博客MODBUS通讯非常简单、应用也非常广泛,有些老生常谈的问题,这里不再赘述,感兴趣的可以参看我的其它博文:SMART200PLC MODBUS通讯专题_RXXW…

unity 一键替换 UI上所有字体,批量替换字体(包括:Text和Text (TMP))

前言&#xff1a;在开发中会遇到这种情况&#xff0c;开发完了&#xff0c;发现UI字体没有替换&#xff0c;特别是需要发布到WebGL端的同学&#xff0c;突然发现无法显示汉字了。下面一个非常方便的方法完美解决。 1.解压出来的脚本放在Edit文件下&#xff0c;没有的创建一个 2…

AI问诊逐渐取代医生是不是伪命题?实测国内外医疗专用大模型

随着贫富差距和人口老龄化的进程加速&#xff0c;以及区域医疗资源的不均衡&#xff0c;医疗成了最让人民群众头疼的事情。虽然互联网和云计算的普及&#xff0c;一定程度上的缓解了这些矛盾。例如&#xff1a;人们可以通过遇到简单的医疗问题的时候&#xff0c;可以去搜索引擎…

使用canvas做了一个最简单的网页版画板,5分钟学会

画板实现的效果&#xff1a;可以切换画笔的粗细&#xff0c;颜色&#xff0c;还可以使用橡皮擦&#xff0c;还可以清除画布&#xff0c;然后将画的内容保存下载成一张图片&#xff1a; 具体用到的canvas功能有&#xff1a;画笔的粗细调整lineWidth&#xff0c;开始一个新的画笔…

postman接收后端返回的文件流并自动下载

不要点send&#xff0c;点send and download&#xff0c;postman接受完文件流会弹出文件保存框让你选择保存路径

Unity Spine 指定导入新Spine动画的默认材质

指定导入新Spine动画的默认材质 找到Spine的Editor导入配置如何修改方法一: 你可以通过脚本 去修改Assets/Editor/SpineSettings.asset文件方法二&#xff1a;通过面板手动设置 找到Spine的Editor导入配置 通常在 Assets/Editor/SpineSettings.asset 配置文件对应着 Edit/Prefe…

从“特种兵游”到Citywalk,年轻人的下一个旅游热点会在哪?

2023年&#xff0c;国内游在逐步放开&#xff0c;境外旅游目的地名单也逐步“扩容”&#xff0c;生活的轨迹在回正&#xff0c;越来越多人重启旅行&#xff0c;感受生活。于此同时&#xff0c;在短短几个月内&#xff0c;寺庙游、citywalk、淄博烧烤、特种兵旅行各种与旅游相关…

docker部署前后端分离springboot+vue项目

前置知识 虚拟网桥 docker容器需要在同一个网段才能通信&#xff0c;当启动一个容器时会自动连接一个docker中默认网桥段但此默认网桥段非本容器固定&#xff0c;当下次容器启动分配的ip会变&#xff0c;并且不可用名称直接访问。 自定义网段将需要互通的容器放入&#xff0c…

Python容器和可迭代对象

在刚开始学Python的时候&#xff0c;是不是经常会听到大佬们在讲容器、可迭代对象、迭代器、生成器、列表/集合/字典推导式等等众多概念&#xff0c;其实这不是大佬们没事就搁那扯专业术语来装B&#xff0c;而是这些东西都得要明白的&#xff0c;光知道字符串、列表等基础还是不…