
原文鏈接 https://jinkey.ai/post/tech/xiang-mian-fei-yong-gu-ge-zi-yuan-xun-lian-shen-jing-wang-luo-colab-xiang-xi-shi-yong-jiao-cheng
本文作者 Jinkey(微信公眾號 jinkey-love,官網(wǎng) https://jinkey.ai)
文章允許非篡改署名轉(zhuǎn)載,刪除或修改本段版權(quán)信息轉(zhuǎn)載的,視為侵犯知識產(chǎn)權(quán),我們保留追求您法律責(zé)任的權(quán)利,特此聲明!
1 簡介
Colab 是谷歌內(nèi)部類 Jupyter Notebook 的交互式 Python 環(huán)境,免安裝快速切換 Python 2和 Python 3 的環(huán)境,支持Google全家桶(TensorFlow、BigQuery、GoogleDrive等),支持 pip 安裝任意自定義庫。
網(wǎng)址:
https://colab.research.google.com
2 庫的安裝和使用
Colab 自帶了 Tensorflow、Matplotlib、Numpy、Pandas 等深度學(xué)習(xí)基礎(chǔ)庫。如果還需要其他依賴,如 Keras,可以新建代碼塊,輸入
# 安裝最新版本Keras
# https://keras.io/
!pip install keras
# 指定版本安裝
!pip install keras==2.0.9
# 安裝 OpenCV
# https://opencv.org/
!apt-get -qq install -y libsm6 libxext6 && pip install -q -U opencv-python
# 安裝 Pytorch
# http://pytorch.org/
!pip install -q http://download.pytorch.org/whl/cu75/torch-0.2.0.post3-cp27-cp27mu-manylinux1_x86_64.whl torchvision
# 安裝 XGBoost
# https://github.com/dmlc/xgboost
!pip install -q xgboost
# 安裝 7Zip
!apt-get -qq install -y libarchive-dev && pip install -q -U libarchive
# 安裝 GraphViz 和 PyDot
!apt-get -qq install -y graphviz && pip install -q pydot
3 Google Drive 文件操作
授權(quán)登錄
對于同一個 notebook,登錄操作只需要進(jìn)行一次,然后才可以進(jìn)度讀寫操作。
# 安裝 PyDrive 操作庫,該操作每個 notebook 只需要執(zhí)行一次
!pip install -U -q PyDrive
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
from google.colab import auth
from oauth2client.client import GoogleCredentials
# 授權(quán)登錄,僅第一次的時候會鑒權(quán)
auth.authenticate_user()
gauth = GoogleAuth()
gauth.credentials = GoogleCredentials.get_application_default()
drive = GoogleDrive(gauth)
執(zhí)行這段代碼后,會打印以下內(nèi)容,點擊連接進(jìn)行授權(quán)登錄,獲取到 token 值填寫到輸入框,按 Enter 繼續(xù)即可完成登錄。

遍歷目錄
# 列出根目錄的所有文件
# "q" 查詢條件教程詳見:https://developers.google.com/drive/v2/web/search-parameters
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"]))
可以看到控制臺打印結(jié)果
title: Colab 測試, id: 1cB5CHKSdL26AMXQ5xrqk2kaBv5LSkIsJ8HuEDyZpeqQ, mimeType: application/vnd.google-apps.document
title: Colab Notebooks, id: 1U9363A12345TP2nSeh2K8FzDKSsKj5Jj, mimeType: application/vnd.google-apps.folder
其中 id 是接下來的教程獲取文件的唯一標(biāo)識。根據(jù) mimeType 可以知道 Colab 測試 文件為 doc 文檔,而 Colab Notebooks 為文件夾(也就是 Colab 的 Notebook 儲存的根目錄),如果想查詢 Colab Notebooks 文件夾下的文件,查詢條件可以這么寫:
# '目錄 id' in parents
file_list = drive.ListFile({'q': "'1cB5CHKSdL26AMXQ5xrqk2kaBv5LBkIsJ8HuEDyZpeqQ' in parents and trashed=false"}).GetList()
讀取文件內(nèi)容
目前測試過可以直接讀取內(nèi)容的格式為 .txt(mimeType: text/plain),讀取代碼:
file = drive.CreateFile({'id': "替換成你的 .txt 文件 id"})
file.GetContentString()
而 .csv 如果用GetContentString()只能打印第一行的數(shù)據(jù),要用``
file = drive.CreateFile({'id': "替換成你的 .csv 文件 id"})
#這里的下載操作只是緩存,不會在你的Google Drive 目錄下多下載一個文件
file.GetContentFile('iris.csv', "text/csv")
# 直接打印文件內(nèi)容
with open('iris.csv') as f:
print f.readlines()
# 用 pandas 讀取
import pandas
pd.read_csv('iris.csv', index_col=[0,1], skipinitialspace=True)
Colab 會直接以表格的形式輸出結(jié)果(下圖為截取 iris 數(shù)據(jù)集的前幾行), iris 數(shù)據(jù)集地址為 http://aima.cs.berkeley.edu/data/iris.csv ,學(xué)習(xí)的同學(xué)可以執(zhí)行上傳到自己的 Google Drive。

寫文件操作
# 創(chuàng)建一個文本文件
uploaded = drive.CreateFile({'title': '示例.txt'})
uploaded.SetContentString('測試內(nèi)容')
uploaded.Upload()
print('創(chuàng)建后文件 id 為 {}'.format(uploaded.get('id')))
更多操作可查看 http://pythonhosted.org/PyDrive/filemanagement.html
4 Google Sheet 電子表格操作
授權(quán)登錄
對于同一個 notebook,登錄操作只需要進(jìn)行一次,然后才可以進(jìn)度讀寫操作。
!pip install --upgrade -q gspread
from google.colab import auth
auth.authenticate_user()
import gspread
from oauth2client.client import GoogleCredentials
gc = gspread.authorize(GoogleCredentials.get_application_default())
讀取
把 iris.csv 的數(shù)據(jù)導(dǎo)入創(chuàng)建一個 Google Sheet 文件來做演示,可以放在 Google Drive 的任意目錄
worksheet = gc.open('iris').sheet1
# 獲取一個列表[
# [第1行第1列, 第1行第2列, ... , 第1行第n列], ... ,[第n行第1列, 第n行第2列, ... , 第n行第n列]]
rows = worksheet.get_all_values()
print(rows)
# 用 pandas 讀取
import pandas as pd
pd.DataFrame.from_records(rows)
打印結(jié)果分別為
[['5.1', '3.5', '1.4', '0.2', 'setosa'], ['4.9', '3', '1.4', '0.2', 'setosa'], ...
寫入
sh = gc.create('谷歌表')
# 打開工作簿和工作表
worksheet = gc.open('谷歌表').sheet1
cell_list = worksheet.range('A1:C2')
import random
for cell in cell_list:
cell.value = random.randint(1, 10)
worksheet.update_cells(cell_list)
5 下載文件到本地
from google.colab import files
with open('example.txt', 'w') as f:
f.write('測試內(nèi)容')
files.download('example.txt')
6 實戰(zhàn)
這里以我在 Github 的開源LSTM 文本分類項目為例子https://github.com/Jinkeycode/keras_lstm_chinese_document_classification
把 master/data 目錄下的三個文件存放到 Google Drive 上。該示例演示的是對健康、科技、設(shè)計三個類別的標(biāo)題進(jìn)行分類。
新建
在 Colab 上新建 Python2 的筆記本

安裝依賴
!pip install keras
!pip install jieba
!pip install h5py
import h5py
import jieba as jb
import numpy as np
import keras as krs
import tensorflow as tf
from sklearn.preprocessing import LabelEncoder
加載數(shù)據(jù)
授權(quán)登錄
# 安裝 PyDrive 操作庫,該操作每個 notebook 只需要執(zhí)行一次
!pip install -U -q PyDrive
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
from google.colab import auth
from oauth2client.client import GoogleCredentials
def login_google_drive():
# 授權(quán)登錄,僅第一次的時候會鑒權(quán)
auth.authenticate_user()
gauth = GoogleAuth()
gauth.credentials = GoogleCredentials.get_application_default()
drive = GoogleDrive(gauth)
return drive
列出 GD 下的所有文件
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"]))
drive = login_google_drive()
list_file(drive)
緩存數(shù)據(jù)到工作環(huán)境
def cache_data():
# id 替換成上一步讀取到的對應(yīng)文件 id
health_txt = drive.CreateFile({'id': "117GkBtuuBP3wVjES0X0L4wVF5rp5Cewi"})
tech_txt = drive.CreateFile({'id': "14sDl4520Tpo1MLPydjNBoq-QjqOKk9t6"})
design_txt = drive.CreateFile({'id': "1J4lndcsjUb8_VfqPcfsDeOoB21bOLea3"})
#這里的下載操作只是緩存,不會在你的Google Drive 目錄下多下載一個文件
health_txt.GetContentFile('health.txt', "text/plain")
tech_txt.GetContentFile('tech.txt', "text/plain")
design_txt.GetContentFile('design.txt', "text/plain")
print("緩存成功")
cache_data()
讀取工作環(huán)境的數(shù)據(jù)
def load_data():
titles = []
print("正在加載健康類別的數(shù)據(jù)...")
with open("health.txt", "r") as f:
for line in f.readlines():
titles.append(line.strip())
print("正在加載科技類別的數(shù)據(jù)...")
with open("tech.txt", "r") as f:
for line in f.readlines():
titles.append(line.strip())
print("正在加載設(shè)計類別的數(shù)據(jù)...")
with open("design.txt", "r") as f:
for line in f.readlines():
titles.append(line.strip())
print("一共加載了 %s 個標(biāo)題" % len(titles))
return titles
titles = load_data()
加載標(biāo)簽
def load_label():
arr0 = np.zeros(shape=[12000, ])
arr1 = np.ones(shape=[12000, ])
arr2 = np.array([2]).repeat(7318)
target = np.hstack([arr0, arr1, arr2])
print("一共加載了 %s 個標(biāo)簽" % target.shape)
encoder = LabelEncoder()
encoder.fit(target)
encoded_target = encoder.transform(target)
dummy_target = krs.utils.np_utils.to_categorical(encoded_target)
return dummy_target
target = load_label()
文本預(yù)處理
max_sequence_length = 30
embedding_size = 50
# 標(biāo)題分詞
titles = [".".join(jb.cut(t, cut_all=True)) for t in titles]
# ?word2vec 詞袋化
vocab_processor = tf.contrib.learn.preprocessing.VocabularyProcessor(max_sequence_length, min_frequency=1)
text_processed = np.array(list(vocab_processor.fit_transform(titles)))
# 讀取詞標(biāo)簽
dict = vocab_processor.vocabulary_._mapping
sorted_vocab = sorted(dict.items(), key = lambda x : x[1])
構(gòu)建神經(jīng)網(wǎng)絡(luò)
這里使用 Embedding 和 lstm 作為前兩層,通過 softmax 激活輸出結(jié)果
# 配置網(wǎng)絡(luò)結(jié)構(gòu)
def build_netword(num_vocabs):
# 配置網(wǎng)絡(luò)結(jié)構(gòu)
model = krs.Sequential()
model.add(krs.layers.Embedding(num_vocabs, embedding_size, input_length=max_sequence_length))
model.add(krs.layers.LSTM(32, dropout=0.2, recurrent_dropout=0.2))
model.add(krs.layers.Dense(3))
model.add(krs.layers.Activation("softmax"))
model.compile(loss="categorical_crossentropy", optimizer="adam", metrics=["accuracy"])
return model
num_vocabs = len(dict.items())
model = build_netword(num_vocabs=num_vocabs)
import time
start = time.time()
# 訓(xùn)練模型
model.fit(text_processed, target, batch_size=512, epochs=10, )
finish = time.time()
print("訓(xùn)練耗時:%f 秒" %(finish-start))
預(yù)測樣本
sen 可以換成你自己的句子,預(yù)測結(jié)果為[健康類文章概率, 科技類文章概率, 設(shè)計類文章概率], 概率最高的為那一類的文章,但最大概率低于 0.8 時判定為無法分類的文章。
sen = "做好商業(yè)設(shè)計需要學(xué)習(xí)的小技巧"
sen_prosessed = " ".join(jb.cut(sen, cut_all=True))
sen_prosessed = vocab_processor.transform([sen_prosessed])
sen_prosessed = np.array(list(sen_prosessed))
result = model.predict(sen_prosessed)
catalogue = list(result[0]).index(max(result[0]))
threshold=0.8
if max(result[0]) > threshold:
if catalogue == 0:
print("這是一篇關(guān)于健康的文章")
elif catalogue == 1:
print("這是一篇關(guān)于科技的文章")
elif catalogue == 2:
print("這是一篇關(guān)于設(shè)計的文章")
else:
print("這篇文章沒有可信分類")
