Skip to content

Commit

Permalink
Fix ArrayField.to_tensor not working with a scalar (allenai#2008)
Browse files Browse the repository at this point in the history
* Add test to get tensor of a scalar ArrayField

* Fix ArrayField.to_tensor not working with a scalar

* Fix line too long

* Add assert to test
  • Loading branch information
bryant1410 authored and matt-gardner committed Nov 7, 2018
1 parent be36374 commit 481c181
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 1 deletion.
3 changes: 2 additions & 1 deletion allennlp/data/fields/array_field.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,8 @@ def as_tensor(self, padding_lengths: Dict[str, int]) -> torch.Tensor:
max_shape = [padding_lengths["dimension_{}".format(i)]
for i in range(len(padding_lengths))]

return_array = numpy.ones(max_shape, "float32") * self.padding_value
# Convert explicitly to an ndarray just in case it's an scalar (it'd end up not being an ndarray otherwise)
return_array = numpy.asarray(numpy.ones(max_shape, "float32") * self.padding_value)

# If the tensor has a different shape from the largest tensor, pad dimensions with zeros to
# form the right shaped list of slices for insertion into the final tensor.
Expand Down
6 changes: 6 additions & 0 deletions allennlp/tests/data/fields/array_field_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,3 +57,9 @@ def test_padding_handles_list_fields_with_padding_values(self):
def test_printing_doesnt_crash(self):
array = ArrayField(numpy.ones([2, 3]), padding_value=-1)
print(array)

def test_as_tensor_works_with_scalar(self):
array = ArrayField(numpy.asarray(42))
returned_tensor = array.as_tensor(array.get_padding_lengths())
current_tensor = numpy.asarray(42)
numpy.testing.assert_array_equal(returned_tensor, current_tensor)

0 comments on commit 481c181

Please sign in to comment.