微信扫一扫
分享到朋友圈

专栏 | 想免费用谷歌资源训练神经网络?Colab详细使用教程

作者:机器之心 来源:机器之心 公众号
分享到:

01-31

机器之心专栏

作者:Jinkey


1 简介


Colab 是谷歌内部类 Jupyter Notebook 的交互式 Python 环境,免安装快速切换 Python 2 和 Python 3 的环境,支持 Google 全家桶 (TensorFlow、BigQuery、GoogleDrive 等),支持 pip 安装任意自定义库。


网址:https://colab.research.google.com


2 库的安装和使用


Colab 自带了 Tensorflow、Matplotlib、Numpy、Pandas 等深度学习基础库。如果还需要其他依赖,如 Keras,可以新建代码块,输入


  1. # 安装最新版本Keras

  2. # https://keras.io/

  3. !pip install keras

  4. # 指定版本安装

  5. !pip install keras==2.0.9

  6. # 安装 OpenCV

  7. # https://opencv.org/

  8. !apt-get -qq install -y libsm6 libxext6 && pip install -q -U opencv-python

  9. # 安装 Pytorch

  10. # http://pytorch.org/

  11. !pip install -q http://download.pytorch.org/whl/cu75/torch-0.2.0.post3-cp27-cp27mu-manylinux1_x86_64.whl torchvision

  12. # 安装 XGBoost

  13. # https://github.com/dmlc/xgboost

  14. !pip install -q xgboost

  15. # 安装 7Zip

  16. !apt-get -qq install -y libarchive-dev && pip install -q -U libarchive

  17. # 安装 GraphViz PyDot

  18. !apt-get -qq install -y graphviz && pip install -q pydot


3 Google Drive 文件操作


授权登录


对于同一个 notebook,登录操作只需要进行一次,然后才可以进度读写操作。


  1. # 安装 PyDrive 操作库,该操作每个 notebook 只需要执行一次

  2. !pip install -U -q PyDrive

  3. from pydrive.auth import GoogleAuth

  4. from pydrive.drive import GoogleDrive

  5. from google.colab import auth

  6. from oauth2client.client import GoogleCredentials


  7. # 授权登录,仅第一次的时候会鉴权

  8. auth.authenticate_user()

  9. gauth = GoogleAuth()

  10. gauth.credentials = GoogleCredentials.get_application_default()

  11. drive = GoogleDrive(gauth)




遍历目录


  1. # 列出根目录的所有文件

  2. # "q" 查询条件教程详见:https://developers.google.com/drive/v2/web/search-parameters

  3. file_list = drive.ListFile({'q': "'root' in parents and trashed=false"}).GetList()

  4. for file1 in file_list:

  5.  print('title: %s, id: %s, mimeType: %s' % (file1['title'], file1['id'], file1["mimeType"]))


可以看到控制台打印结果


title: Colab 测试, id: 1cB5CHKSdL26AMXQ5xrqk2kaBv5LSkIsJ8HuEDyZpeqQ, mimeType: application/vnd.google-apps.document


title: Colab Notebooks, id: 1U9363A12345TP2nSeh2K8FzDKSsKj5Jj, mimeType: application/vnd.google-apps.folder


其中 id 是接下来的教程获取文件的唯一标识。根据 mimeType 可以知道 Colab 测试 文件为 doc 文档,而 Colab Notebooks 为文件夹(也就是 Colab 的 Notebook 储存的根目录),如果想查询 Colab Notebooks 文件夹下的文件,查询条件可以这么写:


  1. # '目录 id' in parents

  2. file_list = drive.ListFile({'q': "'1cB5CHKSdL26AMXQ5xrqk2kaBv5LBkIsJ8HuEDyZpeqQ' in parents and trashed=false"}).GetList()


读取文件内容


目前测试过可以直接读取内容的格式为 .txt(mimeType: text/plain),读取代码:


  1. file = drive.CreateFile({'id': "替换成你的 .txt 文件 id"})

  2. file.GetContentString()


而 .csv 如果用 GetContentString() 只能打印第一行的数据,要用``


  1. file = drive.CreateFile({'id': "替换成你的 .csv 文件 id"})

  2. #这里的下载操作只是缓存,不会在你的Google Drive 目录下多下载一个文件

  3. file.GetContentFile('iris.csv', "text/csv")


  4. # 直接打印文件内容

  5. with open('iris.csv') as f:

  6.  print f.readlines()

  7. # pandas 读取

  8. import pandas

  9. pd.read_csv('iris.csv', index_col=[0,1], skipinitialspace=True)


Colab 会直接以表格的形式输出结果(下图为截取 iris 数据集的前几行),iris 数据集地址为 http://aima.cs.berkeley.edu/data/iris.csv,学习的同学可以执行上传到自己的 Google Drive。

