Challenge: Reshaping Tensors
Compito
Swipe to start coding
- Reshape the given tensor (with an initial shape of
3x4
) into a2x6
tensor. - Create a view of the reshaped tensor as a
4x3
tensor. - Use the appropriate method to add a new dimension at the third position (index
2
) of the tensor. - Use
squeeze()
to remove the added dimension.
Soluzione
99
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import torch
tensor = torch.randint(1, 10, (3, 4))
# Reshape the tensor into a 2x6 tensor
reshaped_tensor = tensor.reshape(2, 6)
# Create a view of the reshaped tensor as a 4x3 tensor
view_tensor = reshaped_tensor.view(4, 3)
# Add a new dimension at the third position
unsqueezed_tensor = reshaped_tensor.unsqueeze(2)
# Remove the added dimension
squeezed_tensor = unsqueezed_tensor.squeeze(2)
# Print results
print("Original tensor:\n", tensor)
print("Reshaped tensor:\n", reshaped_tensor)
print("View tensor:\n", view_tensor)
print("Unsqueezed tensor shape:\n", unsqueezed_tensor.shape)
print("Squeezed tensor shape:\n", squeezed_tensor.shape)
Tutto è chiaro?
Grazie per i tuoi commenti!
Sezione 1. Capitolo 10
single
99
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import torch
tensor = torch.randint(1, 10, (3, 4))
# Reshape the tensor into a 2x6 tensor
reshaped_tensor = tensor.___
# Create a view of the reshaped tensor as a 4x3 tensor
view_tensor = reshaped_tensor.___
# Add a new dimension at the third position
unsqueezed_tensor = reshaped_tensor.___
# Remove the added dimension
squeezed_tensor = unsqueezed_tensor.___
# Print results
print("Original tensor:\n", tensor)
print("Reshaped tensor:\n", reshaped_tensor)
print("View tensor:\n", view_tensor)
print("Unsqueezed tensor shape:\n", unsqueezed_tensor.shape)
print("Squeezed tensor shape:\n", squeezed_tensor.shape)
Chieda ad AI
Chieda ad AI
Chieda pure quello che desidera o provi una delle domande suggerite per iniziare la nostra conversazione