如何使用Matplotlib从多功能kmeans模型绘制聚类和中心? 功能0 功能1 功能2 功能3 功能4 功能5 功能6

如何解决如何使用Matplotlib从多功能kmeans模型绘制聚类和中心? 功能0 功能1 功能2 功能3 功能4 功能5 功能6

我使用kmeans算法来确定数据集中的簇数。在下面的代码中,您可以看到我具有多种功能,有些是绝对的,有些则没有。我对它们进行了编码和缩放,得到了最佳的簇数。

您可以从此处下载数据: https://www.sendspace.com/file/1cnbji

import sklearn.metrics as sm

from sklearn.preprocessing import scale

from sklearn.preprocessing import Normalizer
from sklearn.preprocessing import StandardScaler,MinMaxScaler

from sklearn.cluster import KMeans,SpectralClustering,MiniBatchKMeans
from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import OneHotEncoder

import matplotlib.pyplot as plt

import pandas as pd



df = pd.read_csv('dataset.csv')
print(df.columns)

features = df[['parcela','bruto','neto','osnova','sipovi','nadzemno','podzemno','tavanica','fasada']]

trans = ColumnTransformer(transformers=[('onehot',OneHotEncoder(),['tavanica','fasada']),('StandardScaler',Normalizer(),['parcela','sipovi'])],remainder='passthrough') # Default is to drop untransformed columns

features = trans.fit_transform(features)

Sum_of_squared_distances = []
for i in range(1,19):

     kmeans = KMeans(n_clusters = i,init = 'k-means++',random_state = 0)
     kmeans.fit(features)
     Sum_of_squared_distances.append(kmeans.inertia_)


plt.plot(range(1,19),Sum_of_squared_distances,'bx-')
plt.xlabel('k')
plt.ylabel('Sum_of_squared_distances')
plt.title('Elbow Method For Optimal k')
plt.show()

enter image description here

  • 在图中,肘部方法显示我的最佳簇数为7。
  • 如何绘制7个群集?
    • 我想在图形上看到质心,并用7种不同颜色的群集散布图。

解决方法

  • 给出Plot: kmeans clustering centroid,其中centers是一维。 centers数组的形状为(3,2),其中x(3,1)y(3,1)
    • 针对此一维中心展示的方法已被修改为该问题的模型所产生的针对七个维中心的解决方案。
  • 此问题中为模型返回的centers具有七个维度,形状为(7,14),其中14是7组xy值。
  • 此解决方案回答了以下问题:如何绘制聚类和中心?
# uses the imports as shown in the question
from matplotlib.patches import Rectangle,Patch  # for creating a legend
from matplotlib.lines import Line2D

# beginning with 
features = trans.fit_transform(features)

# create the model and fit it to features
kmeans_model2 = KMeans(n_clusters=7,init='k-means++',random_state=0).fit(features)

# find the centers; there are 7
centers = np.array(kmeans_model2.cluster_centers_)

# unique markers for the labels
markers = ['o','v','s','*','p','d','h']

# get the model labels
labels = kmeans_model2.labels_
labels_unique = set(labels)

# unique colors for each label
colors = sns.color_palette('husl',n_colors=len(labels_unique))

# color map with labels and colors
cmap = dict(zip(labels_unique,colors))

# plot
# iterate through each group of 2 centers
for j in range(0,len(centers)*2,2):
    plt.figure(figsize=(6,6))
    
    x_features = features[:,j]
    y_features = features[:,j+1]
    x_centers = centers[:,j]
    y_centers = centers[:,j+1]
    
    # add the data for each label to the plot
    for i,l in enumerate(labels):
