百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 编程字典 > 正文

居然有免费的GPU可以跑深度学习代码

toyiye 2024-06-21 12:07 11 浏览 0 评论

后台回复【入门资料】

送你十本Python电子书

作者:凌逆战

原文:https://www.cnblogs.com/LXP-Never/p/11614053.html

从事深度学习的研究者都知道,深度学习代码需要设计海量的数据,需要很大很大很大(重要的事情说三遍)的计算量,以至于CPU算不过来,需要通过GPU帮忙,但这必不意味着CPU的性能没GPU强,CPU是那种综合性的,GPU是专门用来做图像渲染的,这我们大家都知道,做图像矩阵的计算GPU更加在行,应该我们一般把深度学习程序让GPU来计算,事实也证明GPU的计算速度比CPU块,但是(但是前面的话都是废话)我们穷,买不起呀,一块1080Ti现在也要3500左右,2080Ti要9000左右,具体价格还要看显存大小,因此本文给大家带来了福利——Google免费的GPU Colaboratory。

Google Colab简介

Google Colaboratory是谷歌开放的一款研究工具,主要用于机器学习的开发研究,这款工具现在可以免费使用,但是不是永久免费暂时还不确定,Google Colab最大的好处是给广大开发AI者提供免费的GPU使用!GPU型号是Tesla K80,你可以在上面轻松地跑例如:Keras、Tensorflow、Pytorch等框架。

Colabortory是一个jupyter notebook环境,它支持python2和python3,还包括TPU和GPU加速,该软件与Google云盘硬盘集成,用户可以轻松共享项目或将其他共享项目复制到自己的帐户中。

Colaboratory使用步骤

1、登录谷歌云盘

https://drive.google.com/drive/my-drive(没有账号的可以注册一个)

(1)、右键新建文件夹,作为我们的项目文件夹。

2、创建Colab文件

右键在更多里面选择google Colaboratry(如果没有Colaboratory需要在关联更多应用里面关联Colaboratory)

3、开始使用

这时候会直接跳转到Colaboratory界面,这个界面很像Jupyter Notebook,Jupyter的命令在Colaboratory一样适用,值得一提的是,Colab不仅可以运行Python代码,只要在命令前面加一个" !",这条命令就变成了linux命令,比如我们可以" ! ls"查看文件夹文件,还可以!pip安装库。以及运行py程序!python2 temp.py

可以写一段代码进行测试

更改工作目录,在Colab中cd命令是无效的,切换工作目录使用chdir函数

  1. !pwd # 用 pwd 命令显示工作路径

  2. # /content

  3. !ls # 查看的是 content 文件夹下有哪些文件

  4. # sample_data

  5. !ls "drive/My Drive"

  6. # TensorFlow (这就是我们之前创建的那个文件夹)


  7. # 更改工作目录

  8. import os

  9. os.chdir("/content/drive/My Drive/TensorFlow")

  10. os.getcwd

  11. # '/content/drive/My Drive/TensorFlow'

重新启动Colab命令:!kill -9 -1

(3)、选择配置环境

我们大家肯定会疑虑,上述方法跑的那段程序是不是用GPU跑的呢?不是,想要用GPU跑程序我们还需要配置环境,

点击工具栏“修改”,选择笔记本设置

在运行时类型我们可以选择Python 2或Python 3,硬件加速器我们可以选择GPU或者TPU(后面会讲到),或者None什么都不用。

加载数据

从本地加载数据

从本地上传数据

files.upload会返回已上传文件的字典。此字典的键为文件名,值为已上传的数据。

  1. from google.colab import files


  2. uploaded = files.upload

  3. for fn in uploaded.keys:

  4. print('用户上传的文件 "{name}" 有 {length} bytes'.format(

  5. name=fn, length=len(uploaded[fn])))

我们运行该段程序之后,就会让我们选择本地文件,点击上传后,该文件就能被读取了

将文件下载到本地

  1. from google.colab import files


  2. files.download('./example.txt') # 下载文件

从谷歌云盘加载数据

使用授权代码在运行时装载 Google 云端硬盘

  1. from google.colab import drive

  2. drive.mount('/content/gdrive')

