Pooled GRU + FastText 实现多标签的代码阅读

背景

知识点

embeding

keras Text Preprocessing Tokenizer

keras.preprocessing.sequence.pad_sequences

keras.layers.Input

keras.layers.Embedding

keras.layers.SpatialDropout1D

keras.layers.Dense

keras.layers.Bidirectional

keras.layers.concatenate

LSTM

全链接神经网络

卷积神经网络

RNN网络

LSTM网络

GRU神经网络

keras.layers.GRU

keras.layers.GlobalAveragePooling1D

keras.layers.GlobalMaxPooling1D

keras.model.complie


背景

kaggle上多标签的一个题目,别人代码的阅读

别人Keras的地址:https://www.kaggle.com/yekenot/pooled-gru-fasttext

得分是0.983

知识点

embeding

感觉类似一个数字化的词典。主要是针对one-hot编码的几个问题,有改进:

1.资源浪费(因为词典有多少词,就有多少列,而且1个单词只有1列为1,其余都是0)

2.无法体现单词和单词之间的关系。

而embeding就解决了这2个问题:

1. 首先emdeding为每个单词分配固定长度的向量表示,目前一般大家选300

2. 单词之间的余弦相似度可以代表2个单词之间的联系

embeding的计算主要有两种方式:

1. Continuous Bag Of Words (CBOW)

2. n-gram

然后用深度模型进行训练,hider layer的维度和最终的

使用的时候,因为其实也是一个类似计算机可以认识的数字词典,所以没必要自己训练,可以直接在网上down别人训练好的,而直接使用。

参考:

词嵌入向量WordEmbedding的原理和生成方法

讲清楚embedding到底在干什么

NE(Network Embedding)论文小览,附21篇经典论文和代码 

keras Text Preprocessing Tokenizer

类的初始化和参数

keras.preprocessing.text.Tokenizer(num_words=None, filters='!"#$%&()*+,-./:;<=>?@[\]^_`{|}~ ', lower=True, split=' ', char_level=False, oov_token=None, document_count=0)

该类允许使用两种方法向量化一个文本语料库: 将每个文本转化为一个整数序列(每个整数都是词典中标记的索引); 或者将其转化为一个向量,其中每个标记的系数可以是二进制值、词频、TF-IDF权重等。

参数

  • num_words: 需要保留的最大词数,基于词频。只有最常出现的 num_words 词会被保留。
  • filters: 一个字符串,其中每个元素是一个将从文本中过滤掉的字符。默认值是所有标点符号,加上制表符和换行符,减去 ' 字符。
  • lower: 布尔值。是否将文本转换为小写。
  • split: 字符串。按该字符串切割文本。
  • char_level: 如果为 True,则每个字符都将被视为标记。
  • oov_token: 如果给出,它将被添加到 word_index 中,并用于在 text_to_sequence 调用期间替换词汇表外的单词。

