torch.from_numpy#
- torch.from_numpy(ndarray) Tensor#
从
numpy.ndarray创建一个Tensor。返回的 tensor 和
ndarray共享同一块内存。对 tensor 的修改会反映在ndarray中,反之亦然。返回的 tensor 不能调整大小。目前支持的
ndarray的 dtypes 包括:numpy.float64、numpy.float32、numpy.float16、numpy.complex64、numpy.complex128、numpy.int64、numpy.int32、numpy.int16、numpy.int8、numpy.uint8和bool。警告
从只读 NumPy 数组创建的 tensor 写入操作不受支持,并将导致未定义行为。
示例
>>> a = numpy.array([1, 2, 3]) >>> t = torch.from_numpy(a) >>> t tensor([ 1, 2, 3]) >>> t[0] = -1 >>> a array([-1, 2, 3])