“达观杯”文本智能处理挑战赛

比赛链接
数据介绍:
数据

*注 : 报名参赛或加入队伍后,可获取数据下载权限。
数据包含2个csv文件:

  • train_set.csv:此数据集用于训练模型,每一行对应一篇文章。文章分别在“字”和“词”的级别上做了脱敏处理。共有四列:
    第一列是文章的索引(id),第二列是文章正文在“字”级别上的表示,即字符相隔正文(article);第三列是在“词”级别上的表示,即词语相隔正文(word_seg);第四列是这篇文章的标注(class)。
    注:每一个数字对应一个“字”,或“词”,或“标点符号”。“字”的编号与“词”的编号是独立的!

  • test_set.csv:此数据用于测试。数据格式同train_set.csv,但不包含class。
    注:test_set与train_test中文章id的编号是独立的。

1.读取数据

import pandas as pd
train_data = pd.read_csv(r"F:\NLP\比赛\“达观杯”文本智能处理挑战赛\new_data\train_set.csv")
# test_data = pd.read_csv(r"F:\NLP\比赛\“达观杯”文本智能处理挑战赛\new_data\test_set.csv")

2.查看数据结构

train_data.columns

Index(['id', 'article', 'word_seg', 'class'], dtype='object')

查看文本有多少类

train_data["class"].unique()
array([14,  3, 12, 13,  1, 10, 19, 18,  7,  9,  4, 17,  2,  8,  6, 11, 15,
        5, 16], dtype=int64)

数字描述的总共有16类

3.思路

构建词向量

数据预处理

TF-IDF

F-IDF是一种统计方法,用以评估一字词对于一个文件集或一个语料库中的其中一份文件的重要程度。字词的重要性随着它在文件中出现的次数成正比增加,但同时会随着它在语料库中出现的频率成反比下降。 TF-IDF加权的各种形式常被搜寻引擎应用,作为文件与用户查询之间相关程度的度量或评级。
TF-IDF有两层意思,一层是"词频"(Term Frequency,缩写为TF),另一层是"逆文档频率"(Inverse Document Frequency,缩写为IDF)。
在一份给定的文件里,词频 (term frequency, TF) 指的是某一个给定的词语在该文件中出现的次数。
逆向文件频率 (inverse document frequency, IDF) 是一个词语普遍重要性的度量
词频(TF)= \frac{词在文章中出现的次数}{文章的总词数}
逆文档频率(IDF)=log(\frac{语料库中文档总数}{包含该词的文档数+1}) 其中+1是平滑项
TF-IDF = 词频(TF)* 逆文档(IDF)
在sklearn中的应用

vectorizer = TfidfVectorizer(ngram_range=(1, 2), min_df=3, max_df=0.9, sublinear_tf=True)
vectorizer.fit(df_all['word_seg'])
x_train = vectorizer.transform(df_train['word_seg'])
x_test = vectorizer.transform(df_test['word_seg'])

Word2vec词向量

参考
词向量(word embedding):
用一个向量表示一个词,机器学习任务需要把任何输入量化成数值表示(稠密向量DenseVector),然后通过充分利用计算机的计算能力,计算得到最终的结果,词向量的一种表达形式为one-hot

CBOW(continuous bag of words)和skip-gram
这是word2vec的两种模式,CBOW是根据目标单词所在的原始语句的上下文来推测目标单词本身,而skip-gram则是利用该目标单词推测原始语句信息也就是上下文

词向量的获取方法

基于奇异值分解的方法:

  • 单词-文档矩阵
    基于的假设:
    相关词往往出现在同一文档中,例如,banks和bonds,stocks,money 更相关常出现在一篇文档中,而banks 和octous,banana,hockey 不太可能同时出现在一起, 因此可以建立词和文档的矩阵,通过对此矩阵做奇异值分解,可以获取词的向量表示.
  • 单词-单词矩阵
    基于的假设:
    一个词的含义由上下文信息决定,那么两个词之间的上下文相似,是否可推测二者非常相似.设定上下文窗口,统计建立词和词之间的共现矩阵,通过对矩阵做奇异值分解获得词向量

