Skip to content
Merged
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
65 changes: 49 additions & 16 deletions python/paddle/fluid/input.py
Original file line number Diff line number Diff line change
Expand Up @@ -220,24 +220,57 @@ def embedding(input,
Returns:
Variable: Embedding Tensor or LoDTensor mapped by input. The data type is the same as :attr:`dtype` .

Examples:
Static Examples:
.. code-block:: python

import paddle
import numpy as np
paddle.enable_static()

x = paddle.static.data(name="x", shape = [2, 4], dtype=np.int64)
embedding = paddle.nn.Embedding(10, 3,
weight_attr=paddle.nn.initializer.Constant(value=1.0))
adam = paddle.optimizer.SGD(parameters=[embedding.weight], learning_rate=0.01)
output = embedding(x)
output=paddle.mean(output)

adam.minimize(output)

place = paddle.CPUPlace()
exe = paddle.static.Executor(place)
exe.run(paddle.static.default_startup_program())

x = np.array([[7, 2, 4, 5],[4, 3, 2, 9]], dtype=np.int64)

out, weight = exe.run(paddle.static.default_main_program(), feed={'x':x}, fetch_list=[output, embedding.weight])


Dygraph Examples:
.. code-block:: python

import paddle.fluid as fluid
import numpy as np
data = fluid.data(name='x', shape=[None, 10], dtype='int64')

# example 1
emb_1 = fluid.embedding(input=data, size=[128, 64])

# example 2: load custom or pre-trained word vectors
weight_data = np.random.random(size=(128, 100)) # word vectors with numpy format
w_param_attrs = fluid.ParamAttr(
name="emb_weight",
learning_rate=0.5,
initializer=fluid.initializer.NumpyArrayInitializer(weight_data),
trainable=True)
emb_2 = fluid.embedding(input=data, size=(128, 100), param_attr=w_param_attrs, dtype='float32')
import paddle
import numpy as np

x_data = np.arange(3, 6).reshape((3, 1)).astype(np.int64)
y_data = np.arange(6, 12).reshape((3, 2)).astype(np.float32)

x = paddle.to_tensor(x_data, stop_gradient=False)
y = paddle.to_tensor(y_data, stop_gradient=False)

embedding = paddle.nn.Embedding(10, 3, sparse=True)

w0 = np.full(shape=(10, 3), fill_value=2).astype(np.float32)

embedding.weight.set_value(w0)

adam = paddle.optimizer.Adam(
parameters=[embedding.weight], learning_rate=0.01)
adam.clear_grad()

out = embedding(x)
out.backward()
adam.step()

"""

helper = LayerHelper('embedding', **locals())
Expand Down