हम टेंसर के आकार (या शेप) और टेंसर में एलिमेंट्स की संख्या को टेंसर के मेटाडेटा के रूप में एक्सेस करते हैं। टेंसर के आकार को एक्सेस करने के लिए, हम .size() मेथड का उपयोग करते हैं और टेंसर के शेप को .shape का उपयोग करके एक्सेस किया जाता है।
.size() और .shape दोनों समान परिणाम देते हैं। हम टेंसर में एलिमेंट्स की कुल संख्या खोजने के लिए torch.numel() फ़ंक्शन का उपयोग करते हैं।
चरण
आवश्यक लाइब्रेरी इम्पोर्ट करें। यहां, आवश्यक लाइब्रेरी torch है। सुनिश्चित करें कि आपने torch इंस्टॉल कर लिया है।
एक PyTorch टेंसर परिभाषित करें।
टेंसर का मेटाडेटा खोजें। टेंसर के आकार और शेप को एक्सेस करने के लिए .size() और .shape का उपयोग करें। टेंसर में एलिमेंट्स की संख्या एक्सेस करने के लिए torch.numel() का उपयोग करें।
बेहतर समझ के लिए टेंसर और मेटाडेटा को प्रिंट करें।
उदाहरण 1
# Python Program to access meta-data of a Tensor # import necessary libraries import torch # Create a tensor of size 4x3 T = torch.Tensor([[1,2,3],[2,1,3],[2,3,5],[5,6,4]]) print("T:\n", T) # Find the meta-data of tensor # Find the size of the above tensor "T" size_T = T.size() print("size of tensor T:\n", size_T) # Other method to get size using .shape print("Shape of tensor:\n", T.shape) # Find the number of elements in the tensor "T" num_T = torch.numel(T) print("Number of elements in tensor T:\n", num_T)आउटपुट
जब आप उपरोक्त पायथन 3 कोड चलाएंगे, तो यह निम्नलिखित आउटपुट देगा।
T: tensor([[1., 2., 3.], [2., 1., 3.], [2., 3., 5.], [5., 6., 4.]]) size of tensor T: torch.Size([4, 3]) Shape of tensor: torch.Size([4, 3]) Number of elements in tensor T: 12
उदाहरण 2
# Python Program to access meta-data of a Tensor # import the libraries import torch # Create a tensor of random numbers T = torch.randn(4,3,2) print("T:\n", T) # Find the meta-data of tensor # Find the size of the above tensor "T" size_T = T.size() print("size of tensor T:\n", size_T) # Other method to get size using .shape print("Shape of tensor:\n", T.shape) # Find the number of elements in the tensor "T" num_T = torch.numel(T) print("Number of elements in tensor T:\n", num_T)आउटपुट
जब आप उपरोक्त पायथन 3 कोड चलाएंगे, तो यह निम्नलिखित आउटपुट देगा।
T: tensor([[[-1.1806, 0.5569], [ 2.2237, 0.9709], [ 0.4775, -0.2491]], [[-0.9703, 1.9916], [ 0.1998, -0.6501], [-0.7489, -1.3013]], [[ 1.3191, 2.0049], [-0.1195, 0.1860], [-0.6061, -1.2451]], [[-0.6044, 0.6153], [-2.2473, -0.1531], [ 0.5341, 1.3697]]]) size of tensor T: torch.Size([4, 3, 2]) Shape of tensor: torch.Size([4, 3, 2]) Number of elements in tensor T: 24