如何使用TensorFlow Hub加载模型并进行预测?

发布于 2025-01-17 15:14:44 字数 2566 浏览 7 评论 0原文

这应该是一个简单的任务:下载以tensorflow_hub格式保存的模型,使用tensorflow_hub加载,然后使用..

这是我尝试使用的模型(存储在Google Cloud中的simCLR):https://console.cloud.google.com/storage/browser/simclr-checkpoints/simclrv2/pretrained/r50_1x_sk0;tab=objects? pageState=(%22StorageObjectListTable%22:(%22f%22:%22%255B%255D%22))&prefix=&forceOnObjectsSortingFiltering=false

我按照他们的说法下载了 /hub 文件夹,使用

gsutil -m cp -r \
"gs://simclr-checkpoints/simclrv2/pretrained/r50_1x_sk0/hub" \

.

/hub 文件夹包含以下文件:

/saved_model.pb
/tfhub_module.pb
/variables/variables.index
/variables/variables.data-00000-of-00001

到目前为止一切顺利。 现在在 python3、tensorflow2、tensorflow_hub 0.12 中,我运行以下代码:

import numpy as np
import tensorflow as tf
import tensorflow_hub as hub

path_to_hub = '/home/my_name/my_path/simclr/hub'

# Attempt 1
m = tf.keras.models.Sequential([hub.KerasLayer(path_to_hub, input_shape=(224,224,3))])

# Attempt 2

m = tf.keras.models.Sequential(hub.KerasLayer(hubmod))
m.build(input_shape=[None,224,224,3])


# Attempt 3

m = hub.KerasLayer(hub.load(hubmod))

# Toy Data Test

X = np.random.random((1,244,244,3)).astype(np.float32)

y = m.predict(X)

这 3 个加载集线器模型的选项都不起作用,并出现以下错误:

Attempt 1 :

ValueError: Error when checking input: expected keras_layer_2_input to have shape (224, 224, 3) but got array with shape (244, 244, 3)

Attempt 2:

tensorflow.python.framework.errors_impl.UnknownError:  Failed to get convolution algorithm. This is probably because cuDNN failed to initialize, so try looking to see if a warning log message was printed above.
     [[{{node sequential_3/keras_layer_3/StatefulPartitionedCall/base_model/conv2d/Conv2D}}]] [Op:__inference_keras_scratch_graph_46402]

Function call stack:
keras_scratch_graph

Attempt 3:

ValueError: Expected a string, got <tensorflow.python.training.tracking.tracking.AutoTrackable object at 0x7fa71c7a2dd0>

这 3 次尝试都是取自 tensorflow_hub 教程的代码,并在 stackoverflow 的其他答案中重复,但没有一个有效,而且我不知道如何从这些错误消息中继续。

感谢任何帮助,谢谢。

更新1: 如果我尝试使用此 ResNet50 集线器/,也会发生同样的问题 https://storage.cloud.google.com/simclr-gcs/检查点/ResNet50_1x.zip

This should be a simple task: Download a model saved in tensorflow_hub format, load using tensorflow_hub, and use..

This is the model I am trying to use (simCLR stored in Google Cloud): https://console.cloud.google.com/storage/browser/simclr-checkpoints/simclrv2/pretrained/r50_1x_sk0;tab=objects?pageState=(%22StorageObjectListTable%22:(%22f%22:%22%255B%255D%22))&prefix=&forceOnObjectsSortingFiltering=false

I downloaded the /hub folder as they say, using

gsutil -m cp -r \
"gs://simclr-checkpoints/simclrv2/pretrained/r50_1x_sk0/hub" \

.

The /hub folder contains the files:

/saved_model.pb
/tfhub_module.pb
/variables/variables.index
/variables/variables.data-00000-of-00001

So far so good.
Now in python3, tensorflow2, tensorflow_hub 0.12 I run the following code:

import numpy as np
import tensorflow as tf
import tensorflow_hub as hub

path_to_hub = '/home/my_name/my_path/simclr/hub'

# Attempt 1
m = tf.keras.models.Sequential([hub.KerasLayer(path_to_hub, input_shape=(224,224,3))])

