Skip to content

Converting NumPy dtype to Torch dtype when using as_tensor #40568

@sumanthratna

Description

@sumanthratna

🚀 Feature

Let the dtype keyword argument of torch.as_tensor be either a np.dtype or torch.dtype.

Motivation

Suppose I have two numpy arrays with different types and I want to convert one of them to a torch tensor with the type of the other array.

According to https://discuss.pytorch.org/t/converting-a-numpy-dtype-to-torch-dtype/52279/2, there's no convenient way to convert a numpy tensor to a torch tensor.

Pitch

import numpy as np
import torch


# currently raises the following:
# TypeError: as_tensor(): argument 'dtype' must be 
# torch.dtype, not numpy.dtype
mytensor = torch.tensor(48., dtype=np.float32)

Alternatives

Additional context

Similar issue: #541

cc @mruberry

Metadata

Metadata

Assignees

No one assigned

    Labels

    module: numpyRelated to numpy support, and also numpy compatibility of our operatorstriagedThis issue has been looked at a team member, and triaged and prioritized into an appropriate module

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions