<jupyter_start><jupyter_text>Reshaping Pytorch Tensors<jupyter_code>import torch
# tensor with rank two tensor with two axis,
# first axis: length = 3, second axis: length = 4
# elements of axis 1: arrays, elements of axis 2 = numbers
t = torch.tensor([
    [1, 2, 3, 4],
    [4, 4, 6, 8],
    [0, 4, 8, 12]
], dtype=torch.float32)
t.size()
print(t.shape)
len(t.shape) # the number of axis
# product of the tensor size shows the number of elements in the shape
torch.tensor(t.shape).prod() # 12 (scalar components)
# we can also use numel (number of elements)
t.numel()
t.reshape(1, 12)

t.reshape(4, 3)
t.reshape(6, 2)<jupyter_output><empty_output><jupyter_text>We can also change the tensor by squezing and unsqueezing allowing us to expandor shrink a tensor.<jupyter_code># Flatten a tensor: Change it into a lower rank tensor 
# (removing axis except from one-- creating a 1d array)
# Occurs when transitioning from a convolutional layer to a fully connected layer
print(t.reshape(1,12).squeeze())
print(t.reshape(1, 12).squeeze().unsqueeze(dim=0))
def flatten(t):
    t = t.reshape(1, -1) # - 1 tells reshape to figure get the length(tensor)
    t = t.squeeze()
    return t

flatten(t)<jupyter_output><empty_output><jupyter_text>Concatenate tensors Use the `cat()` function, resulting in a tensor having a shape that depends on the shape of the two tensors.<jupyter_code>t1 = torch.tensor([
    [1,2],
    [3,4],
])
t2 = torch.tensor([
    [5, 6],
    [7, 8]
])
# combine the tensors on the row axis (axis-0)
torch.cat((t1, t2), dim=0)
# We can combine their column-axis (axis-1) like this
torch.cat((t1, t2), dim=1)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.12772397094430993, 'fraction_numerical': 0.03450363196125908, 'mean_word_length': 4.455445544554456, 'pattern_counts': {'":': 0, '<': 13, '<?xml version=': 0, '>': 13, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '3', 'dir': 'jupyter-structured-clean-dedup', 'id': '344718', 'license': 'MIT', 'n_tokens_mistral': 632, 'n_tokens_neox': 596, 'n_words': 204, 'path': 'intro-notebooks/reshaping_tensors.ipynb', 'repo_name': 'gitgik/pytorch', 'size': '1652'}