【新人赛】阿里云恶意程序检测 -- 实践记录 11.24 - word2vec模型 + xgboost
使用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的更多相关文章
- 【新人赛】阿里云恶意程序检测 -- 实践记录11.3 - n-gram模型调参
		
主要工作 本周主要是跑了下n-gram模型,并调了下参数.大概看了几篇论文,有几个处理方法不错,准备下周代码实现一下. xgboost参数设置为: param = {'max_depth': 6, ' ...
 - 【新人赛】阿里云恶意程序检测 -- 实践记录11.10 - XGBoost学习 / 代码阅读、调参经验总结
		
XGBoost学习: 集成学习将多个弱学习器结合起来,优势互补,可以达到强学习器的效果.要想得到最好的集成效果,这些弱学习器应当"好而不同". 根据个体学习器的生成方法,集成学习方 ...
 - 【新人赛】阿里云恶意程序检测 -- 实践记录10.27 - TF-IDF模型调参 / 数据可视化
		
TF-IDF模型调参 1. 调TfidfVectorizer的参数 ngram_range, min_df, max_df: 上一篇博客调了ngram_range这个参数,得出了ngram_range ...
 - 【新人赛】阿里云恶意程序检测 -- 实践记录10.13 - Google Colab连接 / 数据简单查看 / 模型训练
		
1. 比赛介绍 比赛地址:阿里云恶意程序检测新人赛 这个比赛和已结束的第三届阿里云安全算法挑战赛赛题类似,是一个开放的长期赛. 2. 前期准备 因为训练数据量比较大,本地CPU跑不起来,所以决定用Go ...
 - 【新人赛】阿里云恶意程序检测 -- 实践记录10.20 - 数据预处理 / 训练数据分析 / TF-IDF模型调参
		
Colab连接与数据预处理 Colab连接方法见上一篇博客 数据预处理: import pandas as pd import pickle import numpy as np # 训练数据和测试数 ...
 - 阿里云小程序云应用环境DIY,延长3倍免费期
		
阿里云清明节前刚刚推出了小程序云应用扶持计划一期活动 (活动链接见文章底部).假期研究了下以后,发觉不太给力.基本上就是给了2个月的免费测试环境,和平均2个月的基础版生产环境.而如果选用标准版生产环境 ...
 - Android手机安全软件的恶意程序检测靠谱吗--LBE安全大师、腾讯手机管家、360手机卫士恶意软件检测方法研究
		
转载请注明出处,谢谢. Android系统开放,各大论坛活跃,应用程序分发渠道广泛,这也就为恶意软件的传播提供了良好的环境.好在手机上安装了安全软件,是否能有效的检测出恶意软件呢?下边针对LBE安全大 ...
 - 阿里云centos安装docker-engine实践
		
近日在阿里云ECS服务器(centos系统)中安装docker,参考官方指南 https://docs.docker.com/engine/installation/linux/centos/ 大概 ...
 - 阿里云负载均衡配置https记录
		
配置前端协议是443,后端是80 问题1记录: 例如访问https://www.xxx.com,在后端服务器上面获取是http还是https请求协议实际上是http: 因为我们先请求负载均衡,负载均衡 ...
 
随机推荐
- qt QTreeWidget使用
			
itemwidget.h #ifndef ITEMWIDGET_H #define ITEMWIDGET_H #include <QtWidgets/QWidget> #include & ...
 - how to convert wstring to string
			
#define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <string> #include <local ...
 - 部署 harbor 私有仓库
			
安装下载依赖包 安装docker-compose 从 docker compose 发布页面下载最新的 docker-compose 二进制文件,本文以1.25.4为例 cd /opt/k8s/wor ...
 - Windows虚拟器的安装与使用
			
前言 先说:你们要的东西我会放在文中和文章末尾,拿文件记得点赞,一手交钱一手交货 马上初中朋友们就要开始上网课了哎!(博主也是一位初中生) 有人可能会受网课的影响而不能……, 所以各路神仙研究出了各种 ...
 - java9循环结构进阶
			
public class jh_01_循环嵌套 { public static void main(String[] args) { // for(int i = 1;i<= 5;i++) { ...
 - Django 搭建
			
1.安装python 2.pip 安装 Django 2.1.3 是版本号 命令:pip install Django==2.1.3 3.数据库驱动: mysql 数据库配置文档: 下载 whl 文 ...
 - OFDM Modulation Scheme
 - LeetCode 684. Redundant Connection 冗余连接(C++/Java)
			
题目: In this problem, a tree is an undirected graph that is connected and has no cycles. The given in ...
 - 本地linux搭建的WordPress升级时需要输入FTP信息
			
转自:https://blog.csdn.net/weixin_43837883/article/details/88751871 这是因为目录权限不正确所致 解决方法: 1.使用命令chown -R ...
 - Linux 配置ip 子接口 多网卡绑定
			
linux系统配置ip地址,图形化界面略过,这里只介绍文本行.做以下设置注意是否有此权限 查看当前路由及网关信息: [root@localhost ~]# netstat -r Kernel IP r ...