使用word2vec训练词向量

使用word2vec无监督学习训练词向量,输入的是训练数据和测试数据,输出的是每个词的词向量,总共三百个词左右。

求和:然后再将每行数据中的每个词的词向量加和,得到每行的词向量表示。

其他还可以通过求平均,求众数或者最大值等等方法得到每行的词向量表示。

代码如下:

import time
import csv
import pickle
import numpy as np
import xgboost as xgb
from sklearn.model_selection import StratifiedKFold
from sklearn.feature_extraction.text import CountVectorizer
from gensim.models.word2vec import Word2Vec
import warnings warnings.filterwarnings('ignore') # 忽略警告
with open("security_train.csv.pkl", "rb") as f:
labels = pickle.load(f)
files = pickle.load(f) with open("security_test.csv.pkl", "rb") as f:
file_names = pickle.load(f)
outfiles = pickle.load(f)

训练词向量模型的方法:

def train_w2v_model(files, size, model, flag):
for batch in range(int(len(files)/size) + 1):
sentences = []
print("batch:", batch)
if batch != int(len(files)/size):
for i in range(batch*size, size*(batch+1)):
sentence = files[i].split(' ')
sentences.append(sentence)
else:
for i in range(size*(batch+1), len(files)):
sentence = files[i].split(' ')
sentences.append(sentence) sentences = np.array(sentences) if batch == 0 and flag == True:
model.build_vocab(sentences)
else:
model.build_vocab(sentences, update=True) model.train(sentences, total_examples = model.corpus_count, epochs = model.epochs) print("done.")
return model
# 训练词向量
model = Word2Vec()
model = train_w2v_model(files, 1000, model, True)
model = train_w2v_model(outfiles, 1000, model, False)
model.save('./temp/w2cmodel_train_test')
# model = Word2Vec.load('./temp/w2cmodel0')
print(model)

对每行数据求词向量之和的方法:

def train_sum_vec(files, model, size=100):
rtvec = []
for i in range(len(files)):
if i % 100 == 0:
print(i)
text = files[i].split(' ')
# 对每个句子的词向量进行求和计算
vec = np.zeros(size).reshape((1, size))
for word in text:
try:
vec += model[word].reshape((1, size))
except KeyError:
continue
rtvec.append(vec) train_vec = np.concatenate(rtvec)
return train_vec

得到训练数据的词向量:

# 将词向量保存为 Ndarray
train_vec = train_sum_vec(files, model)
# 保存 Word2Vec 模型及词向量
model.save('w2v_model.pkl')
np.save('X_train_test_vec.npy', train_vec)
print('done.')

得到测试数据的词向量:

test_vec = train_sum_vec(outfiles, model)
np.save('y_test_vec.npy', test_vec)
print('done.')

xgboost训练:

meta_train = np.zeros(shape=(len(files), 8))
meta_test = np.zeros(shape=(len(outfiles), 8)) k = 10
skf = StratifiedKFold(n_splits=k, random_state=42, shuffle=True)
X_vector = np.load('X_train_test_vec.npy')
y_vector = np.load('y_test_vec.npy')
for i, (tr_ind, te_ind) in enumerate(skf.split(X_vector, labels)):
X_train, X_train_label = X_vector[tr_ind], labels[tr_ind]
X_val, X_val_label = X_vector[te_ind], labels[te_ind] print('FOLD: {}'.format(str(i)))
print(len(tr_ind), len(te_ind)) dtrain = xgb.DMatrix(X_train, label=X_train_label)
dtest = xgb.DMatrix(X_val, X_val_label)
dout = xgb.DMatrix(y_vector) param = {'max_depth': 6, 'eta': 0.1, 'eval_metric': 'mlogloss', 'silent': 1, 'objective': 'multi:softprob',
'num_class': 8, 'subsample': 0.8, 'colsample_bytree': 0.85} evallist = [(dtrain, 'train'), (dtest, 'val')] # 测试 , (dtrain, 'train')
num_round = 300 # 循环次数
bst = xgb.train(param, dtrain, num_round, evallist, early_stopping_rounds=50) # dtr = xgb.DMatrix(train_features)
pred_val = bst.predict(dtest)
pred_test = bst.predict(dout)
meta_train[te_ind] = pred_val
meta_test += pred_test meta_test /= 10.0
with open("word2vec_result_{}.pkl".format(
str(time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime()))),
'wb') as f:
pickle.dump(meta_train, f)
pickle.dump(meta_test, f)
result = meta_test
out = [] for i in range(len(file_names)):
tmp = []
a = result[i].tolist()
tmp.append(file_names[i])
tmp.extend(a)
out.append(tmp) with open("word2vec_10k_{}.csv".format(
str(time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime()))),
"w",
newline='') as csvfile:
writer = csv.writer(csvfile) # 先写入columns_name
writer.writerow(["file_id", "prob0", "prob1", "prob2", "prob3", "prob4", "prob5", "prob6", "prob7"])
# 写入多行用writerows
writer.writerows(out)

提交到线上得到的结果为,0.725923

使用词向量的平均值,提交到线上结果为,0.751533

数据增强后,结果为,0.711533

