Google Colab挂载Google Drive并运行程序
Google colab
简介
Google colab在编辑时候和jupyter notebook类似,并且提供免费的GPU以供使用,这对于需要处理大量数据运算的机器项目来说再合适不过了。
新建
new --> more --> colaboratory
代码执行程序 --> 更改运行时类型 --> 选择python版本和加速器
挂载Google Drive
在colab上的操作实际就是在一个分配好的linux系统主机上操作,我们需要手动设置好和程序所中需路径一致的目录结构。最简单并且能够可视化的方法就是怪哉google drive,然后对于文件的上传、新建、删除等工作便可以在google drive中进行。
- 授权google账号
!apt-get install -y -qq software-properties-common python-software-properties module-init-tools
!add-apt-repository -y ppa:alessandro-strada/ppa 2>&1 > /dev/null
!apt-get update -qq 2>&1 > /dev/null
!apt-get -y install -qq google-drive-ocamlfuse fuse
from google.colab import auth
auth.authenticate_user()
from oauth2client.client import GoogleCredentials
creds = GoogleCredentials.get_application_default()
import getpass
!google-drive-ocamlfuse -headless -id={creds.client_id} -secret={creds.client_secret} < /dev/null 2>&1 | grep URL
vcode = getpass.getpass()
!echo {vcode} | google-drive-ocamlfuse -headless -id={creds.client_id} -secret={creds.client_secret}
运行后会先后出现两个链接,分别点击后同意授权,复制verification code至对话框。
授权成功后会看到左侧“文件”中出现“M”
- 挂载drive目录
首先把项目所在文件夹上传至Google Drive,然后将整个drive挂载。
!mkdir -p drive
!google-drive-ocamlfuse -o nonempty drive
执行后可以看到左侧“文件”中出现“drive”目录,这就是你自己的Google Drive了,点开可以发现目录和文件和自己的google drive一致。
- 将项目文件夹设为默认目录
import os
path = "drive/**** "
drive/MachineLearning/GANs/Pokemon_WGANGP
os.chdir(path)
os.listdir(path)
content/drive/后面跟着的就是自己在google drive里的目录。
有时候这条命令会不成功,本人也没细琢磨其中原因…但是可以通过进入目标目录的方式替代。
%cd drive/****
!ls
运行程序
- 安装需要的第三方包
colab默认装好了tensorboard,但是要用到其他不存在的包时还是需要自己安装。直接使用pip的方式就可以。 - 运行程序
到现在为止,工作目录已经安排好,所需第三方包也安装好,可以执行我们的程序了。 - 程序新产生的文件可以在google drive中查看