提交 22788242 authored 作者: Frédéric Bastien's avatar Frédéric Bastien

Merge pull request #2149 from daemonmaker/issue1477

Added code to calculate new shape when '-1' is provided as a value for a...
......@@ -2312,6 +2312,31 @@ class GpuReshape(tensor.Reshape, GpuOp):
raise ValueError('shape argument to Reshape.perform'
' has incorrect length %i'
', should be %i' % (len(shp), self.ndim), shp)
if shp.prod() != x.size:
# We need to do check here to raise the same error as NumPy.
# We should make pygpu do the same.
ss = 1
nb_m1 = 0
m1_idx = -1
for idx, i in enumerate(shp):
if i == -1:
nb_m1 += 1
m1_idx = idx
else:
ss *= i
if nb_m1 > 1:
raise ValueError("Only one -1 is accepted in the new shape")
elif nb_m1 == 1:
if (x.size % ss) != 0:
raise ValueError("When using -1 in new shape, the computed new shape must be an multiple of the original shape.")
shp_new = numpy.copy(shp)
shp_new[m1_idx] = x.size/ss
shp = shp_new
else:
raise ValueError("total size of new array must be unchanged")
out[0] = x.reshape(tuple(shp))
......
......@@ -10,6 +10,7 @@ import theano.tensor as T
# Skip test if cuda_ndarray is not available.
from nose.plugins.skip import SkipTest
from nose.tools import assert_raises
import theano.sandbox.cuda as cuda_ndarray
if cuda_ndarray.cuda_available == False:
raise SkipTest('Optional package cuda disabled')
......@@ -336,6 +337,25 @@ def test_reshape():
return T.Reshape(2)(v, theano._asarray([2, 3], dtype='int32'))
utt.verify_grad(just_vals, [a_val])
# Test for appropriate handling of -1 indices
x = T.tensor3('x')
reshp_val = numpy.array([[[1, 0], [0, 1]], [[0, 1], [1, 0]]], dtype='float32')
f_reshp = theano.function([x], x.reshape((-1, 1, 1)), mode=mode_with_gpu)
y = f_reshp(reshp_val)
assert y.shape == (8, 1, 1)
dim = T.scalar('dim_val', dtype='int32')
f_reshp=theano.function(
[x, dim],
x.reshape((dim, dim, 1)),
mode=mode_with_gpu
)
try:
f_reshp(reshp_val, 4)
raise('Only one -1 is accepted in the new shape')
except ValueError:
pass
def test_elemwise_empty():
#test with 0 element
......
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论