当我使用 Google Colaboratory 时,如何在我的 Google 驱动器中保存图像、权重?

When I use Google Colaboratory, how to save image, weights in my Google Drive?

我使用 Google Colaboratory,然后我想将输出图像保存在我的 Google 驱动器或 SSD、HHD 中,但其目录是“/content”

import os     
print(os.getcwd())
# "/content"

是否可以更改路径(HDD、SSD、googledrive)?

看看example on interfacing with external files。一般的工作流程是将文件输出到云环境,然后下载。

让我们将 "Hello, Colaboratory" example 中的图输出到文件中。我将笔记本复制到我的 Google 驱动器并 运行 以下命令:

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(20)
y = [x_i + np.random.randn(1) for x_i in x]
a, b = np.polyfit(x, y, 1)
f = plt.figure()
_ = plt.plot(x, y, 'o', np.arange(20), a*np.arange(20)+b, '-')

f.savefig( "test.png")

如果我们列出 Google 协作环境中的文件,我们将看到 test.png 其中:

import os
print( os.getcwd() )
print( os.listdir() )
# /content
# ['datalab', '.local', '.config', '.forever', '.cache', '.rnd', 'test.png', '.ipython']

剩下要做的就是使用我在此答案开头链接的示例将其下载到我的本地计算机:

from google.colab import files
files.download( "test.png" )    

最后,如果您确实需要 Google 驱动器而不是本地机器上的文件,您可以使用 the Google Drive API 相应地移动文件。

P.S。如果您不喜欢将文件写入 /content,您可以随时将 create a subdirectoryos.chdir() 写入其中,但请记住,此子目录对于您的云环境仍然是本地的,并且需要您下载文件如上。

为了节省体重,您可以在训练后运行进行以下操作。

saver = tf.train.Saver()
save_path = saver.save(session, "data/dm.ckpt")
print('done saving at',save_path)

检查 ckpt 文件的保存位置。

import os
print( os.getcwd() )
print( os.listdir('data') )

终于下载文件了!

from google.colab import files
files.download( "data/dm.ckpt.meta" ) 

您需要将 google 驱动器装载到您的 Colab 会话。

from google.colab import drive
drive.mount('/content/gdrive')

然后您可以简单地写入 google 驱动器,就像写入本地文件系统一样:

with open('/content/gdrive/My Drive/file.txt', 'w') as f:
  f.write('content')

另一种将文件保存到 Google 我发现 here 驱动器的简单方法是在安装驱动器后使用命令 cp

代码如下:

from google.colab import drive
drive.mount('/content/gdrive')

然后使用这个:

!cp -r <CURRENT FILE PATH> <PATH YOU WANT TO SAVE>

示例:

!cp -r './runs/exp0.h5' /content/drive/MyDrive/Exp1/