在Colab中运行上述代码,会出现一段链接,点击链接,复制链接中的密钥,输入到Colab中就可以成功把Colab与谷歌云盘相连接,连接后进行路径切换,就可以直接读取谷歌云盘数据了。

向Google Colab添加表单

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

点击之后就会出现左右两个框,我们在左框中输入

  1. # @title 字符串


  2. text = 'value' #@param {type:"string"}

  3. dropdown = '1st option' #@param ["1st option", "2nd option", "3rd option"]

  4. text_and_dropdown = 'value' #@param ["选项1", "选项2", "选项3"] {allow-input: true}


  5. print(text)

  6. print(dropdown)

  7. print(text_and_dropdown)

双击右边栏可以隐藏代码

Colab中的GPU

首先我们要让Colab连上GPU,导航栏-->编辑-->笔记本设置-->选择GPU

接下来我们来确认可以使用Tensorflow连接到GPU

  1. import tensorflow as tf


  2. device_name = tf.test.gpu_device_name

  3. if device_name != '/device:GPU:0':

  4. raise SystemError('没有发现GPU device')


  5. print('Found GPU at: {}'.format(device_name))

  6. # Found GPU at: /device:GPU:0

我们可以在Colab上运行以下代码测试GPU和CPU的速度

  1. import tensorflow as tf import timeit


  2. config = tf.ConfigProto

  3. config.gpu_options.allow_growth = True


  4. with tf.device('/cpu:0'):

  5. random_image_cpu = tf.random_normal((100,100,100,3))

  6. net_cpu = tf.layers.conv2d(random_image_cpu, 32,7)

  7. net_cpu = tf.reduce_sum(net_cpu)


  8. with tf.device('/device:GPU:0'):

  9. random_image_gpu = tf.random_normal((100,100,100,3))

  10. net_gpu = tf.layers.conv2d(random_image_gpu, 32,7)

  11. net_gpu = tf.reduce_sum(net_gpu)


  12. sess = tf.Session(config=config) # 确保TF可以检测到GPU

  13. try:

  14. sess.run(tf.global_variables_initializer) except tf.errors.InvalidArgumentError: print( 'nn此错误很可能表示此笔记本未配置为使用GPU。'

  15. '通过命令面板(CMD/CTRL-SHIFT-P)或编辑菜单在笔记本设置中更改此设置.nn') raise


  16. def cpu:

  17. sess.run(net_cpu) def gpu:

  18. sess.run(net_gpu) # 运行一次进行测试

  19. cpu

  20. gpu # 多次运行op

  21. print('将100*100*100*3通过滤波器卷积到32*7*7*3(批处理x高度x宽度x通道)大小的图像'

  22. '计算10次运训时间的总和') print('CPU (s):')

  23. cpu_time = timeit.timeit('cpu', number=10, setup="from __main__ import cpu") print(cpu_time) print('GPU (s):')

  24. gpu_time = timeit.timeit('gpu', number=10, setup="from __main__ import gpu") print(gpu_time) print('GPU加速超过CPU: {}倍'.format(int(cpu_time/gpu_time)))


  25. sess.close # CPU (s): # 3.593296914000007 # GPU (s): # 0.1831514239999592 # GPU加速超过CPU: 19倍

Colab中的TPU

首先我们要让Colab连上GPU,导航栏-->编辑-->笔记本设置-->选择TPU

接下来我们来确认可以使用Tensorflow连接到TPU

  1. import os

  2. import pprint

  3. import tensorflow as tf


  4. if 'COLAB_TPU_ADDR' not in os.environ:

  5. print('您没有连接到TPU,请完成上述操作')

  6. else:

  7. tpu_address = 'grpc://' + os.environ['COLAB_TPU_ADDR']

  8. print ('TPU address is', tpu_address)

  9. # TPU address is grpc://10.97.206.146:8470


  10. with tf.Session(tpu_address) as session:

  11. devices = session.list_devices


  12. print('TPU devices:')

  13. pprint.pprint(devices)

