zoukankan      html  css  js  c++  java
  • BI-LSTM and CRF using Keras

    问题1:CUDA_ERROR_OUT_OF_MEMORY: How to activate multiple GPUs from Keras in Tensorflow

    import keras.backend as K
    
    config = K.tf.ConfigProto()
    config.gpu_options.allow_growth = True
    session = K.tf.Session(config=config)

    讀作者的code就能了解數據的格式了。
    在process_data.py檔案裡。

    稍微解釋一下。

    ###原始數據###
    老 B-PER
    王 I-PER
    很 O
    喜 O
    歡 O
    中 B-LOC
    國 I-LOC
    妹 O
    子 O

    ###要丟進LSTM的數據###
    X_train應該是長這樣[0, 1, 15, 24, 65, 102, 103, 54, 63]之類的,這裡代表每個字的index。
    y_train應該是長這樣 [1, 2, 0, 0, 0, 3, 4, 0, 0]之類的,代表對應到的字的NE。
    最後再把每個句子做個padding就能丟進LSTM了。

    至於怎麼轉換成數據序列的,就請您自行研究研究process_data.py唄!

     
    配置显存
    https://www.jianshu.com/p/99fca5b7fd8a

    ==================================
    使用预训练词向量
    =================================

    Keras 模型中使用预训练的词向量

    Word2vec,为一群用来产生词嵌入的相关模型。这些模型为浅而双层的神经网络,用来训练以重新建构语言学之词文本。网络以词表现,并且需猜测相邻位置的输入词,在word2vec中词袋模型假设下,词的顺序是不重要的。训练完成之后,word2vec模型可用来映射每个词到一个向量,可用来表示词对词之间的关系。该向量为神经网络之隐藏层。
    https://zh.wikipedia.org/wiki/Word2vec

    在这篇 在Keras模型中使用预训练的词向量 讲述了如何利用预先训练好的 GloVe 模型,本文基本大同小异。只写一些不同的地方,更想的可以看这篇文章。

    总体思路就是给 Embedding 层提供一个 [ word_token : word_vector] 的词典来初始化向量,并且标记为不可训练。

    解析 word2vec 模型,其中:

    • word2idx 保存词语和 token 的对应关系,语料库 tokenize 时候需要。
    • embeddings_matrix 存储所有 word2vec 中所有向量的数组,用于初始化模型 Embedding 层
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    import numpy as np
    from gensim.models import Word2Vec


    model = Word2Vec.load(model_path)

    word2idx = {"_PAD": 0} # 初始化 `[word : token]` 字典,后期 tokenize 语料库就是用该词典。

    vocab_list = [(k, model.wv[k]) for k, v in model.wv.vocab.items()]

    # 存储所有 word2vec 中所有向量的数组,留意其中多一位,词向量全为 0, 用于 padding
    embeddings_matrix = np.zeros((len(model.wv.vocab.items()) + 1, model.vector_size))
    for i in range(len(vocab_list)):
    word = vocab_list[i][0]
    word2idx[word] = i + 1
    embeddings_matrix[i + 1] = vocab_list[i][1]

    使用方法:

    1
    2
    3
    4
    5
    6
    7
    8
    from keras.layers import Embedding

    EMBEDDING_DIM = 100 #词向量维度

    embedding_layer = Embedding(len(embeddings_matrix),
    EMBEDDING_DIM,
    weights=[embeddings_matrix]
    trainable=False)
     
  • 相关阅读:
    file is universal (3 slices) but does not contain a(n) armv7s slice error for static libraries on iOS
    WebImageButton does not change images after being enabled in Javascript
    ajax OPTION
    编程遍历页面上所有TextBox控件并给它赋值为string.Empty?
    获取海洋天气预报
    C#线程系列教程(1):BeginInvoke和EndInvoke方法
    js控制只能输入数字和小数点
    Response.AddHeader(,)
    ManualResetEvent的理解
    Convert.ToInt32、int.Parse(Int32.Parse)、int.TryParse、(int) 区别
  • 原文地址:https://www.cnblogs.com/yjybupt/p/10333831.html
Copyright © 2011-2022 走看看