基于鸢尾花数据集实施自组织神经网络聚类分析

基于鸢尾花数据集实施自组织神经网络聚类分析

  • 1. 自组织神经网络的基础知识
  • 2. 鸢尾花数据集的自组织分类
  • 3. SOM的无监督聚类

1. 自组织神经网络的基础知识

自组织神经网络也称自组织映射(SOM)或自组织特征映射(SOFM),是一种使用非监督式学习来产生训练样本的输入空间的一个低维(通常是二维)离散化的表示的人工神经网络(ANN)。自组织映射与其他人工神经网络的不同之处在于它使用一个邻近函数来保持输入空间的拓扑性质。
在这里插入图片描述
在这里插入图片描述

2. 鸢尾花数据集的自组织分类

# 导入必要的库
import numpy as np
from minisom import MiniSom
import matplotlib.pyplot as plt
from sklearn import datasets# 载入鸢尾花数据集
iris = datasets.load_iris()
data = iris.data
labels = iris.target# 数据归一化
data = (data - np.min(data, axis=0)) / (np.max(data, axis=0) - np.min(data, axis=0))# 定义 SOM 网络的参数
som_shape = (10, 10)  # SOM 网格的形状
som = MiniSom(som_shape[0], som_shape[1], data.shape[1], sigma=1.0, learning_rate=0.5)# 初始化权重并开始训练
som.random_weights_init(data)
som.train_random(data, 100)  # 100 次迭代
# 创建 U-matrix
umatrix = som.distance_map()
print(umatrix)
# 绘制 U-matrix
plt.figure(figsize=(4,4))
plt.pcolor(umatrix.T, cmap='bone_r', alpha=0.8)
plt.colorbar()# 绘制聚类中心
for i, target in enumerate(labels):x, y = som.winner(data[i])plt.text(x + 0.5, y + 0.5, str(target), color=plt.cm.rainbow(target / 2.0), fontdict={'weight': 'bold', 'size': 11})plt.xticks(np.arange(som_shape[0] + 1))
plt.yticks(np.arange(som_shape[1] + 1))
plt.grid()
plt.show()

聚类结果
在这里插入图片描述

新聚类

import math
import numpy as np
from minisom import MiniSom
from sklearn import datasets
from numpy import sum as npsum
from sklearn.metrics import classification_report
from sklearn.model_selection import train_test_splitimport matplotlib.pyplot as plt
from matplotlib.patches import Patch
from matplotlib.gridspec import GridSpec# 分类函数
def classify(som,data,winmap):default_class = npsum(list(winmap.values())).most_common()[0][0]result = []for d in data:win_position = som.winner(d)if win_position in winmap:result.append(winmap[win_position].most_common()[0][0])else:result.append(default_class)return result# 可视化
def show(som):""" 在输出层画标签图案 """plt.figure(figsize=(5, 5))# 定义不同标签的图案标记markers = ['o', 's', 'D']colors = ['C0', 'C1', 'C2']category_color = {'setosa': 'C0', 'versicolor': 'C1', 'virginica': 'C2'}# 背景上画U-Matrixheatmap = som.distance_map()# 画背景图plt.pcolor(heatmap, cmap='bone_r')for cnt, xx in enumerate(X_train):w = som.winner(xx)# 在样本Heat的地方画上标记plt.plot(w[0] + .5, w[1] + .5, markers[Y_train[cnt]], markerfacecolor='None',markeredgecolor=colors[Y_train[cnt]], markersize=12, markeredgewidth=2)plt.axis([0, size, 0, size])ax = plt.gca()# 颠倒y轴方向ax.invert_yaxis()legend_elements = [Patch(facecolor=clr, edgecolor='w', label=l) for l, clr in category_color.items()]plt.legend(handles=legend_elements, loc='center left', bbox_to_anchor=(1, .95))plt.show()# """ 在每个格子里画饼图,且用颜色表示类别,用数字表示总样本数量 """# plt.figure(figsize=(16, 16))# the_grid = GridSpec(size, size)# for position in winmap.keys():#     label_fracs = [winmap[position][label] for label in [0, 1, 2]]#     plt.subplot(the_grid[position[1], position[0]], aspect=1)#     patches, texts = plt.pie(label_fracs)#     plt.text(position[0] / 100, position[1] / 100, str(len(list(winmap[position].elements()))),#              color='black', fontdict={'weight': 'bold', 'size': 15}, va='center', ha='center')# plt.legend(patches, class_names, loc='center right', bbox_to_anchor=(-1, 9), ncol=3)# plt.show()if __name__ == '__main__':# 导入数据集iris = datasets.load_iris()# 提取iris数据集的标签与数据feature_names = iris.feature_namesclass_names = iris.target_namesX = iris.dataY = iris.target# 划分训练集、测试集  7:3X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.3, random_state=0)# 样本数量N = X_train.shape[0]# 维度/特征数量M = X_train.shape[1]# 最大迭代次数max_iter = 200# 经验公式:决定输出层尺寸size = math.ceil(np.sqrt(5 * np.sqrt(N)))print("训练样本个数:{}  测试样本个数:{}".format(N, X_test.shape[0]))print("输出网格最佳边长为:", size)# 初始化模型som = MiniSom(size, size, M, sigma=3, learning_rate=0.5, neighborhood_function='bubble')# 初始化权值som.pca_weights_init(X_train)# 模型训练som.train_batch(X_train, max_iter, verbose=False)# 利用标签信息,标注训练好的som网络winmap = som.labels_map(X_train, Y_train)# 进行分类预测y_pred = classify(som, X_test, winmap)print(y_pred)# 展示在测试集上的效果print(classification_report(Y_test, np.array(y_pred)))# 可视化show(som)

