原文連接 https://jinkey.ai/post/tech/x...
本文做者 Jinkey(微信公衆號 jinkey-love,官網 https://jinkey.ai)
文章容許非篡改署名轉載,刪除或修改本段版權信息轉載的,視爲侵犯知識產權,咱們保留追求您法律責任的權利,特此聲明!
Colab 是谷歌內部類 Jupyter Notebook 的交互式 Python 環境,免安裝快速切換 Python 2和 Python 3 的環境,支持Google全家桶(TensorFlow、BigQuery、GoogleDrive等),支持 pip 安裝任意自定義庫。
網址:
https://colab.research.google...html
Colab 自帶了 Tensorflow、Matplotlib、Numpy、Pandas 等深度學習基礎庫。若是還須要其餘依賴,如 Keras,能夠新建代碼塊,輸入python
# 安裝最新版本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
對於同一個 notebook,登陸操做只須要進行一次,而後才能夠進度讀寫操做。linux
# 安裝 PyDrive 操做庫,該操做每一個 notebook 只須要執行一次 !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 # 受權登陸,僅第一次的時候會鑑權 auth.authenticate_user() gauth = GoogleAuth() gauth.credentials = GoogleCredentials.get_application_default() drive = GoogleDrive(gauth)
執行這段代碼後,會打印如下內容,點擊鏈接進行受權登陸,獲取到 token 值填寫到輸入框,按 Enter 繼續便可完成登陸。
git
# 列出根目錄的全部文件 # "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"]))
能夠看到控制檯打印結果github
title: Colab 測試, id: 1cB5CHKSdL26AMXQ5xrqk2kaBv5LSkIsJ8HuEDyZpeqQ, mimeType: application/vnd.google-apps.documenttitle: Colab Notebooks, id: 1U9363A12345TP2nSeh2K8FzDKSsKj5Jj, mimeType: application/vnd.google-apps.folderweb
其中 id 是接下來的教程獲取文件的惟一標識。根據 mimeType 能夠知道 Colab 測試
文件爲 doc 文檔,而 Colab Notebooks 爲文件夾(也就是 Colab 的 Notebook 儲存的根目錄),若是想查詢 Colab Notebooks 文件夾下的文件,查詢條件能夠這麼寫:shell
# '目錄 id' in parents file_list = drive.ListFile({'q': "'1cB5CHKSdL26AMXQ5xrqk2kaBv5LBkIsJ8HuEDyZpeqQ' in parents and trashed=false"}).GetList()
目前測試過能夠直接讀取內容的格式爲 .txt
(mimeType: text/plain),讀取代碼:緩存
file = drive.CreateFile({'id': "替換成你的 .txt 文件 id"}) file.GetContentString()
而 .csv
若是用GetContentString()
只能打印第一行的數據,要用``微信
file = drive.CreateFile({'id': "替換成你的 .csv 文件 id"}) #這裏的下載操做只是緩存,不會在你的Google Drive 目錄下多下載一個文件 file.GetContentFile('iris.csv', "text/csv") # 直接打印文件內容 with open('iris.csv') as f: print f.readlines() # 用 pandas 讀取 import pandas pd.read_csv('iris.csv', index_col=[0,1], skipinitialspace=True)
Colab 會直接以表格的形式輸出結果(下圖爲截取 iris 數據集的前幾行), iris 數據集地址爲 http://aima.cs.berkeley.edu/d... ,學習的同窗能夠執行上傳到本身的 Google Drive。
網絡
# 建立一個文本文件 uploaded = drive.CreateFile({'title': '示例.txt'}) uploaded.SetContentString('測試內容') uploaded.Upload() print('建立後文件 id 爲 {}'.format(uploaded.get('id')))
更多操做可查看 http://pythonhosted.org/PyDri...
對於同一個 notebook,登陸操做只須要進行一次,而後才能夠進度讀寫操做。
!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 的數據導入建立一個 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)
打印結果分別爲
[['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)
with open('example.txt', 'w') as f: f.write('測試內容') files.download('example.txt')
這裏以我在 Github 的開源LSTM 文本分類項目爲例子https://github.com/Jinkeycode...
把 master/data
目錄下的三個文件存放到 Google Drive 上。該示例演示的是對健康、科技、設計三個類別的標題進行分類。
在 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
受權登陸
# 安裝 PyDrive 操做庫,該操做每一個 notebook 只須要執行一次 !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(): # 受權登陸,僅第一次的時候會鑑權 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)
緩存數據到工做環境
def cache_data(): # id 替換成上一步讀取到的對應文件 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()
讀取工做環境的數據
def load_data(): titles = [] print("正在加載健康類別的數據...") with open("health.txt", "r") as f: for line in f.readlines(): titles.append(line.strip()) print("正在加載科技類別的數據...") with open("tech.txt", "r") as f: for line in f.readlines(): titles.append(line.strip()) print("正在加載設計類別的數據...") with open("design.txt", "r") as f: for line in f.readlines(): titles.append(line.strip()) print("一共加載了 %s 個標題" % len(titles)) return titles titles = load_data()
加載標籤
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 個標籤" % 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()
max_sequence_length = 30 embedding_size = 50 # 標題分詞 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))) # 讀取詞標籤 dict = vocab_processor.vocabulary_._mapping sorted_vocab = sorted(dict.items(), key = lambda x : x[1])
這裏使用 Embedding 和 lstm 做爲前兩層,經過 softmax 激活輸出結果
# 配置網絡結構 def build_netword(num_vocabs): # 配置網絡結構 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() # 訓練模型 model.fit(text_processed, target, batch_size=512, epochs=10, ) finish = time.time() print("訓練耗時:%f 秒" %(finish-start))
sen 能夠換成你本身的句子,預測結果爲[健康類文章機率, 科技類文章機率, 設計類文章機率]
, 機率最高的爲那一類的文章,但最大機率低於 0.8 時斷定爲沒法分類的文章。
sen = "作好商業設計須要學習的小技巧" 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("這是一篇關於健康的文章") elif catalogue == 1: print("這是一篇關於科技的文章") elif catalogue == 2: print("這是一篇關於設計的文章") else: print("這篇文章沒有可信分類")