使用TPU进行简单运算

  1. import numpy as np


  2. def add_op(x, y):

  3. return x + y


  4. x = tf.placeholder(tf.float32, [10,])

  5. y = tf.placeholder(tf.float32, [10,])

  6. tpu_ops = tf.contrib.tpu.rewrite(add_op, [x, y])


  7. session = tf.Session(tpu_address)

  8. try:

  9. print('Initializing...')

  10. session.run(tf.contrib.tpu.initialize_system)

  11. print('Running ops')

  12. print(session.run(tpu_ops, {x: np.arange(10), y: np.arange(10)}))

  13. # [array([ 0., 2., 4., 6., 8., 10., 12., 14., 16., 18.], dtype=float32)]

  14. finally:

  15. # 目前,tpu会话必须与关闭会话分开关闭。

  16. session.run(tf.contrib.tpu.shutdown_system)

  17. session.close

在Colab中运行Tensorboard

想要在Google Colab中运行Tensorboard,请运行以下代码

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

  2. !unzip ngrok-stable-linux-amd64.zip


  3. # 添加TensorBoard的路径

  4. import os

  5. log_dir = 'tb_logs'

  6. if not os.path.exists(log_dir):

  7. os.makedirs(log_dir)


  8. # 开启ngrok service,绑定port 6006(tensorboard)

  9. get_ipython.system_raw('tensorboard --logdir {} --host 0.0.0.0 --port 6006 &'.format(log_dir))

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


  11. # 产生网站,点击网站访问tensorboard

  12. !curl -s http://localhost:4040/api/tunnels | python3 -c \

  13. "import sys, json; print(json.load(sys.stdin)['tunnels'][0]['public_url'])"

您可以使用创建的ngrok.io URL 跟踪Tensorboard日志。您将在输出末尾找到URL。请注意,您的Tensorboard日志将保存到tb_logs目录。当然,您可以更改目录名称。

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

  1. from __future__ import print_function

  2. import keras

  3. from keras.datasets import mnist

  4. from keras.models import Sequential

  5. from keras.layers import Dense,Dropout,Flatten

  6. from keras.layers import Conv2D,MaxPooling2D

  7. from keras import backend as K

  8. from keras.callbacks import TensorBoard


  9. batch_size = 128

  10. num_classes = 10

  11. epochs = 12


  12. # input image dimensions

  13. img_rows, img_cols = 28,28


  14. # the data, shuffled and split between train and test sets

  15. (x_train, y_train), (x_test, y_test) = mnist.load_data


  16. if K.image_data_format == 'channels_first':

  17. x_train = x_train.reshape(x_train.shape[0],1, img_rows, img_cols)

  18. x_test = x_test.reshape(x_test.shape[0],1, img_rows, img_cols)

  19. input_shape = (1, img_rows, img_cols)

  20. else:

  21. x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols,1)

  22. x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols,1)

  23. input_shape = (img_rows, img_cols, 1)


  24. x_train = x_train.astype('float32')

  25. x_test = x_test.astype('float32')

  26. x_train /= 255

  27. x_test /= 255

  28. print('x_train shape:', x_train.shape)

  29. print(x_train.shape[0], 'train samples')

  30. print(x_test.shape[0], 'test samples')


  31. # convert class vectors to binary class matrices

  32. y_train = keras.utils.to_categorical(y_train, num_classes)

  33. y_test = keras.utils.to_categorical(y_test, num_classes)


  34. model = Sequential

  35. model.add(Conv2D(32, kernel_size=(3,3),

  36. activation='relu',

  37. input_shape=input_shape))

  38. model.add(Conv2D(64, (3,3), activation='relu'))

  39. model.add(MaxPooling2D(pool_size=(2,2)))

  40. model.add(Dropout(0.25))

  41. model.add(Flatten)

  42. model.add(Dense(128, activation='relu'))

  43. model.add(Dropout(0.5))

  44. model.add(Dense(num_classes, activation='softmax'))


  45. model.compile(loss=keras.losses.categorical_crossentropy,

  46. optimizer=keras.optimizers.Adadelta,

  47. metrics=['accuracy'])



  48. tbCallBack = TensorBoard(log_dir=LOG_DIR,

  49. histogram_freq=1,

  50. write_graph=True,

  51. write_grads=True,

  52. batch_size=batch_size,

  53. write_images=True)


  54. model.fit(x_train, y_train,

  55. batch_size=batch_size,

  56. epochs=epochs,

  57. verbose=1,

  58. validation_data=(x_test, y_test),

  59. callbacks=[tbCallBack])

  60. score = model.evaluate(x_test, y_test, verbose=0)

  61. print('Test loss:', score[0])

  62. print('Test accuracy:', score[1])