默认情况下,删除所有标点符号,将文本转换为空格分隔的单词序列(单词可能包含 ' 字符)。 这些序列然后被分割成标记列表。然后它们将被索引或向量化。

0 是不会被分配给任何单词的保留索引。

成员函数

  • fit_on_text(texts) 使用一系列文档来生成token词典,texts为list类,每个元素为一个文档。
  • texts_to_sequences(texts) 将多个文档转换为word下标的向量形式,shape为[len(texts),len(text)] -- (文档数,每条文档的长度)
  • texts_to_matrix(texts) 将多个文档转换为矩阵表示,shape为[len(texts),num_words]

成员变量

  • document_count 处理的文档数量
  • word_index 一个dict,保存所有word对应的编号id,从1开始
  • word_counts 一个dict,保存每个word在所有文档中出现的次数
  • word_docs 一个dict,保存每个word出现的文档的数量
  • index_docs 一个dict,保存word的id出现的文档的数量

参考:

Keras---text.Tokenizer:文本与序列预处理

官方API文档

官方英文API文档

keras.preprocessing.sequence.pad_sequences

keras.preprocessing.sequence.pad_sequences(sequences, maxlen=None, dtype='int32', padding='pre', truncating='pre', value=0.0)

Pads sequences to the same length. 将序列填充到同一长度。

This function transforms a list of num_samples sequences (lists of integers) into a 2D Numpy array of shape (num_samples, num_timesteps). num_timesteps is either the maxlen argument if provided, or the length of the longest sequence otherwise.

将一个具有num_samples的list变成2纬的[序列长度(句子的个数),句子的长度]其中如果maxlen制定,则将一个句子统一成maxlen的长度,如果没有制定,就统一成最长的。

Sequences that are shorter than num_timesteps are padded with value at the end.如果句子的长度短于num_timesteps就补充value,默认是0.0

Sequences longer than num_timesteps are truncated so that they fit the desired length. The position where padding or truncation happens is determined by the arguments padding and truncating, respectively.如果序列长于num_timesteps就会被截断,参数padding和truncating标示那些地方会填充或被截断。

Pre-padding is the default. 默认会在前面填充

Arguments

  • sequences: List of lists, where each element is a sequence.
  • maxlen: Int, maximum length of all sequences.
  • dtype: Type of the output sequences. To pad sequences with variable length strings, you can use object.
  • padding: String, 'pre' or 'post': pad either before or after each sequence.
  • truncating: String, 'pre' or 'post': remove values from sequences larger than maxlen, either at the beginning or at the end of the sequences.
  • value: Float or String, padding value.

Returns

  • x: Numpy array with shape (len(sequences), maxlen)

Raises

  • ValueError: In case of invalid values for truncating or padding, or in case of invalid shape for a sequences entry.

参考:

官方API文档

keras.layers.Input

Input(shape=None,batch_shape=None,name=None,dtype=K.floatx(),sparse=False,tensor=None)

keras.engine.input_layer.Input()

Input() is used to instantiate a Keras tensor. 该函数用于示例化一个keras的张量

A Keras tensor is a tensor object from the underlying backend (Theano, TensorFlow or CNTK), which we augment with certain attributes that allow us to build a Keras model just by knowing the inputs and outputs of the model.解释了一下什么叫做keras tensor,其实就是基于调用theano, tensorflow或者cntk生成的。只是将这些复杂的东西封装的更简便了。

输入输出,For instance, if a, b and c are Keras tensors, it becomes possible to do: model = Model(input=[a, b], output=c)

增加了2个参数。The added Keras attributes are: _keras_shape: Integer shape tuple propagated via Keras-side shape inference. _keras_history: Last layer applied to the tensor. the entire layer graph is retrievable from that layer, recursively.

Arguments

  • shape: A shape tuple (integer), not including the batch size. For instance, shape=(32,) indicates that the expected input will be batches of 32-dimensional vectors.输入几纬的数据
  • batch_shape: A shape tuple (integer), including the batch size. For instance, batch_shape=(10, 32) indicates that the expected input will be batches of 10 32-dimensional vectors.batch_shape=(None, 32) indicates batches of an arbitrary number of 32-dimensional vectors.输入多少个几纬度的数据
  • name: An optional name string for the layer. Should be unique in a model (do not reuse the same name twice). It will be autogenerated if it isn't provided.该层的名字,不会使用第二次,没有的话自动生成
  • dtype: The data type expected by the input, as a string (float32, float64, int32...)输入的格式
  • sparse: A boolean specifying whether the placeholder to be created is sparse.
  • tensor: Optional existing tensor to wrap into the Input layer. If set, the layer will not create a placeholder tensor.

Returns

A tensor.

Example

# this is a logistic regression in Keras x = Input(shape=(32,)) y = Dense(16, activation='softmax')(x) model = Model(x, y)

参考:

官方API文档

类似于API文档的翻译

keras.layers.Embedding

嵌入层

keras.layers.Embedding(input_dim, output_dim, embeddings_initializer='uniform', embeddings_regularizer=None, activity_regularizer=None, embeddings_constraint=None, mask_zero=False, input_length=None)

Turns positive integers (indexes) into dense vectors of fixed size. eg. [[4], [20]] -> [[0.25, 0.1], [0.6, -0.2]] 将正整数数列转化为限定大小的稠密向量。

This layer can only be used as the first layer in a model. 该层只能用在第一层

Example

model = Sequential() model.add(Embedding(1000, 64, input_length=10)) # the model will take as input an integer matrix of size (batch, input_length). # the largest integer (i.e. word index) in the input should be # no larger than 999 (vocabulary size). # now model.output_shape == (None, 10, 64), where None is the batch dimension. input_array = np.random.randint(1000, size=(32, 10)) model.compile('rmsprop', 'mse') output_array = model.predict(input_array) assert output_array.shape == (32, 10, 64)

Arguments

  • input_dim: int > 0. Size of the vocabulary, i.e. maximum integer index + 1. 词典的大小
  • output_dim: int >= 0. Dimension of the dense embedding. embeding的纬度
  • embeddings_initializer: Initializer for the embeddings matrix (see initializers). 初始化embeding的矩阵
  • embeddings_regularizer: Regularizer function applied to the embeddings matrix (see regularizer).
  • activity_regularizer: Regularizer function applied to the output of the layer (its "activation"). (see regularizer).
  • embeddings_constraint: Constraint function applied to the embeddings matrix (see constraints).
  • mask_zero: Whether or not the input value 0 is a special "padding" value that should be masked out. This is useful when using recurrent layers which may take variable length input. If this is True then all subsequent layers in the model need to support masking or an exception will be raised. If mask_zero is set to True, as a consequence, index 0 cannot be used in the vocabulary (input_dim should equal size of vocabulary + 1).
  • input_length: Length of input sequences, when it is constant. This argument is required if you are going to connect Flatten then Dense layers upstream (without it, the shape of the dense outputs cannot be computed).如果要在该层后接Flatten层,然后接Dense层,则必须指定该参数,否则Dense层的输出维度无法自动推断。

Input shape

2D tensor with shape: (batch_size, sequence_length).

Output shape

3D tensor with shape: (batch_size, sequence_length, output_dim).

参考:

官方API文档

keras:3)Embedding层详解

