爲什麼使用Colab
- 免費GPU提供超大算力和顯存,尤其是最近谷歌爸爸把Colab的GPU從古董級別的K80全面升級成Tesla T4後好像更牛逼了
- 融合了Jupyter使得Colab可視化十分友好
- 和Google Drive的連接提供了高效的雲存儲和團隊協作解決方案(比如當用Colab運行爬蟲的時候可以將結果直接存儲到GoogleDrive的文件夾裏,如果你將這個文件夾與Boss共享,Boss就可以實時Check程序運行結果)
- 是時候薅一波谷歌爸爸的羊毛了
如何配置Colab
從 https://colab.research.google.com/notebooks/welcome.ipynb 進入Colab後,記得 runtime -> changeruntimetype -> hardware accelerator -> GPU,就可以用上谷歌爸爸免費送的GPU加速啦。
薅羊毛攻略
Step1 : 授權登錄
首先登錄GoogleDrive,然後在Colab中運行如下代碼,然後Colab會給出驗證碼鏈接,打開後粘到方框中回車即可。
from google.colab import files
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
from google.colab import auth
from oauth2client.client import GoogleCredentials
# 授權登錄
def login_google_drive():
auth.authenticate_user()
gauth = GoogleAuth()
gauth.credentials = GoogleCredentials.get_application_default()
drive = GoogleDrive(gauth)
return drive
drive = login_google_drive()
Step 2: 指定文件夾並緩存代碼中要用的文件
import os
from google.colab import drive
drive.mount('/content/drive')
path = "/content/drive/My Drive/parseins"
os.chdir(path)
os.listdir(path)
def list_file(drive):
file_list = drive.ListFile({'q': "'root' in parents and trashed=false"}).GetList()
for file1 in file_list:
print('title: %s, id: %s, mimeType: %s' % (file1['title'], file1['id'], file1["mimeType"]))
list_file(drive)
def cache_data():
# id 替換成上一步讀取到的對應文件 id
acclist = drive.CreateFile({'id': "1sCDAXwmPPLem4M_vY4RQdQ_PBVbFMqXb"})
#berlinstagram_postlist = drive.CreateFile({'id': "1-8Cn1LyoFXQIknyXoH8eksOw_2yYbX8M"})
#這裏的下載操作只是緩存,不會在你的Google Drive 目錄下多下載一個文件
acclist.GetContentFile('acclist.txt', "text/plain")
#berlinstagram_postlist.GetContentFile('berlinstagram_postlist.csv', "text/csv")
print("緩存成功")
cache_data()
Step 3: 安裝代碼中用到的module
!pip install requests
!pip install pyquery
!pip install pandas
!pip install PyDrive
Step 4: 將主程序放入Colab中並執行
注意事項
- Colab最多連續運行12個小時,超過12個小時需要重新GoogleDrive授權
- 因爲隨機分配GPU,所以要記得對自己的運行結果進行妥善保存
- GPU更換後可能需要重新加載module和指定文件夾等
主要參考鏈接
- https://blog.csdn.net/linhai1028/article/details/79275945
- https://blog.csdn.net/linhai1028/article/details/79275945
- https://blog.csdn.net/heliucs/article/details/84644372
- https://blog.csdn.net/cocoaqin/article/details/79184540