写文件操作


  1. # 创建一个文本文件

  2. uploaded = drive.CreateFile({'title': '示例.txt'})

  3. uploaded.SetContentString('测试内容')

  4. uploaded.Upload()

  5. print('创建后文件 id 为 {}'.format(uploaded.get('id')))


更多操作可查看 http://pythonhosted.org/PyDrive/filemanagement.html


4 Google Sheet 电子表格操作


授权登录


对于同一个 notebook,登录操作只需要进行一次,然后才可以进度读写操作。


  1. !pip install --upgrade -q gspread

  2. from google.colab import auth

  3. auth.authenticate_user()


  4. import gspread

  5. from oauth2client.client import GoogleCredentials


  6. gc = gspread.authorize(GoogleCredentials.get_application_default())


读取


把 iris.csv 的数据导入创建一个 Google Sheet 文件来做演示,可以放在 Google Drive 的任意目录


  1. worksheet = gc.open('iris').sheet1


  2. # 获取一个列表[

  3. # [第1行第1列, 1行第2列, ... , 1行第n列], ... ,[第n行第1列, n行第2列, ... , n行第n列]]

  4. rows = worksheet.get_all_values()

  5. print(rows)


  6. #   pandas 读取

  7. import pandas as pd

  8. pd.DataFrame.from_records(rows)


打印结果分别为


