def _soft_assignment(self, embeddings, cluster_centers):
"""Implemented a soft assignment as the probability of assigning sample i to cluster j.
Args:
embeddings: (num_points, dim)
cluster_centers: (num_cluster, dim)
Return:
q_i_j: (num_points, num_cluster)
"""
def _pairwise_euclidean_distance(a,b):
p1 = tf.matmul(
tf.expand_dims(tf.reduce_sum(tf.square(a), 1), 1),
tf.ones(shape=(1, self.n_cluster))
)
p2 = tf.transpose(tf.matmul(
tf.reshape(tf.reduce_sum(tf.square(b), 1), shape=[-1, 1]),
tf.ones(shape=(self.ae.input_batch_size, 1)),
transpose_b=True
))
res = tf.sqrt(tf.add(p1, p2) - 2 * tf.matmul(a, b, transpose_b=True))
return res
dist = _pairwise_euclidean_distance(embeddings, cluster_centers)
q = 1.0/(1.0+dist**2/self.alpha)**((self.alpha+1.0)/2.0)
q = (q/tf.reduce_sum(q, axis=1, keepdims=True))
return q
我自己转化不知道是否转化正确了:
def soft_assignment(self, embeddings, cluster_centers):
"""Implemented a soft assignment as the probability of assigning sample i to cluster j.
Args:
embeddings: (num_points, dim)
cluster_centers: (num_cluster, dim)
Return:
q_i_j: (num_points, num_cluster)
"""
n_obj = embeddings.shape[0]
n_clusters = cluster_centers.shape[0]
def _pairwise_euclidean_distance(a, b, n_obj, n_clusters):
p1 = torch.matmul(
torch.unsqueeze(torch.sum(torch.mul(a,a), 1), 1),
torch.ones(1, n_clusters).to(self.device)
)
p2 = torch.transpose(torch.matmul(
torch.reshape(torch.sum(torch.mul(b,b), 1), (-1, 1)),
torch.ones(1, n_obj).to(self.device),
), 0, 1)
res = torch.sqrt(torch.add(p1, p2) - 2 * torch.matmul(a, torch.transpose(b, 0, 1)))
return res
dist = _pairwise_euclidean_distance(embeddings, cluster_centers, n_obj, n_clusters)
q = 1.0 / (1.0 + dist ** 2 / self.alpha) ** ((self.alpha + 1.0) / 2.0)
q = (q / torch.sum(q, dim=1, keepdim=True))
return q