Google Colab KeyError: 'COLAB_TPU_ADDR'

Google Colab KeyError: 'COLAB_TPU_ADDR'

我正尝试使用 TPU 选项在 Google Colab 上 运行 一个简单的 MNIST 分类器。使用 Keras 创建模型后,我尝试通过以下方式将其转换为 TPU:

import tensorflow as tf
import os

tpu_model = tf.contrib.tpu.keras_to_tpu_model(
    model,
    strategy=tf.contrib.tpu.TPUDistributionStrategy(
        tf.contrib.cluster_resolver.TPUClusterResolver(tpu='grpc://' + os.environ['COLAB_TPU_ADDR'])
    )
)
tpu_model.compile(
    optimizer='rmsprop',
    loss='categorical_crossentropy',
    metrics=['accuracy']
)


print(model.summary())

我得到的错误是:

---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-5-63c528142aab> in <module>()
      5     model,
      6     strategy=tf.contrib.tpu.TPUDistributionStrategy(
----> 7         tf.contrib.cluster_resolver.TPUClusterResolver(tpu='grpc://' + os.environ['COLAB_TPU_ADDR'])
      8     )
      9 )

/usr/lib/python3.6/os.py in __getitem__(self, key)
    667         except KeyError:
    668             # raise KeyError with the original key value
--> 669             raise KeyError(key) from None
    670         return self.decodevalue(value)
    671 

KeyError: 'COLAB_TPU_ADDR'

看来我需要更改 TPU 地址,但一直在谷歌搜索,但尚未找到任何内容。感谢您的帮助,谢谢!

您需要更改后端以使用“编辑”->“笔记本设置”菜单中可用的笔记本设置来包含 TPU。