Google Colab免费GPU教程

原文链接:Google Colab免费GPU教程

 

什么是Google Colab?

Google Colab是一项免费的云服务,现在它支持免费的GPU!

你可以;

  • 提高您的Python编程语言编码技能。
  • 开发利用流行的库如深学习应用KerasTensorFlowPyTorch,OpenCV的

将Colab与其他免费云服务区分开来的最重要功能是;Colab提供GPU,并且完全免费。

可以在常见问题页面上找到有关该服务的详细信息。

准备使用Google Colab

在Google云端硬盘上创建文件夹

 

由于Colab在您自己的Google云端硬盘上工作,因此我们首先需要指定将要使用的文件夹。我在Google云端硬盘上创建了一个名为“ app ”的文件夹。当然,您可以使用其他名称,也可以选择默认的Colab Notebooks文件夹而不是app文件夹

 

我创建了一个空的“ app”文件夹

创建新的Colab笔记本

通过右键单击>更多>合作来创建一个新笔记本

 

右键单击>更多>合作

通过单击文件名来重命名笔记本。

 

设置免费GPU

更改默认硬件(将CPU更改为GPU,反之亦然)非常简单;只需按照“编辑”>“笔记本设置”或“运行时”>“更改运行时类型”,然后选择“ GPU”作为“硬件加速器”即可

 

使用Google Colab运行基本的Python代码

现在我们可以开始使用Google Colab了

 

我将从Python Numpy Tutorial运行一些基本数据类型代码。

 

它可以按预期工作:)如果您不知道PythonAI最受欢迎的编程语言,我将推荐这个简单而干净的教程。

使用Google Colab运行或导入.py文件

首先运行这些代码,以安装必要的库并执行授权。

 

当您运行上面的代码时,您应该看到如下结果:

 

单击链接,复制验证码并将粘贴到文本框中。

完成授权过程后,您应该看到以下内容:

 

现在,您可以通过以下方式访问Google云端硬盘:

 

安装Keras:

!pip install -q keras

mnist_cnn.py文件上传到您的Google云端硬盘上的app文件夹中。

 

mnist_cnn.py文件

运行下面的代码在MNIST数据集中训练一个简单的卷积网络

<span style="color:rgba(0, 0, 0, 0.8)"><span style="color:#292929">!python3“ / content / drive /我的驱动器/app/mnist_cnn.py”</span></span>

从结果中可以看到,每个时期仅持续11秒

下载Titanic数据集(.csv文件)并显示前5行

如果要将.csv文件url下载到“ app”文件夹,只需运行:

!wget <a data-cke-saved-href="https://raw.githubusercontent.com/vincentarelbundock/Rdatasets/master/csv/datasets/Titanic.csv" href="https://raw.githubusercontent.com/vincentarelbundock/Rdatasets/master/csv/datasets/Titanic.csv" class="ck hq">https://raw.githubusercontent.com/vincentarelbundock/Rdatasets/master/csv/datasets/Titanic.csv</a> -P“ / content / drive /我的云端硬盘/应用”

您可以将.csv文件直接上传到“ app”文件夹,而不是wget方法。

 

读取“ app ”文件夹中的.csv文件,并显示前5行

将熊猫作为pd 
titanic导入= pd.read_csv(“ / content / drive / My Drive / app / Titanic.csv”)
titanic.head(5)
 

将Github存储库克隆到Google Colab

使用Git克隆Github仓库很容易。

第1步:找到Github存储库并获取“ Git”链接

查找任何要使用的Github存储库。

例如:https : //github.com/wxs/keras-mnist-tutorial

克隆或下载>复制链接!

2. Git克隆

只需运行:

!git克隆<a data-cke-saved-href="https://github.com/wxs/keras-mnist-tutorial.git" href="https://github.com/wxs/keras-mnist-tutorial.git" class="ck hq">https://github.com/wxs/keras-mnist-tutorial.git</a>
 

3.在Google云端硬盘中打开文件夹

文件夹当然与Github仓库相同:)

4.打开笔记本

右键单击>打开方式>合作

