未验证 提交 b0b827c7 编写于 作者: 张春乔 提交者: GitHub

[xdoctest] reformat example code with google style in No. 299 (#56597)

* Update dlpack.py

* Apply suggestions from code review

* Apply suggestions from code review

* xdoc

* Apply suggestions from code review

* Apply suggestions from code review
上级 9999e849
...@@ -76,45 +76,43 @@ class LBFGS(Optimizer): ...@@ -76,45 +76,43 @@ class LBFGS(Optimizer):
Examples: Examples:
.. code-block:: python .. code-block:: python
import paddle >>> import paddle
import numpy as np >>> import numpy as np
from paddle.incubate.optimizer import LBFGS >>> from paddle.incubate.optimizer import LBFGS
paddle.disable_static() >>> paddle.disable_static()
np.random.seed(0) >>> np.random.seed(0)
np_w = np.random.rand(1).astype(np.float32) >>> np_w = np.random.rand(1).astype(np.float32)
np_x = np.random.rand(1).astype(np.float32) >>> np_x = np.random.rand(1).astype(np.float32)
inputs = [np.random.rand(1).astype(np.float32) for i in range(10)] >>> inputs = [np.random.rand(1).astype(np.float32) for i in range(10)]
# y = 2x >>> # y = 2x
targets = [2 * x for x in inputs] >>> targets = [2 * x for x in inputs]
class Net(paddle.nn.Layer): >>> class Net(paddle.nn.Layer):
def __init__(self): ... def __init__(self):
super().__init__() ... super().__init__()
w = paddle.to_tensor(np_w) ... w = paddle.to_tensor(np_w)
self.w = paddle.create_parameter(shape=w.shape, dtype=w.dtype, default_initializer=paddle.nn.initializer.Assign(w)) ... self.w = paddle.create_parameter(shape=w.shape, dtype=w.dtype, default_initializer=paddle.nn.initializer.Assign(w))
... def forward(self, x):
def forward(self, x): ... return self.w * x
return self.w * x
>>> net = Net()
net = Net() >>> opt = LBFGS(learning_rate=1, max_iter=1, max_eval=None, tolerance_grad=1e-07, tolerance_change=1e-09, history_size=100, line_search_fn='strong_wolfe', parameters=net.parameters())
opt = LBFGS(learning_rate=1, max_iter=1, max_eval=None, tolerance_grad=1e-07, tolerance_change=1e-09, history_size=100, line_search_fn='strong_wolfe', parameters=net.parameters()) >>> def train_step(inputs, targets):
def train_step(inputs, targets): ... def closure():
def closure(): ... outputs = net(inputs)
outputs = net(inputs) ... loss = paddle.nn.functional.mse_loss(outputs, targets)
loss = paddle.nn.functional.mse_loss(outputs, targets) ... print('loss: ', loss.item())
print('loss: ', loss.item()) ... opt.clear_grad()
opt.clear_grad() ... loss.backward()
loss.backward() ... return loss
return loss ... opt.step(closure)
opt.step(closure)
>>> for input, target in zip(inputs, targets):
... input = paddle.to_tensor(input)
for input, target in zip(inputs, targets): ... target = paddle.to_tensor(target)
input = paddle.to_tensor(input) ... train_step(input, target)
target = paddle.to_tensor(target)
train_step(input, target)
""" """
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册