Tensorflow 如何将keras模型转换为tpu模型

Tensorflow 如何将keras模型转换为tpu模型,tensorflow,keras,google-cloud-platform,tpu,Tensorflow,Keras,Google Cloud Platform,Tpu,我正试图将谷歌云控制台中的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.ad

我正试图将谷歌云控制台中的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'
使用TensorFlow后端。
回溯(最近一次呼叫最后一次):
文件“cloud_python4.py”,第11行,在
tpu_model=tf.contrib.tpu.keras_to_tpu_model(属性错误:模块'tensorflow.contrib.tpu'没有属性'keras_to_tpu_model'

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

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


例如,使用tensorflow.keras.layers中的
,而不是激活
。等等。

我假设您将TPU工作人员定义如下

导入操作系统
TPU工人='grpc://'+os.environ['COLAB\u TPU地址']
不要将模型转换为TPU,而是建立一个分发策略。这是一种将批次分发到八个TPU的方法,以及如何计算每个TPU的损失

resolver=tf.contrib.cluster\u resolver.TPUClusterResolver(TPU工作者)
tf.contrib.distribute.initialize\u\tpu\u系统(解析器)
策略=tf.contrib.distribute.TPUStrategy(解析器)
使用该策略构建并编译您的模型。这对于回归应该非常有效

与strategy.scope()
模型=顺序()
模型添加(密集型(32,输入尺寸=784))
模型.添加(密度(32))
添加(激活('relu'))
compile(优化器='rmsprop',loss='mse')

不太有效。我确实按照您的建议用tensorflow.keras版本替换了keras模型。但我仍然收到错误消息“AttributeError:module'tensorflow.contrib.tpu'没有属性'keras_to_tpu_model'。它说该属性在tensorflow参考中是实验性的。有没有解决此问题的方法?您是否尝试更新到最新的tensorflow版本?如果您使用的是pip,您可以执行
pip安装--升级tensorflow