5.运行

现在,您可以在Google Colab中运行Github存储库。

一些有用的技巧

1.如何安装库?

凯拉斯

!pip install -q keras
导入keras

火炬

从OS
从wheel.pep425tags导入路径import get_abbr_impl,get_impl_ver,get_abi_tag 
platform ='{} {}-{}'。format(get_abbr_impl(),get_impl_ver(),get_abi_tag())</span><span style="color:#292929">如果path.exists('/ opt / bin / nvidia-smi')则加速器='cu80'否则为'cpu'</span><span style="color:#292929">!pip install -q <a data-cke-saved-href="http://download.pytorch.org/whl/%7Baccelerator%7D/torch-0.3.0.post4-%7Bplatform%7D-linux_x86_64.whl" href="http://download.pytorch.org/whl/%7Baccelerator%7D/torch-0.3.0.post4-%7Bplatform%7D-linux_x86_64.whl" class="ck hq">http://download.pytorch.org/whl/{accelerator}/torch-0.3.0.post4-{platform}-linux_x86_64.whl</a> torchvision
导入炬管

或尝试以下方法:

!pip3 install torch torchvision

网络

!apt安装libnvrtc8.0 
!pip安装mxnet-cu80
将mxnet导入为mx

OpenCV的

!apt-get -qq install -y libsm6 libxext6 && pip install -q -U opencv-python
导入cv2

XGBoost

!pip install -q xgboost == 0.4a30
导入xgboost

GraphViz

!apt-get -qq install -y graphviz && pip install -q pydot
导入pydot

7zip阅读器

!apt-get -qq install -y libarchive-dev && pip install -q -U libarchive
导入libarchive

其他图书馆

!pip install!apt-get install安装其他库。

2. GPU是否正常工作?

要查看您当前是否在Colab中使用GPU,可以运行以下代码以进行交叉检查:

将tensorflow导入为tf 
tf.test.gpu_device_name()
 

3.我正在使用哪个GPU?

从tensorflow.python.client导入device_lib 
device_lib.list_local_devices()

目前,Colab仅提供Tesla K80

 

4. RAM呢?

!cat / proc / meminfo
 

5. CPU呢?

猫/ proc / cpuinfo

6.更改工作目录

通常,当您运行以下代码时:

!ls

您可能会看到datalab和驱动器文件夹。

因此,您必须在定义每个文件名之前添加驱动器/应用程序

要解决此问题,您只需更改工作目录即可。(在本教程中,我使用以下简单代码更改为app folder):

导入os 
os.chdir(“驱动器/应用”)

运行上面的代码后,如果再次运行

!ls

您将看到应用程序文件夹的内容,并且不再需要一直添加驱动器/应用程序

7.“ No backend with GPU available“错误解决方案

如果遇到此错误:

无法分配后端
没有可用的GPU后端。您要使用没有加速器的运行时吗?

请稍后再试。现在有很多人不停地尝试使用GPU,而当所有GPU都在使用时,就会出现此消息。

参考

8.如何清除所有单元格的输出

关注工具>>命令面板>>清除所有输出

9.“不应解析apt-key输出(stdout不是终端)”警告

如果遇到此警告:

警告:不应解析apt-key输出(stdout不是终端)

这意味着身份验证已经完成。您只需要挂载Google云端硬盘:

!mkdir -p驱动器
!google-drive-ocamlfuse驱动器

10.如何在Google Colab中使用Tensorboard?

我推荐这个仓库:

https://github.com/mixuala/colab_utils

11.如何重新启动Google Colab?

为了重新启动(或重置)您的虚拟机,只需运行:

!kill -9 -1

12.如何将表单添加到Google Colab?

为了不每次都在代码中更改超参数,您可以简单地将表单添加到Google Colab。

 

例如,我添加了包含learning_rate变量和optimizer字符串的表格。

 

13.如何查看函数参数?

要在TensorFlow,Keras等中查看函数参数,只需在函数名称后添加问号(?)

 

现在您无需单击TensorFlow网站即可查看原始文档。

 

