【问题标题】:How to transform keras model to tpu model如何将keras模型转换为tpu模型
【发布时间】:2019-06-28 12:20:25
【问题描述】:

我正在尝试将我在 Google 云控制台中的 Keras 模型转换为 TPU 模型。不幸的是,我收到如下所示的错误。我的最小示例如下:

import keras
from keras.models import Sequential
from keras.layers import Dense, Activation
import tensorflow as tf
import os
model = Sequential()
model.add(Dense(32, input_dim=784))
model.add(Dense(32))
model.add(Activation('relu'))
model.compile(optimizer='rmsprop', loss='mse')
tpu_model = tf.contrib.tpu.keras_to_tpu_model(
    model,
    strategy=tf.contrib.tpu.TPUDistributionStrategy(
         tf.contrib.cluster_resolver.TPUClusterResolver(TPU_WORKER)))

我的输出是:

Using TensorFlow backend.
Traceback (most recent call last):
     File "cloud_python4.py", line 11, in <module>
     tpu_model = tf.contrib.tpu.keras_to_tpu_model(AttributeError: module 'tensorflow.contrib.tpu' has no attribute 'keras_to_tpu_model'

keras_to_tpu_model 方法似乎是实验性的,如 tensorflow 网站上所示。它最近被删除了吗?如果是这样,我该如何继续使用 TPU 来估计我的 Keras 模型?如果 keras_to_tpu_model 方法仍然可用,为什么我不能调用它?

【问题讨论】:

    标签: tensorflow keras google-cloud-platform tpu


    【解决方案1】:

    从tensorflow导入keras。 这是因为tf.contrib.tpu.keras_to_tpu_model( )'需要 tensorflow 版本模型,而不是keras版本。

    例如,请使用from tensorflow.keras.layers import Dense, Activation。等等。

    【讨论】:

    • 没有完全起作用。我确实用TensorFlow.Keras版本替换了Keras模型,如您所建议的那样。但我仍然收到错误消息“属性错误:模块'tensorflow.contrib.tpu'没有属性'keras_to_tpu_model''。它说属性在tensorflow引用中是实验性的。任何想法如何解决这个问题? span>
    • 您是否尝试过更新到最新的TensorFlow版本?如果您正在使用pip,您可以在pip install --upgrade tensorflow span>
    【解决方案2】:

    我假设您将 TPU_WORKER 定义如下

    import os
    TPU_WORKER = ‘grpc://’ + os.environ[‘COLAB_TPU_ADDR’]
    

    与其将模型转换为 TPU,不如制定分发策略。这是将批次分配到八个 TPU 以及如何计算每个 TPU 的损失的方法。

    resolver = tf.contrib.cluster_resolver.TPUClusterResolver(TPU_WORKER)
    tf.contrib.distribute.initialize_tpu_system(resolver)
    strategy = tf.contrib.distribute.TPUStrategy(resolver)
    

    使用策略构建并编译您的模型。这应该非常适合回归。

    with strategy.scope():
      model = Sequential() 
      model.add(Dense(32, input_dim=784))
      model.add(Dense(32))
      model.add(Activation('relu'))
      model.compile(optimizer='rmsprop', loss='mse')
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-08
      相关资源
      最近更新 更多