在Python数组索引中使用None

2024-05-15 00:33:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用的是针对Theano(http://deeplearning.net/tutorial/lstm.html)的LSTM教程。在lstm.py(http://deeplearning.net/tutorial/code/lstm.py)文件中,我不理解以下行:

c = m_[:, None] * c + (1. - m_)[:, None] * c_

m_[:, None]是什么意思?在本例中,m_是theano向量,而c是矩阵。


Tags: 文件pynonehttpnethtmlcode教程
2条回答

我认为Theano向量的__getitem__方法需要一个元组作为参数!像这样:

class Vect (object):
    def __init__(self,data):
        self.data=list(data)

    def __getitem__(self,key):
        return self.data[key[0]:key[1]+1]

a=Vect('hello')
print a[0,2]

这里print a[0,2]a是普通列表时,将引发异常:

>>> a=list('hello')
>>> a[0,2]
Traceback (most recent call last):
  File "<string>", line 1, in <module>
TypeError: list indices must be integers, not tuple

但是这里的__getitem__方法不同,它接受元组作为参数。

您可以将:符号传递给__getitem__,如下所示,:表示切片

class Vect (object):
    def __init__(self,data):
        self.data=list(data)

    def __getitem__(self,key):
        return self.data[0:key[1]+1]+list(key[0].indices(key[1]))

a=Vect('hello')
print a[:,2]

谈到None,它也可以在用普通Python编制索引时使用:

>>> 'hello'[None:None]
'hello'

这个问题已经在Theano邮件列表中提出并得到了回答,但实际上是关于numpy索引的基础知识。

这是问题和答案 https://groups.google.com/forum/#!topic/theano-users/jq92vNtkYUI

为了完整起见,这里有另一个解释:使用None切片将轴添加到数组中,请参阅相关的numpy文档,因为它在numpy和Theano中的行为相同:

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

注意np.newaxis is 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)

通常这是用来调整形状,以便能够广播到更高的维度。E、 g.在中轴线上平铺7次

b = a[:, np.newaxis] * np.ones((1, 7, 1))

print b.shape  # yields (5, 7, 6), 7 copies of a along the second axis

相关问题 更多 >

    热门问题