在 numpy 中,[:,None] 的选择有什么作用? [英] In numpy, what does selection by [:,None] do?

查看:80
本文介绍了在 numpy 中,[:,None] 的选择有什么作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习关于深度学习的 Udacity 课程,我遇到了以下代码:

I'm taking the Udacity course on deep learning and I came across the following code:

def reformat(dataset, labels):
    dataset = dataset.reshape((-1, image_size * image_size)).astype(np.float32)
    # Map 0 to [1.0, 0.0, 0.0 ...], 1 to [0.0, 1.0, 0.0 ...]
    labels = (np.arange(num_labels) == labels[:,None]).astype(np.float32)
    return dataset, labels

labels[:,None] 在这里实际上做了什么?

What does labels[:,None] actually do here?

推荐答案

http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html

numpy.newaxis

numpy.newaxis

newaxis 对象可用于所有切片操作以创建长度为 1 的轴.:const: newaxis 是None"的别名,可以使用None"代替它,结果相同.

The newaxis object can be used in all slicing operations to create an axis of length one. :const: newaxis is an alias for ‘None’, and ‘None’ can be used in place of this with the same result.

http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.expand_dims.html

使用您的部分代码进行演示

Demonstrating with part of your code

In [154]: labels=np.array([1,3,5])

In [155]: labels[:,None]
Out[155]: 
array([[1],
       [3],
       [5]])
 
In [157]: np.arange(8)==labels[:,None]
Out[157]: 
array([[False,  True, False, False, False, False, False, False],
       [False, False, False,  True, False, False, False, False],
       [False, False, False, False, False,  True, False, False]], dtype=bool)

In [158]: (np.arange(8)==labels[:,None]).astype(int)
Out[158]: 
array([[0, 1, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 1, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 1, 0, 0]])

这篇关于在 numpy 中,[:,None] 的选择有什么作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