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).

相关推荐
木觞清3 小时前
PyTorch与TensorFlow的对比:哪个框架更适合你的项目?
人工智能·pytorch·tensorflow
鹿鸣悠悠3 小时前
第二月:学习 NumPy、Pandas 和 Matplotlib 是数据分析和科学计算的基础
学习·numpy·pandas
taoqick12 小时前
nn.EmbeddingBag把offsets之间的进行归约,offsets从0开始
pytorch·python·深度学习
Allen-Steven12 小时前
《Stable Diffusion绘画完全指南:从入门到精通的Prompt设计艺术》-配套代码示例
人工智能·pytorch·深度学习·stable diffusion·prompt·checkpoint
赵钰老师15 小时前
【深度学习】遥感影像目标检测:从CNN(Faster-RCNN)到Transformer(DETR)
pytorch·深度学习·目标检测·机器学习·数据分析·cnn·transformer
不打滑的西瓜皮21 小时前
机器学习数理基础:从概率到梯度下降的全面解析
图像处理·人工智能·pytorch·python·深度学习·机器学习
taoqick1 天前
对PosWiseFFN的改进: MoE、PKM、UltraMem
人工智能·pytorch·深度学习
小喵要摸鱼1 天前
【Pytorch 库】自定义数据集相关的类
pytorch·python
懒大王今天不写代码1 天前
为什么Pytorch中实例化模型会直接调用forward方法?
人工智能·pytorch·python