0
0
PyTorchml~10 mins

NumPy bridge (from_numpy, numpy) in PyTorch - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to convert a NumPy array to a PyTorch tensor using the correct function.

PyTorch
import numpy as np
import torch
np_array = np.array([1, 2, 3])
tensor = torch.[1](np_array)
Drag options to blanks, or click blank then click option'
Atensor
Bfrom_numpy
Cas_tensor
Dfrom_array
Attempts:
3 left
💡 Hint
Common Mistakes
Using torch.tensor() which copies data instead of sharing memory.
Using a non-existent function like torch.from_array.
2fill in blank
medium

Complete the code to convert a PyTorch tensor back to a NumPy array.

PyTorch
import torch
import numpy as np
tensor = torch.tensor([4, 5, 6])
np_array = tensor.[1]()
Drag options to blanks, or click blank then click option'
Atoarray
Bto_numpy
Casarray
Dnumpy
Attempts:
3 left
💡 Hint
Common Mistakes
Using .to_numpy() which does not exist in PyTorch.
Using .asarray() which is a NumPy function, not a tensor method.
3fill in blank
hard

Fix the error in the code to correctly convert a NumPy array to a PyTorch tensor and modify the tensor without affecting the original array.

PyTorch
import numpy as np
import torch
np_array = np.array([7, 8, 9])
tensor = torch.[1](np_array).clone()
tensor[0] = 100
Drag options to blanks, or click blank then click option'
Aas_tensor
Btensor
Cfrom_numpy
Dfrom_array
Attempts:
3 left
💡 Hint
Common Mistakes
Using torch.tensor() which copies data but does not share memory.
Not cloning the tensor, so changes affect the original NumPy array.
4fill in blank
hard

Fill both blanks to create a NumPy array from a PyTorch tensor and then modify the tensor without changing the NumPy array.

PyTorch
import torch
import numpy as np
tensor = torch.tensor([10, 20, 30])
np_array = tensor.[1]()
tensor = tensor.[2]()
tensor[1] = 200
Drag options to blanks, or click blank then click option'
Anumpy
Bclone
Cdetach
Dcopy
Attempts:
3 left
💡 Hint
Common Mistakes
Using .detach() instead of .clone(), which does not copy data.
Using .copy() which is not a tensor method.
5fill in blank
hard

Fill all three blanks to create a PyTorch tensor from a NumPy array, convert it back to NumPy, and then modify the tensor without affecting the NumPy array.

PyTorch
import numpy as np
import torch
np_array = np.array([1, 3, 5])
tensor = torch.[1](np_array)
np_array2 = tensor.[2]()
tensor = tensor.[3]()
tensor[2] = 999
Drag options to blanks, or click blank then click option'
Afrom_numpy
Bnumpy
Cclone
Dtensor
Attempts:
3 left
💡 Hint
Common Mistakes
Using torch.tensor() instead of from_numpy.
Not cloning the tensor before modifying it.
Using .detach() instead of .clone().