-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathencoding.py
More file actions
175 lines (119 loc) · 6.76 KB
/
Copy pathencoding.py
File metadata and controls
175 lines (119 loc) · 6.76 KB
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
import re
import numpy as np
class EncodingScheme(object):
"""
EncodingScheme is a class to make Markov model data out of raw data.
Input:
list_of_regex_bins: a list of regular expressions, as strings, representing how to "bin"
the raw data. eg: [ '[0-9]', '[a-z]', '[A-Z]' ]
A -1 is inserted if the item cannot be binned correctly.
Notes: -Try not to overlap bins.
-To specify all unique bins, leave the list empty.
-An exception is thrown if a item is not able to be binned.
-To specify some bins, and have everything else unique,
to_append_to_end:
if the series data is not the same length ( eg: password data), this specifies what to append
to end before performing analysis. If not needed, leave as None. This is still buggy.
garbage_bin: a boolean to include a garbage bin, ie a bin that collects everything not collected.
Notes: having garbage_bin to True is pretty much useless if all unique bins is set, ie.
having list_of_regex_bins = []
attributes:
self.unique_bins: a dictionary of the bins used to encode the data and the encode mapping.
self.realized_bins: a dictionary of the bins used to encode the realized data values that
satisfy the bins. Useful for debugging and seeing what garbage is collected
with realized_bins['garbage']
Methods:
encode(raw_data): returns the encoded data as a generator.
"""
def __init__(self, list_of_regex_bins=[], to_append_to_end = None, garbage_bin=False ):
self.list_of_regex_bins = list_of_regex_bins
self.to_append_to_end = to_append_to_end
self.unique_bins = dict()
self.number_of_bins = -1
self.garbage_bin = garbage_bin
self.realized_bins = dict( zip ( self.list_of_regex_bins, [ set() for i in xrange(len(list_of_regex_bins) ) ] ) )
def encode(self, data):
"""
This function creates a representation of the data.
Input:
data: a list of iterables (eg: strings, lists, arrays, np.arrays).
output:
a generator of 1d numpy arrays of computer-readable time series, starting at 0 to unique_number of elements.
ex:
eScheme = Encoding_scheme( )
input = ['data', 'atad', 'dta']
eScheme.encode( data)
"""
self._init_encode(data)
data = self.yield_data() #returns a generator
self._create_dict(data)
data = self.append_ends( self.data, self.series_length ) #returns a generator
return self._encode_generator(data)
def _encode_generator(self, data):
for series in data:
encoded_data = np.zeros( self.series_length, dtype="int" )
for col_i, item in enumerate(series):
encoded_data[col_i] = self._encode( item )
yield encoded_data
def _create_dict(self, data):
for series in data:
for item in series:
self._encode( item )
def _init_encode(self, data):
self.data = data
self.series_length = self._max_length(data)
def decode(self, sample):
try:
return "".join([ self.inv_map[s] for s in sample ])
except:
self.inv_map = dict((v,k) for k, v in self.unique_bins.iteritems())
return "".join([ self.inv_map[s] for s in sample ])
def _max_length(self,data):
return max( map( len, data ) )
def yield_data(self):
for series in self.data:
yield series
def append_ends( self, data, length):
for series in data:
if len(series)<length:
series+= self.to_append_to_end*(length-len(series) ) #this is too specific
yield series
def _encode(self, item):
"""
This both creates the dictionares/bins and returns the proper encoding.
"""
if not self.list_of_regex_bins:
#more efficient in python to use try-else
try:
return self.unique_bins[str(item)]
except KeyError:
#This won't distinguish 1.0 from 1 etc.
self.number_of_bins +=1
self.unique_bins[str(item)] = self.number_of_bins
return self.unique_bins[str(item)]
else:
for regex in self.list_of_regex_bins:
if re.match( regex, str(item) ):
try:
return self.unique_bins[regex]
except KeyError:
self.number_of_bins +=1
self.unique_bins[regex] = self.number_of_bins
self.realized_bins[regex].add( item)
return self.unique_bins[regex]
#we didnt collect it. See if garbage bin is enabled.
if self.garbage_bin:
if 'garbage' not in self.unique_bins.keys():
self.number_of_bins +=1
self.unique_bins['garbage'] = self.number_of_bins
self.realized_bins['garbage'] = set()
self.realized_bins['garbage'].add( item)
return self.unique_bins['garbage']
else:
raise BinningError(item)
class BinningError( Exception):
#thrown if no bin is found for some value.
def __init__(self, value):
self.value = value
def __str__(self):
return "Could not find a bin for value %s."%repr(self.value)