【新人赛】阿里云恶意程序检测 -- 实践记录 11.24 - word2vec模型 + xgboost的更多相关文章

  1. 【新人赛】阿里云恶意程序检测 -- 实践记录11.3 - n-gram模型调参

    主要工作 本周主要是跑了下n-gram模型,并调了下参数.大概看了几篇论文,有几个处理方法不错,准备下周代码实现一下. xgboost参数设置为: param = {'max_depth': 6, ' ...

  2. 【新人赛】阿里云恶意程序检测 -- 实践记录11.10 - XGBoost学习 / 代码阅读、调参经验总结

    XGBoost学习: 集成学习将多个弱学习器结合起来,优势互补,可以达到强学习器的效果.要想得到最好的集成效果,这些弱学习器应当"好而不同". 根据个体学习器的生成方法,集成学习方 ...

  3. 【新人赛】阿里云恶意程序检测 -- 实践记录10.27 - TF-IDF模型调参 / 数据可视化

    TF-IDF模型调参 1. 调TfidfVectorizer的参数 ngram_range, min_df, max_df: 上一篇博客调了ngram_range这个参数,得出了ngram_range ...

  4. 【新人赛】阿里云恶意程序检测 -- 实践记录10.13 - Google Colab连接 / 数据简单查看 / 模型训练

    1. 比赛介绍 比赛地址:阿里云恶意程序检测新人赛 这个比赛和已结束的第三届阿里云安全算法挑战赛赛题类似,是一个开放的长期赛. 2. 前期准备 因为训练数据量比较大,本地CPU跑不起来,所以决定用Go ...

  5. 【新人赛】阿里云恶意程序检测 -- 实践记录10.20 - 数据预处理 / 训练数据分析 / TF-IDF模型调参

    Colab连接与数据预处理 Colab连接方法见上一篇博客 数据预处理: import pandas as pd import pickle import numpy as np # 训练数据和测试数 ...

  6. 阿里云小程序云应用环境DIY,延长3倍免费期

    阿里云清明节前刚刚推出了小程序云应用扶持计划一期活动 (活动链接见文章底部).假期研究了下以后,发觉不太给力.基本上就是给了2个月的免费测试环境,和平均2个月的基础版生产环境.而如果选用标准版生产环境 ...

  7. Android手机安全软件的恶意程序检测靠谱吗--LBE安全大师、腾讯手机管家、360手机卫士恶意软件检测方法研究

    转载请注明出处,谢谢. Android系统开放,各大论坛活跃,应用程序分发渠道广泛,这也就为恶意软件的传播提供了良好的环境.好在手机上安装了安全软件,是否能有效的检测出恶意软件呢?下边针对LBE安全大 ...

  8. 阿里云centos安装docker-engine实践

    近日在阿里云ECS服务器(centos系统)中安装docker,参考官方指南 https://docs.docker.com/engine/installation/linux/centos/  大概 ...

  9. 阿里云负载均衡配置https记录

    配置前端协议是443,后端是80 问题1记录: 例如访问https://www.xxx.com,在后端服务器上面获取是http还是https请求协议实际上是http: 因为我们先请求负载均衡,负载均衡 ...

随机推荐

  1. (数据科学学习手札75)基于geopandas的空间数据分析——坐标参考系篇

    本文对应代码已上传至我的Github仓库https://github.com/CNFeffery/DataScienceStudyNotes 1 简介 在上一篇文章中我们对geopandas中的数据结 ...

  2. pyhon学习Day18--继承

    [知识点] 面向对象的三大特性:继承.多态.封装 [继承] (1)继承:class Person(Animal): ——括号里的:父类,基类,超类   括号外的:子类,派生类 class Animal ...

  3. Flink安装及实例教程

    通过本教程我们将快速部署好flink在linux下的环境,并通过flink完成一个小demo的测试 一.准备阶段 flink压缩包下载(1.7.2): http://archive.apache.or ...

  4. linux笔记之解压

    从1.15版本开始tar就可以自动识别压缩的格式,故不需人为区分压缩格式就能正确解压: Linux下常见的压缩包格式有5种:zip tar.gz tar.bz2 tar.xz tar.Z 其中tar是 ...

  5. HDU_4570_区间dp

    http://acm.hdu.edu.cn/showproblem.php?pid=4570 连题目都看不懂,直接找了题解,copy了过来= =. 一个长度为n的数列,将其分成若干段(每一段的长度要& ...

  6. Spark Streaming运行流程及源码解析(一)

    本系列主要描述Spark Streaming的运行流程,然后对每个流程的源码分别进行解析 之前总听同事说Spark源码有多么棒,咱也不知道,就是疯狂点头.今天也来撸一下Spark源码. 对Spark的 ...

  7. c++ 中数组的引用

    在C++里,数组也是可以引用的. 代码如下: char str1[] = "abcde"; ] = str1; 解读第二句代码,括号的优先级最高,'str2'首先与'&'相 ...

  8. java8 Stream API笔记

    生成Stream Source的方式 从Collection和数组生成 * Collection.stream() * Collection.parallelStream() * Arrays.str ...

  9. 都闪开,不用任何游戏引擎,html也能开发格斗游戏

    html格斗游戏,对打游戏 不用引擎,不用画布canvas,不用任何库(包括jquery), 原生div+img组件,开发格斗游戏游戏教程视频已经上传 b站:https://www.bilibili. ...

  10. 内网ICMP隧道构建之icmpsh

    下载地址: https://github.com/inquisb/icmpsh#usage kali下载 git clone https://github.com/inquisb/icmpsh.git ...