kearas: 嵌入层的使用(讲了问什么只能在第一层,weight是什么意思)

深度学习中Embedding层有什么用?

keras.layers.SpatialDropout1D

SpatialDropout1D与Dropout的作用类似,但它断开的是整个1D特征图,而不是单个神经元。如果一张特征图的相邻像素之间有很强的相关性(通常发生在低层的卷积层中),那么普通的dropout无法正则化其输出,否则就会导致明显的学习率下降。这种情况下, SpatialDropout1D能够帮助提高特征图之间的独立性,应该用其取代普通的Dropout

参考:

Keras读书笔记----网络层(Core常用层)

SpatialDropout

Spatial Dropout(这一篇更好,上一篇参考的这一篇)

keras.layers.Dense

就是一个Core层的全联接层

keras.layers.Bidirectional

是一个包装器

keras.layers.wrappers.Bidirectional(layer, merge_mode='concat', weights=None)

双向RNN包装器

参数

layer:Recurrent对象

merge_mode:前向和后向RNN输出的结合方式,为sum,mul,concat,ave和None之一,若设为None,则返回值不结合,而是以列表的形式返回

例子

model = Sequential() model.add(Bidirectional(LSTM(10, return_sequences=True), input_shape=(5, 10))) model.add(Bidirectional(LSTM(10))) model.add(Dense(5)) model.add(Activation('softmax')) model.compile(loss='categorical_crossentropy', optimizer='rmsprop')

参考:

keras中文文档笔记9——关于keras层

Bidirectional LSTM-CRF Models for Sequence Tagging阅读笔记

keras.layers.concatenate

该层接收一个列表的同shape张量,并返回它们的按照给定轴相接构成的向量。

LSTM

全链接神经网络

N层和所有的N+1层有链接,但是相同层级之间没有链接。

这样的话不能很好的捕捉到序列信息

卷积神经网络

全联接在处理图像信息时,因为其全联接特性,会比较耗时

所以卷积是部分链接+参数共享处理这个问题。

RNN网络

输入不仅有上一层的全部信息,还有本层上一时刻的信息,这样可以捕捉到序列信息。

(感觉,虽然还是同一层之间没有链接,但是因为上一时刻的信息包含上一时刻的所有上层节点的信息,也就隐含包含了同层的信息)

