Numpy array和Pytorch tensor的区别

1.Numpy array和Pytorch tensor的区别

笔记来源:

1.Comparison between Pytorch Tensor and Numpy Array

2.numpy.array

4.Tensors for Neural Networks, Clearly Explained!!!

5.What is a Tensor in Machine Learning?

1.1 Numpy Array

Numpy array can only hold elements of a single data type.

Create NumPy ndarray (1D array)

python 复制代码
import numpy as np
arr_1D = np.array([1,2,3])
print(arr_1D)

Create NumPy ndarray (2D array)

python 复制代码
import numpy as np
arr_2D = np.array([[1,2,3],[1,2,3],[1,2,3]])
print(arr_2D)

Create NumPy ndarray (3D array)

python 复制代码
import numpy as np
arr_3D = np.array([[[1,2,3],[1,2,3],[1,2,3],],[[1,2,3],[1,2,3],[1,2,3],],[[1,2,3],[1,2,3],[1,2,3]]])
print(arr_3D)

1.2 Pytorch Tensor

A torch.Tensor is a multi-dimensional matrix containing elements of a single data type.

Pytorch tensors are similar to numpy arrays, but can also be operated on CUDA-capable Nvidia GPU.



0-dimensional Tensor

1-dimensional Tensor

2-dimensional Tensor

n-dimensional Tensor

1.3 Difference

1.Numpy arrays are mainly used in typical machine learning algorithms (such as k-means or Decision Tree in scikit-learn) whereas pytorch tensors are mainly used in deep learning which requires heavy matrix computation.

2.The numpy arrays are the core functionality of the numpy package designed to support faster mathematical operations. Unlike python's inbuilt list data structure, they can only hold elements of a single data type. Library like pandas which is used for data preprocessing is built around the numpy array. Pytorch tensors are similar to numpy arrays, but can also be operated on CUDA-capable Nvidia GPU.The biggest difference between a numpy array and a PyTorch Tensor is that a PyTorch Tensor can run on either CPU or GPU.

3.Unlike numpy arrays, while creating pytorch tensor, it also accepts two other arguments called the device_type (whether the computation happens on CPU or GPU) and the requires_grad (which is used to compute the derivatives).

相关推荐
小白开始进步14 小时前
JAKA Zu12 机械臂运动学算法深度解析(含可视化方案)
python·算法·numpy
铁手飞鹰18 小时前
[深度学习]Vision Transformer
人工智能·pytorch·python·深度学习·transformer
weixin_3954489118 小时前
average_weights.py
pytorch·python·深度学习
海天一色y18 小时前
使用 PyTorch RNN 识别手写数字
人工智能·pytorch·rnn
deephub18 小时前
torch.compile 加速原理:kernel 融合与缓冲区复用
人工智能·pytorch·深度学习·神经网络
爱打代码的小林19 小时前
用 PyTorch 实现 CBOW 模型
人工智能·pytorch·python
查无此人byebye20 小时前
深度解析:当前AI视频生成为何普遍“短小精悍”?
人工智能·pytorch·python·深度学习·音视频·transformer
林深现海20 小时前
【刘二大人】PyTorch深度学习实践笔记 —— 第一集:深度学习全景概述(凝练版)
pytorch·笔记·深度学习
zhangfeng113321 小时前
大语言模型llm 量化模型 跑在 边缘设备小显存显卡 GGUF GGML PyTorch (.pth, .bin, SafeTensors)
人工智能·pytorch·深度学习·语言模型
纤纡.21 小时前
深度学习环境搭建:CUDA+PyTorch+TorchVision+Torchaudio 一站式安装教程
人工智能·pytorch·深度学习