PyTorch टेंसर numpy.ndarray जैसा होता है। इन दोनों के बीच अंतर यह है कि टेंसर संख्यात्मक गणना को तेज करने के लिए GPU का उपयोग करता है। हम torch.from_numpy() फ़ंक्शन का उपयोग करके numpy.ndarray को PyTorch टेंसर में बदलते हैं। और टेंसर को .numpy() मेथड का उपयोग करके numpy.ndarray में बदला जाता है।
चरण
आवश्यक लाइब्रेरी इम्पोर्ट करें। यहां, आवश्यक लाइब्रेरी torch और numpy हैं।
एक numpy.ndarray या एक PyTorch टेंसर बनाएं।
torch.from_numpy() फ़ंक्शन का उपयोग करके numpy.ndarray को PyTorch टेंसर में बदलें या .numpy() मेथड का उपयोग करके PyTorch टेंसर को numpy.ndarray में बदलें।
अंत में, परिवर्तित टेंसर या numpy.ndarray को प्रिंट करें।
उदाहरण 1
निम्नलिखित पायथन प्रोग्राम numpy.ndarray को PyTorch टेंसर में बदलता है।
# import the libraries import torch import numpy as np # Create a numpy.ndarray "a" a = np.array([[1,2,3],[2,1,3],[2,3,5],[5,6,4]]) print("a:\n", a) print("Type of a :\n", type(a)) # Convert the numpy.ndarray to tensor t = torch.from_numpy(a) print("t:\n", t) print("Type after conversion:\n", type(t))आउटपुट
जब आप उपरोक्त कोड चलाएंगे, तो यह निम्नलिखित आउटपुट देगा
a: [[1 2 3] [2 1 3] [2 3 5] [5 6 4]] Type of a :t: tensor([[1, 2, 3], [2, 1, 3], [2, 3, 5], [5, 6, 4]], dtype=torch.int32) Type after conversion:
उदाहरण 2
निम्नलिखित पायथन प्रोग्राम PyTorch टेंसर को numpy.ndarray में बदलता है।
# import the libraries import torch import numpy # Create a tensor "t" t = torch.Tensor([[1,2,3],[2,1,3],[2,3,5],[5,6,4]]) print("t:\n", t) print("Type of t :\n", type(t)) # Convert the tensor to numpy.ndarray a = t.numpy() print("a:\n", a) print("Type after conversion:\n", type(a))आउटपुट
जब आप उपरोक्त कोड चलाएंगे, तो यह निम्नलिखित आउटपुट देगा
t: tensor([[1., 2., 3.], [2., 1., 3.], [2., 3., 5.], [5., 6., 4.]]) Type of t :a: [[1. 2. 3.] [2. 1. 3.] [2. 3. 5.] [5. 6. 4.]] Type after conversion: