属性错误:"KMeans"对象没有带pytorch的属性"labels_"

gopyfrb3  于 2022-12-23  发布在  其他
关注(0)|答案(1)|浏览(552)

首先我感谢,我试图训练模型与pytorch,但我得到了以下错误:属性错误:"KMeans"对象没有属性"labels_"。我正在尝试使用pytorch中的深度学习对提取要素点云建模。我收到以下错误。有人能帮助解决此问题吗?*****************************谢谢!

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)
            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 netx.complete_graph(indices).edges]
                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=getDevice(feature_matrix_batch))
        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=getDevice(feature_matrix_batch))
labels = np.apply_along_axis(lambda x: x + (i*self.k), axis=0, arr=kmeans.labels_)
AttributeError: 'KMeans' object has no attribute 'labels_'

谢谢你的帮忙

yhxst69z

yhxst69z1#

一旦通过运行.fit()(或.fit_predict(),或.fit_transform())实际计算了聚类,就会创建KMeans对象的属性labels_
简单举例:

>>> from sklearn.cluster import KMeans
>>> from numpy.random import random

>>> X = random((10,2))
>>> X
array([[0.2096706 , 0.69704806],
       [0.31732618, 0.29607599],
       [0.10372159, 0.56911046],
       [0.30922255, 0.07952464],
       [0.21190404, 0.46823665],
       [0.67134948, 0.95702692],
       [0.14781526, 0.24619197],
       [0.89931979, 0.96301003],
       [0.88256126, 0.07569739],
       [0.70776912, 0.92997521]])

>>> clustering = KMeans(n_clusters=3)
>>> clustering.labels_
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'KMeans' object has no attribute 'labels_'

>>> clustering.fit(X)
KMeans(n_clusters=3)
>>> clustering.labels_
array([0, 0, 0, 0, 0, 1, 0, 1, 2, 1], dtype=int32)

相关问题