但是因为最终求导的公式是连乘的方式,而sigmond和tanh都是小于1的,所以会出现梯度消失

为了防止这种梯度消失一般会用ReLU或者LSTM或GRU

LSTM网络

本质是通过改造网络结构将过去容易引起梯度消失的连乘变成了连加

将RNN的单函数,变成了3个门:遗忘门、输入门、输出门

GRU神经网络

是LSTM的一个变体之一,结构简单,效果不错

将LSTM的3个门缩减到2个门:更新门和遗忘门

参考:

循环神经网络(看下面文章的图就不会那么头晕)

LSTM神经网络

卷积神经网络

GRU神经网络

LSTM和GRU

从RNN到LSTM、GRU、语言模型

理解 LSTM 网络 (Understanding LSTM Networks by colah)

keras.layers.GRU

keras.layers.recurrent.GRU(units, activation='tanh', recurrent_activation='hard_sigmoid', use_bias=True, kernel_initializer='glorot_uniform', recurrent_initializer='orthogonal', bias_initializer='zeros', kernel_regularizer=None, recurrent_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, recurrent_constraint=None, bias_constraint=None, dropout=0.0, recurrent_dropout=0.0)

门限循环单元(详见参考文献)

参数

  • units:输出维度
  • activation:激活函数,为预定义的激活函数名(参考激活函数
  • use_bias: 布尔值,是否使用偏置项
  • kernel_initializer:权值初始化方法,为预定义初始化方法名的字符串,或用于初始化权重的初始化器。参考initializers
  • recurrent_initializer:循环核的初始化方法,为预定义初始化方法名的字符串,或用于初始化权重的初始化器。参考initializers
  • bias_initializer:权值初始化方法,为预定义初始化方法名的字符串,或用于初始化权重的初始化器。参考initializers
  • kernel_regularizer:施加在权重上的正则项,为Regularizer对象
  • bias_regularizer:施加在偏置向量上的正则项,为Regularizer对象
  • recurrent_regularizer:施加在循环核上的正则项,为Regularizer对象
  • activity_regularizer:施加在输出上的正则项,为Regularizer对象
  • kernel_constraints:施加在权重上的约束项,为Constraints对象
  • recurrent_constraints:施加在循环核上的约束项,为Constraints对象
  • bias_constraints:施加在偏置上的约束项,为Constraints对象
  • dropout:0~1之间的浮点数,控制输入线性变换的神经元断开比例
  • recurrent_dropout:0~1之间的浮点数,控制循环状态的线性变换的神经元断开比例
  • 其他参数参考Recurrent的说明

参考文献

keras.layers.GlobalAveragePooling1D

平均值池化

pooling的结果是使得特征减少,参数减少,但pooling的目的并不仅在于此。pooling目的是为了保持某种不变性(旋转、平移、伸缩等),常用的有mean-pooling,max-pooling和Stochastic-pooling三种。

根据相关理论,特征提取的误差主要来自两个方面:

(1)邻域大小受限造成的估计值方差增大;

(2)卷积层参数误差造成估计均值的偏移。

一般来说,mean-pooling能减小第一种误差,更多的保留图像的背景信息,max-pooling能减小第二种误差,更多的保留纹理信息。

Stochastic-pooling则介于两者之间,通过对像素点按照数值大小赋予概率,再按照概率进行亚采样,在平均意义上,与mean-pooling近似,在局部意义上,则服从max-pooling的准则。

参考:

简述平均池化和最大池化

cnn中关于平均池化和最大池化的理解

深度学习基础系列(十)| Global Average Pooling是否可以替代全连接层?

keras.layers.GlobalMaxPooling1D

最大值池化

keras.model.complie

compile(self, optimizer, loss, metrics=[], loss_weights=None, sample_weight_mode=None)

本函数编译模型以供训练,参数有

  • optimizer:优化器,为预定义优化器名或优化器对象,参考优化器
  • loss:目标函数,为预定义损失函数名或一个目标函数,参考目标函数
  • metrics:列表,包含评估模型在训练和测试时的性能的指标,典型用法是metrics=['accuracy']如果要在多输出模型中为不同的输出指定不同的指标,可像该参数传递一个字典,例如metrics={'ouput_a': 'accuracy'}
  • sample_weight_mode:如果你需要按时间步为样本赋权(2D权矩阵),将该值设为“temporal”。默认为“None”,代表按样本赋权(1D权)。如果模型有多个输出,可以向该参数传入指定sample_weight_mode的字典或列表。在下面fit函数的解释中有相关的参考内容。
  • kwargs:使用TensorFlow作为后端请忽略该参数,若使用Theano作为后端,kwargs的值将会传递给 K.function

【Tips】如果你只是载入模型并利用其predict,可以不用进行compile。在Keras中,compile主要完成损失函数和优化器的一些配置,是为训练服务的。predict会在内部进行符号函数的编译工作(通过调用_make_predict_function生成函数)

参看:

keras model.compile(loss='目标函数 ', optimizer='adam', metrics=['accuracy'])

深度学习笔记 目标函数的总结与整理

 

 

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
FastText是Facebook开发的一种文本分类算法,它通过将文本分解成n-gram特征来表示文本,并基于这些特征训练模型。PyTorch是一个流行的深度学习框架,可以用于实现FastText文本分类算法。 以下是使用PyTorch实现FastText文本分类的基本步骤: 1. 数据预处理:将文本数据分成训练集和测试集,并进行预处理,如分词、去除停用词、构建词典等。 2. 构建数据集:将预处理后的文本数据转换成PyTorch中的数据集格式,如torchtext中的Dataset。 3. 定义模型:使用PyTorch定义FastText模型,模型包括嵌入层、平均池化层和全连接层。 4. 训练模型:使用训练集训练FastText模型,并在验证集上进行验证调整超参数。 5. 测试模型:使用测试集评估训练好的FastText模型的性能。 以下是一个简单的PyTorch实现FastText文本分类的示例代码: ```python import torch import torch.nn as nn import torch.optim as optim from torchtext.legacy.data import Field, TabularDataset, BucketIterator # 数据预处理 TEXT = Field(tokenize='spacy', tokenizer_language='en_core_web_sm', include_lengths=True) LABEL = Field(sequential=False, dtype=torch.float) train_data, test_data = TabularDataset.splits( path='data', train='train.csv', test='test.csv', format='csv', fields=[('text', TEXT), ('label', LABEL)] ) TEXT.build_vocab(train_data, max_size=25000, vectors="glove.6B.100d") LABEL.build_vocab(train_data) # 定义模型 class FastText(nn.Module): def __init__(self, vocab_size, embedding_dim, output_dim): super().__init__() self.embedding = nn.Embedding(vocab_size, embedding_dim) self.fc = nn.Linear(embedding_dim, output_dim) def forward(self, x): embedded = self.embedding(x) pooled = embedded.mean(0) output = self.fc(pooled) return output # 训练模型 BATCH_SIZE = 64 device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') train_iterator, test_iterator = BucketIterator.splits( (train_data, test_data), batch_size=BATCH_SIZE, sort_within_batch=True, device=device ) model = FastText(len(TEXT.vocab), 100, 1).to(device) optimizer = optim.Adam(model.parameters()) criterion = nn.BCEWithLogitsLoss().to(device) for epoch in range(10): for batch in train_iterator: text, text_lengths = batch.text labels = batch.label optimizer.zero_grad() output = model(text).squeeze(1) loss = criterion(output, labels) loss.backward() optimizer.step() with torch.no_grad(): total_loss = 0 total_correct = 0 for batch in test_iterator: text, text_lengths = batch.text labels = batch.label output = model(text).squeeze(1) loss = criterion(output, labels) total_loss += loss.item() predictions = torch.round(torch.sigmoid(output)) total_correct += (predictions == labels).sum().item() acc = total_correct / len(test_data) print('Epoch:', epoch+1, 'Test Loss:', total_loss / len(test_iterator), 'Test Acc:', acc) ``` 这个示例代码使用了torchtext库来处理数据集,并定义了一个FastText模型,模型包括一个嵌入层、一个平均池化层和一个全连接层。模型在训练集上训练,并在测试集上进行测试,并输出测试集的损失和准确率。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值