借助 Colaboratory(简称 Colab),您可在浏览器中编写和执行 Python 代码,并且:
- 无需任何配置
- 免费使用
- GPU 轻松共享
其实是一个运行在云端虚拟机中的notebook。
1、导入库和安装依赖项
1)要导入默认情况下不在Colaboratory中的库,可以使用!pip安装或!apt-get安装。
!pip install -q matplotlib-venn
!apt-get -qq install -y libfluidsynth1
2)升级TensorFlow
TensorFlow是默认可用的,但是您可以切换使用的版本。
# 显示你正在使用版本:
!pip show tensorflow
# 获取最新版本:
!pip install --upgrade tensorflow
# 获取特定版本:
!pip install tensorflow==1.2
3)安装GraphViz & PyDot
# https://pypi.python.org/pypi/pydot
!apt-get -qq install -y graphviz && pip install -q pydot
import pydot
Colab预装了两个TensorFlow版本:2.x版本和1.x版本。
Colab默认使用TensorFlow 2.x 不过你可以切换到1.x。
%tensorflow_version 1.x
import tensorflow
print(tensorflow.__version__)
2、加载和保存外部来源中的数据的方法
pydrive方法:
-
挂载GoogleDrive:
from pydrive.auth import GoogleAuth from pydrive.drive import GoogleDrive from google.colab import auth from oauth2client.client import GoogleCredentials
点击链接进行验证
-
创建并上传文本文件:
uploaded = drive.CreateFile({'title': 'Sample upload.txt'}) uploaded.SetContentString('Sample upload file content') uploaded.Upload() print('Uploaded file with ID {}'.format(uploaded.get('id')))
-
按 ID 加载文件,然后输出此文件的内容。当然你也可以按title加载。
downloaded = drive.CreateFile({'id': uploaded.get('id')}) print('Downloaded content "{}"'.format(downloaded.GetContentString()))
-
获取文件列表
file_list = drive.ListFile({'q': "'root' in parents and trashed=false"}).GetList() for file1 in file_list: print('title: %s, id: %s' % (file1['title'], file1['id']))
-
上传文件到特定文件夹中
for folder in file_list: if folder['title'] == "Colab Notebooks": file2 = drive.CreateFile({'parents': [{'id': folder['id']}], 'title': 'Sample upload.txt'}) file2.Upload()