# Attempt 2

m = tf.keras.models.Sequential(hub.KerasLayer(hubmod))
m.build(input_shape=[None,224,224,3])


# Attempt 3

m = hub.KerasLayer(hub.load(hubmod))

# Toy Data Test

X = np.random.random((1,244,244,3)).astype(np.float32)

y = m.predict(X)

None of these 3 options to load the hub model work, with the following errors:

Attempt 1 :

ValueError: Error when checking input: expected keras_layer_2_input to have shape (224, 224, 3) but got array with shape (244, 244, 3)

Attempt 2:

tensorflow.python.framework.errors_impl.UnknownError:  Failed to get convolution algorithm. This is probably because cuDNN failed to initialize, so try looking to see if a warning log message was printed above.
     [[{{node sequential_3/keras_layer_3/StatefulPartitionedCall/base_model/conv2d/Conv2D}}]] [Op:__inference_keras_scratch_graph_46402]

Function call stack:
keras_scratch_graph

Attempt 3:

ValueError: Expected a string, got <tensorflow.python.training.tracking.tracking.AutoTrackable object at 0x7fa71c7a2dd0>

These 3 attempts are all code taken from tensorflow_hub tutorials and are repeated in other answers in stackoverflow, but none works, and I don't know how to continue from those error messages.

Appreciate any help, thanks.

Update 1:
Same issues happen if I try with this ResNet50 hub/
https://storage.cloud.google.com/simclr-gcs/checkpoints/ResNet50_1x.zip

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

一身骄傲 2025-01-24 15:14:44

正如@frightera指出的那样,输入形状存在错误。另外,通过允许在选定的GPU上的内存增长来解决“尝试2”的误差。 “尝试3”仍然不起作用,但至少有两种加载和使用保存在 /集线器格式的模型的方法:

import numpy as np
import tensorflow as tf
import tensorflow_hub as hub   

gpus = tf.config.experimental.list_physical_devices('GPU')
tf.config.experimental.set_visible_devices(gpus[0], 'GPU')
tf.config.experimental.set_memory_growth(gpus[0], True)


hubmod = 'https://tfhub.dev/google/imagenet/mobilenet_v2_035_96/feature_vector/5'

# Alternative 1 - Works!

m = tf.keras.models.Sequential([hub.KerasLayer(hubmod, input_shape=(96,96,3))])
print(m.summary())

# Alternative 2 - Works!

m = tf.keras.models.Sequential(hub.KerasLayer(hubmod))
m.build(input_shape=[None, 96,96,3])
print(m.summary())

# Alternative 3 - Doesnt work

#m = hub.KerasLayer(hub.load(hubmod))
#m.build(input_shape=[None, 96,96,3])
#print(m.summary())

# Test

X = np.random.random((1,96,96,3)).astype(np.float32)
y = m.predict(X)

print(y.shape)

As @Frightera pointed out, there was an error with the input shapes. Also the error on "Attempt 2" was solved by allowing for memory growth on the selected GPU. "Attempt 3" still does not work, but at least there are two methods for loading and using a model saved in /hub format:

import numpy as np
import tensorflow as tf
import tensorflow_hub as hub   

gpus = tf.config.experimental.list_physical_devices('GPU')
tf.config.experimental.set_visible_devices(gpus[0], 'GPU')
tf.config.experimental.set_memory_growth(gpus[0], True)


hubmod = 'https://tfhub.dev/google/imagenet/mobilenet_v2_035_96/feature_vector/5'

# Alternative 1 - Works!

m = tf.keras.models.Sequential([hub.KerasLayer(hubmod, input_shape=(96,96,3))])
print(m.summary())

# Alternative 2 - Works!

m = tf.keras.models.Sequential(hub.KerasLayer(hubmod))
m.build(input_shape=[None, 96,96,3])
print(m.summary())

# Alternative 3 - Doesnt work

#m = hub.KerasLayer(hub.load(hubmod))
#m.build(input_shape=[None, 96,96,3])
#print(m.summary())

# Test

X = np.random.random((1,96,96,3)).astype(np.float32)
y = m.predict(X)

print(y.shape)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文