[['5.1', '3.5', '1.4', '0.2', 'setosa'], ['4.9', '3', '1.4', '0.2', 'setosa'], ...



写入


  1. sh = gc.create('谷歌表')


  2. # 打开工作簿和工作表

  3. worksheet = gc.open('谷歌表').sheet1

  4. cell_list = worksheet.range('A1:C2')


  5. import random

  6. for cell in cell_list:

  7.  cell.value = random.randint(1, 10)

  8. worksheet.update_cells(cell_list)


5 下载文件到本地


  1. from google.colab import files

  2. with open('example.txt', 'w') as f:

  3.  f.write('测试内容')

  4. files.download('example.txt')


6 实战


这里以我在 Github 的开源 LSTM 文本分类项目为例子 https://github.com/Jinkeycode/keras_lstm_chinese_document_classification,把 master/data 目录下的三个文件存放到 Google Drive 上。该示例演示的是对健康、科技、设计三个类别的标题进行分类。


新建


在 Colab 上新建 Python2 的笔记本



安装依赖


  1. !pip install keras

  2. !pip install jieba

  3. !pip install h5py


  4. import h5py

  5. import jieba as jb

  6. import numpy as np

  7. import keras as krs

  8. import tensorflow as tf

  9. from sklearn.preprocessing import LabelEncoder


加载数据


授权登录


  1. # 安装 PyDrive 操作库,该操作每个 notebook 只需要执行一次

  2. !pip install -U -q PyDrive

  3. from pydrive.auth import GoogleAuth

  4. from pydrive.drive import GoogleDrive

  5. from google.colab import auth

  6. from oauth2client.client import GoogleCredentials


  7. def login_google_drive():

  8.  # 授权登录,仅第一次的时候会鉴权

  9.  auth.authenticate_user()

  10.  gauth = GoogleAuth()

  11.  gauth.credentials = GoogleCredentials.get_application_default()

  12.  drive = GoogleDrive(gauth)

  13.  return drive


列出 GD 下的所有文件


  1. def list_file(drive):

  2.  file_list = drive.ListFile({'q': "'root' in parents and trashed=false"}).GetList()

  3.  for file1 in file_list:

  4.    print('title: %s, id: %s, mimeType: %s' % (file1['title'], file1['id'], file1["mimeType"]))


  5. drive = login_google_drive()

  6. list_file(drive)


缓存数据到工作环境


  1. def cache_data():

  2.  # id 替换成上一步读取到的对应文件 id

  3.  health_txt = drive.CreateFile({'id': "117GkBtuuBP3wVjES0X0L4wVF5rp5Cewi"})

  4.  tech_txt = drive.CreateFile({'id': "14sDl4520Tpo1MLPydjNBoq-QjqOKk9t6"})

  5.  design_txt = drive.CreateFile({'id': "1J4lndcsjUb8_VfqPcfsDeOoB21bOLea3"})

  6.  #这里的下载操作只是缓存,不会在你的Google Drive 目录下多下载一个文件


  7.  health_txt.GetContentFile('health.txt', "text/plain")

  8.  tech_txt.GetContentFile('tech.txt', "text/plain")

  9.  design_txt.GetContentFile('design.txt', "text/plain")


  10.  print("缓存成功")


  11. cache_data()


读取工作环境的数据


  1. def load_data():

  2.    titles = []

  3.    print("正在加载健康类别的数据...")

  4.    with open("health.txt", "r") as f:

  5.        for line in f.readlines():

  6.            titles.append(line.strip())


  7.    print("正在加载科技类别的数据...")

  8.    with open("tech.txt", "r") as f:

  9.        for line in f.readlines():

  10.            titles.append(line.strip())


  11.    print("正在加载设计类别的数据...")

  12.    with open("design.txt", "r") as f:

  13.        for line in f.readlines():

  14.            titles.append(line.strip())


  15.    print("一共加载了 %s 个标题" % len(titles))

  16.    

  17.    return titles


  18. titles = load_data()


加载标签


  1. def load_label():

  2.    arr0 = np.zeros(shape=[12000, ])

  3.    arr1 = np.ones(shape=[12000, ])

  4.    arr2 = np.array([2]).repeat(7318)

  5.    target = np.hstack([arr0, arr1, arr2])

  6.    print("一共加载了 %s 个标签" % target.shape)


  7.    encoder = LabelEncoder()

  8.    encoder.fit(target)

  9.    encoded_target = encoder.transform(target)

  10.    dummy_target = krs.utils.np_utils.to_categorical(encoded_target)


  11.    return dummy_target


  12. target = load_label()


文本预处理


  1. max_sequence_length = 30

  2. embedding_size = 50


  3. # 标题分词

  4. titles = [".".join(jb.cut(t, cut_all=True)) for t in titles]


  5. # word2vec 词袋化

  6. vocab_processor = tf.contrib.learn.preprocessing.VocabularyProcessor(max_sequence_length, min_frequency=1)

  7. text_processed = np.array(list(vocab_processor.fit_transform(titles)))


  8. # 读取词标签

  9. dict = vocab_processor.vocabulary_._mapping

  10. sorted_vocab = sorted(dict.items(), key = lambda x : x[1])


构建神经网络


这里使用 Embedding 和 lstm 作为前两层,通过 softmax 激活输出结果


  1. # 配置网络结构

  2. def build_netword(num_vocabs):

  3.    # 配置网络结构

  4.    model = krs.Sequential()

  5.    model.add(krs.layers.Embedding(num_vocabs, embedding_size, input_length=max_sequence_length))

  6.    model.add(krs.layers.LSTM(32, dropout=0.2, recurrent_dropout=0.2))

  7.    model.add(krs.layers.Dense(3))

  8.    model.add(krs.layers.Activation("softmax"))

  9.    model.compile(loss="categorical_crossentropy", optimizer="adam", metrics=["accuracy"])

  10.    

  11.    return model


  12. num_vocabs = len(dict.items())

  13. model = build_netword(num_vocabs=num_vocabs)


  14. import time

  15. start = time.time()

  16. # 训练模型

  17. model.fit(text_processed, target, batch_size=512, epochs=10, )

  18. finish = time.time()

  19. print("训练耗时:%f 秒" %(finish-start))


预测样本


sen 可以换成你自己的句子,预测结果为 [健康类文章概率, 科技类文章概率, 设计类文章概率], 概率最高的为那一类的文章,但最大概率低于 0.8 时判定为无法分类的文章。


  1. sen = "做好商业设计需要学习的小技巧"

  2. sen_prosessed = " ".join(jb.cut(sen, cut_all=True))

  3. sen_prosessed = vocab_processor.transform([sen_prosessed])

  4. sen_prosessed = np.array(list(sen_prosessed))

  5. result = model.predict(sen_prosessed)


  6. catalogue = list(result[0]).index(max(result[0]))

  7. threshold=0.8

  8. if max(result[0]) > threshold:

  9.    if catalogue == 0:

  10.        print("这是一篇关于健康的文章")

  11.    elif catalogue == 1:

  12.        print("这是一篇关于科技的文章")

  13.    elif catalogue == 2:

  14.        print("这是一篇关于设计的文章")

  15.    else:

  16.        print("这篇文章没有可信分类")


原文链接: 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



本文为机器之心专栏,转载请联系本公众号获得授权

✄------------------------------------------------

加入机器之心(全职记者/实习生):hr@jiqizhixin.com

投稿或寻求报道:editor@jiqizhixin.com

广告&商务合作:bd@jiqizhixin.com

阅读8742
资源 网络 
举报0
关注机器之心微信号:almosthuman2014

用微信扫描二维码即可关注
声明

1、头条易读遵循行业规范,任何转载的稿件都会明确标注作者和来源;
2、本文内容来自“机器之心”微信公众号,文章版权归机器之心公众号所有。

评论
更多

文章来自于公众号:

机器之心

微信号:almosthuman2014

邮箱qunxueyuan#163.com(将#换成@)
微信编辑器
免责声明
www.weixinyidu.com   免责声明
版权声明:本站收录微信公众号和微信文章内容全部来自于网络,仅供个人学习、研究或者欣赏使用。版权归原作者所有。禁止一切商业用途。其中内容并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。如果您发现头条易读网站上有侵犯您的知识产权的内容,请与我们联系,我们会及时修改或删除。
本站声明:本站与腾讯微信、微信公众平台无任何关联,非腾讯微信官方网站。