在这里插入图片描述

3. SOM的无监督聚类

from minisom import MiniSom
import numpy as np
import pandas as pd
from sklearn import datasets
import matplotlib.pyplot as plt# 加载鸢尾花数据
iris = datasets.load_iris()
data = iris.data
ds = pd.DataFrame(data)
dt=ds.values
som_shape = (1,3)
som = MiniSom(som_shape[0], som_shape[1], dt.shape[1], sigma=.5, learning_rate=.5,neighborhood_function='gaussian', random_seed=42)
som.train_batch(dt, 1000, verbose=True)
winner_coordinates = np.array([som.winner(x) for x in dt]).T
cluster_index = np.ravel_multi_index(winner_coordinates, som_shape)
## 可视化聚类结果
import matplotlib.pyplot as plt 
from matplotlib import rcParams
from matplotlib.pyplot import MultipleLocatorconfig = {"font.family": 'serif', # 衬线字体"font.size": 10, # 相当于小四大小"font.serif": ['SimSun'], # 宋体"mathtext.fontset": 'stix', # matplotlib渲染数学字体时使用的字体,和Times New Roman差别不大'axes.unicode_minus': False # 处理负号,即-号
}
rcParams.update(config)fig = plt.figure(figsize=(5,5))
ax = plt.subplot(1,1,1,projection='3d')
# plotting the clusters using the first 2 dimentions of the data
for c in np.unique(cluster_index):ax.scatter3D(dt[cluster_index == c, 0],dt[cluster_index == c, 1], dt[cluster_index == c, 2], label='cluster='+str(c), alpha=.7)# plotting centroids
for centroid in som.get_weights():ax.scatter3D(centroid[:, 0], centroid[:, 1],centroid[:, 2], marker='x', alpha=.7,s=10, linewidths=10, color='k', label='centroid')
ax.set_xlabel('Production Function')		
ax.set_ylabel('Economy Function')
ax.set_zlabel('Social Function')
ax.set_title('SOM clustering result')
plt.legend()
# plt.margins(0,0,0)
plt.show()
# plt.savefig('./result.png',dpi=600)

在这里插入图片描述

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

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

相关文章

Coze扣子开发指南:用免费API自己创建插件

虽然Coze扣子现在插件商店已经有几百个插件了,但相对于海量人群的众多差异化需求,还是远远不够的。如果插件商店没有合适的插件,其实完成可以自己创建,过程也很简单,不需要编写任何代码。 首先打开个人空间&#xff0…

AcWing 835:Trie字符串统计 ← 字典树(Trie树)模板题

【题目来源】https://www.acwing.com/problem/content/837/【题目描述】 维护一个字符串集合,支持两种操作: ● I x 向集合中插入一个字符串 x; ● Q x 询问一个字符串在集合中出现了多少次。 共有 N 个操作,所有输入的字符…

Linux sudo 指令

sudo命令 概念: sudo是linux下常用的允许普通用户使用超级用户权限的工具,允许系统管理员让普通用户执行一些或者全部的root命令,如halt,reboot,su等。这样不仅减少了root用户的登录和管理时间,同样也提高…

22、Flink 背压下的 Checkpoint处理

1.概述 通常,对齐 Checkpoint 的时长主要受 Checkpointing 过程中的同步和异步两个部分的影响;但当 Flink 作业正运行在严重的背压下时,Checkpoint 端到端延迟的主要影响因子将会是传递 Checkpoint Barrier 到 所有的算子/子任务的时间&…

线程与进程

进程 进程是程序的一次执行过程,系统程序的基本单位。有自己的main方法,并且主要由主方法运行起来的基本上就是进程。 线程 线程与进程相似,但线程是一个比进程更小的执行单位。一个进程在其执行的过程中可以产生多个线程。与进程不同的是…

局域网语音对讲系统_IP广播对讲系统停车场解决方案

局域网语音对讲系统_IP广播对讲系统停车场解决方案 需求分析: 随着国民经济和社会的发展, 选择坐车出行的民众越来越多。在保护交通安全的同时,也给停车场服务部门提出了更高的要求。人们对停车场系统提出了更高的要求与挑战, 需要…

部分设计模式概述