14.如何将大文件从Colab发送到Google云端硬盘?

# Which file to send?
file_name = "REPO.tar"

from googleapiclient.http import MediaFileUpload
from googleapiclient.discovery import build

auth.authenticate_user()
drive_service = build('drive', 'v3')

def save_file_to_drive(name, path):
  file_metadata = {'name': name, 'mimeType': 'application/octet-stream'}
  media = MediaFileUpload(path, mimetype='application/octet-stream', resumable=True)
  created = drive_service.files().create(body=file_metadata, media_body=media, fields='id').execute()
  
  return created

save_file_to_drive(file_name, file_name)

 

15.如何在Google Colab中运行Tensorboard?

如果您想在Google Colab中破坏Tensorboard,请运行以下代码。

# You can change the directory name
LOG_DIR = 'tb_logs'

!wget https://bin.equinox.io/c/4VmDzA7iaHb/ngrok-stable-linux-amd64.zip
!unzip ngrok-stable-linux-amd64.zip

import os
if not os.path.exists(LOG_DIR):
  os.makedirs(LOG_DIR)
  
get_ipython().system_raw(
    'tensorboard --logdir {} --host 0.0.0.0 --port 6006 &'
    .format(LOG_DIR))

get_ipython().system_raw('./ngrok http 6006 &')

!curl -s http://localhost:4040/api/tunnels | python3 -c \
    "import sys, json; print(json.load(sys.stdin)['tunnels'][0]['public_url'])"

 

您可以使用创建的ngrok.io URL跟踪Tensorboard日志。您将在输出末尾找到该URL。

请注意,您的Tensorboard日志将保存到tb_logs目录。当然,您可以更改目录名称。

 

之后,我们可以看到Tensorboard发挥作用!运行以下代码后,您可以通过ngrok URL跟踪Tensorboard日志。

from __future__ import print_function
import keras
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten
from keras.layers import Conv2D, MaxPooling2D
from keras import backend as K
from keras.callbacks import TensorBoard

batch_size = 128
num_classes = 10
epochs = 12

# input image dimensions
img_rows, img_cols = 28, 28

# the data, shuffled and split between train and test sets
(x_train, y_train), (x_test, y_test) = mnist.load_data()

if K.image_data_format() == 'channels_first':
    x_train = x_train.reshape(x_train.shape[0], 1, img_rows, img_cols)
    x_test = x_test.reshape(x_test.shape[0], 1, img_rows, img_cols)
    input_shape = (1, img_rows, img_cols)
else:
    x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1)
    x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1)
    input_shape = (img_rows, img_cols, 1)

x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
x_train /= 255
x_test /= 255
print('x_train shape:', x_train.shape)
print(x_train.shape[0], 'train samples')
print(x_test.shape[0], 'test samples')

# convert class vectors to binary class matrices
y_train = keras.utils.to_categorical(y_train, num_classes)
y_test = keras.utils.to_categorical(y_test, num_classes)

model = Sequential()
model.add(Conv2D(32, kernel_size=(3, 3),
                 activation='relu',
                 input_shape=input_shape))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(num_classes, activation='softmax'))

model.compile(loss=keras.losses.categorical_crossentropy,
              optimizer=keras.optimizers.Adadelta(),
              metrics=['accuracy'])


tbCallBack = TensorBoard(log_dir=LOG_DIR, 
                         histogram_freq=1,
                         write_graph=True,
                         write_grads=True,
                         batch_size=batch_size,
                         write_images=True)

model.fit(x_train, y_train,
          batch_size=batch_size,
          epochs=epochs,
          verbose=1,
          validation_data=(x_test, y_test),
          callbacks=[tbCallBack])
score = model.evaluate(x_test, y_test, verbose=0)
print('Test loss:', score[0])
print('Test accuracy:', score[1])

 

张量板:)

 

结论

我认为Colab将为全球的深度学习和AI研究带来新的活力。

如果您觉得这篇文章有帮助,那么给您掌声并分享以帮助他人找到它对您来说意义重大!并随时在下面发表评论。

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值