美文网首页
tensorflow自然语言处理-词袋模型文本分类

tensorflow自然语言处理-词袋模型文本分类

作者: 夜尽天明时 | 来源:发表于2017-06-06 15:41 被阅读0次

写在前面

  • 态度决定高度!让优秀成为一种习惯!
  • 世界上没有什么事儿是加一次班解决不了的,如果有,就加两次!(- - -茂强)

词袋模型文本分类

  • 数据准备
    如图数据
数据准备
  • 数据清晰
    数据读取与清晰,这里只过滤出中文,并且两个字以上的词
    target = [] #存储句子的正负面标签,1代表正面,0代表负面
    texts = [] #存储句子
    with open("c:/traindatav.txt", "r", encoding="utf-8") as f:
    for line in f.readlines():
    text = line.split(" => ")
    if len(text) == 2:
    lable = text[0].strip()
    sentence = " ".join([w for w in text[1].split(" ") if re.match("[\u4e00-\u9fa5]+", w) and len(w) >= 2])
    if lable == "正面":
    target.append(1)
    else:
    target.append(0)
    texts.append(sentence)
    最后得到texts和target连个list
texts target
  • 句子的长度不能过长,因此我们需要确定一个最大的句子长度,这样我们需要看一下句子长度的分布是如何的

    text_lengths = [len(x.split()) for x in texts]
    text_lengths = [x for x in text_lengths if x < 100]
    plt.hist(text_lengths, bins=25)
    plt.title('Histogram of # of Words in Texts')
    plt.show()
    

如图:

句子长度分布

从图上可以看出,长度取60时已经涵盖了大部分的句子
因此声明

  sentence_size = 60
  min_word_freq = 3
  • 清晰地数据转化成tensorflow能够接受的数据,这一点,在tensorflow中在 learn.preprocessing包下有一个内置函数VocabularyProcessor()
    vocab_processor = learn.preprocessing.VocabularyProcessor(sentence_size, min_frequency=min_word_freq)
    vocab_processor.fit_transform(texts)
    vocab_processor.vocabulary_
    我们来看一下,vocab_processor.vocabulary_中到底是什么
数据转化

其中_ferq这个就是词频的统计dict

_freq

其中_mapping是一个对每个词编辑一个索引

_mapping

还有一个

_reverse_mapping

就是上一个的reverse,只不过用了list表示
其他的就不解释了

  • 把数据集分成训练集于测试集
    train_indices = np.random.choice(len(texts), round(len(texts)*0.8), replace=False)
    test_indices = np.array(list(set(range(len(texts))) - set(train_indices)))
    texts_train = [x for ix, x in enumerate(texts) if ix in train_indices]
    texts_test = [x for ix, x in enumerate(texts) if ix in test_indices]
    target_train = [x for ix, x in enumerate(target) if ix in train_indices]
    target_test = [x for ix, x in enumerate(target) if ix in test_indices]
    解释一个数据内容
texts_train target_train
  • 声明一个embedding矩阵
    identity_mat = tf.diag(tf.ones(shape=[embedding_size]))

  • 然后声明各logistic回归的变量和placeholder
    A = tf.Variable(tf.random_normal(shape=[embedding_size,1]))
    b = tf.Variable(tf.random_normal(shape=[1,1]))
    # Initialize placeholders
    x_data = tf.placeholder(shape=[sentence_size], dtype=tf.int32)
    y_target = tf.placeholder(shape=[1, 1], dtype=tf.float32)

  • 不得不说的tf.nn.embedding_lookup函数
    其实embedding_lookup的原理很简单,相当于在np.array中直接采用下标数组获取数据。细节是返回的tensor的dtype和传入的被查询的tensor的dtype保持一致;和ids的dtype无关。
    下面看个例子

    import tensorflow as tf 
    import numpy as np
    sess = tf.InteractiveSession()
    mat1 = tf.reshape(tf.range(1, 10, name="m1"), shape=[3, 3])
     [[1, 2, 3],
     [4, 5, 6],
     [7, 8, 9]]
    ids = [[1,2], [0,1]]
    res = tf.nn.embedding_lookup(mat1, ids)
    res.eval()
    
结果

从上边的例子看出, ids = [[1,2], [0,1]]决定要取矩阵的哪一行数据

  • 不得不说的tf.reduce_sum函数
    还是老规矩,先看例子

    # 'x' is [[1, 1, 1]
    #         [1, 1, 1]]
    tf.reduce_sum(x) ==> 6
    tf.reduce_sum(x, 0) ==> [2, 2, 2]
    tf.reduce_sum(x, 1) ==> [3, 3]
    tf.reduce_sum(x, 1, keep_dims=True) ==> [[3], [3]]
    tf.reduce_sum(x, [0, 1]) ==> 6
    

例子看完我想你就明白了吧

  • 下面就是如何把一个句子转成向量了
    x_embed = tf.nn.embedding_lookup(identity_mat, x_data)
    x_col_sums = tf.reduce_sum(x_embed, 0)
    首先是根据diag生成的one-hot矩阵,根据输入的x_data(也就是每个句子中每个词的索引向量),比如“我们 是 中国人”在vocab_processor.vocabulary_中的_mapping中的索引分别是[20, 3, 134]
    那么embedding_lookup会从diag矩阵中找到对应的行号(20,3,134)行的数据,也就是每个词的词向量,然后再reduce_sum注意参数0我们可以从以上例子中看到,其实就是把每个词的向量按index相加,就生成该句子的向量,而对应的20,3,134列的数字就是1其他都是0
    所以x_col_sums就代表一个句子向量

    # 't' is a tensor of shape [2]
    shape(expand_dims(t, 0)) ==> [1, 2]
    shape(expand_dims(t, 1)) ==> [2, 1]
    shape(expand_dims(t, -1)) ==> [2, 1]
    
    # 't2' is a tensor of shape [2, 3, 5]
    shape(expand_dims(t2, 0)) ==> [1, 2, 3, 5]
    shape(expand_dims(t2, 2)) ==> [2, 3, 1, 5]
    shape(expand_dims(t2, 3)) ==> [2, 3, 5, 1]
    

