[英]How do I assign colors to clusters in kmeans?
I keep getting error messages for my kmeans clustering.我不断收到 kmeans 聚类的错误消息。 Note: I am extremely new to everything and coding in general, so I am also looking to improve in any way.注意:我对一切和编码都非常陌生,所以我也希望以任何方式改进。 I tried personally defining each color, but that did not work either.我尝试亲自定义每种颜色,但这也不起作用。
# create map
map_clusters = folium.Map(location=[latitude, longitude], zoom_start=11)
# set color scheme for the clusters
x = np.arange(kclusters)
ys = [i + x + (i*x)**2 for i in range(kclusters)]
colors_array = cm.rainbow(np.linspace(0, 1, len(ys)))
rainbow = [colors.rgb2hex(i) for i in colors_array]
# add markers to the map
markers_colors = []
for lat, lon, poi, cluster in zip(pittsburgh_merged['Latitude'],
pittsburgh_merged['Longitude'], pittsburgh_merged['Neighborhood'],
pittsburgh_merged['Cluster Labels']):
label = folium.Popup(str(poi) + ' Cluster ' + str(cluster),
parse_html=True)
folium.CircleMarker(
[lat, lon],
radius=5,
popup=label,
color=rainbow[cluster-1],
fill=True,
fill_color=rainbow[cluster-1],
fill_opacity=0.7).add_to(map_clusters)
map_clusters
I expect an output of the map_clusters to be visible.我希望 map_clusters 的输出可见。 It is supposed to be a map of Pittsburgh with venues organized by colors.它应该是匹兹堡的地图,场地按颜色组织。 Hence the rainbow assignment.因此彩虹任务。 However, I keep getting the "TypeError: list indices must be integers or slices, not float" error for the color and fill_color assignments.但是,对于 color 和 fill_color 分配,我不断收到“类型错误:列表索引必须是整数或切片,而不是浮点数”错误。
The error you are receiving means that the index that you are using to access the list rainbow
is not an integer, but a float.您收到的错误意味着您用来访问列表rainbow
的索引不是整数,而是浮点数。 In this case, you are trying to access element cluster - 1
of the list rainbow
.在这种情况下,您正在尝试访问列表rainbow
元素cluster - 1
。 However, the expression cluster - 1
seems to be a float, which in turn implies that the variable cluster
does not contain an int, but a float.但是,表达式cluster - 1
似乎是一个浮点数,这又意味着变量cluster
不包含 int,而是一个浮点数。 Try to make sure that you are passing in integer, for example by casting the variable to an integer:尝试确保您传入的是整数,例如通过将变量转换为整数:
color = rainbow[int(cluster)-1]
However, this depends on the actual content of the variable and will not work if cluster
contains a nan-value like inf
.但是,这取决于变量的实际内容,如果cluster
包含像inf
这样的 nan-value 则不起作用。 In this case (or all cases, actually), you should take a look at the data you have and make sure that is makes sense.在这种情况下(或所有情况,实际上),您应该查看您拥有的数据并确保它是有意义的。 Since you are trying to do k-means and receive float values and even nan-values for your cluster labels, it is possible that something went wrong earlier during the clustering process.由于您正在尝试执行 k 均值并接收浮点值甚至是集群标签的 nan 值,因此在集群过程中可能较早出现问题。 Try looking at the actual content of the pittsburgh_merged
variable by printing its content.尝试通过打印其内容来查看pittsburgh_merged
变量的实际内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.