单例模式 工厂模式 适配器模式 模板方法模式 策略模式 责任链 观察者模式(又叫发布订阅模式)

容器化Jenkins远程发布java应用(方式一:pipline+ssh)

1.创建pipline工程 2.准备工程Jenkinsfile文件(java目录) 1.文件脚本内容 env.fileName "planetflix-app.jar" env.configName "planetflix_prod" env.remoteDirectory "/data/project/java" env.sourceFile "/…

Leetcode - 周赛396

目录 一,3136. 有效单词 二,3137. K 周期字符串需要的最少操作次数 三,3138. 同位字符串连接的最小长度 四,3139. 使数组中所有元素相等的最小开销 一,3136. 有效单词 本题就是一道阅读理解题: 字符串长…

NSSCTF | [SWPUCTF 2021 新生赛]easy_sql

打开题目,提示输入一些东西,很显眼的可以看到网站标题为“参数是wllm” 首先单引号判断闭合方式 ?wllm1 报错了,可以判断为单引号闭合。 然后判断字节数(注意‘--’后面的空格) ?wllm1 order by 3-- 接着输入4就…

vue多选功能

废话不多说&#xff0c;直接上代码&#xff01;&#xff01;&#xff01; <template><div class"duo-xuan-page"><liv-for"(item, index) in list":key"index"click"toggleSelection(item)":class"{ active: sel…

ue引擎游戏开发笔记(36)——为射击落点添加特效

1.需求分析&#xff1a; 在debug测试中能看到子弹落点后&#xff0c;需要给子弹添加击中特效&#xff0c;更真实也更具反馈感。 2.操作实现&#xff1a; 1.思路&#xff1a;很简单&#xff0c;类似开枪特效一样&#xff0c;只要在头文件声明特效变量&#xff0c;在fire函数中…

Leetcode—232. 用栈实现队列【简单】

2024每日刷题&#xff08;131&#xff09; Leetcode—232. 用栈实现队列 实现代码 class MyQueue { public:MyQueue() {}void push(int x) {st.push(x);}int pop() {if(show.empty()) {if(empty()) {return -1;} else {int ans show.top();show.pop();return ans;}} else {i…

Burp Suite 抓包,浏览器提示有软件正在阻止Firefox安全地连接到此网站

问题现象 有软件正在阻止Firefox安全地连接到此网站 解决办法 没有安装证书&#xff0c;在浏览器里面安装bp的证书就可以了 参考&#xff1a;教程合集 《H01-启动和激活Burp.docx》——第5步

金蝶BI应收分析报表:关于应收,这样分析

这是一张出自奥威-金蝶BI方案的BI应收分析报表&#xff0c;是一张综合运用了筛选、内存计算等智能分析功能以及数据可视化图表打造而成的BI数据可视化分析报表&#xff0c;可以让企业运用决策层快速知道应收账款有多少&#xff1f;账龄如何&#xff1f;周转情况如何&#xff1f…

ARTS Week 27

Algorithm 本周的算法题为 58. 最后一个单词的长度 给你一个字符串 s&#xff0c;由若干单词组成&#xff0c;单词前后用一些空格字符隔开。返回字符串中 最后一个 单词的长度。 单词 是指仅由字母组成、不包含任何空格字符的最大子字符串。 示例 1&#xff1a;输入&#xff1a…

JAVA基础面试题(第十一篇)上! JVM

Hello好久不见&#xff01;&#xff0c;最近我们讲更新JVM部分的面试题。 JVM 这块比较难理解&#xff0c;而且也是不擅长的点。所以今天我更新一下JVM希望小伙伴们能在面试中取得好成绩&#xff01; JVM 1. 什么是JVM内存结构&#xff1f; jvm将虚拟机分为5大区域&#xff0…

上市公司-库存周转率、供应链效率明细数据集(2000-2022年)

01、数据介绍 库存周转率是衡量企业库存管理效率的关键指标之一&#xff0c;它反映了企业库存的流转速度。而供应链效率则体现了企业在整个供应链管理中的表现&#xff0c;包括采购、生产、物流等环节的协同和优化。 提高库存周转率和供应链效率是上市公司优化企业运营和管理…

ICode国际青少年编程竞赛- Python-2级训练场-识别循环规律2

ICode国际青少年编程竞赛- Python-2级训练场-识别循环规律2 1、 for i in range(3):Dev.step(3)Dev.turnRight()Dev.step(4)Dev.turnLeft()2、 for i in range(3):Spaceship.step(3)Spaceship.turnRight()Spaceship.step(1)3、 Dev.turnLeft() Dev.step(Dev.x - Item[1].…

编译和链接(超详细)

✅博客主页:爆打维c-CSDN博客​​​​​​ &#x1f43e; &#x1f539;分享c语言知识及代码 一、编译和链接实例 假设我们有一个名为main.c的C语言源文件&#xff0c;它包含了一个简单的Hello World程序。我们可以使用gcc编译器对该源文件进行编译&#xff0c;生成一个可执行…