免费视频淫片aa毛片_日韩高清在线亚洲专区vr_日韩大片免费观看视频播放_亚洲欧美国产精品完整版

打開APP
userphoto
未登錄

開通VIP,暢享免費(fèi)電子書等14項(xiàng)超值服

開通VIP
居然有免費(fèi)的GPU可以跑深度學(xué)習(xí)代碼


作者:凌逆戰(zhàn)

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

從事深度學(xué)習(xí)的研究者都知道,深度學(xué)習(xí)代碼需要設(shè)計(jì)海量的數(shù)據(jù),需要很大很大很大(重要的事情說三遍)的計(jì)算量,以至于CPU算不過來,需要通過GPU幫忙,但這必不意味著CPU的性能沒GPU強(qiáng),CPU是那種綜合性的,GPU是專門用來做圖像渲染的,這我們大家都知道,做圖像矩陣的計(jì)算GPU更加在行,應(yīng)該我們一般把深度學(xué)習(xí)程序讓GPU來計(jì)算,事實(shí)也證明GPU的計(jì)算速度比CPU塊,但是(但是前面的話都是廢話)我們窮,買不起呀,一塊1080Ti現(xiàn)在也要3500左右,2080Ti要9000左右,具體價(jià)格還要看顯存大小,因此本文給大家?guī)砹烁@狦oogle免費(fèi)的GPU Colaboratory。

Google Colab簡介

Google Colaboratory是谷歌開放的一款研究工具,主要用于機(jī)器學(xué)習(xí)的開發(fā)研究,這款工具現(xiàn)在可以免費(fèi)使用,但是不是永久免費(fèi)暫時(shí)還不確定,Google Colab最大的好處是給廣大開發(fā)AI者提供免費(fèi)的GPU使用!GPU型號(hào)是Tesla K80,你可以在上面輕松地跑例如:Keras、Tensorflow、Pytorch等框架。

Colabortory是一個(gè)jupyter notebook環(huán)境,它支持python2和python3,還包括TPU和GPU加速,該軟件與Google云盤硬盤集成,用戶可以輕松共享項(xiàng)目或?qū)⑵渌蚕眄?xiàng)目復(fù)制到自己的帳戶中。

Colaboratory使用步驟

1、登錄谷歌云盤

https://drive.google.com/drive/my-drive(沒有賬號(hào)的可以注冊(cè)一個(gè))

(1)、右鍵新建文件夾,作為我們的項(xiàng)目文件夾。

2、創(chuàng)建Colab文件

右鍵在更多里面選擇google Colaboratry(如果沒有Colaboratory需要在關(guān)聯(lián)更多應(yīng)用里面關(guān)聯(lián)Colaboratory)

3、開始使用

這時(shí)候會(huì)直接跳轉(zhuǎn)到Colaboratory界面,這個(gè)界面很像Jupyter Notebook,Jupyter的命令在Colaboratory一樣適用,值得一提的是,Colab不僅可以運(yùn)行Python代碼,只要在命令前面加一個(gè)' !',這條命令就變成了linux命令,比如我們可以' ! ls'查看文件夾文件,還可以!pip安裝庫。以及運(yùn)行py程序!python2 temp.py

可以寫一段代碼進(jìn)行測(cè)試

更改工作目錄,在Colab中cd命令是無效的,切換工作目錄使用chdir函數(shù)

  1. !pwd # 用 pwd 命令顯示工作路徑

  2. # /content

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

  4. # sample_data

  5. !ls 'drive/My Drive'

  6. # TensorFlow (這就是我們之前創(chuàng)建的那個(gè)文件夾)


  7. # 更改工作目錄

  8. import os

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

  10. os.getcwd

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

重新啟動(dòng)Colab命令:!kill -9 -1

(3)、選擇配置環(huán)境

我們大家肯定會(huì)疑慮,上述方法跑的那段程序是不是用GPU跑的呢?不是,想要用GPU跑程序我們還需要配置環(huán)境,

點(diǎn)擊工具欄“修改”,選擇筆記本設(shè)置

在運(yùn)行時(shí)類型我們可以選擇Python 2或Python 3,硬件加速器我們可以選擇GPU或者TPU(后面會(huì)講到),或者None什么都不用。

加載數(shù)據(jù)

從本地加載數(shù)據(jù)從本地上傳數(shù)據(jù)

files.upload會(huì)返回已上傳文件的字典。此字典的鍵為文件名,值為已上傳的數(shù)據(jù)。

  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])))

我們運(yùn)行該段程序之后,就會(huì)讓我們選擇本地文件,點(diǎn)擊上傳后,該文件就能被讀取了

