用 Python 使用 Google Colab?岂止是炫酷

阅读本文大概需要 3 分钟。


选自Medium

作者:Towards AI Team

机器之心编译

机器之心编辑部

一篇教你如何使用 Google Colab,更好利用免费资源的文章。

Google Colab 是一个免费的 Jupyter 环境,用户可以用它创建 Jupyter notebook,在浏览器中编写和执行 Python 代码,以及其他基于 Python 的第三方工具和机器学习框架,如 Pandas、PyTorch、Tensorflow、Keras、Monk、OpenCV 等。

Google Colab 的好处在于,不需要任何配置就能直接上手使用,并提供免费的 GPU,你可以和任何人共享实时代码、数学公式、数据可视化结果、数据处理、数值模拟、机器学习模型等各种项目。

本文将介绍如何用 Python 使用 Google Colab,以及一些 Colab 使用技巧。

项目地址:https://github.com/towardsai/tutorials/tree/master/google_colab_tutorial

为什么大家都爱 Colab

Colab 的优点包括:

  • 提供了免费的 Jupyter notebook 环境;

  • 带有预安装的软件包;

  • 完全托管在谷歌云上;

  • 用户无需在服务器或工作站上进行设置;

  • Notebook 会自动保存在用户的 Google Drive 中;

  • 提供基于浏览器的 Jupyter notebook;

  • 完全免费,且提供 GPU 和 TPU(Pro 用户可以使用更多资源,但需要付费);

  • 支持 Python 2 和 Python 3;

  • 提供两种硬件加速器:GPU 和 TPU。


第一步:启动 Google Colab

我们可以使用 Colab 在 Web 浏览器上直接运行 Python 代码,使用指南:https://mktg.best/d7b6u。

启动窗口随之打开,弹窗中提供了多项功能:

用 Python 使用 Google Colab?岂止是炫酷


它提供了创建 notebook 以及从不同来源上传和选择的选项,比如 GitHub、Google Drive 或本地计算机。

从 GitHub 上传 Notebook

我们可以使用项目 URL,或者搜索组织和用户等方法,直接从 GitHub 上传 Python 代码。

使用 URL 的步骤上传项目的步骤如下图所示:

  • 启动 Google Colab

  • 从弹框中选择 GitHub 这一项。


用 Python 使用 Google Colab?岂止是炫酷


输入 GitHub 项目 URL 并搜索以获取代码


用 Python 使用 Google Colab?岂止是炫酷


将完整代码一键上传到 Google Colab notebook


用 Python 使用 Google Colab?岂止是炫酷


同样地,用户可以通过按名称、日期、所有者或者修改日期过滤保存的 notebook,直接从 Google Drive 上传代码。

用 Python 使用 Google Colab?岂止是炫酷


从 Kaggle 上传数据

从 Kaggle 生成 API Token

来自 Kaggle 的数据可以直接上传到 Colab,不过这需要 Kaggle 的 API Token 才能完成数据导入,步骤如下:

  • 打开 Kaggle

  • 转至「我的账户」

  • 向下滚动到「API」部分


用 Python 使用 Google Colab?岂止是炫酷


  • 如果需要,先单击「Expire API Token」以删除先前的 token

  • 点击「Create New API Token」,生成一个新的 token 并下载一个名为「kaggle.json」的 JSON 文件

  • 「kaggle.json」文件包含用户名和密钥,如下所示:


用 Python 使用 Google Colab?岂止是炫酷


从 Kaggle 上传数据的步骤

将「kaggle.json」文件保存在本地计算机上。

安装 Kaggle 软件包:

!pip install -q kaggle

导入包:

from google.colab import files

上传本地文件「kaggle.json」:

files.upload()


用 Python 使用 Google Colab?岂止是炫酷


检查 Colab notebook 是否与 Kaggle 正确连接:

!kaggle datasets list

用 Python 使用 Google Colab?岂止是炫酷


从 Kaggle 下载任意比赛数据:

!kaggle competitions download -c competitive-data-science-predict-future-sales

用 Python 使用 Google Colab?岂止是炫酷


Kaggle 数据将在 Colab 中下载和上传,如下所示:

用 Python 使用 Google Colab?岂止是炫酷


从 Google Drive 中读取文件

Colab 还提供从 Google Drive 读取数据的功能。

导入包

import globimport pandas as pdfrom google.colab import drive

挂载 Google Drive

drive.mount('/gdrive')

这一步要求填写 Google Drive 的授权码:

用 Python 使用 Google Colab?岂止是炫酷


  • 授权码输入框

  • 单击链接并生成授权码

  • 从 Google Drive 读取 CSV 文件