基于迭代的方法:

目前基于迭代的方法获取词向量大多是基于语言模型的训练得到的,对于一个合理的句子,希望语言模型能够给予一个较大的概率,同理,对于一个不合理的句子,给予较小的概率评估,具体的形式化表示如下:
P(w^1w^2...w^n) = \prod_{i=1}^{n} p(w^i)
第一个公式:一元语言模型,假设当前词的概率只和自己有关;
第二个公式: 二元语言模型,假设当前词的概率和前一个词有关.那么问题来了,如何从语料库中学习给定上下文预测当前词的概率值呢?
就是使用我们上面说的两种模式:CBOW与skip-gram

gensim的使用 实现word2vec

1.安装

# 依赖环境
python>=2.6
NumPy>=1.3
Scipy>=0.7
## 开始安装
pip install gensim

2 参数介绍

word2vec(sentences=None, size=100, alpha=0.025, window=5, min_count=5, max_vocab_size=None, sample=1e-3, seed=1, workers=3, min_alpha=0.0001,sg=0, hs=0, negative=5, cbow_mean=1, hashfxn=hash, iter=5, null_word=0,trim_rule=None, sorted_vocab=1, batch_words=MAX_WORDS_IN_BATCH, compute_loss=False)

    sg defines the training algorithm. By default (sg=0), CBOW is used.Otherwise (sg=1), skip-gram is employed.
    size is the dimensionality of the feature vectors.
    window is the maximum distance between the current and predicted word within a sentence.
    alpha is the initial learning rate (will linearly drop to min_alpha as training progresses).
    seed = for the random number generator. Initial vectors for eachword are seeded with a hash of the concatenation of word + str(seed).Note that for a fully deterministically-reproducible run, you must also limit the model toa single worker thread, to eliminate ordering jitter from OS thread scheduling. (In Python3, reproducibility between interpreter launches also requires use of the PYTHONHASHSEEDenvironment variable to control hash randomization.)
    min_count = ignore all words with total frequency lower than this.
    max_vocab_size = limit RAM during vocabulary building; if there are more uniquewords than this, then prune the infrequent ones. Every 10 million word typesneed about 1GB of RAM. Set to
    None for no limit (default).
    sample = threshold for configuring which higher-frequency words are randomly downsampled;    default is 1e-3, useful range is (0, 1e-5).
    workers = use this many worker threads to train the model (=faster training with multicore machines).hs = if 1, hierarchical softmax will be used for model training.If set to 0 (default), and
    negative is non-zero, negative sampling will be used.negative = if > 0, negative sampling will be used, the int for negativespecifies how many "noise words" should be drawn (usually between 5-20).Default is 5. If set to 0, no negative samping is used.
    cbow_mean = if 0, use the sum of the context word vectors. If 1 (default), use the mean.Only applies when cbow is used.
    hashfxn = hash function to use to randomly initialize weights, for increasedtraining reproducibility. Default is Python's rudimentary built in hash function.
    iter = number of iterations (epochs) over the corpus. Default is 5.
    trim_rule = vocabulary trimming rule, specifies whether certain words should remainin the vocabulary, be trimmed away, or handled using the default (discard if word count < min_count).Can be None (min_count will be used), or a callable that accepts parameters (word, count, min_count) andreturns either utils.RULE_DISCARD, utils.RULE_KEEP or utils.RULE_DEFAULT.Note: The rule, if given, is only used to prune vocabulary during build_vocab() and is not stored as partof the model.
    sorted_vocab = if 1 (default), sort the vocabulary by descending frequency beforeassigning word indexes.
    batch_words= target size (in words) for batches of examples passed to worker threads (andthus cython routines). Default is 10000. (Larger batches will be passed if individualtexts are longer than 10000 words, but the standard cython code truncates to that maximum.)

1.sg=1是skip-gram算法,对低频词敏感;默认sg=0为CBOW算法。

2.size是输出词向量的维数,值太小会导致词映射因为冲突而影响结果,值太大则会耗内存并使算法计算变慢,一般值取为100到200之间。

