提交 ccbb4876 authored 作者: Olivier Delalleau's avatar Olivier Delalleau

More explicit error message

Makes it more obvious to users what may be their mistake when they get a TypeError after trying to index a shared variable.
上级 0fe8bcb1
......@@ -7,6 +7,9 @@ import logging
import traceback
import warnings
# Third-party imports
import numpy
# Theano imports
from theano import config
from theano.configparser import (TheanoConfigParser, AddConfigVar, EnumStr,
......@@ -168,6 +171,28 @@ class SharedVariable(Variable):
update = shared(update)
return update
def __getitem__(self, *args):
# __getitem__ is not available for generic SharedVariable objects.
# We raise a TypeError like Python would do if __getitem__ was not
# implemented at all, but with a more explicit error message to help
# Theano users figure out the root of the problem more easily.
value = self.get_value(borrow=True)
if isinstance(value, numpy.ndarray):
# Array probably had an unknown dtype.
msg = ("a Numpy array with dtype: '%s'. This data type is not "
"currently recognized by Theano tensors: please cast "
"your data into a supported numeric type if you need "
"Theano tensor functionalities." % value.dtype)
else:
msg = ('an object of type: %s. Did you forget to cast it into '
'a Numpy array before calling theano.shared()?' %
type(value))
raise TypeError(
"The generic 'SharedVariable' object is not subscriptable. "
"This shared variable contains %s" % msg)
def shared_constructor(ctor):
shared.constructors.append(ctor)
return ctor
......
......@@ -140,6 +140,12 @@ class CudaNdarraySharedVariable(SharedVariable, _operators):
other.type.broadcastable)))
return GpuFromHost()(other)
def __getitem__(self, *args):
# Defined to explicitly use the implementation from `_operators`, since
# the definition in `SharedVariable` is only meant to raise an error.
return _operators.__getitem__(self, *args)
CudaNdarrayType.SharedVariable = CudaNdarraySharedVariable
def cuda_shared_constructor(value, name=None, strict=False,
......
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论