將文件下載到本地
  1. from google.colab import files


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

從谷歌云盤加載數(shù)據(jù)

使用授權(quán)代碼在運(yùn)行時(shí)裝載 Google 云端硬盤

  1. from google.colab import drive

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

在Colab中運(yùn)行上述代碼,會(huì)出現(xiàn)一段鏈接,點(diǎn)擊鏈接,復(fù)制鏈接中的密鑰,輸入到Colab中就可以成功把Colab與谷歌云盤相連接,連接后進(jìn)行路徑切換,就可以直接讀取谷歌云盤數(shù)據(jù)了。

向Google Colab添加表單

為了不每次都在代碼中更改超參數(shù),您可以簡單地將表單添加到Google Colab。

點(diǎn)擊之后就會(huì)出現(xiàn)左右兩個(gè)框,我們?cè)谧罂蛑休斎?/p>

  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 ['選項(xiàng)1', '選項(xiàng)2', '選項(xiàng)3'] {allow-input: true}


  5. print(text)

  6. print(dropdown)

  7. print(text_and_dropdown)

雙擊右邊欄可以隱藏代碼

Colab中的GPU

首先我們要讓Colab連上GPU,導(dǎo)航欄-->編輯-->筆記本設(shè)置-->選擇GPU

接下來我們來確認(rèn)可以使用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('沒有發(fā)現(xiàn)GPU device')


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

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

我們可以在Colab上運(yùn)行以下代碼測(cè)試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可以檢測(cè)到GPU

  13. try:

  14. sess.run(tf.global_variables_initializer) except tf.errors.InvalidArgumentError: print( 'nn此錯(cuò)誤很可能表示此筆記本未配置為使用GPU。'

  15. '通過命令面板(CMD/CTRL-SHIFT-P)或編輯菜單在筆記本設(shè)置中更改此設(shè)置.nn') raise


  16. def cpu:

  17. sess.run(net_cpu) def gpu:

  18. sess.run(net_gpu) # 運(yùn)行一次進(jìn)行測(cè)試

  19. cpu

  20. gpu # 多次運(yùn)行op

  21. print('將100*100*100*3通過濾波器卷積到32*7*7*3(批處理x高度x寬度x通道)大小的圖像'

  22. '計(jì)算10次運(yùn)訓(xùn)時(shí)間的總和') 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,導(dǎo)航欄-->編輯-->筆記本設(shè)置-->選擇TPU

接下來我們來確認(rèn)可以使用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,請(qǐng)完成上述操作')

  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進(jìn)行簡單運(yùn)算

  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會(huì)話必須與關(guān)閉會(huì)話分開關(guān)閉。

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

  17. session.close

在Colab中運(yùn)行Tensorboard

想要在Google Colab中運(yùn)行Tensorboard,請(qǐng)運(yùn)行以下代碼

  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. # 產(chǎn)生網(wǎng)站,點(diǎn)擊網(wǎng)站訪問tensorboard

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

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

您可以使用創(chuàng)建的ngrok.io URL 跟蹤Tensorboard日志。您將在輸出末尾找到URL。請(qǐng)注意,您的Tensorboard日志將保存到tb_logs目錄。當(dāng)然,您可以更改目錄名稱。

之后,我們可以看到Tensorboard發(fā)揮作用!運(yùn)行以下代碼后,您可以通過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 授權(quán)。

本站僅提供存儲(chǔ)服務(wù),所有內(nèi)容均由用戶發(fā)布,如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請(qǐng)點(diǎn)擊舉報(bào)。
打開APP,閱讀全文并永久保存 查看更多類似文章
猜你喜歡
類似文章
【服務(wù)器系列】Google Colab簡介
1美元從零開始訓(xùn)練Bert,手把手教你優(yōu)雅地薅谷歌云TPU羊毛
深度學(xué)習(xí)利器:TensorFlow實(shí)戰(zhàn)
PyTorch 1.3發(fā)布!能在移動(dòng)端部署,支持Colab云TPU,阿里云上也能用
TensorFlow深度學(xué)習(xí),一篇文章就夠了
Tensorflow Docker是我的深度學(xué)習(xí)開發(fā)環(huán)境,你的呢?
更多類似文章 >>
生活服務(wù)
分享 收藏 導(dǎo)長圖 關(guān)注 下載文章
綁定賬號(hào)成功
后續(xù)可登錄賬號(hào)暢享VIP特權(quán)!
如果VIP功能使用有故障,
可點(diǎn)擊這里聯(lián)系客服!

聯(lián)系客服