zoukankan      html  css  js  c++  java
  • 利用深度学习解决直播支付风控[转]

    原文地址:http://2014.54chen.com/blog/2017/02/09/deeplearning/

    前言

    在直播软件中,典型的过程是A用户充值,送花给B用户,B用户提现。

    正是有这样一条变现的道路,无数盗刷、退款、36技术的黑产人盯上了直播,报道见到映客的损失一度到了300万人民币(本文价值至少300万了:P)。外链https://www.douban.com/group/topic/89441680/

    本文介绍利用keras+tensorflow,快速完成一个神经网络,从工程角度看深度学习带来的实际作用。

    安装

    1.先升级pip

    chenzhen$ pip install --upgrade pip

    2.安装keras

    chenzhen$ pip install keras
    ...
    installing collected packages: numpy, scipy, six, theano, pyyaml, keras
    Successfully installed keras-1.2.1 numpy-1.12.0 pyyaml-3.12 scipy-0.18.1 six-1.10.0 theano-0.8.2

    3.安装tensorflow

    chenzhen$ export TF_BINARY_URL=https://storage.googleapis.com/tensorflow/mac/cpu/tensorflow-1.0.0rc2-py2-none-any.whl
    chenzhen$ pip install --upgrade $TF_BINARY_URL
    ...
    Installing collected packages: funcsigs, pbr, mock, wheel, pyparsing, packaging, appdirs, setuptools, protobuf, tensorflow
      Found existing installation: wheel 0.24.0
        Uninstalling wheel-0.24.0:
          Successfully uninstalled wheel-0.24.0
      Found existing installation: setuptools 18.0.1
        Uninstalling setuptools-18.0.1:
          Successfully uninstalled setuptools-18.0.1
    Successfully installed appdirs-1.4.0 funcsigs-1.0.2 mock-2.0.0 packaging-16.8 pbr-1.10.0 protobuf-3.2.0 pyparsing-2.1.10 setuptools-34.1.1 tensorflow-1.0.0rc2 wheel-0.29.0

    4.检查安装是否成功

    chenzhen$ python -c "import keras; print keras.__version__"
    Using TensorFlow backend.
    1.2.1

    5.检查配置是否正确

    chenzhen$ cat ~/.keras/keras.json
    {
        "image_dim_ordering": "tf", 
        "epsilon": 1e-07, 
        "floatx": "float32", 
        "backend": "tensorflow"
    }

    6.安装h5py 用来保存权重数据

    chenzhen$ pip install h5py
    ...
    Installing collected packages: h5py
    Successfully installed h5py-2.6.0

    7.安装 scikit-learn 用来写代码自动计算最优超参

    chenzhen$ pip install scikit-learn
    ...
    Installing collected packages: scikit-learn
    Successfully installed scikit-learn-0.18.1

    8.安装hyperas 用来自动计算最优超参

    pip install hyperas

    准备数据

    首先拿线上两天的数据,一天用来训练,一天用来测试。

    数据都是csv的,根据过去的经验,一个用户给另一个用户刷钱,能拿到的数据项有:

    1.是否白名单 2.是否签约 3.粉丝数量 4.是否入库 5.播放次数 6.播放时长 7.充值总次数 8.关注数量 等8个数据

    所有数据均为数字,再在9位上加上0表示正常1表示有问题的用户(有问题的用户是通过之前不正常的充值靠人肉挑的)。

    准备模型

    chenzhen$ cat deep.py 
    from keras.models import Sequential
    from keras.layers import Dense
    import numpy
    dataset = numpy.loadtxt("0207.csv", delimiter=",")
    X = dataset[:,0:8]
    Y = dataset[:,8]
    dataset2 = numpy.loadtxt("0208.csv", delimiter=",")
    Z = dataset2[:,0:8]
    Q = dataset2[:,8]
    
    # 输入8个参数,隐藏层12个神经元,先用relu激活,输出用sigmoid激活
    model = Sequential()
    model.add(Dense(12, input_dim=8, activation='relu'))
    model.add(Dense(1, activation='sigmoid'))
    
    # loss用mse 优化用Adamax  准确率衡量
    model.compile(loss='mse', optimizer='Adamax', metrics=['accuracy'])
    
    # 训练100次,每次取60行
    history = model.fit(X, Y, nb_epoch=100, batch_size=60)
    
    # 测试数据
    loss, accuracy = model.evaluate(Z, Q)
    print("
    Loss: %.2f, Accuracy: %.2f%%" % (loss, accuracy*100))
    
    # 保存下来训练好的模型供线上使用
    # serialize model to JSON
    model_json = model.to_json()
    with open("model.json", "w") as json_file:
        json_file.write(model_json)
    # serialize weights to HDF5
    model.save_weights("model.h5")
    print("Saved model to disk")

    使用模型

    chenzhen$ cat run.py 
    from keras.models import Sequential
    from keras.layers import Dense
    from keras.models import model_from_json
    import numpy
    
    dataset2 = numpy.loadtxt("0208.csv", delimiter=",")
    Z = dataset2[:,0:8]
    Q = dataset2[:,8]
    # load json and create model
    json_file = open('model.json', 'r')
    loaded_model_json = json_file.read()
    json_file.close()
    loaded_model = model_from_json(loaded_model_json)
    # load weights into new model
    loaded_model.load_weights("model.h5")
    print("Loaded model from disk")
    # test data
    loaded_model.compile(loss='mse', optimizer='Adamax', metrics=['accuracy'])
    score = loaded_model.evaluate(Z, Q, verbose=0)
    print "for test %s: %.2f%%" % (loaded_model.metrics_names[1], score[1]*100)
    
    # prediction probabilities里有预测的结果,需要启动一个简单的server对外服务即可。
    probabilities = loaded_model.predict(Z)
    predictions = [float(round(x)) for x in probabilities]
    accuracy = numpy.mean(predictions == Q)
    print("Prediction Accuracy: %.2f%%" % (accuracy*100))

    超参调优

    前面讲了工程使用的步骤,里面的参数都是随便写的,准确率大约60%,现在来讲如何让预测更加准确。

    test1是认好训练50次每次10条效果最好。

    chenzhen$ python test1.py
    Best: 0.696000 using {'nb_epoch': 50, 'batch_size': 10}

    test2确认好优化器使用Adam效果最好。

    chenzhen$ python test1.py
    Best: 0.686000 using {'optimizer': 'Adam'}

    test3是优化器使用SGD时,确认里面的两个参数。

    chenzhen$ python test3.py
    Best: 0.654000 using {'learn_rate': 0.001, 'momentum': 0.8}

    test4是初化类型。

    test5是激活函数类型。

    test6是dropout层的参数。

    test7是隐藏层神经元数量确定。

    相关的python代码见后。

    Hyperas超参调优

    上面一种调优办法有点麻烦,要一个一个试。

    Hyperas可以一次性完成。

    chenzhen$ python testh.py
    Evalutation of best performing model:
    192/200 [===========================>..] - ETA: 0s[0.35499999999999998, 0.64500000000000002]

    Hyperas的执行结果直接保存了model,简单粗暴。代码见后。

    后记

    前面的模型,都比较简单,只定义了两三层,输入8个参数输出1个参数,然后有15个神经元的隐藏层,在testh.py里的调整参数时,增加了一些Activation层。

    要在工程上使用,还得上到分布式tensorflow上,进行更多的训练,以达到测试集的准确率更高。

    然后将保存下来的model,使用run.py里的逻辑,做成线上server,提供预测判断服务。

    预测的同时,要提供人工抽检反复训练,将判断错和判断漏的,都加入到训练的过程中去,做成定时过程,才能满足需要。

    另外不得不提的一点:将输入的数字归一化到0-1之间,对BPNN网络的训练效率会大大提升。

    相关代码

  • 相关阅读:
    WPF 使用 Direct2D1 画图 绘制基本图形
    WPF 使用 Direct2D1 画图 绘制基本图形
    dot net core 使用 IPC 进程通信
    dot net core 使用 IPC 进程通信
    win2d 图片水印
    win2d 图片水印
    Java实现 LeetCode 240 搜索二维矩阵 II(二)
    PHP closedir() 函数
    PHP chroot() 函数
    PHP chdir() 函数
  • 原文地址:https://www.cnblogs.com/huacw/p/7490514.html
Copyright © 2011-2022 走看看