Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I want to extend a tensor in PyTorch in the following way:

Let C be a 3x4 tensor which requires_grad = True. I want to have a new C which is 3x5 tensor and C = [C, ones(3,1)] (the last column is a one-vector, and others are the old C) Moreover, I need requires_grad = True for new C.

What is an efficient way to do this?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
285 views
Welcome To Ask or Share your Answers For Others

1 Answer

You could do something like this -

c = torch.rand((3,4), requires_grad=True)  # a random matrix c of shape 3x4
ones = torch.ones(c.shape[0], 1)  # creating a vector of 1's using shape of c

# merging vector of ones with 'c' along dimension 1 (columns)
c = torch.cat((c, ones), 1)

# c.requires_grad will still return True...

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...