INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Input a graph and output a DAG.
def dagify_min_edge(g): """Input a graph and output a DAG. The heuristic is to reverse the edge with the lowest score of the cycle if possible, else remove it. Args: g (networkx.DiGraph): Graph to modify to output a DAG Returns: networkx.DiGraph: DAG made out of the input graph. ...
Returns the weighted average and standard deviation.
def weighted_mean_and_std(values, weights): """ Returns the weighted average and standard deviation. values, weights -- numpy ndarrays with the same shape. """ average = np.average(values, weights=weights, axis=0) variance = np.dot(weights, (values - average) ** 2) / weights.sum() # Fast and n...
Run an instance of GNN testing causal direction.
def GNN_instance(x, idx=0, device=None, nh=20, **kwargs): """Run an instance of GNN, testing causal direction. :param m: data corresponding to the config : (N, 2) data, [:, 0] cause and [:, 1] effect :param pair_idx: print purposes :param run: numner of the run (for GPU dispatch) :param device: dev...
Pass data through the net structure.
def forward(self, x): """Pass data through the net structure. :param x: input data: shape (:,1) :type x: torch.Variable :return: output of the shallow net :rtype: torch.Variable """ self.noise.normal_() return self.layers(th.cat([x, self.noise], 1))
Run the GNN on a pair x y of FloatTensor data.
def run(self, x, y, lr=0.01, train_epochs=1000, test_epochs=1000, idx=0, verbose=None, **kwargs): """Run the GNN on a pair x,y of FloatTensor data.""" verbose = SETTINGS.get_default(verbose=verbose) optim = th.optim.Adam(self.parameters(), lr=lr) running_loss = 0 teloss = 0 ...
Run multiple times GNN to estimate the causal direction.
def predict_proba(self, a, b, nb_runs=6, nb_jobs=None, gpu=None, idx=0, verbose=None, ttest_threshold=0.01, nb_max_runs=16, train_epochs=1000, test_epochs=1000): """Run multiple times GNN to estimate the causal direction. Args: a (np.ndarray): Var...
Redefine the causes of the graph.
def init_variables(self, verbose=False): """Redefine the causes of the graph.""" # Resetting adjacency matrix for i in range(self.nodes): for j in np.random.choice(range(self.nodes), np.random.randint( 0,...
Generate data from an FCM containing cycles.
def generate(self, nb_steps=100, averaging=50, rescale=True): """Generate data from an FCM containing cycles.""" if self.cfunctions is None: self.init_variables() new_df = pd.DataFrame() causes = [[c for c in np.nonzero(self.adjacency_matrix[:, j])[0]] for j...
Apply causal discovery on observational data using CAM.
def create_graph_from_data(self, data, **kwargs): """Apply causal discovery on observational data using CAM. Args: data (pandas.DataFrame): DataFrame containing the data Returns: networkx.DiGraph: Solution given by the CAM algorithm. """ # Building setup...
For one variable predict its neighbouring nodes.
def predict_features(self, df_features, df_target, idx=0, **kwargs): """For one variable, predict its neighbouring nodes. Args: df_features (pandas.DataFrame): df_target (pandas.Series): idx (int): (optional) for printing purposes kwargs (dict): additiona...
For one variable predict its neighbouring nodes.
def predict_features(self, df_features, df_target, idx=0, C=.1, **kwargs): """For one variable, predict its neighbouring nodes. Args: df_features (pandas.DataFrame): df_target (pandas.Series): idx (int): (optional) for printing purposes kwargs (dict): add...
For one variable predict its neighbouring nodes.
def predict_features(self, df_features, df_target, idx=0, **kwargs): """For one variable, predict its neighbouring nodes. Args: df_features (pandas.DataFrame): df_target (pandas.Series): idx (int): (optional) for printing purposes kwargs (dict): additiona...
For one variable predict its neighbouring nodes.
def predict_features(self, df_features, df_target, idx=0, **kwargs): """For one variable, predict its neighbouring nodes. Args: df_features (pandas.DataFrame): df_target (pandas.Series): idx (int): (optional) for printing purposes kwargs (dict): additiona...
For one variable predict its neighbouring nodes.
def predict_features(self, df_features, df_target, idx=0, **kwargs): """For one variable, predict its neighbouring nodes. Args: df_features (pandas.DataFrame): df_target (pandas.Series): idx (int): (optional) for printing purposes kwargs (dict): additiona...
Passing data through the network.
def forward(self, x): """Passing data through the network. :param x: 2d tensor containing both (x,y) Variables :return: output of the net """ features = self.conv(x).mean(dim=2) return self.dense(features)
Fit the NCC model.
def fit(self, x_tr, y_tr, epochs=50, batchsize=32, learning_rate=0.01, verbose=None, device=None): """Fit the NCC model. Args: x_tr (pd.DataFrame): CEPC format dataframe containing the pairs y_tr (pd.DataFrame or np.ndarray): labels associated to the pairs ...
Infer causal directions using the trained NCC pairwise model.
def predict_proba(self, a, b, device=None): """Infer causal directions using the trained NCC pairwise model. Args: a (numpy.ndarray): Variable 1 b (numpy.ndarray): Variable 2 device (str): Device to run the algorithm on (defaults to ``cdt.SETTINGS.default_device``) ...
Args: x_tr ( pd. DataFrame ): CEPC format dataframe containing the pairs y_tr ( pd. DataFrame or np. ndarray ): labels associated to the pairs epochs ( int ): number of train epochs learning rate ( float ): learning rate of Adam verbose ( bool ): verbosity ( defaults to cdt. SETTINGS. verbose ) device ( str ): cuda or ...
def predict_dataset(self, df, device=None, verbose=None): """ Args: x_tr (pd.DataFrame): CEPC format dataframe containing the pairs y_tr (pd.DataFrame or np.ndarray): labels associated to the pairs epochs (int): number of train epochs learning rate (float)...
Convert phrase to normilized file name.
def phrase_to_filename(self, phrase): """Convert phrase to normilized file name.""" # remove non-word characters name = re.sub(r"[^\w\s\.]", '', phrase.strip().lower()) # replace whitespace with underscores name = re.sub(r"\s+", '_', name) return name + '.png'
A URL that can be used to open the page.
def seed_url(self): """A URL that can be used to open the page. The URL is formatted from :py:attr:`URL_TEMPLATE`, which is then appended to :py:attr:`base_url` unless the template results in an absolute URL. :return: URL that can be used to open the page. :rtype: str ...
Open the page.
def open(self): """Open the page. Navigates to :py:attr:`seed_url` and calls :py:func:`wait_for_page_to_load`. :return: The current page object. :rtype: :py:class:`Page` :raises: UsageError """ if self.seed_url: self.driver_adapter.open(self.seed_ur...
Wait for the page to load.
def wait_for_page_to_load(self): """Wait for the page to load.""" self.wait.until(lambda _: self.loaded) self.pm.hook.pypom_after_wait_for_page_to_load(page=self) return self
Register the Selenium specific driver implementation.
def register(): """ Register the Selenium specific driver implementation. This register call is performed by the init module if selenium is available. """ registerDriver( ISelenium, Selenium, class_implements=[ Firefox, Chrome, Ie,...
Root element for the page region.
def root(self): """Root element for the page region. Page regions should define a root element either by passing this on instantiation or by defining a :py:attr:`_root_locator` attribute. To reduce the chances of hitting :py:class:`~selenium.common.exceptions.StaleElementReferenceExcept...
Wait for the page region to load.
def wait_for_region_to_load(self): """Wait for the page region to load.""" self.wait.until(lambda _: self.loaded) self.pm.hook.pypom_after_wait_for_region_to_load(region=self) return self
Finds an element on the page.
def find_element(self, strategy, locator): """Finds an element on the page. :param strategy: Location strategy to use. See :py:class:`~selenium.webdriver.common.by.By` or :py:attr:`~pypom.splinter_driver.ALLOWED_STRATEGIES`. :param locator: Location of target element. :type strategy: st...
Finds elements on the page.
def find_elements(self, strategy, locator): """Finds elements on the page. :param strategy: Location strategy to use. See :py:class:`~selenium.webdriver.common.by.By` or :py:attr:`~pypom.splinter_driver.ALLOWED_STRATEGIES`. :param locator: Location of target elements. :type strategy: st...
Checks whether an element is present.
def is_element_present(self, strategy, locator): """Checks whether an element is present. :param strategy: Location strategy to use. See :py:class:`~selenium.webdriver.common.by.By` or :py:attr:`~pypom.splinter_driver.ALLOWED_STRATEGIES`. :param locator: Location of target element. :typ...
Checks whether an element is displayed.
def is_element_displayed(self, strategy, locator): """Checks whether an element is displayed. :param strategy: Location strategy to use. See :py:class:`~selenium.webdriver.common.by.By` or :py:attr:`~pypom.splinter_driver.ALLOWED_STRATEGIES`. :param locator: Location of target element. ...
Register driver adapter used by page object
def registerDriver(iface, driver, class_implements=[]): """ Register driver adapter used by page object""" for class_item in class_implements: classImplements(class_item, iface) component.provideAdapter(factory=driver, adapts=[iface], provides=IDriver)
Detects whether a string is JSON or HCL: param s: String that may contain HCL or JSON: returns: True if HCL False if JSON raises ValueError if neither
def isHcl(s): ''' Detects whether a string is JSON or HCL :param s: String that may contain HCL or JSON :returns: True if HCL, False if JSON, raises ValueError if neither ''' for c in s: if c.isspace(): continue if c ==...
Deserializes a string and converts it to a dictionary. The contents of the string must either be JSON or HCL.: returns: Dictionary
def loads(s): ''' Deserializes a string and converts it to a dictionary. The contents of the string must either be JSON or HCL. :returns: Dictionary ''' s = u(s) if isHcl(s): return HclParser().parse(s) else: return json.loads(s)
r - ?0 [ xX ] [ 0 - 9a - fA - F ] +
def t_hexnumber(self, t): r'-?0[xX][0-9a-fA-F]+' t.value = int(t.value, base=16) t.type = 'NUMBER' return t
r - ? \ d +
def t_intnumber(self, t): r'-?\d+' t.value = int(t.value) t.type = 'NUMBER' return t
r \
def t_string(self, t): # Start of a string r'\"' # abs_start is the absolute start of the string. We use this at the end # to know how many new lines we've consumed t.lexer.abs_start = t.lexer.lexpos # rel_pos is the begining of the unconsumed part of the string. It will ...
r ( ?< = \\ ) ( \ | \\ )
def t_string_escapedchar(self, t): # If a quote or backslash is escaped, build up the string by ignoring # the escape character. Should this be done for other characters? r'(?<=\\)(\"|\\)' t.lexer.string_value += ( t.lexer.lexdata[t.lexer.rel_pos : t.lexer.lexpos - 2] + t.val...
r \
def t_string_STRING(self, t): # End of the string r'\"' t.value = ( t.lexer.string_value + t.lexer.lexdata[t.lexer.rel_pos : t.lexer.lexpos - 1] ) t.lexer.lineno += t.lexer.lexdata[t.lexer.abs_start : t.lexer.lexpos - 1].count( '\n' ) t.lex...
r \ }
def t_stringdollar_rbrace(self, t): r'\}' t.lexer.braces -= 1 if t.lexer.braces == 0: # End of the dollar brace, back to the rest of the string t.lexer.begin('string')
r << - \ S + \ r? \ n
def t_tabbedheredoc(self, t): r'<<-\S+\r?\n' t.lexer.is_tabbed = True self._init_heredoc(t) t.lexer.begin('tabbedheredoc')
r << \ S + \ r? \ n
def t_heredoc(self, t): r'<<\S+\r?\n' t.lexer.is_tabbed = False self._init_heredoc(t) t.lexer.begin('heredoc')
Similar to the dict constructor but handles dups HCL is unclear on what one should do when duplicate keys are encountered. These comments aren t clear either: from decoder. go: if we re at the root or we re directly within a list decode into dicts otherwise lists from object. go: there s a flattened list structure
def objectlist_flat(self, lt, replace): ''' Similar to the dict constructor, but handles dups HCL is unclear on what one should do when duplicate keys are encountered. These comments aren't clear either: from decoder.go: if we're at the r...
top: objectlist
def p_top(self, p): "top : objectlist" if DEBUG: self.print_p(p) p[0] = self.objectlist_flat(p[1], True)
objectlist: objectlist objectitem
def p_objectlist_1(self, p): "objectlist : objectlist objectitem" if DEBUG: self.print_p(p) p[0] = p[1] + [p[2]]
objectlist: objectlist COMMA objectitem
def p_objectlist_2(self, p): "objectlist : objectlist COMMA objectitem" if DEBUG: self.print_p(p) p[0] = p[1] + [p[3]]
object: LEFTBRACE objectlist RIGHTBRACE
def p_object_0(self, p): "object : LEFTBRACE objectlist RIGHTBRACE" if DEBUG: self.print_p(p) p[0] = self.objectlist_flat(p[2], False)
object: LEFTBRACE objectlist COMMA RIGHTBRACE
def p_object_1(self, p): "object : LEFTBRACE objectlist COMMA RIGHTBRACE" if DEBUG: self.print_p(p) p[0] = self.objectlist_flat(p[2], False)
objectitem: objectkey EQUAL number | objectkey EQUAL BOOL | objectkey EQUAL STRING | objectkey EQUAL object | objectkey EQUAL list
def p_objectitem_0(self, p): ''' objectitem : objectkey EQUAL number | objectkey EQUAL BOOL | objectkey EQUAL STRING | objectkey EQUAL object | objectkey EQUAL list ''' if DEBUG: self.print_p(p) ...
block: blockId object
def p_block_0(self, p): "block : blockId object" if DEBUG: self.print_p(p) p[0] = (p[1], p[2])
block: blockId block
def p_block_1(self, p): "block : blockId block" if DEBUG: self.print_p(p) p[0] = (p[1], {p[2][0]: p[2][1]})
listitems: listitems COMMA listitem
def p_listitems_1(self, p): "listitems : listitems COMMA listitem" if DEBUG: self.print_p(p) p[0] = p[1] + [p[3]]
number: float
def p_number_1(self, p): "number : float" if DEBUG: self.print_p(p) p[0] = float(p[1])
number: int exp
def p_number_2(self, p): "number : int exp" if DEBUG: self.print_p(p) p[0] = float("{0}{1}".format(p[1], p[2]))
number: float exp
def p_number_3(self, p): "number : float exp" if DEBUG: self.print_p(p) p[0] = float("{0}{1}".format(p[1], p[2]))
exp: EPLUS NUMBER
def p_exp_0(self, p): "exp : EPLUS NUMBER" if DEBUG: self.print_p(p) p[0] = "e{0}".format(p[2])
exp: EMINUS NUMBER
def p_exp_1(self, p): "exp : EMINUS NUMBER" if DEBUG: self.print_p(p) p[0] = "e-{0}".format(p[2])
Initialize the parse table at install time
def _pre_install(): '''Initialize the parse table at install time''' # Generate the parsetab.dat file at setup time dat = join(setup_dir, 'src', 'hcl', 'parsetab.dat') if exists(dat): os.unlink(dat) sys.path.insert(0, join(setup_dir, 'src')) import hcl from hcl.parser import HclPa...
Add another row of data from a test suite
def append(self, linenumber, raw_text, cells): """Add another row of data from a test suite""" self.rows.append(Row(linenumber, raw_text, cells))
Return a list of steps ( statements that are not settings or comments )
def steps(self): """Return a list of steps (statements that are not settings or comments)""" steps = [] for statement in self.statements: if ((not statement.is_comment()) and (not statement.is_setting())): steps.append(statement) return steps
Return True if the first non - empty cell starts with #
def is_comment(self): '''Return True if the first non-empty cell starts with "#"''' for cell in self[:]: if cell == "": continue # this is the first non-empty cell. Check whether it is # a comment or not. if cell.lstrip().startswith("#"):...
Return an instance of SuiteFile ResourceFile SuiteFolder
def RobotFactory(path, parent=None): '''Return an instance of SuiteFile, ResourceFile, SuiteFolder Exactly which is returned depends on whether it's a file or folder, and if a file, the contents of the file. If there is a testcase table, this will return an instance of SuiteFile, otherwise it will ...
Iterator which visits all suites and suite files yielding test cases and keywords
def walk(self, *types): ''' Iterator which visits all suites and suite files, yielding test cases and keywords ''' requested = types if len(types) > 0 else [SuiteFile, ResourceFile, SuiteFolder, Testcase, Keyword] for thing in self.robot_files: if thing.__cla...
Return a list of all folders and test suite files (. txt. robot )
def robot_files(self): '''Return a list of all folders, and test suite files (.txt, .robot) ''' result = [] for name in os.listdir(self.path): fullpath = os.path.join(self.path, name) if os.path.isdir(fullpath): result.append(RobotFactory(fullpath,...
Iterator which can return all test cases and/ or keywords
def walk(self, *types): ''' Iterator which can return all test cases and/or keywords You can specify with objects to return as parameters; if no parameters are given, both tests and keywords will be returned. For example, to get only test cases, you could call it ...
The general idea is to do a quick parse creating a list of tables. Each table is nothing more than a list of rows with each row being a list of cells. Additional parsing such as combining rows into statements is done on demand. This first pass is solely to read in the plain text and organize it by table.
def _load(self, path): ''' The general idea is to do a quick parse, creating a list of tables. Each table is nothing more than a list of rows, with each row being a list of cells. Additional parsing such as combining rows into statements is done on demand. This first pas...
Return suite or resource or None
def type(self): '''Return 'suite' or 'resource' or None This will return 'suite' if a testcase table is found; It will return 'resource' if at least one robot table is found. If no tables are found it will return None ''' robot_tables = [table for table in self.tables i...
Generator which returns all keywords in the suite
def keywords(self): '''Generator which returns all keywords in the suite''' for table in self.tables: if isinstance(table, KeywordTable): for keyword in table.keywords: yield keyword
Regurgitate the tables and rows
def dump(self): '''Regurgitate the tables and rows''' for table in self.tables: print("*** %s ***" % table.name) table.dump()
Generator which returns all of the statements in all of the settings tables
def settings(self): '''Generator which returns all of the statements in all of the settings tables''' for table in self.tables: if isinstance(table, SettingTable): for statement in table.statements: yield statement
Generator which returns all of the statements in all of the variables tables
def variables(self): '''Generator which returns all of the statements in all of the variables tables''' for table in self.tables: if isinstance(table, VariableTable): # FIXME: settings have statements, variables have rows WTF? :-( for statement in table.rows: ...
Return a list of statements
def statements(self): '''Return a list of statements This is done by joining together any rows that have continuations ''' # FIXME: no need to do this every time; we should cache the # result if len(self.rows) == 0: return [] current_statemen...
The idea is we recognize when we have a new testcase by checking the first cell. If it s not empty and not a comment we have a new test case.
def append(self, row): ''' The idea is, we recognize when we have a new testcase by checking the first cell. If it's not empty and not a comment, we have a new test case. ''' if len(row) == 0: # blank line. Should we throw it away, or append a BlankLine ob...
Report an error or warning
def report(self, obj, message, linenum, char_offset=0): """Report an error or warning""" self.controller.report(linenumber=linenum, filename=obj.path, severity=self.severity, message=message, rulename = self.__class__.__name__, ...
Algorithm from https:// www. python. org/ dev/ peps/ pep - 0257/
def doc(self): '''Algorithm from https://www.python.org/dev/peps/pep-0257/''' if not self.__doc__: return "" lines = self.__doc__.expandtabs().splitlines() # Determine minimum indentation (first line doesn't count): indent = sys.maxsize for line in lines[1:]...
Parse command line arguments and run rflint
def run(self, args): """Parse command line arguments, and run rflint""" self.args = self.parse_and_process_args(args) if self.args.version: print(__version__) return 0 if self.args.rulefile: for filename in self.args.rulefile: ...
Print a list of all rules
def list_rules(self): """Print a list of all rules""" for rule in sorted(self.all_rules, key=lambda rule: rule.name): print(rule) if self.args.verbose: for line in rule.doc.split("\n"): print(" ", line)
Report a rule violation
def report(self, linenumber, filename, severity, message, rulename, char): """Report a rule violation""" if self._print_filename is not None: # we print the filename only once. self._print_filename # will get reset each time a new file is processed. print("+ " + self...
Returns a list of rules of a given class Rules are treated as singletons - we only instantiate each rule once.
def _get_rules(self, cls): """Returns a list of rules of a given class Rules are treated as singletons - we only instantiate each rule once. """ result = [] for rule_class in cls.__subclasses__(): rule_name = rule_class.__name__.lower() ...
Import the given rule file
def _load_rule_file(self, filename): """Import the given rule file""" if not (os.path.exists(filename)): sys.stderr.write("rflint: %s: No such file or directory\n" % filename) return try: basename = os.path.basename(filename) (name, ext) = os.path....
Handle the parsing of command line arguments.
def parse_and_process_args(self, args): """Handle the parsing of command line arguments.""" parser = argparse.ArgumentParser( prog="python -m rflint", description="A style checker for robot framework plain text files.", formatter_class=argparse.RawDescriptionHelpForm...
Creates a customized Draft4ExtendedValidator.
def from_resolver(cls, spec_resolver): """Creates a customized Draft4ExtendedValidator. :param spec_resolver: resolver for the spec :type resolver: :class:`jsonschema.RefResolver` """ spec_validators = cls._get_spec_validators(spec_resolver) return validators.extend(Draf...
Creates json documents validator from spec resolver.: param spec_resolver: reference resolver.
def create(self, spec_resolver): """Creates json documents validator from spec resolver. :param spec_resolver: reference resolver. :return: RefResolver for spec with cached remote $refs used during validation. :rtype: :class:`jsonschema.RefResolver` """ valid...
While yaml supports integer keys these are not valid in json and will break jsonschema. This method coerces all keys to strings.
def construct_mapping(self, node, deep=False): """While yaml supports integer keys, these are not valid in json, and will break jsonschema. This method coerces all keys to strings. """ mapping = super(ExtendedSafeConstructor, self).construct_mapping( node, deep) ...
Open a file read it and return its contents.
def read_yaml_file(path, loader=ExtendedSafeLoader): """Open a file, read it and return its contents.""" with open(path) as fh: return load(fh, loader)
Creates validators generator for the spec resolver.
def from_spec_resolver(cls, spec_resolver): """Creates validators generator for the spec resolver. :param spec_resolver: resolver for the spec :type instance_resolver: :class:`jsonschema.RefResolver` """ deref = DerefValidatorDecorator(spec_resolver) for key, validator_c...
Grades a specified submission using specified models grader_data - A dictionary: { model: trained model extractor: trained feature extractor prompt: prompt for the question algorithm: algorithm for the question } submission - The student submission ( string )
def grade(grader_data,submission): """ Grades a specified submission using specified models grader_data - A dictionary: { 'model' : trained model, 'extractor' : trained feature extractor, 'prompt' : prompt for the question, 'algorithm' : algorithm for the question, } ...
Grades a set of numeric and textual features using a generic model grader_data -- dictionary containing: { algorithm - Type of algorithm to use to score } numeric_features - list of numeric features to predict on textual_features - list of textual feature to predict on
def grade_generic(grader_data, numeric_features, textual_features): """ Grades a set of numeric and textual features using a generic model grader_data -- dictionary containing: { 'algorithm' - Type of algorithm to use to score } numeric_features - list of numeric features to predict on ...
Determines a confidence in a certain score given proper input parameters algorithm - from util_functions. AlgorithmTypes model - a trained model grader_feats - a row of features used by the model for classification/ regression score - The score assigned to the submission by a prior model
def get_confidence_value(algorithm,model,grader_feats,score, scores): """ Determines a confidence in a certain score, given proper input parameters algorithm- from util_functions.AlgorithmTypes model - a trained model grader_feats - a row of features used by the model for classification/regression ...
Creates a path to model files model_path - string
def create_model_path(model_path): """ Creates a path to model files model_path - string """ if not model_path.startswith("/") and not model_path.startswith("models/"): model_path="/" + model_path if not model_path.startswith("models"): model_path = "models" + model_path if n...
Strips illegal characters from a string. Used to sanitize input essays. Removes all non - punctuation digit or letter characters. Returns sanitized string. string - string
def sub_chars(string): """ Strips illegal characters from a string. Used to sanitize input essays. Removes all non-punctuation, digit, or letter characters. Returns sanitized string. string - string """ #Define replacement patterns sub_pat = r"[^A-Za-z\.\?!,';:]" char_pat = r"\." ...
Uses aspell to spell correct an input string. Requires aspell to be installed and added to the path. Returns the spell corrected string if aspell is found original string if not. string - string
def spell_correct(string): """ Uses aspell to spell correct an input string. Requires aspell to be installed and added to the path. Returns the spell corrected string if aspell is found, original string if not. string - string """ # Create a temp file so that aspell could be used # By d...
Generates ngrams ( word sequences of fixed length ) from an input token sequence. tokens is a list of words. min_n is the minimum length of an ngram to return. max_n is the maximum length of an ngram to return. returns a list of ngrams ( words separated by a space )
def ngrams(tokens, min_n, max_n): """ Generates ngrams(word sequences of fixed length) from an input token sequence. tokens is a list of words. min_n is the minimum length of an ngram to return. max_n is the maximum length of an ngram to return. returns a list of ngrams (words separated by a spa...
Makes a list unique
def f7(seq): """ Makes a list unique """ seen = set() seen_add = seen.add return [x for x in seq if x not in seen and not seen_add(x)]
Generates a count of the number of times each unique item appears in a list
def count_list(the_list): """ Generates a count of the number of times each unique item appears in a list """ count = the_list.count result = [(item, count(item)) for item in set(the_list)] result.sort() return result
Given an input string part of speech tags the string then generates a list of ngrams that appear in the string. Used to define grammatically correct part of speech tag sequences. Returns a list of part of speech tag sequences.
def regenerate_good_tokens(string): """ Given an input string, part of speech tags the string, then generates a list of ngrams that appear in the string. Used to define grammatically correct part of speech tag sequences. Returns a list of part of speech tag sequences. """ toks = nltk.word_to...
Uses a fisher test to find words that are significant in that they separate high scoring essays from low scoring essays. text is a list of input essays. score is a list of scores with score [ n ] corresponding to text [ n ] max_feats is the maximum number of features to consider in the first pass max_feats2 is the maxi...
def get_vocab(text, score, max_feats=750, max_feats2=200): """ Uses a fisher test to find words that are significant in that they separate high scoring essays from low scoring essays. text is a list of input essays. score is a list of scores, with score[n] corresponding to text[n] max_feats is t...
Calculates string edit distance between string 1 and string 2. Deletion insertion substitution and transposition all increase edit distance.
def edit_distance(s1, s2): """ Calculates string edit distance between string 1 and string 2. Deletion, insertion, substitution, and transposition all increase edit distance. """ d = {} lenstr1 = len(s1) lenstr2 = len(s2) for i in xrange(-1, lenstr1 + 1): d[(i, -1)] = i + 1 f...
Generates cross validated predictions using an input classifier and data. clf is a classifier that implements that implements the fit and predict methods. arr is the input data array ( X ) sel_score is the target list ( y ). y [ n ] corresponds to X [ n: ] num_chunks is the number of cross validation folds to use Retur...
def gen_cv_preds(clf, arr, sel_score, num_chunks=3): """ Generates cross validated predictions using an input classifier and data. clf is a classifier that implements that implements the fit and predict methods. arr is the input data array (X) sel_score is the target list (y). y[n] corresponds to X...
Fits a classifier to data and a target score clf is an input classifier that implements the fit method. arr is a data array ( X ) sel_score is the target list ( y ) where y [ n ] corresponds to X [ n: ] sim_fit is not a useful return value. Instead the clf is the useful output.
def gen_model(clf, arr, sel_score): """ Fits a classifier to data and a target score clf is an input classifier that implements the fit method. arr is a data array(X) sel_score is the target list (y) where y[n] corresponds to X[n,:] sim_fit is not a useful return value. Instead the clf is the u...
Generates predictions on a novel data array using a fit classifier clf is a classifier that has already been fit arr is a data array identical in dimension to the array clf was trained on Returns the array of predictions.
def gen_preds(clf, arr): """ Generates predictions on a novel data array using a fit classifier clf is a classifier that has already been fit arr is a data array identical in dimension to the array clf was trained on Returns the array of predictions. """ if(hasattr(clf, "predict_proba")): ...
Calculates the average value of a list of numbers Returns a float
def calc_list_average(l): """ Calculates the average value of a list of numbers Returns a float """ total = 0.0 for value in l: total += value return total / len(l)