-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclassifier.py
More file actions
53 lines (42 loc) · 1.71 KB
/
classifier.py
File metadata and controls
53 lines (42 loc) · 1.71 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
# -*- mode: Python; coding: utf-8 -*-
"""A simple framework for supervised text classification."""
from abc import ABCMeta, abstractmethod, abstractproperty
from cPickle import dump, load, HIGHEST_PROTOCOL as HIGHEST_PICKLE_PROTOCOL
class Classifier(object):
"""An abstract text classifier.
Subclasses must provide training and classification methods, as well as
an implementation of the model property. The internal representation of
a classifier's model is entirely up to the subclass, but the read/write
model property must return/accept a single object (e.g., a list of
probability distributions)."""
__metaclass__ = ABCMeta
def __init__(self, model=None):
if isinstance(model, (basestring, file)):
self.load_model(model)
else:
self.model = model
def get_model(self): return None
def set_model(self, model): pass
model = abstractproperty(get_model, set_model)
def save(self, file):
"""Save the current model to the given file."""
if isinstance(file, basestring):
with open(file, "wb") as file:
self.save(file)
else:
dump(self.model, file, HIGHEST_PICKLE_PROTOCOL)
def load(self, file):
"""Load a saved model from the given file."""
if isinstance(file, basestring):
with open(file, "rb") as file:
self.load(file)
else:
self.model = load(file)
@abstractmethod
def train(self, instances):
"""Construct a statistical model from labeled instances."""
pass
@abstractmethod
def classify(self, instance):
"""Classify an instance and return the expected label."""
return None