在 Python 中的数组索引中使用 None [英] Use of None in Array indexing in Python
问题描述
我正在使用 Theano 的 LSTM 教程 (http://deeplearning.net/tutorial/lstm.html).在 lstm.py (http://deeplearning.net/tutorial/code/lstm.py) 文件中,我不明白以下行:
I am using the LSTM tutorial for Theano (http://deeplearning.net/tutorial/lstm.html). In the lstm.py (http://deeplearning.net/tutorial/code/lstm.py) file, I don't understand the following line:
c = m_[:, None] * c + (1. - m_)[:, None] * c_
m_[:, None]
是什么意思?在这种情况下,m_
是 theano 向量,而 c
是一个矩阵.
What does m_[:, None]
mean? In this case m_
is the theano vector while c
is a matrix.
推荐答案
这个问题已经在 Theano 邮件列表中提出和回答,但实际上是关于 numpy 索引的基础知识.
This question has been asked and answered on the Theano mailing list, but is actually about the basics of numpy indexing.
这是问题和答案https://groups.google.com/forum/#!topic/theano-users/jq92vNtkYUI
为了完整起见,这里有另一种解释:使用 None
切片会向数组添加一个轴,请参阅相关的 numpy 文档,因为它在 numpy 和 Theano 中的行为相同:
For completeness, here is another explanation: slicing with None
adds an axis to your array, see the relevant numpy documentation, because it behaves the same in both numpy and Theano:
http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#numpy.newaxis
注意np.newaxis是None
:
import numpy as np
a = np.arange(30).reshape(5, 6)
print a.shape # yields (5, 6)
print a[np.newaxis, :, :].shape # yields (1, 5, 6)
print a[:, np.newaxis, :].shape # yields (5, 1, 6)
print a[:, :, np.newaxis].shape # yields (5, 6, 1)
这通常用于调整形状,以便能够广播到更高的维度.例如.中轴平铺7次可以实现为
Typically this is used to adjust shapes to be able to broadcast to higher dimensions. E.g. tiling 7 times in the middle axis can be achieved as
b = a[:, np.newaxis] * np.ones((1, 7, 1))
print b.shape # yields (5, 7, 6), 7 copies of a along the second axis
这篇关于在 Python 中的数组索引中使用 None的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!