今天从github下载了别人的源码,hparams.py其中有一段代码如下,在tf2.0以上已经弃用了,我找了好几种方法都不行,现在分享一下我从别的项目借鉴到的经验
hparams = tf.contrib.training.HParams(...) # tf2.0已失效
在同样的文件夹下新建一个包,我这里就叫tfcompat,与hparams.py同级。

2、新建一个属于tfcompat包的子文件hparam.py,例如

3、然后编写子文件hparam.py,代码太长,附在文章最后。
4、在与tfcompat同级的hparams.py中导入子文件hparam.py即可。
最后hparams.py中代码改为:
from tfcompat.hparam import HParams
# hparams = tf.contrib.training.HParams(...)
hparams = HParams(...)
其中子文件hparam.py的代码为:
# Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Hyperparameter values."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import json
import numbers
import re
import six
## from tensorflow.contrib.training.python.training import hparam_pb2
## from tensorflow.python.framework import ops
## from tensorflow.python.util import compat
## from tensorflow.python.util import deprecation
# Define the regular expression for parsing a single clause of the input
# (delimited by commas). A legal clause looks like:
# <variable name>[<index>]? = <rhs>
# where <rhs> is either a single token or [] enclosed list of tokens.
# For example: "var[1] = a" or "x = [1,2,3]"
PARAM_RE = re.compile(r"""
(?P<name>[a-zA-Z][\w\.]*) # variable name: "var" or "x"
(\[\s*(?P<index>\d+)\s*\])? # (optional) index: "1" or None
\s*=\s*
((?P<val>[^,\[]*) # single value: "a" or None
|
\[(?P<vals>[^\]]*)\]) # list of values: None or "1,2,3"
($|,\s*)""", re.VERBOSE)
def _parse_fail(name, var_type, value, values):
"""Helper function for raising a value error for bad assignment."""
raise ValueError(
'Could not parse hparam \'%s\' of type \'%s\' with value \'%s\' in %s' %
(name, var_type.__name__, value, values))
def _reuse_fail(name, values):
"""Helper function for raising a value error for reuse of name."""
raise ValueError('Multiple assignments to variable \'%s\' in %s' % (name,
values))
def _process_scalar_value(name, parse_fn, var_type, m_dict, values,
results_dictionary):
&#