diff --git a/allennlp/data/fields/array_field.py b/allennlp/data/fields/array_field.py index d888d542781..93e677e05cf 100644 --- a/allennlp/data/fields/array_field.py +++ b/allennlp/data/fields/array_field.py @@ -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. diff --git a/allennlp/tests/data/fields/array_field_test.py b/allennlp/tests/data/fields/array_field_test.py index 63abad1e3c0..cad198575bb 100644 --- a/allennlp/tests/data/fields/array_field_test.py +++ b/allennlp/tests/data/fields/array_field_test.py @@ -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)