#         print(f'Label: {l}')  # uncomment as needed
#         print(f'feature x coordinates for label:\n{x_features[i]}')  # uncomment as needed
#         print(f'feature y coordinates for label:\n{y_features[i]}')  # uncomment as needed
        plt.plot(x_features[i],y_features[i],color=colors[l],marker=markers[l],alpha=0.5)

    # print values for given plot,rounded for easier interpretation; all 4 can be commented out
    print(f'feature labels:\n{list(labels)}')
    print(f'x_features:\n{list(map(lambda x: round(x,3),x_features))}')
    print(f'y_features:\n{list(map(lambda x: round(x,y_features))}')
    print(f'x_centers:\n{list(map(lambda x: round(x,x_centers))}')
    print(f'y_centers:\n{list(map(lambda x: round(x,y_centers))}')
    
    # add the centers
    # this loop is to color the center marker to correspond to the color of the corresponding label.
    for k in range(len(centers)):  
        plt.scatter(x_centers[k],y_centers[k],marker="X",color=colors[k])
    
    # title
    plt.title(f'Features: Dimension {int(j/2)}')
    
    # create the rectangles for the legend
    patches = [Patch(color=v,label=k) for k,v in cmap.items()]
    # create centers marker for the legend
    black_x = Line2D([],[],color='k',marker='X',linestyle='None',label='centers',markersize=10)
    # add the legend
    plt.legend(title='Labels',handles=patches + [black_x],bbox_to_anchor=(1.04,0.5),loc='center left',borderaxespad=0,fontsize=15)
    
    plt.show()

绘图输出

  • 许多绘制的要素具有重叠的值和中心。
  • 已打印xy的{​​{1}}和features值,以更容易地看到重叠并确认绘制的值。
    • 负责的centers行可以在不再需要时被注释掉或删除。

功能0

print

enter image description here

功能1

feature labels:
[6,1,5,3,4,2,6,6]
x_features:
[0.0,1.0,0.0,0.0]
y_features:
[1.0,1.0]
x_centers:
[1.0,0.0]
y_centers:
[0.0,-0.0,1.0]

enter image description here

功能2

feature labels:
[6,1.0]

enter image description here

功能3

feature labels:
[6,0.0]
y_features:
[0.0,0.0]
x_centers:
[0.0,0.125,0.0]

enter image description here

功能4

feature labels:
[6,0.0]
y_features:
[0.298,0.193,0.18,0.336,0.181,0.174,0.197,0.23,0.175,0.212,0.196,0.186,0.2,0.15,0.141,0.304,0.108,0.101,0.105,0.459,0.16,0.224,0.216,0.246,0.139,0.111,0.227,0.177,0.159,0.25,0.298,0.223,0.335,0.431,0.17,0.381,0.255,0.222,0.296,0.156,0.202,0.145,0.195,0.336]
x_centers:
[0.0,0.875,0.0]
y_centers:
[0.196,0.188,0.249,0.237,0.182,0.328]

enter image description here

功能5

feature labels:
[6,6]
x_features:
[0.712,0.741,0.763,0.704,0.749,0.754,0.735,0.744,0.738,0.743,0.747,0.758,0.759,0.714,0.766,0.748,0.728,0.755,0.681,0.752,0.762,0.734,0.721,0.756,0.737,0.742,0.724,0.712,0.733,0.73,0.688,0.722,0.705,0.777,0.764,0.739,0.76,0.704]
y_features:
[0.614,0.636,0.612,0.601,0.631,0.64,0.62,0.624,0.633,0.632,0.63,0.61,0.629,0.641,0.616,0.65,0.644,0.539,0.628,0.623,0.627,0.603,0.648,0.614,0.58,0.562,0.666,0.587,0.565,0.591,0.646,0.642,0.625,0.601]
x_centers:
[0.745,0.708]
y_centers:
[0.63,0.611,0.604]

enter image description here

功能6

feature labels:
[6,6]
x_features:
[0.164,0.096,0.103,0.171,0.091,0.106,0.094,0.132,0.098,0.102,0.115,0.079,0.095,0.135,0.075,0.088,0.126,0.063,0.134,0.107,0.09,0.072,0.097,0.073,0.123,0.165,0.154,0.133,0.158,0.084,0.11,0.1,0.164,0.069,0.171]
y_features:
[0.001,0.002,0.001,0.005,0.004,0.003,0.001]
x_centers:
[0.093,0.116,0.112,0.152]
y_centers:
[0.001,0.001]

enter image description here

在一个图上更新所有尺寸

  • 根据OP的要求
feature labels:
[6,0.0]
  • 正如各个地块所指出的,有很多重叠之处。 enter image description here

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 <select id="xxx"> SELECT di.id, di.name, di.work_type, di.updated... <where> <if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 <property name="dynamic.classpath" value="tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams['font.sans-serif'] = ['SimHei'] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -> systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping("/hires") public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate<String
使用vite构建项目报错 C:\Users\ychen\work>npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-