def _vectorize(self, strings, method='first'): method = method.lower() if method not in ['first', 'last', 'mean', 'word']: raise ValueError( "method not supported, only support 'first', 'last', 'mean' and 'word'" ) input_ids, input_masks, _, s_tokens = bert_tokenization( self._tokenizer, strings) v = self._sess.run( self._vectorizer, feed_dict={ self._X: input_ids, self._input_masks: input_masks }, ) if method == 'first': v = v[:, 0] elif method == 'last': v = v[:, -1] elif method == 'mean': v = np.mean(v, axis=1) else: v = [ merge_sentencepiece_tokens( list(zip(s_tokens[i], v[i][:len(s_tokens[i])])), weighted=False, vectorize=True, ) for i in range(len(v)) ] return v
def _translate(self, strings, beam_search=True): input_ids, input_masks, input_segments, _ = bert_tokenization( self._tokenizer, strings, cleaning=translation_textcleaning) if beam_search: output = self._beam else: output = self._greedy p = sess.run( output, feed_dict={ model.X: batch_x, model.input_masks: batch_mask, model.segment_ids: batch_segment, }, ) result = [] for output in p: output = [i for i in output if i > 1] output = self._tokenizer.convert_ids_to_tokens(output) output = [(t, 1) for t in output] output = merge_wordpiece_tokens(output) output = [t[0] for t in output] results.append(' '.join(output)) return result
def _vectorize(self, strings, method='first'): method = method.lower() if method not in ['first', 'last', 'mean', 'word']: raise ValueError( "method not supported, only support 'first', 'last', 'mean' and 'word'" ) input_ids, input_masks, _, s_tokens = bert_tokenization( self._tokenizer, strings) r = self._execute( inputs=[input_ids, input_masks], input_labels=['Placeholder', 'Placeholder_1'], output_labels=['vectorizer'], ) v = r['vectorizer'] if method == 'first': v = v[:, 0] elif method == 'last': v = v[:, -1] elif method == 'mean': v = np.mean(v, axis=1) else: v = [ merge_sentencepiece_tokens( list(zip(s_tokens[i], v[i][:len(s_tokens[i])])), weighted=False, vectorize=True, ) for i in range(len(v)) ] return v
def vectorize(self, strings): """ Vectorize string inputs using bert attention. Parameters ---------- strings : str / list of str Returns ------- array: vectorized strings """ if isinstance(strings, list): if not isinstance(strings[0], str): raise ValueError('input must be a list of strings or a string') else: if not isinstance(strings, str): raise ValueError('input must be a list of strings or a string') if isinstance(strings, str): strings = [strings] batch_x, _, _, _ = bert_tokenization( self._tokenizer, strings, cls = self._cls, sep = self._sep ) return self._sess.run(self.logits, feed_dict = {self.X: batch_x})
def vectorize(self, strings: List[str]): """ Vectorize string inputs using bert attention. Parameters ---------- strings : List[str] Returns ------- result: np.array """ batch_x, batch_masks, batch_segments, _ = bert_tokenization( self._tokenizer, strings ) return self._sess.run( self.logits, feed_dict = { self.X: batch_x, self.MASK: batch_masks, self.segment_ids: batch_segments, }, )
def _attention(self, strings): batch_x, _, _, s_tokens = bert_tokenization( self._tokenizer, strings, cls = self._cls, sep = self._sep ) maxlen = max([len(s) for s in s_tokens]) s_tokens = padding_sequence(s_tokens, maxlen, pad_int = self._sep) attentions = self._sess.run(self.attns, feed_dict = {self.X: batch_x}) return attentions, s_tokens
def _classify(self, strings): input_ids, input_masks, _, _ = bert_tokenization( self._tokenizer, strings ) return self._sess.run( self._softmax, feed_dict = {self._X: input_ids, self._input_masks: input_masks}, )
def _classify(self, strings): input_ids, input_masks, _, _ = bert_tokenization( self._tokenizer, strings) r = self._execute( inputs=[input_ids, input_masks], input_labels=['Placeholder', 'Placeholder_1'], output_labels=['logits'], ) return softmax(r['logits'], axis=-1)
def _attention(self, strings): batch_x, batch_masks, _, s_tokens = bert_tokenization( self._tokenizer, strings ) maxlen = max([len(s) for s in s_tokens]) s_tokens = padding_sequence(s_tokens, maxlen, pad_int = '[SEP]') attentions = self._sess.run( self.attns, feed_dict = {self.X: batch_x, self.MASK: batch_masks} ) return attentions, s_tokens, batch_masks
def _classify(self, strings): input_ids, _, _, _ = bert_tokenization(self._tokenizer, strings) input_ids = tf.keras.preprocessing.sequence.pad_sequences( input_ids, padding='post', maxlen=self._maxlen) r = self._execute( inputs=[input_ids], input_labels=['Placeholder'], output_labels=['logits'], ) return softmax(r['logits'], axis=-1)
def _base(self, strings_left, strings_right): input_ids_left, input_masks_left, _, _ = bert_tokenization( self._tokenizer, strings_left) input_ids_right, input_masks_right, _, _ = bert_tokenization( self._tokenizer, strings_right) r = self._execute( inputs=[ input_ids_left, input_masks_left, input_ids_right, input_masks_right, ], input_labels=[ 'Placeholder', 'Placeholder_1', 'Placeholder_2', 'Placeholder_3', ], output_labels=['logits'], ) return softmax(r['logits'], axis=-1)
def _classify(self, strings): input_ids, input_masks, _, _ = bert_tokenization( self._tokenizer, strings, socialmedia=self._socialmedia ) r = self._execute( inputs=[input_ids, input_masks], input_labels=['Placeholder'], output_labels=['logits'], ) if self._multilabels: return sigmoid(r['logits']) else: return softmax(r['logits'], axis=-1)
def vectorize(self, strings: List[str], method: str = 'first'): """ vectorize list of strings. Parameters ---------- strings: List[str] method : str, optional (default='first') Vectorization layer supported. Allowed values: * ``'last'`` - vector from last sequence. * ``'first'`` - vector from first sequence. * ``'mean'`` - average vectors from all sequences. * ``'word'`` - average vectors based on tokens. Returns ------- result: np.array """ method = method.lower() if method not in ['first', 'last', 'mean', 'word']: raise ValueError( "method not supported, only support 'first', 'last', 'mean' and 'word'" ) input_ids, input_masks, _, s_tokens = bert_tokenization( self._tokenizer, strings ) r = self._execute( inputs=[input_ids, input_masks], input_labels=['Placeholder', 'Placeholder_1'], output_labels=['vectorizer'], ) v = r['vectorizer'] if method == 'first': v = v[:, 0] elif method == 'last': v = v[:, -1] elif method == 'mean': v = np.mean(v, axis=1) else: v = [ merge_sentencepiece_tokens( list(zip(s_tokens[i], v[i][: len(s_tokens[i])])), weighted=False, vectorize=True, ) for i in range(len(v)) ] return v
def _paraphrase(self, strings): batch_x, input_masks, input_segments, _ = bert_tokenization( self._tokenizer, strings) outputs = self._sess.run( self._logits, feed_dict={ self._X: batch_x, self._segment_ids: input_segments, self._input_masks: input_masks, }, )[:, 0, :].tolist() results = [] for output in outputs: output = [i for i in output if i > 0] output = self._tokenizer.convert_ids_to_tokens(output) output = [(t, 1) for t in output] output = merge_sentencepiece_tokens(output) output = [t[0] for t in output] results.append(' '.join(output)) return results
def vectorize(self, strings: List[str]): """ Vectorize list of strings. Parameters ---------- strings : List[str] Returns ------- result: np.array """ input_ids, input_masks, _, _ = bert_tokenization( self._tokenizer, strings) r = self._execute( inputs=[input_ids, input_masks], input_labels=['Placeholder', 'Placeholder_1'], output_labels=['bert/summary'], ) return r['bert/summary']
def vectorize(self, strings: List[str]): """ Vectorize list of strings. Parameters ---------- strings : List[str] Returns ------- result: np.array """ input_ids, input_masks, segment_ids, _ = bert_tokenization( self._tokenizer, strings) segment_ids = np.array(segment_ids) + 1 return self._sess.run( self._vectorizer, feed_dict={ self._X: input_ids, self._segment_ids: segment_ids, self._input_masks: input_masks, }, )
def _predict_words(self, string, method, visualization, add_neutral=False): method = method.lower() if method not in ['last', 'first', 'mean']: raise ValueError( "method not supported, only support 'last', 'first' and 'mean'" ) if add_neutral: label = self._label + ['neutral'] else: label = self._label batch_x, batch_mask, _, s_tokens = bert_tokenization( self._tokenizer, [string]) result, attentions, words = self._sess.run( [self._softmax, self._attns, self._softmax_seq], feed_dict={ self._X: batch_x, self._input_masks: batch_mask }, ) if method == 'first': cls_attn = list(attentions[0].values())[0][:, :, 0, :] if method == 'last': cls_attn = list(attentions[-1].values())[0][:, :, 0, :] if method == 'mean': combined_attentions = [] for a in attentions: combined_attentions.append(list(a.values())[0]) cls_attn = np.mean(combined_attentions, axis=0).mean(axis=2) cls_attn = np.mean(cls_attn, axis=1) total_weights = np.sum(cls_attn, axis=-1, keepdims=True) attn = cls_attn / total_weights words = words[0] if add_neutral: result = neutral(result) words = neutral(words) result = result[0] weights = [] merged = merge_sentencepiece_tokens(list(zip(s_tokens[0], attn[0]))) for i in range(words.shape[1]): m = merge_sentencepiece_tokens(list(zip(s_tokens[0], words[:, i])), weighted=False) _, weight = zip(*m) weights.append(weight) w, a = zip(*merged) words = np.array(weights).T distribution_words = words[:, np.argmax(words.sum(axis=0))] y_histogram, x_histogram = np.histogram(distribution_words, bins=np.arange(0, 1, 0.05)) y_histogram = y_histogram / y_histogram.sum() x_attention = np.arange(len(w)) left, right = np.unique(np.argmax(words, axis=1), return_counts=True) left = left.tolist() y_barplot = [] for i in range(len(label)): if i not in left: y_barplot.append(i) else: y_barplot.append(right[left.index(i)]) dict_result = {label[i]: result[i] for i in range(len(result))} dict_result['alphas'] = {w: a[no] for no, w in enumerate(w)} dict_result['word'] = {w: words[no] for no, w in enumerate(w)} dict_result['histogram'] = {'x': x_histogram, 'y': y_histogram} dict_result['attention'] = {'x': x_attention, 'y': np.array(a)} dict_result['barplot'] = {'x': label, 'y': y_barplot} dict_result['class_name'] = self._class_name if visualization: render_dict[self._class_name](dict_result) else: return dict_result
def predict_words(self, string: str, method: str = 'last', visualization: bool = True): """ classify words. Parameters ---------- string : str method : str, optional (default='last') Attention layer supported. Allowed values: * ``'last'`` - attention from last layer. * ``'first'`` - attention from first layer. * ``'mean'`` - average attentions from all layers. visualization: bool, optional (default=True) If True, it will open the visualization dashboard. Returns ------- dictionary: results """ method = method.lower() if method not in ['last', 'first', 'mean']: raise ValueError( "method not supported, only support 'last', 'first' and 'mean'" ) batch_x, input_masks, _, s_tokens = bert_tokenization( self._tokenizer, [string]) result, attentions, words = self._sess.run( [self._sigmoid, self._attns, self._sigmoid_seq], feed_dict={ self._X: batch_x, self._input_masks: input_masks }, ) if method == 'first': cls_attn = list(attentions[0].values())[0][:, :, 0, :] if method == 'last': cls_attn = list(attentions[-1].values())[0][:, :, 0, :] if method == 'mean': combined_attentions = [] for a in attentions: combined_attentions.append(list(a.values())[0]) cls_attn = np.mean(combined_attentions, axis=0).mean(axis=2) cls_attn = np.mean(cls_attn, axis=1) total_weights = np.sum(cls_attn, axis=-1, keepdims=True) attn = cls_attn / total_weights result = result[0] words = words[0] weights = [] merged = merge_sentencepiece_tokens(list(zip(s_tokens[0], attn[0]))) for i in range(words.shape[1]): m = merge_sentencepiece_tokens(list(zip(s_tokens[0], words[:, i])), weighted=False) _, weight = zip(*m) weights.append(weight) w, a = zip(*merged) words = np.array(weights).T distribution_words = words[:, np.argmax(words.sum(axis=0))] y_histogram, x_histogram = np.histogram(distribution_words, bins=np.arange(0, 1, 0.05)) y_histogram = y_histogram / y_histogram.sum() x_attention = np.arange(len(w)) left, right = np.unique(np.argmax(words, axis=1), return_counts=True) left = left.tolist() y_barplot = [] for i in range(len(self._label)): if i not in left: y_barplot.append(i) else: y_barplot.append(right[left.index(i)]) dict_result = {self._label[i]: result[i] for i in range(len(result))} dict_result['alphas'] = {w: a[no] for no, w in enumerate(w)} dict_result['word'] = {w: words[no] for no, w in enumerate(w)} dict_result['histogram'] = {'x': x_histogram, 'y': y_histogram} dict_result['attention'] = {'x': x_attention, 'y': np.array(a)} dict_result['barplot'] = {'x': self._label, 'y': y_barplot} dict_result['class_name'] = self._class_name if visualization: _render_toxic(dict_result) else: return dict_result
def _predict_words( self, string, method, visualization, add_neutral=False, bins_size=0.05, **kwargs, ): method = method.lower() if method not in ['last', 'first', 'mean']: raise ValueError( "method not supported, only support 'last', 'first' and 'mean'" ) if add_neutral and not self._multilabels: label = self._label + ['neutral'] else: label = self._label input_ids, input_masks, _, s_tokens = bert_tokenization( self._tokenizer, [string] ) r = self._execute( inputs=[input_ids, input_masks], input_labels=['Placeholder', 'Placeholder_1'], output_labels=['logits', 'attention', 'logits_seq'], ) if self._multilabels: result = sigmoid(r['logits']) words = sigmoid(r['logits_seq']) else: result = softmax(r['logits'], axis=-1) words = softmax(r['logits_seq'], axis=-1) attentions = r['attention'] if method == 'first': cls_attn = list(attentions[0].values())[0][:, :, 0, :] if method == 'last': cls_attn = list(attentions[-1].values())[0][:, :, 0, :] if method == 'mean': combined_attentions = [] for a in attentions: combined_attentions.append(list(a.values())[0]) cls_attn = np.mean(combined_attentions, axis=0).mean(axis=2) cls_attn = np.mean(cls_attn, axis=1) total_weights = np.sum(cls_attn, axis=-1, keepdims=True) attn = cls_attn / total_weights words = words[0] if add_neutral and not self._multilabels: result = neutral(result) words = neutral(words) result = result[0] weights = [] merged = merge_sentencepiece_tokens(list(zip(s_tokens[0], attn[0]))) for i in range(words.shape[1]): m = merge_sentencepiece_tokens( list(zip(s_tokens[0], words[:, i])), weighted=False ) _, weight = zip(*m) weights.append(weight) w, a = zip(*merged) words = np.array(weights).T distribution_words = words[:, np.argmax(words.sum(axis=0))] y_histogram, x_histogram = np.histogram( distribution_words, bins=np.arange(0, 1 + bins_size, bins_size) ) y_histogram = y_histogram / y_histogram.sum() x_attention = np.arange(len(w)) left, right = np.unique( np.argmax(words, axis=1), return_counts=True ) left = left.tolist() y_barplot = [] for i in range(len(label)): if i not in left: y_barplot.append(i) else: y_barplot.append(right[left.index(i)]) dict_result = {label[i]: result[i] for i in range(len(result))} dict_result['alphas'] = {w: a[no] for no, w in enumerate(w)} dict_result['word'] = {w: words[no] for no, w in enumerate(w)} dict_result['histogram'] = {'x': x_histogram, 'y': y_histogram} dict_result['attention'] = {'x': x_attention, 'y': np.array(a)} dict_result['barplot'] = {'x': label, 'y': y_barplot} dict_result['module'] = self._module if visualization: render_dict[self._module](dict_result, **kwargs) else: return dict_result