import pandas as pd import matplotlib.pyplot as plt from sklearn.cluster import KMeans df = pd.read_csv(r"D:\数学建模\重航数学建模校赛\附件1(前50行).csv",encoding='gbk') # 文件目录加文件名 df.head() #定位数据 X = df.iloc[:,1:] X.head() # 标准化数据 from sklearn.preprocessing import StandardScaler scaler = StandardScaler() standX = scaler.fit_transform(X) standX # 肘部法则的可视化 from sklearn import metrics # 创建遍历,找到最合适的k值 scores = [] for k in range(2,150): labels = KMeans(n_clusters=k,n_init='auto').fit(X).labels_ score = metrics.silhouette_score(X,labels) scores.append(score) # 通过画图找出最合适的K值 plt.plot(list(range(2,150)),scores) plt.xlabel('Number of Clusters Initialized') plt.ylabel('Sihouette Score') plt.show()代码修改
时间: 2024-04-01 07:34:05 浏览: 208
import pandas as pd.docx
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
from sklearn.preprocessing import StandardScaler
from sklearn import metrics
df = pd.read_csv(r"D:\数学建模\重航数学建模校赛\附件1(前50行).csv",encoding='gbk') # 文件目录加文件名
X = df.iloc[:,1:]
scaler = StandardScaler()
standX = scaler.fit_transform(X)
scores = []
for k in range(2,150):
labels = KMeans(n_clusters=k,n_init='auto').fit(X).labels_
score = metrics.silhouette_score(X,labels)
scores.append(score)
plt.plot(list(range(2,150)),scores)
plt.xlabel('Number of Clusters Initialized')
plt.ylabel('Sihouette Score')
plt.show()
阅读全文