forked from rmalouf/learning
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathndl.py
183 lines (117 loc) · 4.27 KB
/
ndl.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
178
179
180
181
182
183
import pandas as pd
import numpy as np
from sklearn.feature_extraction import DictVectorizer
import alias
def explode(cues):
if isinstance(cues, basestring):
cues = cues.split('_')
return {}.fromkeys(cues,True)
def orthoCoding(strs,grams=2,sep=None):
if not np.iterable(grams):
grams = [grams]
result = [ ]
for str in strs:
cues = [ ]
str = list(str)
for n in grams:
if n > 1:
seq = ['#'] + str + ['#']
else:
seq = str
count = max(0, len(seq) - n + 1)
cues.extend(''.join(seq[i:i+n]) for i in xrange(count))
if sep:
result.append(sep.join(cues))
else:
result.append(tuple(cues))
return result
def danks(data):
## Rescorla-Wagner equilibirum (Danks 2003)
feats = DictVectorizer(dtype=int,sparse=False)
marginals = data.groupby('Cues',as_index=False).Frequency.sum()
marginals = marginals.rename(columns={'Frequency':'Total'})
data = pd.merge(data,marginals,on='Cues')
result = pd.DataFrame()
for outcome in data.Outcomes.unique():
yes = data[data.Outcomes==outcome]
M = feats.fit_transform([explode(c) for c in yes.Cues])
P = np.diag(yes.Total/sum(yes.Total))
MTP = M.T.dot(P)
O = yes.Frequency / yes.Total
left = MTP.dot(M)
right = MTP.dot(O)
V = np.linalg.solve(left,right)
result[outcome] = V
result.index = feats.get_feature_names()
return result
def ndl(data):
## Naive discriminative learning (Baayen et al. 2011)
vec = DictVectorizer(dtype=float,sparse=False)
D = vec.fit_transform([explode(c) for c in data.Cues]) * data.Frequency[:,np.newaxis]
# Make co-occurrence matrix C
n = len(vec.get_feature_names())
C = np.zeros((n,n))
for row in D:
for nz in np.nonzero(row):
C[nz] += row
# Normalize
Z = C.sum(axis=1)
C1 = C / Z[:,np.newaxis]
# Make outcome matrix O
out = DictVectorizer(dtype=float,sparse=False)
X = out.fit_transform([explode(c) for c in data.Outcomes]) * data.Frequency[:,np.newaxis]
O = np.zeros((len(vec.get_feature_names()),len(out.get_feature_names())))
for i in xrange(len(X)):
for nz in np.nonzero(D[i]):
O[nz] += X[i]
# Normalize
O1 = O / Z[:,np.newaxis]
# Solve
# (fails if C is singular)
# W = np.linalg.solve(C1,O1)
W = np.linalg.pinv(C1).dot(O1)
return pd.DataFrame(W,columns=out.get_feature_names(),index=vec.get_feature_names())
def activation(cues, W):
A = np.zeros(len(W.columns))
if isinstance(cues, basestring):
cues = cues.split('_')
for cue in cues:
A += W.loc[cue]
return pd.Series(A,index=W.columns)
def activation(cues, W):
if isinstance(cues, basestring):
cues = cues.split('_')
return W[[(c in cues) for c in W.index]].sum()
def _rwUpdate(W, D, O, Alpha, Beta, Lambda):
Vtotal = np.dot(W.T, D)
L = O * Lambda
Vdelta = Alpha * Beta * (L - Vtotal)
W += D[:,np.newaxis] * Vdelta
try:
import _ndl
rwUpdate = _ndl.rwUpdate
except ImportError:
rwUpdate = _rwUpdate
def rw(data, Alpha=0.1, Beta=0.1, Lambda=1.0, M=50000, trajectory=False):
# code cues
cues = DictVectorizer(dtype=np.int, sparse=False)
D = cues.fit_transform([explode(c) for c in data.Cues])
# code outcomes
out = DictVectorizer(dtype=np.int, sparse=False)
O = out.fit_transform([explode(c) for c in data.Outcomes])
# weight matrix
W = np.zeros((len(cues.get_feature_names()), len(out.get_feature_names())))
E = data.Frequency / sum(data.Frequency)
rand = alias.multinomial(E)
history = dict()
iter = 0
while iter < M:
iter += 1
item = rand.draw()
rwUpdate(W, D[item,:], O[item,:], Alpha, Beta, Lambda)
if trajectory:
history[iter] = pd.DataFrame(W, columns=out.get_feature_names(), index=cues.get_feature_names(), copy=True)
if trajectory:
return pd.Panel.from_dict(history)
else:
return pd.DataFrame(W, columns=out.get_feature_names(), index=cues.get_feature_names())