Get the cost from the regularizers in ``tf.GraphKeys.REGULARIZATION_LOSSES``. If in replicated mode, will only regularize variables created within the current tower. Args: name (str): the name of the returned tensor Returns: tf.Tensor: a scalar, the total regulariz
(name='regularize_cost')
| 101 | |
| 102 | |
| 103 | def regularize_cost_from_collection(name='regularize_cost'): |
| 104 | """ |
| 105 | Get the cost from the regularizers in ``tf.GraphKeys.REGULARIZATION_LOSSES``. |
| 106 | If in replicated mode, will only regularize variables created within the current tower. |
| 107 | |
| 108 | Args: |
| 109 | name (str): the name of the returned tensor |
| 110 | |
| 111 | Returns: |
| 112 | tf.Tensor: a scalar, the total regularization cost. |
| 113 | """ |
| 114 | ctx = get_current_tower_context() |
| 115 | if not ctx.is_training: |
| 116 | # TODO Currently cannot build the wd_cost correctly at inference, |
| 117 | # because ths vs_name used in inference can be '', therefore the |
| 118 | # variable filter will fail |
| 119 | return tf.constant(0, dtype=tf.float32, name='empty_' + name) |
| 120 | |
| 121 | # NOTE: this collection doesn't always grow with towers. |
| 122 | # It only grows with actual variable creation, but not get_variable call. |
| 123 | if ctx.has_own_variables: # be careful of the first tower (name='') |
| 124 | losses = ctx.get_collection_in_tower(tfv1.GraphKeys.REGULARIZATION_LOSSES) |
| 125 | else: |
| 126 | losses = tfv1.get_collection(tfv1.GraphKeys.REGULARIZATION_LOSSES) |
| 127 | if len(losses) > 0: |
| 128 | logger.info("regularize_cost_from_collection() found {} regularizers " |
| 129 | "in REGULARIZATION_LOSSES collection.".format(len(losses))) |
| 130 | |
| 131 | def maploss(l): |
| 132 | assert l.dtype.is_floating, l |
| 133 | if l.dtype != tf.float32: |
| 134 | l = tf.cast(l, tf.float32) |
| 135 | return l |
| 136 | |
| 137 | losses = [maploss(l) for l in losses] |
| 138 | reg_loss = tf.add_n(losses, name=name) |
| 139 | return reg_loss |
| 140 | else: |
| 141 | return tf.constant(0, dtype=tf.float32, name='empty_' + name) |
| 142 | |
| 143 | |
| 144 | @layer_register(use_scope=None) |
no test coverage detected
searching dependent graphs…