EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 360+ Courses All in One Bundle
  • Login

PyTorch Transpose

Home » Data Science » Data Science Tutorials » Machine Learning Tutorial » PyTorch Transpose

PyTorch Transpose

Introduction to PyTorch Transpose

PyTorch Transpose is a tensor version where the output is the transpose format of the input. The dimensions are swapped so that we get the output of our requirement. The output shares its storage with input data and hence when we change the content of input, it affects the output as well. We can use the PyTorch T operation to do transpose a matrix in PyTorch. A new tensor is formed with a different shape but with the same data.

Overview of PyTorch Transpose

The main purpose of Transpose is to change row elements to columns and column elements to rows in the output and hence the shape and dimensions of the matrix will be changed by using this module. We can apply transpose in both contiguous and non-contiguous matrices where we get the output as our requirement. Here we get the output either in sequence or not depending on the input. We can use transpose only for two-dimensional tensors and the input values need not be in any particular order. We also have axes parameter that changes the array based on the permutation where the value is list of integers to permute the array.

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

Creating PyTorch Transpose

The equation is like this:

torch.transpose(input_value, dimension1, dimension2) where the output is a tensor.

Let us see an example where the code is transformed to transpose values.

The first step is to import PyTorch.

Import torch

We can check the versions of pytorch as well.

print(torch.__version__)

Next step is to create a matrix in PyTorch.

Py_matrix = torch.tensor([[9,5],
[12,4]])

We can print the same to check whether the values are entered in the right format.

Print(py_matrix)

Now we will do the transpose operation on the above matrix.

Py_matrix_transpose = py_matrix.t()

If we print the transposed value, we can see the output where the values have been interchanged.

Popular Course in this category
Sale
Machine Learning Training (20 Courses, 29+ Projects)19 Online Courses | 29 Hands-on Projects | 178+ Hours | Verifiable Certificate of Completion | Lifetime Access
4.7 (14,326 ratings)
Course Price

View Course

Related Courses
Deep Learning Training (17 Courses, 24+ Projects)Artificial Intelligence Training (5 Courses, 2 Project)

Print(py_matrix_transpose)

While doing the transpose, we assigned the transposed matrix to a new variable and hence the original matrix is left untouched. This helps us to make any transformations to the original matrix by assigning it to a new variable where we can determine the shape and dimensions of the matrix. We can also do transpose NumPy arrays where any dimensional values can be used in the matrix. This is an easier way to do transpose as the dimensions can be changed based on our requirements.

Parameters:

We have only three parameters for PyTorch transpose. They are input, dimension, and dimension2.

  • Input value ( this is a tensor) – the input tensor which is mostly a matrix where we give all the values of the matrix.
  • dimension0 (integer value) – the first dimension in the matrix that is to be transposed
  • dimension1 (integer value) – the second dimension in the matrix that is to be transposed

Let us see an example based on this parametric proposition.

a = torch.randn(4, 1)
a
tensor([[ 1.00, 0.7921, -0.4120],
[0.7300, -0.8219, 0.3819]])
torch.transpose(a, 0, 1)
tensor([[ 1.00, 0.7300],
[0.7921, -0.8219],
[ -0.4120, 0.3819]])

Now, if our requirement is to use weight over the linear layer or embedded layer in the transpose, then the function changes the way and the code is also different.

b = F.linear(a, emb_mod.weight.t())

It should be noted that we should not assign the parameter of a module in the optimization loop in the code and hence the code will work fine by assigning it to a second variable. And we need not call networks over this code which will throw an error saying the nn. the parameter will not work here.

PyTorch Transpose Examples

Since we have seen simple examples of PyTorch transpose, let us see some machine learning examples where transpose is used to obtain required results.

