Skip to content
This repository was archived by the owner on Dec 16, 2022. It is now read-only.

Commit 481c181

Browse files
bryant1410matt-gardner
authored andcommitted
Fix ArrayField.to_tensor not working with a scalar (#2008)
* 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
1 parent be36374 commit 481c181

File tree

2 files changed

+8
-1
lines changed

2 files changed

+8
-1
lines changed

allennlp/data/fields/array_field.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,8 @@ def as_tensor(self, padding_lengths: Dict[str, int]) -> torch.Tensor:
2727
max_shape = [padding_lengths["dimension_{}".format(i)]
2828
for i in range(len(padding_lengths))]
2929

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

3233
# If the tensor has a different shape from the largest tensor, pad dimensions with zeros to
3334
# form the right shaped list of slices for insertion into the final tensor.

allennlp/tests/data/fields/array_field_test.py

+6
Original file line numberDiff line numberDiff line change
@@ -57,3 +57,9 @@ def test_padding_handles_list_fields_with_padding_values(self):
5757
def test_printing_doesnt_crash(self):
5858
array = ArrayField(numpy.ones([2, 3]), padding_value=-1)
5959
print(array)
60+
61+
def test_as_tensor_works_with_scalar(self):
62+
array = ArrayField(numpy.asarray(42))
63+
returned_tensor = array.as_tensor(array.get_padding_lengths())
64+
current_tensor = numpy.asarray(42)
65+
numpy.testing.assert_array_equal(returned_tensor, current_tensor)

0 commit comments

Comments
 (0)