PyTorch点云特征提取模型报错:'KMeans'对象无'labels_'属性
解决KMeans对象无labels_属性的问题
错误原因
你创建了KMeans实例后,没有调用fit()或fit_predict()方法对数据进行聚类拟合。sklearn的KMeans只有在完成数据拟合后才会生成labels_属性,直接访问未拟合的实例自然会触发属性不存在的错误。
修改后的代码
def forward(self, feature_matrix_batch): # feature_matrix_batch size = (N,I,D) where N=batch number, I=members, D=member dimensionality N, I, D = feature_matrix_batch.size() clusters = [] for i, feature_matrix in enumerate(feature_matrix_batch): kmeans = KMeans(n_clusters=self.k, init=self.kmeansInit, n_init=self.n_init) # 关键修改:先将tensor转为numpy数组,再执行聚类拟合 feature_np = feature_matrix.cpu().numpy() # GPU tensor需先转CPU再转numpy kmeans.fit(feature_np) # 拟合后kmeans.labels_才会生成 # 也可以用fit_predict一步获取标签:labels = kmeans.fit_predict(feature_np) labels = np.apply_along_axis(lambda x: x + (i*self.k), axis=0, arr=kmeans.labels_) clusters.extend(labels) clusters = np.asarray(clusters) list1 = [] list2 = [] for i in range(self.k*N): indices = np.argwhere(clusters == i).flatten().tolist() if len(indices) != 1: edges = [e for e in nx.complete_graph(indices).edges] # 修正笔误:netx -> nx inverse_edges = list(map(lambda x: (x[1], x[0]), edges)) edges.extend(inverse_edges) unzip = list(zip(*edges)) list1.extend(unzip[0]) list2.extend(unzip[1]) else: list1.append(indices[0]) list2.append(indices[0]) edge_index = torch.tensor([list1, list2], dtype=torch.long, device=feature_matrix_batch.device) edge_index = sort_edge_index(add_self_loops(edge_index)[0])[0] conv_feature_matrix_batch = self.conv(feature_matrix_batch.view(-1, D), edge_index).view(N, I, -1) # conv_feature_matrix_batch size = (N,I,L) where N=batch number, I=members, L=C+P return feature_matrix_batch, conv_feature_matrix_batch, torch.tensor(clusters, dtype=torch.long, device=feature_matrix_batch.device)
额外注意事项
- 代码中的
netx是笔误,应该是nx(networkx库的常规别名),不修正会触发NameError。 - 若输入tensor在GPU上,必须先转至CPU再转为numpy数组——sklearn不支持直接处理GPU张量。
- 可以用
fit_predict简化流程:直接通过labels = kmeans.fit_predict(feature_np)获取聚类标签,无需单独调用fit()。
内容的提问来源于stack exchange,提问作者abdou
相关产品推荐
相关产品推荐

