ground_truth = np.squeeze(np.asarray(true_labels))

时间:2019-03-21 15:18:17

标签: python pandas numpy

请帮助我理解这一行代码?

squeezeasarray函数的作用是什么?

在这种方法中,k均值聚类,其中k = 5,并且已经进行了随机初始化。

ground_truth = np.squeeze(np.asarray(true_labels))

非常感谢

1 个答案:

答案 0 :(得分:0)

如果可以的话,请在将来提供更多特定于该问题的示例代码,以使您从问题中获得的结果更加清晰。 K均值聚类和随机初始化没有明确告诉我们true_labels的值是什么,但我猜测它是一维类别标签数组,因此我将纯粹从您想要理解这些的角度回答事情:

  1. np.asarray()在做什么
  2. np.squeeze()在做什么
  3. 将它们放在一起会发生什么情况。

首先,np.asarray()的作用是将可接受的输入(例如列表或元组)转换为numpy数组。示例:

# List to Array
>> list = [1, 2, 3, 4, 5, 6]
>> print(np.asarray(list))
Output: [1 2 3 4 5 6]
# Produces an array of shape (6,)

# Tuple to Array
>> tuple = ([1, 2, 3], [4, 5, 6])
>> print(np.asarray(tuple))
Output: [[1 2 3]
         [4 5 6]]
# This produces an array of shape (2, 3)

现在,我们继续进行np.squeeze()的操作。如果您查看documentation,它说明该函数的描述是:

  

从数组形状中删除一维条目。

这意味着如果有任何多余的尺寸,则将从输出中将其省略。示例:

>> x = np.array([[[0], [1], [2]]])
>> print(x)
Output: [[[0]
          [1]
          [2]]]

>> print(x.shape)
Output: (1, 3, 1)

>> print(np.squeeze(x))
Output: [0 1 2]

>> print(np.squeeze(x).shape)
Output: (3,)


现在牢记上面的示例,让我们重新访问原始表达式ground_truth = np.squeeze(np.asarray(true_labels))

  1. 让我们将变量true_labels设为对应于类别的数字列表。
  2. true_labels被传递到np.asarray中。返回一个numpy一维数组。
  3. 此numpy数组传递到np.squeeze中,如果存在冗余维(例如,从形状(6,1)到形状(6,)),它将删除冗余尺寸。
  4. 将压缩的numpy数组分配为变量ground_truth

我希望这可以为您澄清该行中发生的事情。