{"id":20459828,"url":"https://github.com/explangcn/aliyun_malwaredetection","last_synced_at":"2026-03-19T15:58:59.112Z","repository":{"id":62633981,"uuid":"561225515","full_name":"ExpLangcn/Aliyun_MalwareDetection","owner":"ExpLangcn","description":"阿里云-安全恶意程序检测","archived":false,"fork":false,"pushed_at":"2022-11-03T08:16:20.000Z","size":0,"stargazers_count":1,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-01-16T00:24:57.801Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":null,"has_issues":false,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/ExpLangcn.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2022-11-03T08:23:48.000Z","updated_at":"2022-11-03T13:29:54.000Z","dependencies_parsed_at":"2022-11-04T07:40:31.920Z","dependency_job_id":null,"html_url":"https://github.com/ExpLangcn/Aliyun_MalwareDetection","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ExpLangcn%2FAliyun_MalwareDetection","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ExpLangcn%2FAliyun_MalwareDetection/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ExpLangcn%2FAliyun_MalwareDetection/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ExpLangcn%2FAliyun_MalwareDetection/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/ExpLangcn","download_url":"https://codeload.github.com/ExpLangcn/Aliyun_MalwareDetection/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":242014722,"owners_count":20057880,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-11-15T12:17:23.536Z","updated_at":"2026-02-06T18:05:23.705Z","avatar_url":"https://github.com/ExpLangcn.png","language":null,"funding_links":[],"categories":[],"sub_categories":[],"readme":"# Aliyun_MalwareDetection\n\n# 阿里云-安全恶意程序检测\n\n## 赛题说明\n\n赛题链接：[阿里云：安全恶意程序检测](https://tianchi.aliyun.com/competition/entrance/231694/information)\n\n代码仓库：[阿里云-安全恶意程序检测--代码仓库](https://github.com/wxydaydayup/Aliyun_MalwareDetection/tree/master)\n\n### 一、背景介绍 \n\n恶意软件是一种被设计用来对目标计算机造成破坏或者占用目标计算机资源的软件，传统的恶意软件包括蠕虫、木马等，这些恶意软件严重侵犯用户合法权益，甚至将为用户及他人带来巨大的经济或其他形式的利益损失。近年来随着虚拟货币进入大众视野，挖矿类的恶意程序也开始大量涌现，黑客通过入侵恶意挖矿程序获取巨额收益。当前恶意软件的检测技术主要有特征码检测、行为检测和启发式检测等，配合使用机器学习可以在一定程度上提高泛化能力，提升恶意样本的识别率。\n\n### 二、任务介绍\n\n本题目提供的数据来自文件（windows 可执行程序）经过沙箱程序模拟运行后的API指令序列，全为windows二进制可执行程序，经过脱敏处理。\n其中恶意文件的类型有感染型病毒、木马程序、挖矿程序、DDOS木马、勒索病毒等，数据总计6亿条。\n\n### 三、数据集\n\n1、训练数据（train.zip）：调用记录近9000万次，文件1万多个（以文件编号汇总）\n\n+ 一个文件调用的api数量有可能很多，对于一个tid中调用超过5000个api的文件，我们进行了截断，按照顺序保留了每个tid前5000个api的记录。\n\n+ 不同线程tid之间没有顺序关系，同一个tid里的index由小到大代表调用的先后顺序关系。\n    注3：index是单个文件在沙箱执行时的全局顺序，由于沙箱执行时间有精度限制，所以会出现一个index上出现同线程或者不同线程都在执行多次api的情况，可以保证同tid内部的顺序，但不保证连续。\n\n2、测试数据（test.zip）：调用记录近8000万次，文件1万多个。\n\n说明：格式除了没有label字段，其他数据规格与训练数据一致。\n\n### 四、字段说明\n\ntrain.csv和test.csv字段说明\n\n| 字段    | 类型   | 解释                                                         |\n| ------- | ------ | ------------------------------------------------------------ |\n| file_id | bigint | 文件编号                                                     |\n| label   | bigint | 文件标签，0-正常/1-勒索病毒/2-挖矿程序/3-DDoS木马/4-蠕虫病毒/5-感染型病毒/6-后门程序/7-木马程序 |\n| api     | string | 文件调用的API名称                                            |\n| tid     | bigint | 调用API的线程编号                                            |\n| index   | string | 线程中API调用的顺序编号                                      |\n\n## BaseLine V1_lgb--分数: 0.715840\n\n### 一、数据探索\n\n**写法1**\n\nPandas使用chunksize分块处理大型csv文件，加载数据\n\n```python\nimport pandas as pd\n# 分段数据加载基础方法\ndef get_data(file_name):\n    result = []\n    chunk_index = 0\n    for df in pd.read_csv(open(file_name, 'r'), chunksize = 1000000):\n        result.append(df)\n        chunk_index += 1\n    result = pd.concat(result, ignore_index=True, axis=0)\n    return result\n\n#数据加载\ntrain = get_data('./security_train.csv')\ntest = get_data('./security_test.csv')\n\n#将数据采用pickle方式存储，加快文件的读取速度\nimport pickle\nwith open('./train.pkl', 'wb') as file:\n    pickle.dump(train,file)\nwith open('./test.pkl', 'wb') as file:\n    pickle.dump(test,file)\nwith open('./train.pkl', 'rb') as f:\n    train = pickle.load(f)    \nwith open('./test.pkl', 'rb') as f:\n    test = pickle.load(f) \n```\n\n**写法2**\n\n```python\n# 获取读文件指针 \ndata=pd.read_csv(filename, iterator=True)\n# 顺序读取100000行数据 \nchunk = data.get_chunk(100000)\n```\n\n查看内存使用情况\n\n```python\nimport os\nimport psutil\nmem = psutil.virtual_memory()\nprint('总内存：',mem.total/1024/1024)\nprint('已使用内存：',mem.used/1024/1024)\nprint('空闲内存：',mem.free/1024/1024)\nprint('使用占卜：',mem.percent)\nprint('当前线程PID：',os.getpid())\n```\n\n查看某个变量的资源使用情况\n\n```python\nimport sys\nsys.getsizeof(df_all)/1024/1024\n```\n\n针对不同的变量，进行内存释放\n\n### 二、特征工程\n\n对File_id做聚合处理，并去重操作和使用统计特征，主要包括数量，最大值，最小值，平均值，并保存下来\n\n1. 去除完全重复的行数据\n\n```python\ndata.drop_duplicates(inplace=True)\n```\n\n2. 去除某几列重复的行数据\n\n```python\ndata.drop_duplicates(subset=['A','B'],keep='first',inplace=True)\n```\n\n+ subset： 列名，可选，默认为None\n+ keep： {‘first’, ‘last’, False}, 默认值 ‘first’\n  + first： 保留第一次出现的重复行，删除后面的重复行。\n  + last： 删除重复项，除了最后一次出现。\n  + False： 删除所有重复项。\n+ inplace：布尔值，默认为False表示生成一个副本，inplace=True表示直接在原来的DataFrame上删除重复项。\n\n```python\n#定义重要特征，主要包括数量，最大值，最小值，平均值等等\ndef get_features(df):\n    df_file = df.groupby('file_id')\n    if 'label' in df.columns: \n        df1 = df.drop_duplicates(subset=['file_id', 'label'], keep='first')\n    else:\n        df1 = df.drop_duplicates(subset=['file_id'], keep='first')\n    df1 = df1.sort_values('file_id')\n    features = ['api', 'tid', 'index']\n    for f in features:\n        df1[f+'_count'] = df_file[f].count().values\n        df1[f+'_nunique'] = df_file[f].nunique().values\n        df1[f+'_min'] = df_file[f].min().values\n        df1[f+'_max'] = df_file[f].max().values\n        df1[f+'_mean'] = df_file[f].mean().values  \n        df1[f+'_median'] = df_file[f].median().values  \n        df1[f+'_std'] = df_file[f].std().values  \n        df1[f+'_ptp'] = df1[f+'_max'] - df1[f+'_min']\n    return df1\n#训练集与测试集添加特征\ndf_train = get_features(train)\ndf_test = get_features(test)\n#将特征的结果集保持，一遍后续直接使用\ndf_train.to_pickle('.df_train.pkl')\ndf_test.to_pickle('./df_test.pkl')\n```\n\n### 三、建立模型\n\n```python\nimport lightgbm as lgb\nimport pandas as pd\nclf = lgb.LGBMClassifier(num_leaves=2**5-1,reg_alpha=0.25,reg_lambda=0.25,objective='multiclass',                              \n                         max_depth=-1,learning_rate=0.005,min_child_sample=3,random_state=2021,\n                         n_estimators=2000,subsample=1,colsample_bytree=1)\n                         #,device= gpu,gpu_platform_id=0,gpu_device_id = 0)\n \nclf.fit(df_train.drop(['label'],axis=1),df_train['label'])\n \nresult = clf.predict_proba(df_test)\nresult_lgb = pd.DataFrame(result, columns=['prob0','prob1','prob2','prob3','prob4','prob5','prob6','prob7'])\nresult_lgb['file_id'] = df_test['file_id'].values\ncolumns=['file_id','prob0','prob1','prob2','prob3','prob4','prob5','prob6','prob7']\nresult_lgb.to_csv('./baselineV1.csv',index=False,columns = columns )\nprint(\"已完成\")\n```\n\n## BaseLine V2_lgb--分数: 0.715840\n\n## 一、特征工程优化\n\n针对file_id 按照线程tid 和 顺序index进行排序 , 并拼接成字符串\n\n```python\ndef get_apis(df):\n    # 按照file_id进行分组\n    group_fileid = df.groupby('file_id')    \n    # 统计file_id 和对应的 api_sequence\n    file_api = {}    \n    # 计算每个file_id的api_sequence\n    for file_id, file_group in group_fileid:\n        # 针对file_id 按照线程tid 和 顺序index进行排序\n        result = file_group.sort_values(['tid', 'index'], ascending=True)\n        #得到api的调用序列\n        api_sequence = ' '.join(result['api'])\n        #print(api_sequence)\n        file_api[file_id] = api_sequence\n    return file_api\n\ntrain_apis = get_apis(train)\ntest_apis = get_apis(test)\n```\n\n将文本信息与BaselineV1中的统计特征合并\n\n```python\nimport pandas as pd\nwith open('./df_train.pkl', 'rb') as file:\n    df_train = pickle.load(file)\n    \nwith open('./df_test.pkl', 'rb') as file:\n    df_test = pickle.load(file)\n    \ndf_train.drop(['api','tid','index'],axis=1,inplace=True)\ndf_test.drop(['api','tid','index'],axis=1,inplace=True)\n\ntemp = pd.DataFrame.from_dict(train_apis, orient='index', columns=['api'])\ntemp = temp.reset_index().rename(columns={'index': 'file_id'})\ndf_train = df_train.merge(temp, on='file_id', how='left') \ntemp = pd.DataFrame.from_dict(test_apis, orient='index', columns=['api'])\ntemp = temp.reset_index().rename(columns={'index': 'file_id'})\ndf_test = df_test.merge(temp, on='file_id', how='left')\n \ndf_all = pd.concat([df_train, df_test], axis=0)\n\n```\n\n放入TfidfVectorizer做训练\n\n```python\nfrom sklearn.feature_extraction.text import TfidfVectorizer\n#使用1-3元语法（1元语法 + 2元语法 + 3 元语法）\nvec=TfidfVectorizer(ngram_range=(1,3),min_df=0.01)\napi_features=vec.fit_transform(df_all['api'])\n\ndf_apis = pd.DataFrame(api_features.toarray(), columns=vec.get_feature_names())\ndf_apis.to_pickle('./df_apis.pkl')\ndf_apis\n```\n\n将tfidf特征 与原特征进行合并\n\n```python\ndf_train_apis=df_apis[df_apis.index\u003c=13886]\ndf_test_apis=df_apis[df_apis.index\u003e13886]\n#将tfidf特征前面的索引重新开始\ndf_test_apis.index=range(len(df_test_apis))\n \n# 将tfidf特征 与原特征进行合并\ndf_train = df_train.merge(df_train_apis, left_index=True, right_index=True)\ndf_test = df_test.merge(df_test_apis, left_index=True, right_index=True)\n\n#去掉object类型api后保存\ndf_train.drop('api', axis=1, inplace=True)\ndf_test.drop('api', axis=1, inplace=True)\ndf_train.to_pickle('./df_train2.pkl')\ndf_test.to_pickle('./df_test2.pkl')\n```\n\n## BaseLine V3_lgb\u0026xgb--分数: 0.715840\n\n### 一、模型融合\n\n#### 1、lightgbm与xgboost做模型融合\n\n```python\nimport xgboost as xgb\nmodel_xgb = xgb.XGBClassifier(\n            max_depth=5, learning_rate=0.005, n_estimators=3250, \n            objective='multi:softprob', tree_method='gpu_hist', \n            subsample=0.8, colsample_bytree=0.8, \n            min_child_samples=3, eval_metric='logloss', reg_lambda=0.5)\nmodel_xgb.fit(df_train.drop('label', axis=1), df_train['label'])\nresult_xgb = model_xgb.predict_proba(df_test)\nresult_xgb = pd.DataFrame(result_xgb, columns=['prob0','prob1','prob2','prob3','prob4','prob5','prob6','prob7'])\nresult_xgb['file_id'] = df_test['file_id'].values\n \n# 对两个模型的结果 进行加权平均\nresult = result_lgb.copy()\nweight_lgb, weight_xgb = 0.5, 0.5\nresult['prob0'] = result['prob0'] * weight_lgb + result_xgb['prob0'] * weight_xgb\nresult['prob1'] = result['prob1'] * weight_lgb + result_xgb['prob1'] * weight_xgb\nresult['prob2'] = result['prob2'] * weight_lgb + result_xgb['prob2'] * weight_xgb\nresult['prob3'] = result['prob3'] * weight_lgb + result_xgb['prob3'] * weight_xgb\nresult['prob4'] = result['prob4'] * weight_lgb + result_xgb['prob4'] * weight_xgb\nresult['prob5'] = result['prob5'] * weight_lgb + result_xgb['prob5'] * weight_xgb\nresult['prob6'] = result['prob6'] * weight_lgb + result_xgb['prob6'] * weight_xgb\nresult['prob7'] = result['prob7'] * weight_lgb + result_xgb['prob7'] * weight_xgb\ncolumns = ['file_id', 'prob0','prob1','prob2','prob3','prob4','prob5','prob6','prob7']\nresult.to_csv('./baselineV3.csv', index=False, columns=columns)\n```\n**全部代码已放代码仓库：**[阿里云-安全恶意程序检测--代码仓库](https://github.com/wxydaydayup/Aliyun_MalwareDetection/tree/master)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fexplangcn%2Faliyun_malwaredetection","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fexplangcn%2Faliyun_malwaredetection","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fexplangcn%2Faliyun_malwaredetection/lists"}