天天看點

2.2、Softmax Regression算法實踐

Softmax Regression算法實踐

  有了上篇部落格的理論知識,我們可以利用實作好的函數,來建構Softmax Regression分類器,在訓練分類器的過程中,我們使用多分類資料作為訓練資料:如圖

2.2、Softmax Regression算法實踐

1、利用訓練資料對模型進行訓練:

完整代碼為:

1 # -*- coding: UTF-8 -*-
 2 # date:2018/5/29
 3 # User:WangHong
 4 import numpy as np
 5 def gradientAscent(feature_data,label_data,k,maxCycle,alpha):
 6     '''利用梯度下降法訓練Softmax模型
 7     :param feature_data: 特征
 8     :param label_data: 标簽
 9     :param k: 類别個數
10     :param maxCycle: 最大疊代次數
11     :param alpha: 學習率
12     :return weights: 權重
13     '''
14     m,n = np.shape(feature_data)
15     weights = np.mat(np.ones((n,k)))#初始化權重
16     i = 0
17     while i<=maxCycle:
18         err = np.exp(feature_data*weights)
19         if i % 500 == 0:
20             print("\t--------iter:",i,\
21                   ",cost:",cost(err,label_data))
22         rowsum = -err.sum(axis=1)
23         rowsum = rowsum.repeat(k,axis = 1)
24         err = err/rowsum
25         for x in range(m):
26             err[x,label_data[x,0]]+=1
27         weights = weights+(alpha/m)*feature_data.T*err
28         i+=1
29     return  weights
30 
31 def cost(err,label_data):
32     '''
33     :param err: exp的值
34     :param label_data: 标簽的值
35     :return: 損失函數的值
36     '''
37     m = np.shape(err)[0]
38     sum_cost = 0.0
39     for i in range(m):
40         if err[i,label_data[i,0]]/np.sum(err[i,:])>0:
41             sum_cost -=np.log(err[i,label_data[i,0]]/np.sum(err[i,:]))
42         else:
43             sum_cost -= 0
44     return sum_cost / m
45 
46 
47 def load_data(inputfile):
48     '''導入訓練資料
49     input:  inputfile(string)訓練樣本的位置
50     output: feature_data(mat)特征
51             label_data(mat)标簽
52             k(int)類别的個數
53     '''
54     f = open(inputfile)  # 打開檔案
55     feature_data = []
56     label_data = []
57     for line in f.readlines():
58         feature_tmp = []
59         feature_tmp.append(1)  # 偏置項
60         lines = line.strip().split("\t")
61         for i in range(len(lines) - 1):
62             feature_tmp.append(float(lines[i]))
63         label_data.append(int(lines[-1]))
64 
65         feature_data.append(feature_tmp)
66     f.close()  # 關閉檔案
67     return np.mat(feature_data), np.mat(label_data).T, len(set(label_data))
68 
69 def save_model(file_name, weights):
70     '''儲存最終的模型
71     input:  file_name(string):儲存的檔案名
72             weights(mat):softmax模型
73     '''
74     f_w = open(file_name, "w")
75     m, n = np.shape(weights)
76     for i in range(m):
77         w_tmp = []
78         for j in range(n):
79             w_tmp.append(str(weights[i, j]))
80         f_w.write("\t".join(w_tmp) + "\n")
81     f_w.close()
82 
83 
84 if __name__=="__main__":
85     inputfile = "SoftInput.txt"
86     #導入資料
87     print("--------------1.load data-------------")
88     feature,label,k = load_data(inputfile)
89     #訓練模型
90     print("--------------2.traing----------------")
91     weights = gradientAscent(feature,label,k,5000,0.2)
92     #儲存模型
93     print("--------------3.save model------------")
94     save_model("weights",weights)      

View Code

訓練結果為

2.2、Softmax Regression算法實踐

weights檔案内容

2.2、Softmax Regression算法實踐

 2、用訓練好的模型對資料進行預測:

預測的代碼:

1 # -*- coding: UTF-8 -*-
 2 # date:2018/5/29
 3 # User:WangHong
 4 import numpy as np
 5 import random as rd
 6 def load_weights(weights_path):
 7     '''導入訓練好的Softmax模型
 8     input:  weights_path(string)權重的存儲位置
 9     output: weights(mat)将權重存到矩陣中
10             m(int)權重的行數
11             n(int)權重的列數
12     '''
13     f = open(weights_path)
14     w = []
15     for line in f.readlines():
16         w_tmp = []
17         lines = line.strip().split("\t")
18         for x in lines:
19             w_tmp.append(float(x))
20         w.append(w_tmp)
21     f.close()
22     weights = np.mat(w)
23     m, n = np.shape(weights)
24     return weights, m, n
25 
26 
27 def load_data(num, m):
28     '''導入測試資料
29     input:  num(int)生成的測試樣本的個數
30             m(int)樣本的維數
31     output: testDataSet(mat)生成測試樣本
32     '''
33     testDataSet = np.mat(np.ones((num, m)))
34     for i in range(num):
35         testDataSet[i, 1] = rd.random() * 6 - 3  # 随機生成[-3,3]之間的随機數
36         testDataSet[i, 2] = rd.random() * 15  # 随機生成[0,15]之間是的随機數
37     return testDataSet
38 
39 
40 def predict(test_data, weights):
41     '''利用訓練好的Softmax模型對測試資料進行預測
42     input:  test_data(mat)測試資料的特征
43             weights(mat)模型的權重
44     output: h.argmax(axis=1)所屬的類别
45     '''
46     h = test_data * weights
47     return h.argmax(axis=1)  # 獲得所屬的類别
48 
49 
50 def save_result(file_name, result):
51     '''儲存最終的預測結果
52     input:  file_name(string):儲存最終結果的檔案名
53             result(mat):最終的預測結果
54     '''
55     f_result = open(file_name, "w")
56     m = np.shape(result)[0]
57     for i in range(m):
58         f_result.write(str(result[i, 0]) + "\n")
59     f_result.close()
60 
61 
62 if __name__ == "__main__":
63     # 1、導入Softmax模型
64     print("---------- 1.load model ----------------")
65     w, m, n = load_weights("weights")
66     # 2、導入測試資料
67     print("---------- 2.load data -----------------")
68     test_data = load_data(4000, m)
69     # 3、利用訓練好的Softmax模型對測試資料進行預測
70     print("---------- 3.get Prediction ------------")
71     result = predict(test_data, w)
72     # 4、儲存最終的預測結果
73     print("---------- 4.save prediction ------------")
74     save_result("result", result)      

View Code

預測結果;

2.2、Softmax Regression算法實踐

會生成一個result檔案用于存儲預測結果

2.2、Softmax Regression算法實踐
2.2、Softmax Regression算法實踐

 在本次測試中随機生成4000個樣本,最終分類的結果為:

2.2、Softmax Regression算法實踐

轉載于:https://www.cnblogs.com/wanshuai/p/9106413.html