-
Notifications
You must be signed in to change notification settings - Fork 32
/
Copy pathFeatureCombination.py
151 lines (129 loc) · 5.68 KB
/
FeatureCombination.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
"""
@ Filename: FeatureCombination.py
@ Author: Ryuk
@ Create Date: 2019-11-18
@ Update Date: 2019-11-20
@ Description: Implement FM
"""
import numpy as np
import preProcess
import pickle
class FM:
def __init__(self, n, norm_type="Standardization", k=5):
self.norm_type = norm_type
self.n = n # the number of feature
self.k = k # the dimension of latency
self.w_0 = 0 # numerical parameter
self.W = np.random.random([self.n, 1]) # one order parameter
self.V = np.random.random([self.n, self.k]) # second order parameter
self.sample_num = None # the number of samples of trainset
'''
Function: sigmoid
Description: sigmoid function
Input: x dataType: ndarray description: input vector
derivative dataType: bool description: whether to calculate the derivative of sigmoid
Output: output dataType: float description: output
'''
def sigmoid(self, x, derivative=False):
output = 1/(1 + np.exp(-x))
if derivative:
output = output * (1 - output)
return output
'''
Function: train
Description: train the model
Input: train_data dataType: ndarray description: features
train_label dataType: ndarray description: labels
alpha dataType: float description: the stride of the target
iterations dataType: int description: the times of iteration
Output: self dataType: obj description: the trained model
'''
def train(self, train_data, train_label, alpha=0.01, iterations=100):
if self.norm_type == "Standardization":
train_data = preProcess.Standardization(train_data)
else:
train_data = preProcess.Normalization(train_data)
for epoch in range(iterations):
for id in range(self.sample_num):
# second order computation
inter_1 = train_data[id] * self.V
inter_2 = np.multiply(train_data[id], train_data[id]) * np.multiply(self.V, self.V)
interaction = np.sum(np.multiply(inter_1, inter_1) - inter_2) / 2.
# prediction result
pred = self.w_0 + train_data[id] * self.W + interaction
# calculate loss, cross entropy
base = [np.log(self.sigmoid(train_label[id] * float(pred))) - 1] * train_label
# update numerical parameters
self.w_0 -= alpha * base
x = train_data[id]
for i in range(self.n):
# update first-order parameter
if train_data[id, i] != 0:
self.W[id, i] -= alpha * base * train_data[id, i]
for j in range(self.n):
# update second-order parameter
self.V[i, j] -= alpha * base * (
train_data[id, i] * self.V[j, i] * train_data[id, j] - self.V[i, j] * train_data[id, i] * train_data[id, i])
return self
'''
Function: predict
Description: predict the testing set
Input: train_data dataType: ndarray description: features
prob dataType: bool description: return probaility of label
Output: prediction dataType: ndarray description: the prediction results for testing set
'''
def predict(self, test_data, prob="False"):
# Normalization
if self.norm_type == "Standardization":
test_data = preProcess.Standardization(test_data)
else:
test_data = preProcess.Normalization(test_data)
test_num = test_data.shape[0]
prediction = np.zeros([test_num, 1])
probability = np.zeros([test_num, 1])
for i in range(test_num):
inter_1 = test_data[i] * self.V
inter_2 = np.multiply(test_data[i], test_data[i]) * np.multiply(self.V, self.V)
interaction = sum(np.multiply(inter_1, inter_1) - inter_2) / 2.
pre = self.w_0 + test_data[i] * self.W + interaction
probability = self.sigmoid(float(pre))
if probability[i] > 0.5:
prediction[i] = 1
else:
prediction[i] = 0.5
self.prediction = prediction
self.probability = probability
if prob:
return probability
else:
return prediction
'''
Function: accuracy
Description: show detection result
Input: test_label dataType: ndarray description: labels of test data
Output: accuracy dataType: float description: detection accuarcy
'''
def accuarcy(self, test_label):
test_label = np.expand_dims(test_label, axis=1)
prediction = self.prediction
accuarcy = sum(prediction == test_label)/len(test_label)
return accuarcy
'''
Function: save
Description: save the model as pkl
Input: filename dataType: str description: the path to save model
'''
def save(self, filename):
f = open(filename, 'w')
pickle.dump(self.weights, f)
f.close()
'''
Function: load
Description: load the model
Input: filename dataType: str description: the path to save model
Output: self dataType: obj description: the trained model
'''
def load(self, filename):
f = open(filename)
self.weights = pickle.load(f)
return self