import tables import pickle import numpy as np import logging logger = logging.getLogger("SemanticModel") class SemanticModel(object): """This class defines a semantic vector-space model based on HAL or LSA with some prescribed preprocessing pipeline. It contains two important variables: vocab and data. vocab is a 1D list (or array) of words. data is a 2D array (features by words) of word-feature values. """ def __init__(self, data, vocab): """Initializes a SemanticModel with the given [data] and [vocab]. """ self.data = data self.vocab = vocab def get_ndim(self): """Returns the number of dimensions in this model. """ return self.data.shape[0] ndim = property(get_ndim) def get_vindex(self): """Return {vocab: index} dictionary. """ if "_vindex" not in dir(self): self._vindex = dict([(v,i) for (i,v) in enumerate(self.vocab)]) return self._vindex vindex = property(get_vindex) def __getitem__(self, word): """Returns the vector corresponding to the given [word]. """ return self.data[:,self.vindex[word]] def load_root(self, rootfile, vocab): """Load the SVD-generated semantic vector space from [rootfile], assumed to be an HDF5 file. """ roothf = tables.open_file(rootfile) self.data = roothf.get_node("/R").read() self.vocab = vocab roothf.close() def load_ascii_root(self, rootfile, vocab): """Loads the SVD-generated semantic vector space from [rootfile], assumed to be an ASCII dense matrix output from SDVLIBC. """ vtfile = open(rootfile) nrows, ncols = map(int, vtfile.readline().split()) Vt = np.zeros((nrows,ncols)) nrows_done = 0 for row in vtfile: Vt[nrows_done,:] = map(float, row.split()) nrows_done += 1 self.data = Vt self.vocab = vocab def restrict_by_occurrence(self, min_rank=60, max_rank=60000): """Restricts the data to words that have an occurrence rank lower than [min_rank] and higher than [max_rank]. """ logger.debug("Restricting words by occurrence..") nwords = self.data.shape[1] wordranks = np.argsort(np.argsort(self.data[0,:])) goodwords = np.nonzero(np.logical_and((nwords-wordranks)>min_rank, (nwords-wordranks)