How to transfer the follow Embedding code in tensorflow to pytorch?
I have an Embedding code in Tensorflow as follow

self.input_u = tf.placeholder(tf.int32, [None, user_length], name="input_u")
with tf.name_scope("user_embedding"):
        self.W1 = tf.Variable(
            tf.random_uniform([user_vocab_size, embedding_size], -1.0, 1.0),
            name="W")
        self.embedded_user = tf.nn.embedding_lookup(self.W1, self.input_u)
        self.embedded_users = tf.expand_dims(self.embedded_user, -1)


And I want to re-write in pytorch, How to do that?

Method 1: Use Embedding layer and freeze the weight to act as lookup table

import numpy as np
import torch
# user_vocab_size = 10
# embedding_size = 5
W1 = torch.FloatTensor(np.random.uniform(-1,1,size=(user_vocab_size,embedding_size)))
embedded_user = torch.nn.Embedding(user_vocab_size,embedding_size, _weight=W1)
embedded_user.weight.requires_grad = False
embedded_users = torch.unsqueeze(embedded_user, -1)

# user_length = 5
# batch_size = 4
#input = torch.LongTensor(np.random.randint(0,user_vocab_size,(batch_size,user_length)))
#embb = embedded_user(input)


You can change the dimensions of embb tensor to your needs using torch.unqueeze


W1 : A tensor of uniform distribution between (-1,1) of size (user_vocab_size,  embedding_size)
embedded_user : Is an embedding layer which uses W1 as embedding vectors


Method 2: Use Embedding functional api

input_u = torch.LongTensor(np.random.randint(0,user_vocab_size,(batch_size,user_length)))
embedded_user = torch.nn.functional.embedding(input_u,W1)
embedded_users = torch.unsqueeze(embedded_user, -1)