如果看不明白,就用一个例子来看
labels = [1,2,3]
x = tf.expand_dims(labels, 0)
[[1 2 3]] #结果增加了一个维度
x = tf.expand_dims(labels, 1)
[[1]
[2]
[3]]
看了上边的例子就能够有个理解了

  • 变换与计算
    x_col_sums_2D = tf.expand_dims(x_col_sums, 0)
    model_output = tf.add(tf.matmul(x_col_sums_2D, A), b)
    首先把x_col_sums按照0方式变换增加一维,主要是为了矩阵运算,然后计算y=AX+B

  • 然后定义损失函数
    loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(model_output, y_target))
    其实就是逻辑回归表达式

  • 然后定义激活函数
    prediction = tf.sigmoid(model_output)

  • 接下来就是优化算法
    my_opt = tf.train.GradientDescentOptimizer(0.001)
    train_step = my_opt.minimize(loss)

  • 紧接着就是参数初始化
    init = tf.initialize_all_variables()
    sess.run(init)

  • 接着对所有的句子进行迭代训练
    loss_vec = []
    train_acc_all = []
    train_acc_avg = []
    for ix, t in enumerate(vocab_processor.fit_transform(texts_train)):y_data = [[target_train[ix]]]
    sess.run(train_step, feed_dict={x_data: t, y_target: y_data})
    temp_loss = sess.run(loss, feed_dict={x_data: t, y_target: y_data})
    loss_vec.append(temp_loss)
    if (ix+1)%10==0:
    print('Training Observation #' + str(ix+1) + ': Loss = ' +str(temp_loss))
    # Keep trailing average of past 50 observations accuracy
    # Get prediction of single observation
    [[temp_pred]] = sess.run(prediction, feed_dict={x_data:t, y_target:y_data})
    # Get True/False if prediction is accurate
    train_acc_temp = target_train[ix]==np.round(temp_pred)
    train_acc_all.append(train_acc_temp)
    if len(train_acc_all) >= 50:
    train_acc_avg.append(np.mean(train_acc_all[-50:]))
    loss_vec存放的是每次训练的损失值,train_acc_all存放的是所有的acc值,train_acc_avg存放的是每50次的平均acc值
    声明一点,这里是对每一个句子进行迭代的,而不是批计算的

  • 最后就是测试
    print('Getting Test Set Accuracy')
    test_acc_all = []
    for ix, t in enumerate(vocab_processor.fit_transform(texts_test)):
    y_data = [[target_test[ix]]]
    if (ix+1)%50==0:
    print('Test Observation #' + str(ix+1))
    # Keep trailing average of past 50 observations accuracy
    # Get prediction of single observation
    [[temp_pred]] = sess.run(prediction, feed_dict={x_data:t,y_target:y_data})
    # Get True/False if prediction is accurate
    test_acc_temp = target_test[ix]==np.round(temp_pred)
    test_acc_all.append(test_acc_temp)
    print('\nOverall Test Accuracy: {}'.format(np.mean(test_acc_all)))

相关文章

  • nlp面试题大全

    自然语言处理面试题 有哪些文本表示模型,它们各有什么优缺点? 词袋模型与N-gram  最基本的文本表示模型是词袋...

  • tensorflow自然语言处理-词袋模型文本分类

    写在前面 态度决定高度!让优秀成为一种习惯! 世界上没有什么事儿是加一次班解决不了的,如果有,就加两次!(- - ...

  • 词袋模型BoW和词集模型SoW

    Bag-of-Words词袋模型,经常用在自然语言处理和信息检索当中.在词袋模型中,一篇文本(文章)被表示成"装着...

  • Explicit Interaction Model towar

    文本分类的显式交互模型 摘要   文本分类是自然语言处理的基本任务之一。最近,与浅模型相比,深度神经网络在文本分类...

  • 文本分类V1

    outline 什么是文本分类 特征工程+分类器 TextCNN 什么是文本分类 文本分类是自然语言处理的一个基本...

  • 词袋模型(新闻文本分类)

    我们要用词袋模型进行文本分类,训练模型大致可以分为两步:第一步,用TF-IDF表示文本特征;第二步,把TF-IDF...

  • NLP 学习3

    Task3 基于机器学习的文本分类 文本表示方式 one-hot Bags of Words 词袋模型1.若采用只...

  • 机器学习之CreateML使用(二)

    上篇文章, 我们介绍了 CreateML 制作图片分类模型, 在这篇文章里我们研究一下自然语言处理中的文本分类, ...

  • NLP常用专业术语

    常用概念: 自然语言处理(NLP) 数据挖掘 推荐算法 用户画像 知识图谱 信息检索 文本分类 常用技术: 词级别...

  • 文本分类;数据增强;模型微调 2020-02-25

    文本分类 文本情感分类数据集 使用循环神经网络进行情感分类 使用卷积神经网络进行情感分类文本分类是自然语言处理的一...

网友评论

      本文标题:tensorflow自然语言处理-词袋模型文本分类

      本文链接:https://www.haomeiwen.com/subject/ntixfxtx.html