file_path = glob.glob("/gdrive/My Drive/***.csv")for file in file_path:       df = pd.read_csv(file)       print(df)

用 Python 使用 Google Colab?岂止是炫酷


将运行时硬件加速器设置为 GPU

Google Colab 提供免费的 GPU 硬件加速器云服务。在机器学习和深度学习中需要同时处理多个计算,高性能 GPU 的价格很高,但非常重要。

用 Python 使用 Google Colab?岂止是炫酷


GPU 通过并行化提供优秀的性能,可在一次调用中启动数百万个线程。尽管与 CPU 相比,GPU 的 clock speed 较低,且缺少多核管理功能,但 GPU 的表现通常比 CPU 好。

在 Colab 中设置 GPU 硬件加速器

设置步骤如下:

  • 选择 Runtime → Change runtime type

  • 在弹出窗口中选择「GPU」


用 Python 使用 Google Colab?岂止是炫酷


检查 Colab 中 GPU 的详细信息

导入重要的包

import tensorflow as tffrom tensorflow.python.client import device_lib

检查 GPU 加速器

tf.test.gpu_device_name()


用 Python 使用 Google Colab?岂止是炫酷


检查用于 GPU 的硬件

device_lib.list_local_devices()

用 Python 使用 Google Colab?岂止是炫酷


使用 GPU 的代码示例

在未选择运行时 GPU 的情况下检查可用 GPU 的数量,使其设置为「None」。

用 Python 使用 Google Colab?岂止是炫酷


import tensorflow as tfno_of_gpu = len(tf.config.experimental.list_physical_devices('GPU'))print("Total GPUS:", no_of_gpu)

用 Python 使用 Google Colab?岂止是炫酷

硬件加速器为 None,因此 GPU 数量的值为 0。

将运行时硬件加速器设置为 GPU:

用 Python 使用 Google Colab?岂止是炫酷


import tensorflow as tfno_of_gpu =len(tf.config.experimental.list_physical_devices('GPU'))print("Total GPUS:", no_of_gpu)

用 Python 使用 Google Colab?岂止是炫酷

硬件加速器为 GPU,因此 GPU 数量值为 1。

在 GPU 上执行张量乘法:

try:      with tf.device('/device:GPU:1'):            tensor1 = tf.constant([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])            tensor2 = tf.constant([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]])           result = tf.matmul(tensor1, tensor2)            print(result)except RuntimeError as exception:       print(exception)

用 Python 使用 Google Colab?岂止是炫酷

张量乘法结果。

将 GitHub repo 复制到 Google Drive

GitHub repo 代码可以复制和存储到 Google Drive 中,具体步骤如下:

挂载 Google Drive

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

用 Python 使用 Google Colab?岂止是炫酷


进入 Google drive,创建目录「project」。

%cd gdrive/My Drive/mkdir project%cd project/

用 Python 使用 Google Colab?岂止是炫酷


复制 GitHub repo,例如:

!git clone https://github.com/saniyaparveez/youtube_video_type_prediction.git

用 Python 使用 Google Colab?岂止是炫酷


检查复制的项目

!ls


用 Python 使用 Google Colab?岂止是炫酷


Colab 魔法

Colab 提供许多有趣的 trick,包括多个可以执行快速操作的命令,这些命令通常使用 % 作为前缀。

Colab 魔法命令列表

%lsmagic

用 Python 使用 Google Colab?岂止是炫酷


本地目录

%ldir

用 Python 使用 Google Colab?岂止是炫酷


获取 Notebook 历史

%history

CPU 时间

%time

用 Python 使用 Google Colab?岂止是炫酷


系统运行多久?

!uptime

用 Python 使用 Google Colab?岂止是炫酷


展示可用和已用的内存

!free -hprint("-"*100)

用 Python 使用 Google Colab?岂止是炫酷


展示 CPU 产品规格

!lscpuprint("-"*70)

用 Python 使用 Google Colab?岂止是炫酷


列出所有运行虚拟机进程

%%shecho "List all running VM processes."ps -efecho "Done"

用 Python 使用 Google Colab?岂止是炫酷


在 HTML 中嵌入文本

%%html<marquee>Towards AI is a great publication platform</marquee>

设计 HTML 格式

#@title Personal Details#@markdown Information.Name = 'Peter' #@param {type: "string"}Age = 25  #@param {type: "slider", min: 1, max: 100}zip = 1234  #@param {type: "number"}Date = '2020-01-26'  #@param {type: "date"}Gender = "Male"  #@param ['Male', 'Female', 'Other']#@markdown ---print("Submitting the form")print(string_type, slider_value, number, date, pick_me)print("Submitted")

用 Python 使用 Google Colab?岂止是炫酷

在 Google Colab 中生成 HTML 格式。

