**Notes**: **This API is ONLY available in Dygraph mode** Get the Gradient of Current Variable Returns: ndarray or tuple of ndarray: if Variable's type is DenseTensor, return numpy value of the gradient of current Variable, if Variable's type is Sel
(self)
| 2022 | |
| 2023 | @fake_interface_only |
| 2024 | def gradient(self): |
| 2025 | """ |
| 2026 | **Notes**: |
| 2027 | **This API is ONLY available in Dygraph mode** |
| 2028 | |
| 2029 | Get the Gradient of Current Variable |
| 2030 | |
| 2031 | Returns: |
| 2032 | ndarray or tuple of ndarray: if Variable's type is DenseTensor, return numpy value of the gradient of current Variable, if Variable's type is SelectedRows, return tuple of ndarray, first element of tuple is numpy value of the gradient of current Variable, second element of tuple is numpy value of the rows of current Variable. |
| 2033 | |
| 2034 | Examples: |
| 2035 | .. code-block:: pycon |
| 2036 | |
| 2037 | >>> import paddle |
| 2038 | >>> import paddle.base as base |
| 2039 | >>> import numpy as np |
| 2040 | |
| 2041 | >>> # example1: return ndarray |
| 2042 | >>> x = np.ones([2, 2], np.float32) |
| 2043 | >>> with base.dygraph.guard(): |
| 2044 | ... inputs2 = [] |
| 2045 | ... for _ in range(10): |
| 2046 | ... tmp = paddle.to_tensor(x) |
| 2047 | ... tmp.stop_gradient = False |
| 2048 | ... inputs2.append(tmp) |
| 2049 | ... ret2 = paddle.add_n(inputs2) |
| 2050 | ... loss2 = paddle.sum(ret2) |
| 2051 | ... loss2.retain_grads() |
| 2052 | ... loss2.backward() |
| 2053 | ... print(loss2.gradient()) |
| 2054 | |
| 2055 | >>> # example2: return tuple of ndarray |
| 2056 | >>> with base.dygraph.guard(): |
| 2057 | ... embedding = paddle.nn.Embedding( |
| 2058 | ... 20, |
| 2059 | ... 32, |
| 2060 | ... weight_attr="emb.w", |
| 2061 | ... sparse=True, |
| 2062 | ... ) |
| 2063 | ... x_data = np.arange(12).reshape(4, 3).astype('int64') |
| 2064 | ... x_data = x_data.reshape((-1, 3, 1)) |
| 2065 | ... x_tensor = paddle.to_tensor(x_data) |
| 2066 | ... out = embedding(x_tensor) |
| 2067 | ... out.backward() |
| 2068 | ... print(embedding.weight.gradient()) |
| 2069 | |
| 2070 | """ |
| 2071 | pass |
| 2072 | |
| 2073 | @fake_interface_only |
| 2074 | def clear_gradient(self): |
no outgoing calls