题图:pexels,CC0 授权。

相关推荐

为何越来越多的编程语言使用JSON(为什么编程)

JSON是JavascriptObjectNotation的缩写,意思是Javascript对象表示法,是一种易于人类阅读和对编程友好的文本数据传递方法,是JavaScript语言规范定义的一个子...

何时在数据库中使用 JSON(数据库用json格式存储)

在本文中,您将了解何时应考虑将JSON数据类型添加到表中以及何时应避免使用它们。每天?分享?最新?软件?开发?,Devops,敏捷?,测试?以及?项目?管理?最新?,最热门?的?文章?,每天?花?...

MySQL 从零开始:05 数据类型(mysql数据类型有哪些,并举例)

前面的讲解中已经接触到了表的创建,表的创建是对字段的声明,比如:上述语句声明了字段的名称、类型、所占空间、默认值和是否可以为空等信息。其中的int、varchar、char和decimal都...

JSON对象花样进阶(json格式对象)

一、引言在现代Web开发中,JSON(JavaScriptObjectNotation)已经成为数据交换的标准格式。无论是从前端向后端发送数据,还是从后端接收数据,JSON都是不可或缺的一部分。...

深入理解 JSON 和 Form-data(json和formdata提交区别)

在讨论现代网络开发与API设计的语境下,理解客户端和服务器间如何有效且可靠地交换数据变得尤为关键。这里,特别值得关注的是两种主流数据格式:...

JSON 语法(json 语法 priority)

JSON语法是JavaScript语法的子集。JSON语法规则JSON语法是JavaScript对象表示法语法的子集。数据在名称/值对中数据由逗号分隔花括号保存对象方括号保存数组JS...

JSON语法详解(json的语法规则)

JSON语法规则JSON语法是JavaScript对象表示法语法的子集。数据在名称/值对中数据由逗号分隔大括号保存对象中括号保存数组注意:json的key是字符串,且必须是双引号,不能是单引号...

MySQL JSON数据类型操作(mysql的json)

概述mysql自5.7.8版本开始,就支持了json结构的数据存储和查询,这表明了mysql也在不断的学习和增加nosql数据库的有点。但mysql毕竟是关系型数据库,在处理json这种非结构化的数据...

JSON的数据模式(json数据格式示例)

像XML模式一样,JSON数据格式也有Schema,这是一个基于JSON格式的规范。JSON模式也以JSON格式编写。它用于验证JSON数据。JSON模式示例以下代码显示了基本的JSON模式。{"...

前端学习——JSON格式详解(后端json格式)

JSON(JavaScriptObjectNotation)是一种轻量级的数据交换格式。易于人阅读和编写。同时也易于机器解析和生成。它基于JavaScriptProgrammingLa...

什么是 JSON:详解 JSON 及其优势(什么叫json)

现在程序员还有谁不知道JSON吗?无论对于前端还是后端,JSON都是一种常见的数据格式。那么JSON到底是什么呢?JSON的定义...

PostgreSQL JSON 类型:处理结构化数据

PostgreSQL提供JSON类型,以存储结构化数据。JSON是一种开放的数据格式,可用于存储各种类型的值。什么是JSON类型?JSON类型表示JSON(JavaScriptO...

JavaScript:JSON、三种包装类(javascript 包)

JOSN:我们希望可以将一个对象在不同的语言中进行传递,以达到通信的目的,最佳方式就是将一个对象转换为字符串的形式JSON(JavaScriptObjectNotation)-JS的对象表示法...

Python数据分析 只要1分钟 教你玩转JSON 全程干货

Json简介:Json,全名JavaScriptObjectNotation,JSON(JavaScriptObjectNotation(记号、标记))是一种轻量级的数据交换格式。它基于J...

比较一下JSON与XML两种数据格式?(json和xml哪个好)

JSON(JavaScriptObjectNotation)和XML(eXtensibleMarkupLanguage)是在日常开发中比较常用的两种数据格式,它们主要的作用就是用来进行数据的传...

取消回复欢迎 发表评论:

请填写验证码