Restore variables from a dictionary.
| 194 | |
| 195 | |
| 196 | class DictRestore(SessionInit): |
| 197 | """ |
| 198 | Restore variables from a dictionary. |
| 199 | """ |
| 200 | |
| 201 | def __init__(self, variable_dict, ignore_mismatch=False): |
| 202 | """ |
| 203 | Args: |
| 204 | variable_dict (dict): a dict of {name: value} |
| 205 | ignore_mismatch (bool): ignore failures when the value and the |
| 206 | variable does not match in their shapes. |
| 207 | If False, it will throw exception on such errors. |
| 208 | If True, it will only print a warning. |
| 209 | """ |
| 210 | assert isinstance(variable_dict, dict), type(variable_dict) |
| 211 | # use varname (with :0) for consistency |
| 212 | self._prms = {get_op_tensor_name(n)[1]: v for n, v in six.iteritems(variable_dict)} |
| 213 | self._ignore_mismatch = ignore_mismatch |
| 214 | |
| 215 | def _run_init(self, sess): |
| 216 | variables = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES) |
| 217 | variable_names_list = [k.name for k in variables] |
| 218 | |
| 219 | variable_names = set(variable_names_list) |
| 220 | param_names = set(six.iterkeys(self._prms)) |
| 221 | |
| 222 | # intersect has the original ordering of variables |
| 223 | intersect = [v for v in variable_names_list if v in param_names] |
| 224 | |
| 225 | # use opname (without :0) for clarity in logging |
| 226 | logger.info("Variables to restore from dict: {}".format( |
| 227 | ', '.join(get_op_tensor_name(x)[0] for x in intersect))) |
| 228 | |
| 229 | mismatch = MismatchLogger('graph', 'dict') |
| 230 | for k in sorted(variable_names - param_names): |
| 231 | if not is_training_name(k): |
| 232 | mismatch.add(k) |
| 233 | mismatch.log() |
| 234 | mismatch = MismatchLogger('dict', 'graph') |
| 235 | for k in sorted(param_names - variable_names): |
| 236 | mismatch.add(k) |
| 237 | mismatch.log() |
| 238 | |
| 239 | upd = SessionUpdate(sess, [v for v in variables if v.name in intersect], ignore_mismatch=self._ignore_mismatch) |
| 240 | logger.info("Restoring {} variables from dict ...".format(len(intersect))) |
| 241 | upd.update({name: value for name, value in six.iteritems(self._prms) if name in intersect}) |
| 242 | |
| 243 | |
| 244 | class ChainInit(SessionInit): |
no outgoing calls
no test coverage detected
searching dependent graphs…