# _*_coding:UTF-8_*_

import operator
import tldextract
import random
import pickle
import os
import tflearn from math import log
from tflearn.data_utils import to_categorical, pad_sequences
from tflearn.layers.core import input_data, dropout, fully_connected
from tflearn.layers.conv import conv_1d, max_pool_1d
from tflearn.layers.estimator import regression
from tflearn.layers.normalization import batch_normalization
from sklearn.model_selection import train_test_split def get_cnn_model(max_len, volcab_size=None):
if volcab_size is None:
volcab_size = 10240000 # Building convolutional network
network = tflearn.input_data(shape=[None, max_len], name='input')
network = tflearn.embedding(network, input_dim=volcab_size, output_dim=32) network = conv_1d(network, 64, 3, activation='relu', regularizer="L2")
network = max_pool_1d(network, 2)
network = conv_1d(network, 64, 3, activation='relu', regularizer="L2")
network = max_pool_1d(network, 2) network = batch_normalization(network)
network = fully_connected(network, 64, activation='relu')
network = dropout(network, 0.5) network = fully_connected(network, 2, activation='softmax')
sgd = tflearn.SGD(learning_rate=0.1, lr_decay=0.96, decay_step=1000)
network = regression(network, optimizer=sgd, loss='categorical_crossentropy') model = tflearn.DNN(network, tensorboard_verbose=0)
return model def get_data_from(file_name):
ans = []
with open(file_name) as f:
for line in f:
domain_name = line.strip()
ans.append(domain_name)
return ans def get_local_data(tag="labeled"):
white_data = get_data_from(file_name="dga_360_sorted.txt")
black_data = get_data_from(file_name="top-1m.csv")
return black_data, white_data def get_data():
black_x, white_x = get_local_data()
black_y, white_y = [1]*len(black_x), [0]*len(white_x) X = black_x + white_x
labels = black_y + white_y # Generate a dictionary of valid characters
valid_chars = {x:idx+1 for idx, x in enumerate(set(''.join(X)))} max_features = len(valid_chars) + 1
print("max_features:", max_features)
maxlen = max([len(x) for x in X])
print("max_len:", maxlen)
maxlen = min(maxlen, 256) # Convert characters to int and pad
X = [[valid_chars[y] for y in x] for x in X]
X = pad_sequences(X, maxlen=maxlen, value=0.) # Convert labels to 0-1
Y = to_categorical(labels, nb_classes=2) volcab_file = "volcab.pkl"
output = open(volcab_file, 'wb')
# Pickle dictionary using protocol 0.
data = {"valid_chars": valid_chars, "max_len": maxlen, "volcab_size": max_features}
pickle.dump(data, output)
output.close() return X, Y, maxlen, max_features def train_model():
X, Y, max_len, volcab_size = get_data() print("X len:", len(X), "Y len:", len(Y))
trainX, testX, trainY, testY = train_test_split(X, Y, test_size=0.2, random_state=42)
print(trainX[:1])
print(trainY[:1])
print(testX[-1:])
print(testY[-1:]) model = get_cnn_model(max_len, volcab_size)
model.fit(trainX, trainY, validation_set=(testX, testY), show_metric=True, batch_size=1024) filename = 'finalized_model.tflearn'
model.save(filename) model.load(filename)
print("Just review 3 sample data test result:")
result = model.predict(testX[0:3])
print(result) def test_model():
volcab_file = "volcab.pkl"
assert os.path.exists(volcab_file)
pkl_file = open(volcab_file, 'rb')
data = pickle.load(pkl_file)
valid_chars, max_document_length, max_features = data["valid_chars"], data["max_len"], data["volcab_size"] print("max_features:", max_features)
print("max_len:", max_document_length) cnn_model = get_cnn_model(max_document_length, max_features)
filename = 'finalized_model.tflearn'
cnn_model.load(filename)
print("predict domains:")
bls = list() with open("dga_360_sorted.txt") as f:
# with open("todo.txt") as f:
lines = f.readlines()
print("domain_list len:", len(lines))
cnt = 1000
for i in range(0, len(lines), cnt):
lines2 = lines[i:i+cnt]
domain_list = [line.strip() for line in lines2]
#print("domain_list sample:", domain_list[:5]) # Convert characters to int and pad
X = [[valid_chars[y] if y in valid_chars else 0 for y in x] for x in domain_list]
X = pad_sequences(X, maxlen=max_document_length, value=0.) result = cnn_model.predict(X)
for i, domain in enumerate(domain_list):
if result[i][1] > .5: #.95:
#print(lines2[i], domain + " is GDA")
print(lines2[i].strip() + "\t" + domain, result[i][1])
bls.append(domain)
else:
#print(lines2[i], domain )
pass
#print(bls)
print(len(bls) , "dga found!") if __name__ == "__main__":
print("train model...")
train_model()
print("test model...")
test_model()

