How to reshape matrices using index instead of shape inputs?
Question:
Given an array of shape (8, 3, 4, 4), reshape them into an arbitrary new shape (8, 4, 4, 3) by inputting the new indices compared to the old positions (0, 2, 3, 1).
Answers:
Numpy’s transpose
"reverses or permutes":
>>> mat = np.ones((8, 3, 4, 4))
>>> new_indices = (0, 2, 3, 1)
>>> mat.transpose(new_indices).shape
(8, 4, 4, 3)
Maybe this is what you are looking for:
arr = np.array([[[1, 2], [3, 4], [5, 6]]])
s = arr.shape
new_indexes = (1, 0, 2) # permutation
new_arr = arr.reshape(*[s[index] for index in new_indexes])
print(arr.shape) # (1, 3, 2)
print(new_arr.shape) # (3, 1, 2)
Given an array of shape (8, 3, 4, 4), reshape them into an arbitrary new shape (8, 4, 4, 3) by inputting the new indices compared to the old positions (0, 2, 3, 1).
Numpy’s transpose
"reverses or permutes":
>>> mat = np.ones((8, 3, 4, 4))
>>> new_indices = (0, 2, 3, 1)
>>> mat.transpose(new_indices).shape
(8, 4, 4, 3)
Maybe this is what you are looking for:
arr = np.array([[[1, 2], [3, 4], [5, 6]]])
s = arr.shape
new_indexes = (1, 0, 2) # permutation
new_arr = arr.reshape(*[s[index] for index in new_indexes])
print(arr.shape) # (1, 3, 2)
print(new_arr.shape) # (3, 1, 2)