在直播軟件中,典型的過程是A用戶充值,送花給B用戶,B用戶提現。python
正是有這樣一條變現的道路,無數盜刷、退款、36技術的黑產人盯上了直播,報道見到映客的損失一度到了300萬人民幣(本文價值至少300萬了:P)。外鏈https://www.douban.com/group/topic/89441680/json
本文介紹利用keras+tensorflow,快速完成一個神經網絡,從工程角度看深度學習帶來的實際做用。api
1.先升級pip網絡
chenzhen$ pip install --upgrade pip
2.安裝kerasapp
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("\nLoss: %.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能夠一次性完成。
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網絡的訓練效率會大大提高。