dga model train and test code的更多相关文章

  1. 一步步开发自己的博客 .NET版(9、从model first替换成code first 问题记录)

    为什么要改用code first 用过code first的基本上都不会再想用回model first或是db first(谁用谁知道).不要问我为什么不一开始就直接使用code first,因为那个 ...

  2. Pytorch本人疑问(2)model.train()和model.eval()的区别

    我们在训练时如果使用了BN层和Dropout层,我们需要对model进行标识: model.train():在训练时使用BN层和Dropout层,对模型进行更改. model.eval():在评价时将 ...

  3. MVC学习6 学习使用Code First Migrations功能 把Model的更新同步到DB中

     参考:http://www.asp.net/mvc/tutorials/mvc-4/getting-started-with-aspnet-mvc4/adding-a-new-field-to-th ...

  4. EF7 - What Does “Code First Only” Really Mean

    这篇文章很有价值,但翻译了一段,实在翻译不下去了,没办法,只能转载了. 英文地址:http://blogs.msdn.com/b/adonet/archive/2014/10/21/ef7-what- ...

  5. Code First :使用Entity. Framework编程(8) ----转发 收藏

    第8章 Code First将走向哪里? So far, this book has covered all of the Code First components that reached the ...

  6. Code First :使用Entity. Framework编程(7) ----转发 收藏

    第7章 高级概念 The Code First modeling functionality that you have seen so far should be enough to get you ...

  7. Create Entity Data Model

    http://www.entityframeworktutorial.net/EntityFramework5/create-dbcontext-in-entity-framework5.aspx 官 ...

  8. Clean Code – Chapter 6 Objects and Data Structures

    Data Abstraction Hiding implementation Data/Object Anti-Symmetry Objects hide their data behind abst ...

  9. CV code references

    转:http://www.sigvc.org/bbs/thread-72-1-1.html 一.特征提取Feature Extraction:   SIFT [1] [Demo program][SI ...

随机推荐

  1. GitHub密钥生成

    前提电脑上需装有Git软件 这里提供百度云下载地址:https://pan.baidu.com/s/1r0y4XRyQCz7ZJBnZJhAtqw 提取码:88qf  1.登录GitHub账号 2.点 ...

  2. c# WF 第2节 窗体的添加与删除

    本节内容: 1: 窗体的添加 2: 窗体的删除 1: 窗体的添加 2: 窗体的删除 3:窗口的运行,发现只有一个form1 是因为

  3. Linux中自旋锁

    传统的spinlock Linux的的内核最常见的锁是自旋锁.自旋锁最多只能被一个可执行线程持有.如果一个执行线程试图获得一个被已经持有(争用)的自旋锁,那么该线程就会一直进行忙循环-旋转-等待锁重新 ...

  4. 剑指Offer-17.树的子结构(C++/Java)

    题目: 输入两棵二叉树A,B,判断B是不是A的子结构.(ps:我们约定空树不是任意一个树的子结构) 分析: 注意这道题是判断B是不是A的子结构,而不是子树,这一点要注意下,且空树不是任意一个树的子结构 ...

  5. Tensorflow加载预训练模型和保存模型(ckpt文件)以及迁移学习finetuning

    转载自:https://blog.csdn.net/huachao1001/article/details/78501928 使用tensorflow过程中,训练结束后我们需要用到模型文件.有时候,我 ...

  6. 【2019.8.11上午 慈溪模拟赛 T3】欢迎回来(back)(设阈值+莫队)

    设阈值 考虑对于询问的\(d\)设阈值进行分别处理. 对于\(d\le\sqrt{max\ d}\)的询问,我们可以\(O(n\sqrt{max\ d})\)预处理答案,\(O(1)\)输出. 对于\ ...

  7. php explode容易犯的错误

    php explode容易犯的错误 <pre> $pos = strpos($v, 'Controller'); if (is_numeric($pos)) { $kongzhiqifeg ...

  8. make 安装

    wget https://kojipkgs.fedoraproject.org//packages/make/4.2.1/14.fc31/src/make-4.2.1-14.fc31.src.rpm ...

  9. JVM的监控工具之jconsole

    JConsole(Java Monitoring and Management Console)是一种基于JMX的可视化监视.管理工具.管理的是什么?管理的是监控信息.永久代的使用信息.类加载等等 如 ...

  10. 【转载】百度百科:FusionCube超融合

    [转载]百度百科:FusionCube超融合 华为FusionCube融合基础设施一体机(Huawei FusionCube Converged Infrastructure)是华为公司IT产品线云计 ...