-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnlpnn.py
177 lines (152 loc) · 4.23 KB
/
nlpnn.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
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
# -*- coding: utf-8 -*-
"""
A hand craft NN NLP model using numpy package.
@author: Zhang Long
"""
from collections import defaultdict
ids=defaultdict(lambda:len(ids))
x='hello my world my friend'
words=x.split(' ')
phi=[None]*len(words)
for word in words:
index=ids['uni' + word]
if phi[index] != None:
phi[index] +=1
else:
phi[index] = 1
print(index)
print(ids)
print(phi)
## perceptron training code (numpy version)
import numpy as np
from collections import defaultdict
import codecs
ftrain_file=".\\data\\titles-en-train.labeled"
ftest_file=".\\data\\titles-en-test.labeled"
phi=[None]*27290
ids=defaultdict(lambda:len(ids))
def create_features(sentence):
phi=[0]*27290
words = sentence.split(' ')
for word in words:
indx = ids['uni ' + word]
if indx >= 27290:
continue
if phi[indx] != None:
phi[indx] += 1
else:
phi[indx] = 1
return phi
def predict_one(w, phi):
score = 0
score = np.dot(w,phi)
if score >=0:
return 1
else:
return -1
def update_weight(w, phi, y):
w += np.array(phi)*y
return w
#ftrain = codecs.open(ftrain_file, 'r', 'utf-8')
#for line in ftrain:
# line = line.split('\t')
# sentence = line[1]
# y=int(line[0])
# create_features(sentence)
#
#w=np.zeros(len(ids))
#
#ftrain.seek(0)
#for iter in range(1):
# for line in ftrain:
# line = line.split('\t')
# sentence = line[1]
# y = int(line[0])
# phi = create_features(sentence)
# ypred = predict_one(w, phi)
# #print('y %d ypred %d' %(y, ypred))
# if ypred != y:
# w=update_weight(w, phi, y)
#
#print(w)
############################
# nn forward
# network model : w and b of each layer, it is a list of list.
# the inner list has w as 0th element and b as 1st element
# phi0 input
def forward_nn(network, phi0):
phi = [phi0]
for layer in range(1,len(network)+1):
w=network[layer-1][0]
b=network[layer-1][1]
phinu = np.tanh(np.dot(phi[layer-1],w)+b)
phi.insert(layer,phinu)
return phi
def backward_nn(network, phi, ypred):
J=len(network)
lst = ([0]*J)
lst.append(np.array(ypred-phi[J][0]))
delta = [np.array([0])]*(J+1)
delta[J]=np.array(ypred-phi[J][0])
delta_drv = [np.array([0])]*(J+1)
for i in range(J-1,-1, -1):
phii1 = phi[i+1]
onei1 = np.ones_like(phii1)
phi2 = phii1**2
delta_drv[i+1] = delta[i+1]*(onei1-phi2)
w = network[i][0]
#b = network[i][1]
delta[i] = np.array(np.dot(w,delta_drv[i+1]))
return delta_drv
def update_weights(network, phi, delta_drv, lmbd):
for i in range(len(network)):
w=network[i][0]
b=network[i][1]
w+=lmbd*np.outer(phi[i], delta_drv[i+1])
b+=lmbd*delta_drv[i+1]
def create_network(layers):
network=[]
for layernum in range(len(layers)-1):
wblst = []
wblst.append(0.2*np.random.rand(layers[layernum],layers[layernum+1])-0.1)
wblst.append(np.random.rand(layers[layernum+1]))
network.append(wblst)
return network
def create_nnfeatures(sentence,size):
phi=[0]*size
words = sentence.split(' ')
senlen = len(words)
if senlen > size:
senlen = size
for i in range(senlen):
if phi[i] != None:
phi[i] += 1
else:
phi[i] = 1
return phi
nnet = create_network([27290, 20,10,1])
#train
ftrain = codecs.open(ftrain_file, 'r', 'utf-8')
for line in ftrain:
line = line.split('\t')
sentence = line[1]
y=int(line[0])
phi0 = create_features(sentence)
ypred=forward_nn(nnet, phi0)
delta_drv=backward_nn(nnet, ypred, y)
update_weights(nnet, ypred, delta_drv, 0.1)
print(nnet)
ftest=codecs.open(ftest_file,'r','utf-8')
for line in ftest:
line=line.split('\t')
sentence=line[1]
y=int(line[0])
phi=create_features(sentence)
ypred=forward_nn(nnet,phi)
print(y)
print(ypred[3])
def main():
pass
# Any code you like
if __name__ == '__main__':
main()