def machine(self, a_x, a_y, b_xy, opt={}):
p = Variable(torch.zeros(a_y.size(0), a_y.size(1), self.args['output']).type_as(a_y.data))
for k in range(a_y.size(1)):
if torch.nonzero(e_xy[:, y, :].data).size():
for j, e in enumerate(self.args['h_label']):
integer = (e == b_xy[:,y,:]).type_as(self.learn_args[0][j])
parameter_matrices = self.learn_args[0][j][None, ...].expand(a_y.size(0), self.learn_args[0][j].size(0),
self.learn_args[0][j].size(1))
p_y = torch.transpose(torch.bmm(torch.transpose(parameter_mat, 1, 2),
torch.transpose(torch.unsqueeze(a_y[:, y, :], 1),
1, 2)), 1, 2)
p_y = torch.squeeze(p_y)
p[:,y,:] = ind.expand_as(p_y)*p_y
return p
Here it returns the message where the functions and transpose is applied.
We will see another example of modules where transpose is used.
def max_min_pools(in, size, stride=3):
'''
in: [A, B, C] out: [A, B // stride, C] '''
in = in.transpose(1, 2)
if padding == none:
leftside = (size - 3) // 5
rightside = (size - 3) - leftside
padding = (leftside, rightside)
else:
padding = (0, 0)
in = F.padding(in, padding)
out = F. max_min_pools (in, size, stride)
out = out.transpose(1, 2)
return out
def principal(inputs, outputs, first, second, kernel_multiplier=3.0, kernel_numbers=7, fixed_sigma=None):
first = first.cpu()
first = first.view(22,3)
first = torch.zeros(22, 41).scatter_(3, first.data, 3)
first = Variable(first).cuda()
second = second.cpu()
second = second.view(22, 3)
second = torch.zeros(22, 41).scatter_(1, second.data, 3)
second = Variable(second).cuda()
batch = int(inputs.size()[0])
kernels = guassian_kernel(inputs, outputs,
kernel_multiplier=kernel_multiplier, kernel_numbers =kernel_numbers, fixed_sigma=fixed_sigma)
loss_value = 0
AA = kernels[:batch, :batch] BB = kernels[batch:, batch:] AB = kernels[:batch, batch:] Loss_value += torch.mean(torch.minimum(first, torch.transpose(first, 2, 3)) * AA +
torch.minimum(second, torch.transpose(second, 2, 3)) * BB -
2 * torch.minimum(first, torch.transpose(second, 2, 3)) * AB)
return loss_value
def rainy_example(self, input_values):
"""
:parameter input_values: sequences
:return: output_values
"""
batch = input_values.size()[0] if self.time_dimension == 2:
input_values = input_values.transpose(1, 2).contiguous()
input_values = input_values.view(-1, self.input_values.size)
output = self.linear(input_values).view(batch -1, self.output_values.size)
if self.time_dimension == 2:
output = output.contiguous().transpose(1, 2)
return output
def p_case():
torch.manual_seed(12)
new_shape = manifold_shapes[geoopt.manifolds.Polytope] examples = torch.randn(*new_shape, dtype=torch.float64).abs()
evaluate = torch.randn(*new_shape, dtype=torch.float64)
max_iter = 50
epsilon = 1e-6
tolerance = 1e-2
iteration = 0
c = 1.0 / (torch.sum(examples, dimensions=-2, keepdimensions=True) + epsilon)
r = 1.0 / (torch.matmul(examples, c.transpose(-1, -2)) + epsilon)
while iteration < max_iterationa:
iteration += 1
cinvoice = torch.matmult(r.transpose(-1, -2), examples)
if torch.max(torch.abs(cinvoice * c - 1)) <= tolerance:
break

Conclusion

An easy way to change the axes of the matrices is by using transpose in the matrix with the help of PyTorch so that we will get the output in tensors format. Also, NumPy arrays is another option to get the axes in the required format by changing the dimensions where transpose can be used. Swapping axes is another option to change the axes and dimensions.

Recommended Articles

