Returns a hashable reference object to this Variable. Warning: Experimental API that could be changed or removed. The primary usecase for this API is to put variables in a set/dictionary. We can't put variables in a set/dictionary as `variable.__hash__()` is no longer available sta
(self)
| 1428 | return self._save_slice_info |
| 1429 | |
| 1430 | def experimental_ref(self): |
| 1431 | # tf.Tensor also has the same experimental_ref() API. If you update the |
| 1432 | # documenation here, please update tf.Tensor.experimental_ref() as well. |
| 1433 | """Returns a hashable reference object to this Variable. |
| 1434 | |
| 1435 | Warning: Experimental API that could be changed or removed. |
| 1436 | |
| 1437 | The primary usecase for this API is to put variables in a set/dictionary. |
| 1438 | We can't put variables in a set/dictionary as `variable.__hash__()` is no |
| 1439 | longer available starting Tensorflow 2.0. |
| 1440 | |
| 1441 | ```python |
| 1442 | import tensorflow as tf |
| 1443 | |
| 1444 | x = tf.Variable(5) |
| 1445 | y = tf.Variable(10) |
| 1446 | z = tf.Variable(10) |
| 1447 | |
| 1448 | # The followings will raise an exception starting 2.0 |
| 1449 | # TypeError: Variable is unhashable if Variable equality is enabled. |
| 1450 | variable_set = {x, y, z} |
| 1451 | variable_dict = {x: 'five', y: 'ten'} |
| 1452 | ``` |
| 1453 | |
| 1454 | Instead, we can use `variable.experimental_ref()`. |
| 1455 | |
| 1456 | ```python |
| 1457 | variable_set = {x.experimental_ref(), |
| 1458 | y.experimental_ref(), |
| 1459 | z.experimental_ref()} |
| 1460 | |
| 1461 | print(x.experimental_ref() in variable_set) |
| 1462 | ==> True |
| 1463 | |
| 1464 | variable_dict = {x.experimental_ref(): 'five', |
| 1465 | y.experimental_ref(): 'ten', |
| 1466 | z.experimental_ref(): 'ten'} |
| 1467 | |
| 1468 | print(variable_dict[y.experimental_ref()]) |
| 1469 | ==> ten |
| 1470 | ``` |
| 1471 | |
| 1472 | Also, the reference object provides `.deref()` function that returns the |
| 1473 | original Variable. |
| 1474 | |
| 1475 | ```python |
| 1476 | x = tf.Variable(5) |
| 1477 | print(x.experimental_ref().deref()) |
| 1478 | ==> <tf.Variable 'Variable:0' shape=() dtype=int32, numpy=5> |
| 1479 | ``` |
| 1480 | """ |
| 1481 | return object_identity.Reference(self) |
| 1482 | |
| 1483 | class SaveSliceInfo(object): |
| 1484 | """Information on how to save this Variable as a slice. |