gpt4 book ai didi

python-3.x - 如何获得一维数据的k均值聚类?

转载 作者:行者123 更新时间:2023-12-03 16:14:36 25 4
gpt4 key购买 nike

我有一个如下所示的 csv 文件

date                       mse                                                  
2018-02-11 14.34
2018-02-12 7.24
2018-02-13 4.5
2018-02-14 3.5
2018-02-16 12.67
2018-02-21 45.66
2018-02-22 15.33
2018-02-24 98.44
2018-02-26 23.55
2018-02-27 45.12
2018-02-28 78.44
2018-03-01 34.11
2018-03-05 23.33
2018-03-06 7.45
... ...

现在我想为 mse 获取两个集群值,以便我知道哪个值属于哪个集群及其平均值。

现在因为除了 mse 之外我没有任何其他值集(我必须提供 X 和 Y),我只想使用 mse获得 k 的值意味着集群。现在对于另一组值,我将它作为范围传递,该范围与 mse 的大小相同值(value)观。这就是我所做的
from sklearn.cluster import KMeans
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

df = pd.read_csv("generate_csv/all_data_device.csv", parse_dates=["date"])
f1 = df['mse'].values
# generate another list
f2 = list(range(0, len(f1)))
X = np.array(list(zip(f1, f2)))
kmeans = KMeans(n_clusters=2).fit(X)
labels = kmeans.predict(X)
# Centroid values
centroids = kmeans.cluster_centers_
#print(centroids)

fig = plt.figure()
ax = Axes3D(fig)
ax.scatter(X[:, 0], X[:, 1], c=labels)
ax.scatter(centroids[:, 0], centroids[:, 1], marker='*', c='#050505', s=1000)
plt.title('K Mean Classification')
plt.show()

我如何才能使用 mse值来获得 k 意味着集群?我知道函数 'reshape()' 但不太确定如何使用它?

最佳答案

演示:

In [29]: kmeans = KMeans(n_clusters=2)

In [30]: df['label'] = kmeans.fit_predict(df[['mse']])
# NOTE: ----> ^ ^

In [31]: df
Out[31]:
date mse label
0 2018-02-11 14.34 0
1 2018-02-12 7.24 0
2 2018-02-13 4.50 0
3 2018-02-14 3.50 0
4 2018-02-16 12.67 0
5 2018-02-21 45.66 0
6 2018-02-22 15.33 0
7 2018-02-24 98.44 1
8 2018-02-26 23.55 0
9 2018-02-27 45.12 0
10 2018-02-28 78.44 1
11 2018-03-01 34.11 0
12 2018-03-05 23.33 0
13 2018-03-06 7.45 0

绘图:
In [64]: ax = df[df['label']==0].plot.scatter(x='mse', y='label', s=50, color='white', edgecolor='black')

In [65]: df[df['label']==1].plot.scatter(x='mse', y='label', s=50, color='white', ax=ax, edgecolor='red')
Out[65]: <matplotlib.axes._subplots.AxesSubplot at 0xfa42be0>

In [66]: plt.scatter(kmeans.cluster_centers_.ravel(), [0.5]*len(kmeans.cluster_centers_), s=100, color='green', marker='*')
Out[66]: <matplotlib.collections.PathCollection at 0xfabf208>

enter image description here

关于python-3.x - 如何获得一维数据的k均值聚类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50113595/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com