This is a guide to PyTorch Transpose. Here we discuss the Introduction, Overviews, How to create, examples with code implementation respectively. You may also have a look at the following articles to learn more –

  1. Mxnet vs Pytorch
  2. What is PyTorch?
  3. PyTorch vs Keras
  4. PyTorch Versions

All in One Data Science Bundle (360+ Courses, 50+ projects)

360+ Online Courses

50+ projects

1500+ Hours

Verifiable Certificates

Lifetime Access

Learn More

0 Shares
Share
Tweet
Share
Primary Sidebar
Machine Learning Tutorial
  • PyTorch
    • PyTorch Tensors
    • What is PyTorch?
    • PyTorch MSELoss()
    • PyTorch NLLLOSS
    • PyTorch MaxPool2d
    • PyTorch Pretrained Models
    • PyTorch Squeeze
    • PyTorch Reinforcement Learning
    • PyTorch zero_grad
    • PyTorch norm
    • PyTorch VAE
    • PyTorch Early Stopping
    • PyTorch requires_grad
    • PyTorch MNIST
    • PyTorch Conv2d
    • Dataset Pytorch
    • PyTorch tanh
    • PyTorch bmm
    • PyTorch profiler
    • PyTorch unsqueeze
    • PyTorch adam
    • PyTorch backward
    • PyTorch concatenate
    • PyTorch Embedding
    • PyTorch Tensor to NumPy
    • PyTorch Normalize
    • PyTorch ReLU
    • PyTorch Autograd
    • PyTorch Transpose
    • PyTorch Object Detection
    • PyTorch Autoencoder
    • PyTorch Loss
    • PyTorch repeat
    • PyTorch gather
    • PyTorch sequential
    • PyTorch U-NET
    • PyTorch Sigmoid
    • PyTorch Neural Network
    • PyTorch Quantization
    • PyTorch Ignite
    • PyTorch Versions
    • PyTorch TensorBoard
    • PyTorch Dropout
    • PyTorch Model
    • PyTorch optimizer
    • PyTorch ResNet
    • PyTorch CNN
    • PyTorch Detach
    • Single Layer Perceptron
    • PyTorch vs Keras
    • torch.nn Module
  • Basic
    • Introduction To Machine Learning
    • What is Machine Learning?
    • Uses of Machine Learning
    • Applications of Machine Learning
    • Naive Bayes in Machine Learning
    • Dataset Labelling
    • DataSet Example
    • Dataset ZFS
    • Careers in Machine Learning
    • What is Machine Cycle?
    • Machine Learning Feature
    • Machine Learning Programming Languages
    • What is Kernel in Machine Learning
    • Machine Learning Tools
    • Machine Learning Models
    • Machine Learning Platform
    • Machine Learning Libraries
    • Machine Learning Life Cycle
    • Machine Learning System
    • Machine Learning Datasets
    • Machine Learning Certifications
    • Machine Learning Python vs R
    • Optimization for Machine Learning
    • Types of Machine Learning
    • Machine Learning Methods
    • Machine Learning Software
    • Machine Learning Techniques
    • Machine Learning Feature Selection
    • Ensemble Methods in Machine Learning
    • Support Vector Machine in Machine Learning
    • Decision Making Techniques
    • Restricted Boltzmann Machine
    • Regularization Machine Learning
    • What is Regression?
    • What is Linear Regression?
    • Dataset for Linear Regression
    • Decision tree limitations
    • What is Decision Tree?
    • What is Random Forest
  • Algorithms
    • Machine Learning Algorithms
    • Apriori Algorithm in Machine Learning
    • Types of Machine Learning Algorithms
    • Bayes Theorem
    • AdaBoost Algorithm
    • Classification Algorithms
    • Clustering Algorithm
    • Gradient Boosting Algorithm
    • Mean Shift Algorithm
    • Hierarchical Clustering Algorithm
    • Hierarchical Clustering Agglomerative
    • What is a Greedy Algorithm?
    • What is Genetic Algorithm?
    • Random Forest Algorithm
    • Nearest Neighbors Algorithm
    • Weak Law of Large Numbers
    • Ray Tracing Algorithm
    • SVM Algorithm
    • Naive Bayes Algorithm
    • Neural Network Algorithms
    • Boosting Algorithm
    • XGBoost Algorithm
    • Pattern Searching
    • Loss Functions in Machine Learning
    • Decision Tree in Machine Learning
    • Hyperparameter Machine Learning
    • Unsupervised Machine Learning
    • K- Means Clustering Algorithm
    • KNN Algorithm
    • Monty Hall Problem
  • Supervised
    • What is Supervised Learning
    • Supervised Machine Learning
    • Supervised Machine Learning Algorithms
    • Perceptron Learning Algorithm
    • Simple Linear Regression
    • Polynomial Regression
    • Multivariate Regression
    • Regression in Machine Learning
    • Hierarchical Clustering Analysis
    • Linear Regression Analysis
    • Support Vector Regression
    • Multiple Linear Regression
    • Linear Algebra in Machine Learning
    • Statistics for Machine Learning
    • What is Regression Analysis?
    • Clustering Methods
    • Backward Elimination
    • Ensemble Techniques
    • Bagging and Boosting
    • Linear Regression Modeling
    • What is Reinforcement Learning
  • Classification
    • Kernel Methods in Machine Learning
    • Clustering in Machine Learning
    • Machine Learning Architecture
    • Automation Anywhere Architecture
    • Machine Learning C++ Library
    • Machine Learning Frameworks
    • Data Preprocessing in Machine Learning
    • Data Science Machine Learning
    • Classification of Neural Network
    • Neural Network Machine Learning
    • What is Convolutional Neural Network?
    • Single Layer Neural Network
    • Kernel Methods
    • Forward and Backward Chaining
    • Forward Chaining
    • Backward Chaining
  • Deep Learning
    • What Is Deep learning
    • Overviews Deep Learning
    • Application of Deep Learning
    • Careers in Deep Learnings
    • Deep Learning Frameworks
    • Deep Learning Model
    • Deep Learning Algorithms
    • Deep Learning Technique
    • Deep Learning Networks
    • Deep Learning Libraries
    • Deep Learning Toolbox
    • Types of Neural Networks
    • Convolutional Neural Networks
    • Create Decision Tree
    • Deep Learning for NLP
    • Caffe Deep Learning
    • Deep Learning with TensorFlow
  • RPA
    • What is RPA
    • What is Robotics?
    • Benefits of RPA
    • RPA Applications
    • Types of Robots
    • RPA Tools
    • Line Follower Robot
    • What is Blue Prism?
    • RPA vs BPM
  • UiPath
    • What is UiPath
    • UiPath Action Center
    • UiPath?Orchestrator
    • UiPath web automation
    • UiPath Orchestrator API
    • UiPath Delay
    • UiPath Careers
    • UiPath Insights
    • UiPath Split String
    • UiPath Installation
    • UiPath Filter Data Table
    • UiPath Test Suite
    • UiPath Competitors
    • UiPath Architecture
    • UiPath version
    • Uipath Reframework
    • UiPath Studio
  • Interview Questions
    • Deep Learning Interview Questions And Answer
    • Machine Learning Cheat Sheet

Related Courses

Machine Learning Training

Deep Learning Training

Artificial Intelligence Training

Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Database Management
  • Machine Learning
  • All Tutorials
Certification Courses
  • All Courses
  • Data Science Course - All in One Bundle
  • Machine Learning Course
  • Hadoop Certification Training
  • Cloud Computing Training Course
  • R Programming Course
  • AWS Training Course
  • SAS Training Course

© 2022 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Data Science Course

Hadoop, Data Science, Statistics & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA
Free Data Science Course

Hadoop, Data Science, Statistics & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more

Special Offer - Machine Learning Training Learn More