docstring
stringlengths
52
499
function
stringlengths
67
35.2k
__index_level_0__
int64
52.6k
1.16M
Given the location of the 'middle snake', split the diff in two parts and recurse. Args: text1: Old string to be diffed. text2: New string to be diffed. x: Index of split point in text1. y: Index of split point in text2. deadline: Time at which to bail if not yet complete. Re...
def diff_bisectSplit(self, text1, text2, x, y, deadline): text1a = text1[:x] text2a = text2[:y] text1b = text1[x:] text2b = text2[y:] # Compute both diffs serially. diffs = self.diff_main(text1a, text2a, False, deadline) diffsb = self.diff_main(text1b, text2b, False, deadline) ret...
368,591
Split two texts into an array of strings. Reduce the texts to a string of hashes where each Unicode character represents one line. Args: text1: First string. text2: Second string. Returns: Three element tuple, containing the encoded text1, the encoded text2 and the array of unique...
def diff_linesToChars(self, text1, text2): lineArray = [] # e.g. lineArray[4] == "Hello\n" lineHash = {} # e.g. lineHash["Hello\n"] == 4 # "\x00" is a valid character, but various debuggers don't like it. # So we'll insert a junk entry to avoid generating a null character. lineArray.append(...
368,592
Rehydrate the text in a diff from a string of line hashes to real lines of text. Args: diffs: Array of diff tuples. lineArray: Array of unique strings.
def diff_charsToLines(self, diffs, lineArray): for i in range(len(diffs)): text = [] for char in diffs[i][1]: text.append(lineArray[ord(char)]) diffs[i] = (diffs[i][0], "".join(text))
368,593
Determine the common prefix of two strings. Args: text1: First string. text2: Second string. Returns: The number of characters common to the start of each string.
def diff_commonPrefix(self, text1, text2): # Quick check for common null cases. if not text1 or not text2 or text1[0] != text2[0]: return 0 # Binary search. # Performance analysis: https://neil.fraser.name/news/2007/10/09/ pointermin = 0 pointermax = min(len(text1), len(text2)) po...
368,594
Determine the common suffix of two strings. Args: text1: First string. text2: Second string. Returns: The number of characters common to the end of each string.
def diff_commonSuffix(self, text1, text2): # Quick check for common null cases. if not text1 or not text2 or text1[-1] != text2[-1]: return 0 # Binary search. # Performance analysis: https://neil.fraser.name/news/2007/10/09/ pointermin = 0 pointermax = min(len(text1), len(text2)) ...
368,595
Determine if the suffix of one string is the prefix of another. Args: text1 First string. text2 Second string. Returns: The number of characters common to the end of the first string and the start of the second string.
def diff_commonOverlap(self, text1, text2): # Cache the text lengths to prevent multiple calls. text1_length = len(text1) text2_length = len(text2) # Eliminate the null case. if text1_length == 0 or text2_length == 0: return 0 # Truncate the longer string. if text1_length > text2_...
368,596
Do the two texts share a substring which is at least half the length of the longer text? This speedup can produce non-minimal diffs. Args: text1: First string. text2: Second string. Returns: Five element Array, containing the prefix of text1, the suffix of text1, the prefix of ...
def diff_halfMatch(self, text1, text2): if self.Diff_Timeout <= 0: # Don't risk returning a non-optimal diff if we have unlimited time. return None if len(text1) > len(text2): (longtext, shorttext) = (text1, text2) else: (shorttext, longtext) = (text1, text2) if len(longtext...
368,597
Reduce the number of edits by eliminating semantically trivial equalities. Args: diffs: Array of diff tuples.
def diff_cleanupSemantic(self, diffs): changes = False equalities = [] # Stack of indices where equalities are found. lastEquality = None # Always equal to diffs[equalities[-1]][1] pointer = 0 # Index of current position. # Number of chars that changed prior to the equality. length_inser...
368,598
Look for single edits surrounded on both sides by equalities which can be shifted sideways to align the edit to a word boundary. e.g: The c<ins>at c</ins>ame. -> The <ins>cat </ins>came. Args: diffs: Array of diff tuples.
def diff_cleanupSemanticLossless(self, diffs): def diff_cleanupSemanticScore(one, two): if not one or not two: # Edges are the best. return 6 # Each port of this function behaves slightly differently due to # subtle differences in each language's definition of things ...
368,599
Reduce the number of edits by eliminating operationally trivial equalities. Args: diffs: Array of diff tuples.
def diff_cleanupEfficiency(self, diffs): changes = False equalities = [] # Stack of indices where equalities are found. lastEquality = None # Always equal to diffs[equalities[-1]][1] pointer = 0 # Index of current position. pre_ins = False # Is there an insertion operation before the last e...
368,600
Reorder and merge like edit sections. Merge equalities. Any edit section can move as long as it doesn't cross an equality. Args: diffs: Array of diff tuples.
def diff_cleanupMerge(self, diffs): diffs.append((self.DIFF_EQUAL, '')) # Add a dummy entry at the end. pointer = 0 count_delete = 0 count_insert = 0 text_delete = '' text_insert = '' while pointer < len(diffs): if diffs[pointer][0] == self.DIFF_INSERT: count_insert += 1 ...
368,601
loc is a location in text1, compute and return the equivalent location in text2. e.g. "The cat" vs "The big cat", 1->1, 5->8 Args: diffs: Array of diff tuples. loc: Location within text1. Returns: Location within text2.
def diff_xIndex(self, diffs, loc): chars1 = 0 chars2 = 0 last_chars1 = 0 last_chars2 = 0 for x in range(len(diffs)): (op, text) = diffs[x] if op != self.DIFF_INSERT: # Equality or deletion. chars1 += len(text) if op != self.DIFF_DELETE: # Equality or insertion. ...
368,602
Convert a diff array into a pretty HTML report. Args: diffs: Array of diff tuples. Returns: HTML representation.
def diff_prettyHtml(self, diffs): html = [] for (op, data) in diffs: text = (data.replace("&", "&amp;").replace("<", "&lt;") .replace(">", "&gt;").replace("\n", "&para;<br>")) if op == self.DIFF_INSERT: html.append("<ins style=\"background:#e6ffe6;\">%s</ins>" % text) ...
368,603
Compute and return the source text (all equalities and deletions). Args: diffs: Array of diff tuples. Returns: Source text.
def diff_text1(self, diffs): text = [] for (op, data) in diffs: if op != self.DIFF_INSERT: text.append(data) return "".join(text)
368,604
Compute and return the destination text (all equalities and insertions). Args: diffs: Array of diff tuples. Returns: Destination text.
def diff_text2(self, diffs): text = [] for (op, data) in diffs: if op != self.DIFF_DELETE: text.append(data) return "".join(text)
368,605
Compute the Levenshtein distance; the number of inserted, deleted or substituted characters. Args: diffs: Array of diff tuples. Returns: Number of changes.
def diff_levenshtein(self, diffs): levenshtein = 0 insertions = 0 deletions = 0 for (op, data) in diffs: if op == self.DIFF_INSERT: insertions += len(data) elif op == self.DIFF_DELETE: deletions += len(data) elif op == self.DIFF_EQUAL: # A deletion and an i...
368,606
Given the original text1, and an encoded string which describes the operations required to transform text1 into text2, compute the full diff. Args: text1: Source string for the diff. delta: Delta text. Returns: Array of diff tuples. Raises: ValueError: If invalid input.
def diff_fromDelta(self, text1, delta): diffs = [] pointer = 0 # Cursor in text1 tokens = delta.split("\t") for token in tokens: if token == "": # Blank tokens are ok (from a trailing \t). continue # Each token begins with a one character parameter which specifies the ...
368,607
Locate the best instance of 'pattern' in 'text' near 'loc'. Args: text: The text to search. pattern: The pattern to search for. loc: The location to search around. Returns: Best match index or -1.
def match_main(self, text, pattern, loc): # Check for null inputs. if text == None or pattern == None: raise ValueError("Null inputs. (match_main)") loc = max(0, min(loc, len(text))) if text == pattern: # Shortcut (potentially not guaranteed by the algorithm) return 0 elif no...
368,608
Locate the best instance of 'pattern' in 'text' near 'loc' using the Bitap algorithm. Args: text: The text to search. pattern: The pattern to search for. loc: The location to search around. Returns: Best match index or -1.
def match_bitap(self, text, pattern, loc): # Python doesn't have a maxint limit, so ignore this check. #if self.Match_MaxBits != 0 and len(pattern) > self.Match_MaxBits: # raise ValueError("Pattern too long for this application.") # Initialise the alphabet. s = self.match_alphabet(pattern) ...
368,609
Initialise the alphabet for the Bitap algorithm. Args: pattern: The text to encode. Returns: Hash of character locations.
def match_alphabet(self, pattern): s = {} for char in pattern: s[char] = 0 for i in range(len(pattern)): s[pattern[i]] |= 1 << (len(pattern) - i - 1) return s
368,610
Increase the context until it is unique, but don't let the pattern expand beyond Match_MaxBits. Args: patch: The patch to grow. text: Source text.
def patch_addContext(self, patch, text): if len(text) == 0: return pattern = text[patch.start2 : patch.start2 + patch.length1] padding = 0 # Look for the first and last matches of pattern in text. If two different # matches are found, increase the pattern length. while (text.find(pa...
368,611
Given an array of patches, return another array that is identical. Args: patches: Array of Patch objects. Returns: Array of Patch objects.
def patch_deepCopy(self, patches): patchesCopy = [] for patch in patches: patchCopy = patch_obj() # No need to deep copy the tuples since they are immutable. patchCopy.diffs = patch.diffs[:] patchCopy.start1 = patch.start1 patchCopy.start2 = patch.start2 patchCopy.length...
368,613
Merge a set of patches onto the text. Return a patched text, as well as a list of true/false values indicating which patches were applied. Args: patches: Array of Patch objects. text: Old text. Returns: Two element Array, containing the new text and an array of boolean values.
def patch_apply(self, patches, text): if not patches: return (text, []) # Deep copy the patches so that no changes are made to originals. patches = self.patch_deepCopy(patches) nullPadding = self.patch_addPadding(patches) text = nullPadding + text + nullPadding self.patch_splitMax(p...
368,614
Add some padding on text start and end so that edges can match something. Intended to be called only from within patch_apply. Args: patches: Array of Patch objects. Returns: The padding string added to each side.
def patch_addPadding(self, patches): paddingLength = self.Patch_Margin nullPadding = "" for x in range(1, paddingLength + 1): nullPadding += chr(x) # Bump all the patches forward. for patch in patches: patch.start1 += paddingLength patch.start2 += paddingLength # Add som...
368,615
Look through the patches and break up any which are longer than the maximum limit of the match algorithm. Intended to be called only from within patch_apply. Args: patches: Array of Patch objects.
def patch_splitMax(self, patches): patch_size = self.Match_MaxBits if patch_size == 0: # Python has the option of not splitting strings due to its ability # to handle integers of arbitrary precision. return for x in range(len(patches)): if patches[x].length1 <= patch_size: ...
368,616
Take a list of patches and return a textual representation. Args: patches: Array of Patch objects. Returns: Text representation of patches.
def patch_toText(self, patches): text = [] for patch in patches: text.append(str(patch)) return "".join(text)
368,617
Crush the diff into an encoded string which describes the operations required to transform text1 into text2. E.g. =3\t-2\t+ing -> Keep 3 chars, delete 2 chars, insert 'ing'. Operations are tab-separated. Inserted text is escaped using %xx notation. Args: diffs: Array of diff tuples. Return...
def diff_toDelta(self, diffs): text = [] for (op, data) in diffs: if op == self.DIFF_INSERT: # High ascii will raise UnicodeDecodeError. Use Unicode instead. data = data.encode("utf-8") text.append("+" + urllib.quote(data, "!~*'();/?:@&=+$,# ")) elif op == self.DIFF_DEL...
368,619
Initialise the alphabet for the Bitap algorithm. Args: pattern: The text to encode. Returns: Hash of character locations.
def match_alphabet(self, pattern): s = {} for char in pattern: s[char] = 0 for i in xrange(len(pattern)): s[pattern[i]] |= 1 << (len(pattern) - i - 1) return s
368,620
Parse a textual representation of patches and return a list of patch objects. Args: textline: Text representation of patches. Returns: Array of Patch objects. Raises: ValueError: If invalid input.
def patch_fromText(self, textline): if type(textline) == unicode: # Patches should be composed of a subset of ascii chars, Unicode not # required. If this encode raises UnicodeEncodeError, patch is invalid. textline = textline.encode("ascii") patches = [] if not textline: retur...
368,621
Compute distance. Args: x_arr: `np.ndarray` of vectors. y_arr: `np.ndarray` of vectors. Retruns: `np.ndarray` of distances.
def compute(self, x_arr, y_arr): y_arr += 1e-08 return np.sum(x_arr * np.log(x_arr / y_arr), axis=-1)
368,727
Generate the N-gram's pair. Args: token_list: The list of tokens. n N Returns: zip of Tuple(Training N-gram data, Target N-gram data)
def generate_ngram_data_set(self, token_list, n=2): n_gram_tuple_zip = self.generate_tuple_zip(token_list, n) n_gram_tuple_list = [n_gram_tuple for n_gram_tuple in n_gram_tuple_zip] n_gram_data_set = self.generate_tuple_zip(n_gram_tuple_list, 2) return n_gram_data_set
368,728
Generate the Skip-gram's pair. Args: token_list: The list of tokens. Returns: zip of Tuple(Training N-gram data, Target N-gram data)
def generate_skip_gram_data_set(self, token_list): n_gram_tuple_zip = self.generate_tuple_zip(token_list, 3) skip_gram_list = [] for pre, point, post in n_gram_tuple_zip: skip_gram_list.append((point, pre)) skip_gram_list.append((point, post)) retu...
368,729
Generate the N-gram. Args: token_list: The list of tokens. n N Returns: zip of Tuple(N-gram)
def generate_tuple_zip(self, token_list, n=2): return zip(*[token_list[i:] for i in range(n)])
368,730
Download PDF file and transform its document to string. Args: url: PDF url. Returns: string.
def url_to_text(self, url): path, headers = urllib.request.urlretrieve(url) return self.path_to_text(path)
368,733
Transform local PDF file to string. Args: path: path to PDF file. Returns: string.
def path_to_text(self, path): rsrcmgr = PDFResourceManager() retstr = StringIO() codec = 'utf-8' laparams = LAParams() device = TextConverter(rsrcmgr, retstr, codec=codec, laparams=laparams) fp = open(path, 'rb') interpreter = PDFPageInterpreter(rsrcmgr, ...
368,734
Divide string into sentence list. Args: data: string. counter: recursive counter. Returns: List of sentences.
def listup_sentence(self, data, counter=0): delimiter = self.delimiter_list[counter] sentence_list = [] [sentence_list.append(sentence + delimiter) for sentence in data.split(delimiter) if sentence != ""] if counter + 1 < len(self.delimiter_list): sentence_list_r = [...
368,736
Entry Point. Args: url: PDF url.
def Main(url): # The object of Web-scraping. web_scrape = WebScraping() # Set the object of reading PDF files. web_scrape.readable_web_pdf = WebPDFReading() # Execute Web-scraping. document = web_scrape.scrape(url) # The object of automatic sumamrization. auto_abstractor = AutoAbstr...
368,737
Initialization Args: default_alpha: Alpha default_beta: Beta
def __init__(self, default_alpha=1, default_beta=1): if isinstance(default_alpha, int) is False: if isinstance(default_alpha, float) is False: raise TypeError() if isinstance(default_beta, int) is False: if isinstance(default_beta, float) is False: ...
368,738
Observation data. Args: success: The number of success. failure: The number of failure.
def observe(self, success, failure): if isinstance(success, int) is False: if isinstance(success, float) is False: raise TypeError() if isinstance(failure, int) is False: if isinstance(failure, float) is False: raise TypeError() i...
368,739
Concreat method. Args: state_key The key of state. this value is point in map. Returns: [(x, y)]
def extract_possible_actions(self, state_key): if state_key in self.__state_action_list_dict: return self.__state_action_list_dict[state_key] else: action_list = [] state_key_list = [action_list.extend(self.__state_action_list_dict[k]) for k in self.__state_a...
368,747
Compute the reward value. Args: state_key: The key of state. action_key: The key of action. Returns: Reward value.
def observe_reward_value(self, state_key, action_key): reward_value = 0.0 if state_key in self.__state_action_list_dict: if action_key in self.__state_action_list_dict[state_key]: reward_value = 1.0 return reward_value
368,748
Initialize. Args: token_list: The list of all tokens.
def __init__(self, token_list): self.__token_arr = np.array(list(set(token_list)))
368,749
Create matrix of sentences. Args: token_list: The list of tokens. Returns: 2-D `np.ndarray` of sentences. Each row means one hot vectors of one sentence.
def convert_tokens_into_matrix(self, token_list): return np.array(self.vectorize(token_list)).astype(np.float32)
368,750
Tokenize vector. Args: vector_list: The list of vector of one token. Returns: token
def tokenize(self, vector_list): vector_arr = np.array(vector_list) if vector_arr.ndim == 1: key_arr = vector_arr.argmax() else: key_arr = vector_arr.argmax(axis=-1) return self.__token_arr[key_arr]
368,751
Tokenize token list. Args: token_list: The list of tokens.. Returns: [vector of token, vector of token, vector of token, ...]
def vectorize(self, token_list): vector_list = [self.__collection.tf_idf(token, self.__collection) for token in token_list] return vector_list
368,753
Move in the feature map. Args: current_pos: The now position. Returns: The next position.
def __move(self, current_pos): if self.__move_range is not None: next_pos = np.random.randint(current_pos - self.__move_range, current_pos + self.__move_range) if next_pos < 0: next_pos = 0 elif next_pos >= self.var_arr.shape[0] - 1: n...
368,755
Update this Discriminator by ascending its stochastic gradient. Args: grad_arr: `np.ndarray` of gradients. Returns: `np.ndarray` of delta or gradients.
def learn(self, grad_arr): deconvolution_layer_list = self.__deconvolution_layer_list[::-1] for i in range(len(deconvolution_layer_list)): try: grad_arr = deconvolution_layer_list[i].back_propagate(grad_arr) except: self.__logger.de...
368,759
Back propagation for Deconvolution layer. Args: learning_rate: Learning rate. epoch: Now epoch.
def __optimize_deconvolution_layer(self, learning_rate, epoch): params_list = [] grads_list = [] for i in range(len(self.__deconvolution_layer_list)): if self.__deconvolution_layer_list[i].delta_weight_arr.shape[0] > 0: params_list.append(self.__decon...
368,760
Execute Web-Scraping. The target dom objects are in self.__dom_object_list. Args: url: Web site url. Returns: The result. this is a string. @TODO(chimera0): check URLs format.
def scrape(self, url): if isinstance(url, str) is False: raise TypeError("The type of url must be str.") if self.readable_web_pdf is not None and self.readable_web_pdf.is_pdf_url(url) is True: web_data = self.readable_web_pdf.url_to_text(url) else: w...
368,764
Extract MIDI file. Args: file_path: File path of MIDI. is_drum: Extract drum data or not. Returns: pd.DataFrame(columns=["program", "start", "end", "pitch", "velocity", "duration"])
def extract(self, file_path, is_drum=False): midi_data = pretty_midi.PrettyMIDI(file_path) note_tuple_list = [] for instrument in midi_data.instruments: if (is_drum is False and instrument.is_drum is False) or (is_drum is True and instrument.is_drum is True): ...
368,765
Save MIDI file. Args: file_path: File path of MIDI. note_df: `pd.DataFrame` of note data.
def save(self, file_path, note_df): chord = pretty_midi.PrettyMIDI() for program in note_df.program.drop_duplicates().values.tolist(): df = note_df[note_df.program == program] midi_obj = pretty_midi.Instrument(program=program) for i in range(df.shape[0]): ...
368,766
Init. Args: greedy_q_learning: is-a `GreedyQLearning`. init_state_key: First state key.
def __init__( self, greedy_q_learning, init_state_key ): if isinstance(greedy_q_learning, GreedyQLearning): self.__greedy_q_learning = greedy_q_learning else: raise TypeError() self.__init_state_key = init_state_key
368,767
Compute cost. Args: x: `np.ndarray` of explanatory variables. Returns: cost
def compute(self, x): q_learning = copy(self.__greedy_q_learning) q_learning.epsilon_greedy_rate = x[0] q_learning.alpha_value = x[1] q_learning.gamma_value = x[2] if self.__init_state_key is not None: q_learning.learn(state_key=self.__init_state_key, limit=i...
368,768
Entry Point. Args: url: target url.
def Main(url): # The object of Web-Scraping. web_scrape = WebScraping() # Execute Web-Scraping. document = web_scrape.scrape(url) # The object of automatic summarization with N-gram. auto_abstractor = NgramAutoAbstractor() # n-gram object auto_abstractor.n_gram = Ngram() # n of ...
368,769
Execute summarization. Args: document: The target document. Abstractor: The object of AbstractableDoc. similarity_filter The object of SimilarityFilter. Returns: dict data. - "summarize_result": The list of summarized sent...
def summarize(self, document, Abstractor, similarity_filter=None): if isinstance(document, str) is False: raise TypeError("The type of document must be str.") if isinstance(Abstractor, AbstractableDoc) is False: raise TypeError("The type of Abstractor must be Abstractab...
368,776
Scoring the sentence with closely associations. Args: normalized_sentences: The list of sentences. top_n_words: Important sentences. Returns: The list of scores.
def __closely_associated_score(self, normalized_sentences, top_n_words): scores_list = [] sentence_idx = -1 for sentence in normalized_sentences: self.tokenize(sentence) sentence = self.token sentence_idx += 1 word_idx = [] ...
368,777
Init. Args: mu: `float` or `array_like of floats`. Mean (`centre`) of the distribution. sigma: `float` or `array_like of floats`. Standard deviation (spread or `width`) of the distribution. ...
def __init__(self, mu, sigma, output_shape): self.__mu = mu self.__sigma = sigma self.__output_shape = output_shape
368,778
Multi-Agent Learning. Override. Args: initial_state_key: Initial state. limit: Limit of the number of learning. game_n: The number of games.
def learn(self, initial_state_key, limit=1000, game_n=1): end_flag = False state_key_list = [None] * len(self.q_learning_list) action_key_list = [None] * len(self.q_learning_list) next_action_key_list = [None] * len(self.q_learning_list) for game in range(game_n): ...
368,780
Update this Discriminator by ascending its stochastic gradient. Args: grad_arr: `np.ndarray` of gradients. fix_opt_flag: If `False`, no optimization in this model will be done. Returns: `np.ndarray` of delta or gradients.
def learn(self, grad_arr, fix_opt_flag=False): channel = grad_arr.shape[1] // 2 grad_arr = self.__deconvolution_model.learn(grad_arr[:, :channel], fix_opt_flag=fix_opt_flag) delta_arr = self.__cnn.back_propagation(grad_arr) if fix_opt_flag is False: self.__cnn....
368,783
Init. Args: deconvolution_layer_list: `list` of `DeconvolutionLayer`. opt_params: is-a `OptParams`. If `None`, this value will be `Adam`. learning_rate: Learning rate. verbose_mode: Verbose mode or not.
def __init__( self, deconvolution_layer_list, opt_params=None, learning_rate=1e-05, verbose_mode=False ): for deconvolution_layer in deconvolution_layer_list: if isinstance(deconvolution_layer, DeconvolutionLayer) is False: ...
368,784
Draws samples from the `fake` distribution. Args: observed_arr: `np.ndarray` of observed data points. Returns: `np.ndarray` of inferenced.
def inference(self, observed_arr): for i in range(len(self.__deconvolution_layer_list)): try: observed_arr = self.__deconvolution_layer_list[i].forward_propagate(observed_arr) except: self.__logger.debug("Error raised in Deconvolution layer ...
368,785
Update this Discriminator by ascending its stochastic gradient. Args: grad_arr: `np.ndarray` of gradients. fix_opt_flag: If `False`, no optimization in this model will be done. Returns: `np.ndarray` of delta or gradients.
def learn(self, grad_arr, fix_opt_flag=False): deconvolution_layer_list = self.__deconvolution_layer_list[::-1] for i in range(len(deconvolution_layer_list)): try: grad_arr = deconvolution_layer_list[i].back_propagate(grad_arr) except: ...
368,786
Draws samples from the `true` distribution. Args: observed_arr: `np.ndarray` of observed data points. Returns: `np.ndarray` of inferenced.
def inference(self, observed_arr): self.__pred_arr = self.__lstm_model.inference(observed_arr) return self.__pred_arr
368,788
Update this Discriminator by ascending its stochastic gradient. Args: grad_arr: `np.ndarray` of gradients. fix_opt_flag: If `False`, no optimization in this model will be done. Returns: `np.ndarray` of delta or gradients.
def learn(self, grad_arr, fix_opt_flag=False): if grad_arr.ndim > 3: grad_arr = grad_arr.reshape(( grad_arr.shape[0], grad_arr.shape[1], -1 )) delta_arr, grads_list = self.__lstm_model.back_propagation(self.__pred...
368,789
Init. Args: low: Lower boundary of the output interval. All values generated will be greater than or equal to low. high: Upper boundary of the output interval. All values generated will be less than hi...
def __init__(self, low, high, output_shape): self.__low = low self.__high = high self.__output_shape = output_shape
368,790
Remove duplicated elements. Args: token_list_x: [token, token, token, ...] token_list_y: [token, token, token, ...] Returns: Tuple(token_list_x, token_list_y)
def unique(self, token_list_x, token_list_y): x = set(list(token_list_x)) y = set(list(token_list_y)) return (x, y)
368,797
Count the number of tokens in `token_list`. Args: token_list: The list of tokens. Returns: {token: the numbers}
def count(self, token_list): token_dict = {} for token in token_list: if token in token_dict: token_dict[token] += 1 else: token_dict[token] = 1 return token_dict
368,798
Filter mutually similar sentences. Args: sentence_list: The list of sentences. Returns: The list of filtered sentences.
def similar_filter_r(self, sentence_list): result_list = [] recursive_list = [] try: self.nlp_base.tokenize(sentence_list[0]) subject_token = self.nlp_base.token result_list.append(sentence_list[0]) if len(sentence_list) > 1: ...
368,799
Calculate similarity with the Jaccard coefficient. Concrete method. Args: token_list_x: [token, token, token, ...] token_list_y: [token, token, token, ...] Returns: Similarity.
def calculate(self, token_list_x, token_list_y): x, y = self.unique(token_list_x, token_list_y) try: result = len(x & y) / len(x | y) except ZeroDivisionError: result = 0.0 return result
368,803
Infernce Q-Value. Args: predicted_q_arr: `np.ndarray` of predicted Q-Values. real_q_arr: `np.ndarray` of real Q-Values.
def learn_q(self, predicted_q_arr, real_q_arr): loss = self.__computable_loss.compute_loss(predicted_q_arr, real_q_arr) delta_arr = self.__computable_loss.compute_delta(predicted_q_arr, real_q_arr) delta_arr = self.__cnn.back_propagation(delta_arr) self.__cnn.optimize(...
368,807
引数で指定した条件でビートを鳴らす Args: frequencys: (左の周波数(Hz), 右の周波数(Hz))のtuple play_time: 再生時間(秒) sample_rate: サンプルレート volume: 音量 Returns: void
def play_beat( self, frequencys, play_time, sample_rate=44100, volume=0.01 ): # 依存するライブラリの基底オブジェクト audio = pyaudio.PyAudio() # ストリーム stream = audio.open( format=pyaudio.paFloat32, channels=2, ...
368,811
引数で指定した条件でビートを鳴らす Args: frequencys: (左の周波数(Hz), 右の周波数(Hz))のtuple play_time: 再生時間(秒) sample_rate: サンプルレート volume: 音量 Returns: void
def save_beat( self, output_file_name, frequencys, play_time, sample_rate=44100, volume=0.01 ): left_frequency, right_frequency = frequencys left_chunk = self.__create_chunk(left_frequency, play_time, sample_rate) right_chun...
368,812
チャンクを生成する Args: frequency: 周波数 play_time: 再生時間(秒) sample_rate: サンプルレート Returns: チャンクのnumpy配列
def __create_chunk(self, frequency, play_time, sample_rate): chunks = [] wave_form = self.wave_form.create(frequency, play_time, sample_rate) chunks.append(wave_form) chunk = numpy.concatenate(chunks) return chunk
368,813
Init. Args: image_true_sampler: is-a `ImageTrueSampler`.
def __init__(self, image_true_sampler): if isinstance(image_true_sampler, ImageTrueSampler) is False: raise TypeError() self.__image_true_sampler = image_true_sampler
368,814
Add condtion. Args: observed_arr: `np.ndarray` of samples. Returns: `np.ndarray` of samples.
def add_condition(self, observed_arr): condition_arr = self.__image_true_sampler.draw() return np.concatenate((observed_arr, condition_arr), axis=1)
368,816
音の波形を生成する Args: frequency: 周波数 play_time: 再生時間 sample_rate: サンプルレート Returns: 波形要素を格納した配列
def create(self, frequency, play_time, sample_rate): length = int(play_time * sample_rate) factor = float(frequency) * (math.pi * 2) / sample_rate return numpy.sin(numpy.arange(length) * factor)
368,817
Init. Args: function_approximator: is-a `FunctionApproximator`. map_size: Size of map. memory_num: The number of step of agent's memory. repeating_penalty: The value of penalty in the case that agent revisit.
def __init__(self, function_approximator, map_size=(10, 10), memory_num=4, repeating_penalty=0.5): self.__map_arr = self.__create_map(map_size) self.__agent_pos = self.START_POS self.__reward_list = [] self.__route_memory_list = [] self.__memory_num = memory_num ...
368,818
Infernce. Args: state_arr: `np.ndarray` of state. limit: The number of inferencing. Returns: `list of `np.ndarray` of an optimal route.
def inference(self, state_arr, limit=1000): agent_x, agent_y = np.where(state_arr[0] == 1) agent_x, agent_y = agent_x[0], agent_y[0] result_list = [(agent_x, agent_y, 0.0)] self.t = 1 while self.t <= limit: next_action_arr = self.extract_possible_actions(stat...
368,819
Compute the reward value. Args: state_arr: `np.ndarray` of state. action_arr: `np.ndarray` of action. Returns: Reward value.
def observe_reward_value(self, state_arr, action_arr): if self.__check_goal_flag(action_arr) is True: return 1.0 else: x, y = np.where(action_arr[-1] == 1) x, y = x[0], y[0] goal_x, goal_y = self.__goal_pos if x == goal_x ...
368,820
Update state. Override. Args: state_arr: `np.ndarray` of state in `self.t`. action_arr: `np.ndarray` of action in `self.t`. Returns: `np.ndarray` of state in `self.t+1`.
def update_state(self, state_arr, action_arr): x, y = np.where(action_arr[-1] == 1) self.__agent_pos = (x[0], y[0]) self.__route_memory_list.append((x[0], y[0])) self.__route_long_memory_list.append((x[0], y[0])) self.__route_long_memory_list = list(set(self.__route_long...
368,822
Draws samples from the `true` distribution. Args: observed_arr: `np.ndarray` of observed data points. Returns: `np.ndarray` of inferenced.
def inference(self, observed_arr): if observed_arr.ndim < 4: # Add rank for channel. observed_arr = np.expand_dims(observed_arr, axis=1) self.__add_channel_flag = True else: self.__add_channel_flag = False return super().inferenc...
368,826
Update this Discriminator by ascending its stochastic gradient. Args: grad_arr: `np.ndarray` of gradients. fix_opt_flag: If `False`, no optimization in this model will be done. Returns: `np.ndarray` of delta or gradients.
def learn(self, grad_arr, fix_opt_flag=False): delta_arr = super().learn(grad_arr, fix_opt_flag) if self.__add_channel_flag is True: return delta_arr[:, 0] else: return delta_arr
368,827
Calculate similarity with the so-called Cosine similarity of Tf-Idf vectors. Concrete method. Args: token_list_x: [token, token, token, ...] token_list_y: [token, token, token, ...] Returns: Similarity.
def calculate(self, token_list_x, token_list_y): if len(token_list_x) == 0 or len(token_list_y) == 0: return 0.0 document_list = token_list_x.copy() [document_list.append(v) for v in token_list_y] document_list = list(set(document_list)) tfidf_vectorizer = ...
368,828
Init. Args: params_arr: The parameters. cost_functionable: is-a `CostFunctionable`.
def __init__(self, params_arr, cost_functionable): self.__params_arr = params_arr if isinstance(cost_functionable, CostFunctionable): self.__cost_functionable = cost_functionable else: raise TypeError
368,829
Compute distance. Args: x: Data point. y: Data point. Returns: Distance.
def compute(self, x, y): if x in self.__memo_dict: x_v = self.__memo_dict[x] else: x_v = self.__cost_functionable.compute(self.__params_arr[x, :]) self.__memo_dict.setdefault(x, x_v) if y in self.__memo_dict: y_v = self.__memo_dict[y] ...
368,830
Initialize map of maze and setup reward value. Args: map_arr: Map. the 2d- `np.ndarray`. start_point_label: Label of start point. end_point_label: Label of end point. wall_label: Label of wall. agent_label: Labe...
def initialize(self, map_arr, start_point_label="S", end_point_label="G", wall_label="#", agent_label="@"): np.set_printoptions(threshold=np.inf) self.__agent_label = agent_label self.__map_arr = map_arr self.__start_point_label = start_point_label start_arr_tuple = np....
368,832
Concreat method. Args: state_key The key of state. this value is point in map. Returns: [(x, y)]
def extract_possible_actions(self, state_key): x, y = state_key if self.__map_arr[y][x] == self.__wall_label: raise ValueError("It is the wall. (x, y)=(%d, %d)" % (x, y)) around_map = [(x, y-1), (x, y+1), (x-1, y), (x+1, y)] possible_actoins_list = [(_x, _y) for _x,...
368,833
Compute the reward value. Args: state_key: The key of state. action_key: The key of action. Returns: Reward value.
def observe_reward_value(self, state_key, action_key): x, y = state_key if self.__map_arr[y][x] == self.__end_point_label: return 100.0 elif self.__map_arr[y][x] == self.__start_point_label: return 0.0 elif self.__map_arr[y][x] == self.__wall_label: ...
368,834
Check the end flag. If this return value is `True`, the learning is end. Args: state_key: The key of state in `self.t`. Returns: bool
def check_the_end_flag(self, state_key): # As a rule, the learning can not be stopped. x, y = state_key end_point_tuple = np.where(self.__map_arr == self.__end_point_label) end_point_x_arr, end_point_y_arr = end_point_tuple if x == end_point_x_arr[0] and y == end_point_y...
368,836
Inference route. Args: limit: the number of inferencing. Returns: [(x_1, y_1), (x_2, y_2), ...]
def inference(self, limit=1000): route_list = [] memory_list = [] state_key = self.__start_point_tuple x, y = state_key end_x, end_y = self.__end_point_tuple for i in range(limit): q_df = self.q_df[self.q_df.state_key == state_key] if len(...
368,839
Update this Discriminator by ascending its stochastic gradient. Args: grad_arr: `np.ndarray` of gradients. Returns: `np.ndarray` of delta or gradients.
def learn(self, grad_arr): encoder_delta_arr, _, encoder_grads_list = self.__encoder_decoder_controller.encoder.hidden_back_propagate( grad_arr[:, -1] ) encoder_grads_list.insert(0, None) encoder_grads_list.insert(0, None) self.__encoder_decoder_cont...
368,842
Init. Args: function_approximator: is-a `FunctionApproximator`.
def __init__(self, function_approximator): if isinstance(function_approximator, FunctionApproximator): self.__function_approximator = function_approximator else: raise TypeError() self.t = 1 self.__q_logs_arr = np.array([])
368,844
Learning and searching the optimal solution. Args: state_arr: `np.ndarray` of initial state. limit: The maximum number of iterative updates based on value iteration algorithms.
def learn(self, state_arr, limit=1000): while self.t <= limit: # Draw samples of next possible actions from any distribution. next_action_arr = self.extract_possible_actions(state_arr) # Inference Q-Values. predicted_q_arr = self.__function_approximator.i...
368,845
Update Q. Args: predicted_q_arr: `np.ndarray` of predicted Q-Values. reward_value_arr: `np.ndarray` of reward values. next_max_q_arr: `np.ndarray` of maximum Q-Values in next time step. Returns: `np.ndarray` of real Q-Values.
def update_q(self, predicted_q_arr, reward_value_arr, next_max_q_arr): # Update Q-Value. return predicted_q_arr + (self.alpha_value * (reward_value_arr + (self.gamma_value * next_max_q_arr) - predicted_q_arr))
368,846
Compute distance. Args: x_arr: `np.ndarray` of vectors. y_arr: `np.ndarray` of vectors. Retruns: `np.ndarray` of distances.
def compute(self, x_arr, y_arr): x_arr = x_arr / np.linalg.norm(x_arr, ord=1) y_arr = y_arr / np.linalg.norm(y_arr, ord=1) mixture_arr = 0.5 * (x_arr + y_arr) return 0.5 * (super().compute(x_arr, mixture_arr) + super().compute(y_arr, mixture_arr))
368,852
Filtering with top-n ranking. Args: scored_list: The list of scoring. Retruns: The list of filtered result.
def filter(self, scored_list): top_n_key = -1 * self.top_n top_n_list = sorted(scored_list, key=lambda x: x[1])[top_n_key:] result_list = sorted(top_n_list, key=lambda x: x[0]) return result_list
368,855
Tokenize sentence. Args: [n-gram, n-gram, n-gram, ...]
def tokenize(self, data): super().tokenize(data) token_tuple_zip = self.n_gram.generate_tuple_zip(self.token, self.n) token_list = [] self.token = ["".join(list(token_tuple)) for token_tuple in token_tuple_zip]
368,858
Extract Q-Value from `self.q_df`. Args: state_key: The key of state. action_key: The key of action. Returns: Q-Value.
def extract_q_df(self, state_key, action_key): q = 0.0 if self.q_df is None: self.save_q_df(state_key, action_key, q) return q q_df = self.q_df[self.q_df.state_key == state_key] q_df = q_df[q_df.action_key == action_key] if q_df.shape[0]: ...
368,861
Insert or update Q-Value in `self.q_df`. Args: state_key: State. action_key: Action. q_value: Q-Value. Exceptions: TypeError: If the type of `q_value` is not float.
def save_q_df(self, state_key, action_key, q_value): if isinstance(q_value, float) is False: raise TypeError("The type of q_value must be float.") new_q_df = pd.DataFrame([(state_key, action_key, q_value)], columns=["state_key", "action_key", "q_value"]) if self.q_df is not...
368,862
Insert or update R-Value in `self.r_df`. Args: state_key: The key of state. r_value: R-Value(Reward). action_key: The key of action if it is nesesary for the parametar of value function. Exceptions: TypeError: If the type of `r_value` i...
def extract_r_df(self, state_key, r_value, action_key=None): if isinstance(r_value, float) is False: raise TypeError("The type of r_value must be float.") r = 0.0 if self.r_df is None: self.save_r_df(state_key, r, action_key) return r r_df =...
368,865