tensorflow 运行时错误:variable_scope module_1/未使用,但相应的name_scope已被占用,如何修复它

jk9hmnmh  于 2022-11-25  发布在  其他
关注(0)|答案(1)|浏览(139)

我得到了这个问题与埃尔莫和tensorflow,我想修复它没有降级。我该怎么办

`**CODE**
import tensorflow_hub as hub
import tensorflow as tf
#Elmo
elmo = hub.Module("https://tfhub.dev/google/elmo/2", trainable=True)

# Provide input tensor and create embeddings
input_tensor = ["my birthday is the best day of the year"]
embeddings_tensor = elmo(input_tensor, signature="default", as_dict=True)["elmo"]
* here i got the problem *
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    embeddings = sess.run(embeddings_tensor)
    print(embeddings.shape)
    print(embeddings) 
`
vfh0ocws

vfh0ocws1#

hub.module()只与TF 1.x兼容,不建议在TF 2.x中使用。我们可以在TF 2.x代码中使用hub.load()来代替它。
您可以通过在TF 2.8(或TF 2.x)中进行以下更改来运行代码而不会出错。

import tensorflow_hub as hub
import tensorflow as tf
#Elmo
elmo = hub.load("https://tfhub.dev/google/elmo/2").signatures["default"]

# Provide input tensor and create embeddings
input_tensor = ["my birthday is the best day of the year"]
embeddings_tensor = elmo(tf.constant(input_tensor))["elmo"]  #, signature="default", as_dict=True)

#with tf.Session() as sess:
   # sess.run(tf.global_variables_initializer())
    #embeddings = sess.run(embeddings_tensor)
print(embeddings_tensor.shape)
print(embeddings_tensor)

输出量:

(1, 9, 1024)
tf.Tensor(
[[[-0.05932237 -0.13262326 -0.12817773 ...  0.05492031  0.55205816
   -0.15840778]
  [ 0.06928141  0.28926378  0.37178952 ... -0.22100006  0.6793189
    1.0836271 ]
  [ 0.02626347  0.16981134 -0.14045191 ... -0.53703904  0.9646159
    0.7538886 ]
  ...
  [-0.09166492  0.19069327 -0.14435166 ... -0.8409722   0.3632321
   -0.41222304]
  [ 0.40042678 -0.02149609  0.38503993 ...  0.49869162  0.07260808
   -0.3582598 ]
  [ 0.10684142  0.23578405 -0.4308424  ...  0.06925966 -0.14734827
    0.13421637]]], shape=(1, 9, 1024), dtype=float32)

或者,可以使用以下代码在您的代码上方运行相同的代码(通过将其转换为TF 1.x),它将成功执行:

%tensorflow_version 1.x

相关问题