soggle /soggle/features.py

Language Python Lines 317
MD5 Hash 8b7b1a5636cf0f740faaec69d392ea6e Estimated Cost $5,958 (why?)
Repository https://bitbucket.org/dnouri/soggle.git View Raw File View Project SPDX
  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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
import dateutil
import re

import nltk
import numpy as np
import pandas
from scipy import sparse
from sklearn.base import BaseEstimator
from sklearn.utils import shuffle

from .introspect import print_stats
from .util import cached
from .util import timed


df_converters = {
    'PostCreationDate': dateutil.parser.parse,
    'OwnerCreationDate': dateutil.parser.parse,
    }


def read_dataframe(filename, converters=df_converters):
    with timed("Reading dataframe from %s ..." % filename):
        df = pandas.io.parsers.read_csv(filename, converters=df_converters)
    return df


class Dataset(object):
    classes = {
        'not a real question': 0,
        'not constructive': 1,
        'off topic': 2,
        'open': 3,
        'too localized': 4,
        }
    n_classes = len(set(classes.values()))

    def __init__(self, filename, truncate_start=0.0, truncate_end=1.0):
        df = read_dataframe(filename)  # load directly with numpy?

        truncate_start = df.shape[0] * truncate_start
        truncate_end = df.shape[0] * truncate_end
        df = df[truncate_start:truncate_end]
        print_stats(df)

        if "OpenStatus" in df:
            self.target = np.array(df["OpenStatus"].map(self.classes))
            del df['OpenStatus']
            del df['PostClosedDate']

        self.data = np.array(df)

        # Convert nan tags to ''
        self.data[:, 8:13][self.data[:, 8:13] == np.nan] = ''

    @property
    def categories(self):
        items = sorted(self.classes.items(), key=lambda p: p[1])
        return [p[0] for p in items]

    def shuffle(self, random_state=43):
        self.data, self.target = shuffle(
            self.data, self.target, random_state=random_state)


class TextExtractor(BaseEstimator):
    def __init__(
        self,
        include_title=2,
        include_body=True,
        include_tags=1,
        replace_code=False,
        ):
        self.include_title = include_title
        self.include_body = include_body
        self.include_tags = include_tags
        self.replace_code = replace_code

    def _get_param_names(self):
        return (
            'include_title',
            'include_body',
            'include_tags',
            'replace_code',
            )

    @staticmethod
    def _replace_code(text):
        # XXX turn into regex replace
        result = ''
        for line in text.splitlines(True):
            if line.startswith('    ') or line.startswith('\t'):
                result += 'CODE\n'
            else:
                result += line
        return result

    def fit(self, X, y=None):
        return self

    def transform(self, X):
        text = ''

        if self.include_title:
            title = X[:, 6]
            text += (title + '\n') * self.include_title

        if self.include_body:
            body = X[:, 7]
            if self.replace_code:
                body = np.array([self._replace_code(b) for b in body],
                                dtype=object)
            text += body + '\n'

        if self.include_tags:
            for num in range(0, 5):
                text += (X[:, 8 + num] + ' ') * self.include_tags

        return text


# Blatanlty stolen from https://github.com/amueller/kaggle_insults
class DensifyTransformer(BaseEstimator):
    def fit(self, X, y=None):
        return self

    def transform(self, X):
        if sparse.issparse(X):
            X = X.toarray()
        return X


# Blatanlty stolen from https://github.com/amueller/kaggle_insults
class FeatureStacker(BaseEstimator):
    """Stacks several transformer objects to yield concatenated features.
    Similar to pipeline, a list of tuples ``(name, estimator)`` is passed
    to the constructor.
    """
    def __init__(self, transformer_list, verbose=0):
        self.transformer_list = transformer_list
        self.verbose = verbose

    def get_feature_names(self):
        pass

    def fit(self, X, y=None):
        for name, trans in self.transformer_list:
            trans.fit(X, y)
        return self

    def transform(self, X):
        features = []
        for name, trans in self.transformer_list:
            features.append(trans.transform(X))
        issparse = [sparse.issparse(f) for f in features]
        if np.any(issparse):
            if len(features) > 1:
                features = sparse.hstack(features).tocsr()
            else:
                features = features[0].tocsr()
        else:
            features = np.hstack(features)
        if self.verbose:
            print "[FeatureStacker] Collected %s features." % (features.shape,)
        return features

    def get_params(self, deep=True):
        if not deep:
            return super(FeatureStacker, self).get_params(deep=False)
        else:
            out = dict(self.transformer_list)
            for name, trans in self.transformer_list:
                for key, value in trans.get_params(deep=True).iteritems():
                    out['%s__%s' % (name, key)] = value
            return out


