Fonction PyTorch torch.from_numpy
Manuel de référence Pytorch torch
torch.from_numpyest une fonction de PyTorch utilisée pour créer un tenseur à partir d'un tableau NumPy. Le tenseur créé partage la mémoire avec le tableau NumPy d'origine.
Ceci est très utile dans les scénarios où PyTorch et NumPy sont tous deux nécessaires pour le traitement des données.
Définition de fonction
torch.from_numpy(ndarray)
Parameters:
ndarray(numpy.ndarray) : Le tableau NumPy d'entrée.
Valeur de retour:
torch.Tensor: Renvoie un tenseur qui partage la mémoire avec le tableau NumPy.
Exemples d'utilisation
Exemple 1 : Création d'un tenseur à partir d'un tableau NumPy
Exemple
import torch
import numpy as np
# Créer un tableau NumPy
numpy_array = np.array([[1, 2, 3], [4, 5, 6]])
# Convertir en tenseur PyTorch
tensor = torch.from_numpy(numpy_array)
print("Tableau NumPy :")
print(numpy_array)
print("Tenseur PyTorch :")
print(tensor)
import numpy as np
# Créer un tableau NumPy
numpy_array = np.array([[1, 2, 3], [4, 5, 6]])
# Convertir en tenseur PyTorch
tensor = torch.from_numpy(numpy_array)
print("Tableau NumPy :")
print(numpy_array)
print("Tenseur PyTorch :")
print(tensor)
La sortie est :
NumPy 数组:
[[1 2 3]
[4 5 6]]
PyTorch 张量:
tensor([[1, 2, 3],
[4, 5, 6]])
Exemple 2 : Partage de mémoire
Exemple
import torch
import numpy as np
# Créer un tableau NumPy
numpy_array = np.array([1, 2, 3])
# Convertir en tenseur PyTorch
tensor = torch.from_numpy(numpy_array)
# Modifier le tenseur
tensor[0] = 100
# Le tableau NumPy changera aussi
print("Tableau NumPy :", numpy_array)
print("PyTorch tensor:", tensor)
import numpy as np
# Créer un tableau NumPy
numpy_array = np.array([1, 2, 3])
# Convertir en tenseur PyTorch
tensor = torch.from_numpy(numpy_array)
# Modifier le tenseur
tensor[0] = 100
# Le tableau NumPy changera aussi
print("Tableau NumPy :", numpy_array)
print("PyTorch tensor:", tensor)
La sortie est :
NumPy 数组: [100 2 3] PyTorch 张量: tensor([100, 2, 3])
En raison de la mémoire partagée, modifier l'un affectera l'autre.
Exemple 3 : Conversion de type de données
Exemple
import torch
import numpy as np
# NumPy crée int64 par défaut
numpy_array = np.array([1, 2, 3])
tensor = torch.from_numpy(numpy_array)
print("dtype:", tensor.dtype) # torch.int64
import numpy as np
# NumPy crée int64 par défaut
numpy_array = np.array([1, 2, 3])
tensor = torch.from_numpy(numpy_array)
print("dtype:", tensor.dtype) # torch.int64
Autres extensions