|
| 1 | +# coding:UTF-8 |
| 2 | +''' |
| 3 | +Date:20160901 |
| 4 | +@author: zhaozhiyong |
| 5 | +''' |
| 6 | +import numpy as np |
| 7 | +from lr_train import sig |
| 8 | + |
| 9 | +def load_weight(w): |
| 10 | + '''导入LR模型 |
| 11 | + input: w(string)权重所在的文件位置 |
| 12 | + output: np.mat(w)(mat)权重的矩阵 |
| 13 | + ''' |
| 14 | + f = open(w) |
| 15 | + w = [] |
| 16 | + for line in f.readlines(): |
| 17 | + lines = line.strip().split("\t") |
| 18 | + w_tmp = [] |
| 19 | + for x in lines: |
| 20 | + w_tmp.append(float(x)) |
| 21 | + w.append(w_tmp) |
| 22 | + f.close() |
| 23 | + return np.mat(w) |
| 24 | + |
| 25 | +def load_data(file_name, n): |
| 26 | + '''导入测试数据 |
| 27 | + input: file_name(string)测试集的位置 |
| 28 | + n(int)特征的个数 |
| 29 | + output: np.mat(feature_data)(mat)测试集的特征 |
| 30 | + ''' |
| 31 | + f = open(file_name) |
| 32 | + feature_data = [] |
| 33 | + for line in f.readlines(): |
| 34 | + feature_tmp = [] |
| 35 | + lines = line.strip().split("\t") |
| 36 | + # print lines[2] |
| 37 | + if len(lines) <> n - 1: |
| 38 | + continue |
| 39 | + feature_tmp.append(1) |
| 40 | + for x in lines: |
| 41 | + # print x |
| 42 | + feature_tmp.append(float(x)) |
| 43 | + feature_data.append(feature_tmp) |
| 44 | + f.close() |
| 45 | + return np.mat(feature_data) |
| 46 | + |
| 47 | +def predict(data, w): |
| 48 | + '''对测试数据进行预测 |
| 49 | + input: data(mat)测试数据的特征 |
| 50 | + w(mat)模型的参数 |
| 51 | + output: h(mat)最终的预测结果 |
| 52 | + ''' |
| 53 | + h = sig(data * w.T)#sig |
| 54 | + m = np.shape(h)[0] |
| 55 | + for i in xrange(m): |
| 56 | + if h[i, 0] < 0.5: |
| 57 | + h[i, 0] = 0.0 |
| 58 | + else: |
| 59 | + h[i, 0] = 1.0 |
| 60 | + return h |
| 61 | + |
| 62 | +def save_result(file_name, result): |
| 63 | + '''保存最终的预测结果 |
| 64 | + input: file_name(string):预测结果保存的文件名 |
| 65 | + result(mat):预测的结果 |
| 66 | + ''' |
| 67 | + m = np.shape(result)[0] |
| 68 | + #输出预测结果到文件 |
| 69 | + tmp = [] |
| 70 | + for i in xrange(m): |
| 71 | + tmp.append(str(h[i, 0])) |
| 72 | + f_result = open(file_name, "w") |
| 73 | + f_result.write("\t".join(tmp)) |
| 74 | + f_result.close() |
| 75 | + |
| 76 | +if __name__ == "__main__": |
| 77 | + # 1、导入LR模型 |
| 78 | + print "---------- 1.load model ------------" |
| 79 | + w = load_weight("weights") |
| 80 | + n = np.shape(w)[1] |
| 81 | + # 2、导入测试数据 |
| 82 | + print "---------- 2.load data ------------" |
| 83 | + testData = load_data("test_data", n) |
| 84 | + # 3、对测试数据进行预测 |
| 85 | + print "---------- 3.get prediction ------------" |
| 86 | + h = predict(testData, w)#进行预测 |
| 87 | + # 4、保存最终的预测结果 |
| 88 | + print "---------- 4.save prediction ------------" |
| 89 | + save_result("result", h) |
| 90 | + |
0 commit comments