def _transform_cache_key(self, X):
    return ','.join([
        str(X[:20]),
        str(X[-20:]),
        str(X.shape),
        str(sorted(self.get_params().items())),
        ])


def multiply_features(X, names=None):
    new_features = []
    new_names = []
    for i in range(X.shape[1] - 1):
        for j in range(i + 1, X.shape[1]):
            new_features.append(X[:, i] * X[:, j])
            if names is not None:
                new_names.append('%s X %s' % (names[i], names[j]))

    new_features = np.vstack(new_features).T
    if new_names:
        new_features = new_features, new_names

    return new_features


class TextFeatures(BaseEstimator):
    """Features from the posts' texts.  Does not include tf-idf.
    """
    token_pattern = re.compile(ur"\b\w\w+\b")

    feature_names = np.array([
        'n_words',
        'n_chars',
        'n_words_title',
        'n_chars_title',
        'n_tags',
        'question2',
        'excla2',
        'paragraphs',
        'urls',
        ])

    def get_feature_names(self):
        return self.feature_names

    def fit(self, X, y=None):
        return self

    # Beware: the cached decorator potentially hides any changes you
    # make inside this method.
    @cached(_transform_cache_key)
    def transform(self, X):
        documents = TextExtractor().transform(X)
        titles = X[:, 6]

        word_lists = [
            np.array(self.token_pattern.findall(d)) for d in documents]

        n_words = np.array([len(w) for w in word_lists], dtype=float)
        n_chars = [len(d) for d in documents]
        n_words_title = [len(t.split()) for t in titles]
        n_chars_title = [len(t) for t in titles]
        n_tags = [len(d[d.rfind('\n'):].split()) for d in documents]
        question2 = [c.count("??") for c in documents]
        excla2 = [c.count("!!") for c in documents]
        paragraphs = [c.count("\n\n") for c in documents]
        urls = [c.count("://") for c in documents]

        features = np.array([
            n_words,
            n_chars,
            n_words_title,
            n_chars_title,
            n_tags,
            question2,
            excla2,
            paragraphs,
            urls,
            ]).T

        return np.hstack([
            features,
            (features + 0.1) ** -1.0,
            ])


class LanguageFeatures(BaseEstimator):
    features_names = np.array([
        ])

    def get_feature_names(self):
        return self.feature_names

    def fit(self, X, y=None):
        return self

    def transform(self, X):
        titles = X[:, 6]

        tagged = []
        for title in titles:
            tokens = nltk.word_tokenize(title)
            pos_tagged = nltk.pos_tag(tokens)
            tagged.append(' '.join([t[1] for t in pos_tagged]))

        return np.array(tagged)


class PostFeatures(BaseEstimator):
    """Features extracted from post metadata, such as dates.
    """
    features_names = np.array([
        'user_age',
        'reputation_at_post_creation',
        'owner_undeleted_answer_count_at_post_time',
        ])

    def get_feature_names(self):
        return self.feature_names

    def fit(self, X, y=None):
        return self

    def transform(self, X):
        post_creation_date = X[:, 1]
        owner_creation_date = X[:, 3]
        seconds = np.vectorize(lambda x: x.seconds)
        user_age = seconds(post_creation_date - owner_creation_date)

        reputation_at_post_creation = X[:, 4]
        owner_undeleted_answer_count_at_post_time = X[:, 5]

        features = np.array([
            user_age,
            reputation_at_post_creation.astype('float'),
            owner_undeleted_answer_count_at_post_time.astype('float'),
            ]).T

        return np.hstack([features, (features + 0.1) ** -1.0])
Back to Top