3.window是句子中当前词与目标词之间的最大距离,3表示在目标词前看3-b个词,后面看b个词(b在0-3之间随机)。

4.min_count是对词进行过滤,频率小于min-count的单词则会被忽视,默认值为5。

5.negative和sample可根据训练结果进行微调,sample表示更高频率的词被随机下采样到所设置的阈值,默认值为1e-3。

6.hs=1表示层级softmax将会被使用,默认hs=0且negative不为0,则负采样将会被选择使用。

7.workers控制训练的并行,此参数只有在安装了Cpython后才有效,否则只能使用单核

使用代码

import gensim.models as g
from gensim.models.word2vec import LineSentence
'''Word2vec的输入是一个LineSentence的迭代器,即我们需要将原始的训练语料转化成一个sentence的迭代器;每一次迭代返回的sentence是一个word(utf8格式)的列表。我们再用这个迭代器作为输入,构造一个Gensim内建的word2vec模型的对象。
'''
# data/Corpus.txt为输入的文件
model=g.Word2Vec(LineSentence('data/Corpus.txt'),size=100,window=1,min_count=1)

#--------------------------------------------------
# 将训练的词向量结果保存至data/vectors.bin文件,一般将文件保存为二进制文件,方便以后做研究用。
model.save('data/vectors.bin')
# 为了方便查看训练的词向量结果,也可以将训练的结果保存至data/vectors.txt文本文件。
model.wv.save_word2vec_format('data/vectors.txt', binary=False)

4.使用knn进行预测

from sklearn.model_selection import train_test_split
train_voc,test_voc, train_y, test_y = train_test_split(voc,label,test_size=0.1,shuffle=True)
vectorizer = HashingVectorizer(stop_words='english', non_negative=True,
                                       n_features=10000)
fea_train = vectorizer.fit_transform(train_voc)
fea_test = vectorizer.fit_transform(test_voc)
knnclf = KNeighborsClassifier()
knnclf.fit(fea_train, train_y)
precdict = knnclf.predict(fea_test)

评价函数 :

from sklearn import metrics
def get_score(actual, pred):
    """
    :param actual:真实值
    :param pred:预测值
    :return:
    """
    m_precision = metrics.precision_score(actual, pred,average=None)
    m_recall = metrics.recall_score(actual, pred, average=None)
    m_f1 = metrics.f1_score(actual, pred,average=None)
    return m_precision, m_recall, m_f1
m_precision, m_recall, m_f1 = get_score(train_y,precdict)

结果:
准确率:
array([0.37407953, 0.38492063, 0.61172902, 0.76487252, 0.75113122,
0.88423154, 0.53184713, 0.59090909, 0.82114883, 0.61748634,
0.57777778, 0.55202312, 0.48722317, 0.75415282, 0.88945578,
0.52380952, 0.64822134, 0.81324278, 0.34197731])
整体准确率:
0.645804050307131
召回率:
array([0.46098004, 0.69039146, 0.7202381 , 0.71808511, 0.66135458,
0.66020864, 0.52351097, 0.67651195, 0.86282579, 0.45934959,
0.65 , 0.36380952, 0.71055901, 0.65512266, 0.68997361,
0.2483871 , 0.53770492, 0.66251729, 0.39962121])
0.6198670316777474
F1:
array([0.41300813, 0.49426752, 0.6615637 , 0.74074074, 0.70338983,
0.7559727 , 0.52764613, 0.63081967, 0.84147157, 0.52680653,
0.61176471, 0.43857635, 0.57806973, 0.7011583 , 0.77711738,
0.33698031, 0.58781362, 0.73018293, 0.36855895])
0.6228989846281351

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,175评论 5 466
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,674评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,151评论 0 328
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,597评论 1 269
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,505评论 5 359
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 47,969评论 1 275
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,455评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,118评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,227评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,213评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,214评论 1 328
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,928评论 3 316
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,512评论 3 302
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,616评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,848评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,228评论 2 344
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,772评论 2 339

推荐阅读更多精彩内容