# From\_numpy vs as\_tensor

**URL:** <https://discuss.pytorch.org/t/from-numpy-vs-as-tensor/79932>\
**Category:** vision\
**Created:** [May 6, 2020, 5:34am UTC](https://discuss.pytorch.org/t/from-numpy-vs-as-tensor/79932 "2020-05-06T05:34:40Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![cheng](https://discuss.pytorch.org/letter_avatar_proxy/v4/letter/c/ecccb3/32.png) [@cheng](https://discuss.pytorch.org/u/cheng)\
**Post date:** [May 6, 2020, 5:34am UTC](https://discuss.pytorch.org/t/from-numpy-vs-as-tensor/79932/1 "2020-05-06T05:34:40Z")

</div>

According to my understanding, when `a` is ndarray, `torch.from_numpy(a)` is same as `torch.as_tensor(a)`, and they don’t copy the data just share the same memory, so I think they are same speed when applied, but I test that `from_numpy` faster than `as_tensor`. Could someone explaine for me? Thanks a lot first

---

<div class="post-metadata">

**Author:** ![ptrblck](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/ptrblck/32/1823_2.png) [@ptrblck](https://discuss.pytorch.org/u/ptrblck)\
**Post date:** [May 6, 2020, 7:20am UTC](https://discuss.pytorch.org/t/from-numpy-vs-as-tensor/79932/2 "2020-05-06T07:20:42Z")

</div>

Yes, both approaches share the underlying memory.  
`torch.as_tensor` accepts a bit more that `torch.from_numpy`, such as `list` objects, and might thus have a slightly higher overhead for these checks.

---

<div class="post-metadata">

**Author:** ![cheng](https://discuss.pytorch.org/letter_avatar_proxy/v4/letter/c/ecccb3/32.png) [@cheng](https://discuss.pytorch.org/u/cheng)\
**Post date:** [May 6, 2020, 10:50am UTC](https://discuss.pytorch.org/t/from-numpy-vs-as-tensor/79932/3 "2020-05-06T10:50:56Z")

</div>

Thank you for your reply！

---

<div class="post-metadata">

**Author:** ![jumlauft](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/jumlauft/32/48415_2.png) [@jumlauft](https://discuss.pytorch.org/u/jumlauft)\
**Post date:** [April 7, 2022, 6:21pm UTC](https://discuss.pytorch.org/t/from-numpy-vs-as-tensor/79932/4 "2022-04-07T18:21:04Z")

</div>

`as_tensor()` returns a tensor on the default device whereas `from_numpy()` returns a tensor on the cpu:

```auto
torch.set_default_tensor_type(torch.cuda.FloatTensor)
torch.as_tensor(np_array).device
>>> device(type='cuda', index=0)
torch.from_numpy(np_array).device
>>> device(type='cpu')

```