用 Python 使用 Google Colab?岂止是炫酷

单元格执行输出

绘图

Google Colab 还可用于数据可视化。以下代码和图展示了 Google Colab 对一个以上多项式的绘图,Y = X³+X²+X。

x = np.arange(-10,10)y = np.power(x,3)y1 = np.power(x,3) + np.power(x,2) + xplt.scatter(x,y1,c="red")plt.scatter(x,y)

用 Python 使用 Google Colab?岂止是炫酷


以下代码和图用于生成热图:

import matplotlib.pyplot as pltimport numpy as npimport seaborn as snslength = 10data = 5 + np.random.randn(length, length)data += np.arange(length)data += np.reshape(np.arange(length), (length, 1))sns.heatmap(data)plt.show()

用 Python 使用 Google Colab?岂止是炫酷


Google Colab 中的 TPU

Google Colab 使用 TPU(张量处理单元)进行 Tensorflow 图上的加速。TPU 是谷歌开发的、专为神经网络机器设计的 AI 加速器专用集成电路 (ASIC)。

TPU 具备优秀的 teraflop 配置、浮点运算性能等。每个 TPU 的计算能力达到每秒 180 万亿次浮点运算(180 teraflops),拥有 64 GB 的高带宽内存。

在 Colab 中设置 TPU

在 Google Colab 中设置 TPU 的步骤如下:

运行时菜单 → 更改运行时

用 Python 使用 Google Colab?岂止是炫酷

选择 TPU 硬件加速器

确认在 TPU 硬件加速器上运行

这需要 TensorFlow 包。以下代码和实现可以确认 Colab 是否设置 TPU 加速器:

import tensorflow as tftry:       tpu = tf.distribute.cluster_resolver.TPUClusterResolver()        print('Running on TPU', tpu.cluster_spec().as_dict()['worker'])except ValueError:       print('Exception')

用 Python 使用 Google Colab?岂止是炫酷


如果 TPU 未设置成功,则代码会报错。

结论

Google Colab 是一种 Jupyter notebook 环境,通过执行基于 Python 的代码来构建机器学习或深度学习模型。Google Colab 完全免费(pro 版除外),并提供 GPU 和 TPU 硬件加速器,易于使用和共享。

本文列举了 Google Colab 的使用技巧,希望能够帮助大家更好地利用 Google Colab 资源。

资源

  • Google colab 实现:https://colab.research.google.com/drive/1ymIYzFg4Q7iBjnTut31aBqPHgOpkjHYD?usp=sharing

  • Github repository:https://github.com/towardsai/tutorials/tree/master/google_colab_tutorial


参考文献

[1] Google Colab, https://colab.research.google.com/
[2] Python 2 Deprecation, Google Colab, Google, https://research.google.com/colaboratory/faq.html#python-2-deprecation
[3] Machine Learning Algorithms for Beginners with Code Examples in Python, Pratik Shukla, Roberto Iriondo, Towards AI, https://towardsai.net/p/machine-learning/machine-learning-algorithms-for-beginners-with-python-code-examples-ml-19c6afd60daa
[4] Project Jupyter, https://jupyter.org/
[5] Google Colab, FAQ, https://research.google.com/colaboratory/faq.html


原文链接:https://medium.com/towards-artificial-intelligence/google-colab-101-tutorial-with-python-tips-tricks-and-faq-7689bd4d24b4

推荐阅读

1

Prometheus | 自从上线了 Prometheus 监控告警,真香!

2

马保国一年能挣多少钱?

3

厉害了!GitHub 中文开源项目榜单出炉,揭露了程序员的硬性需求

4

今日头条起诉今日油条,后者还申请了明日油条、饼多多、快手抓饼等商标




崔庆才

静觅博客博主,《Python3网络爬虫开发实战》作者

隐形字

个人公众号:进击的Coder

用 Python 使用 Google Colab?岂止是炫酷
用 Python 使用 Google Colab?岂止是炫酷
用 Python 使用 Google Colab?岂止是炫酷

长按识别二维码关注




好文和朋友一起看~

原文始发于微信公众号(进击的Coder):用 Python 使用 Google Colab?岂止是炫酷

本站文章资源均来源自网络,除非特别声明,否则均不代表站方观点,并仅供查阅,不作为任何参考依据!
如有侵权请及时跟我们联系,本站将及时删除!
如遇版权问题,请查看 本站版权声明
THE END
分享
二维码
海报
用 Python 使用 Google Colab?岂止是炫酷
“ 阅读本文大概需要 3 分钟。 ” 选自Medium 作者:Towards AI Team 机器之心编译 机器之心编辑部 一篇教你如何使用 Google Colab,更好利用免……
<<上一篇
下一篇>>