Python print matrix
60 Python code examples are found related to "
print matrix".
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
Example 1
Source File: gf2matrix.py From sp800_22_tests with GNU General Public License v2.0 | 6 votes |
def print_matrix(matrix): #print "PRINT MATRIX" #print "len matrix = ",str(len(matrix)) #for line in matrix: # print line for i in range(len(matrix)): #print "Line %d" % i line = matrix[i] #print "Line %d = %s" % (i,str(line)) if i==0: astr = "["+str(line)+" : " else: astr += " "+str(line)+" : " for ch in line: astr = astr + str(ch) if i == (len(matrix)-1): astr += "]" else: astr = astr + "\n" print(astr) #print "END PRINT MATRIX"
Example 2
Source File: pycm_obj.py From pycm with MIT License | 6 votes |
def print_matrix(self, one_vs_all=False, class_name=None, sparse=False): """ Print confusion matrix. :param one_vs_all : One-Vs-All mode flag :type one_vs_all : bool :param class_name : target class name for One-Vs-All mode :type class_name : any valid type :param sparse : sparse mode printing flag :type sparse : bool :return: None """ classes = self.classes table = self.table if one_vs_all: [classes, table] = one_vs_all_func( classes, table, self.TP, self.TN, self.FP, self.FN, class_name) if sparse is True: if self.sparse_matrix is None: self.sparse_matrix = sparse_matrix_calc(classes, table) print(sparse_table_print(self.sparse_matrix)) else: print(table_print(classes, table)) if len(classes) >= CLASS_NUMBER_THRESHOLD: warn(CLASS_NUMBER_WARNING, RuntimeWarning)
Example 3
Source File: helpers.py From bioinformatics with GNU General Public License v3.0 | 6 votes |
def print_matrix(B,out='./print_matrix.txt'): with open(out,'w') as f: for row in B: line="" for x in row: if len(line)>0: line=line+' ' line=line+"{:15.12f}".format(x) f.write(line+'\n') #Tree --> Subtree ";" | Branch ";" #Subtree --> Leaf | Internal #Leaf --> Name #Internal --> "(" BranchSet ")" Name #BranchSet --> Branch | Branch "," BranchSet #Branch --> Subtree Length #Name --> empty | string #Length --> empty | ":" number
Example 4
Source File: q1.py From algorithm_qa with MIT License | 6 votes |
def print_cycle_of_matrix(cls, matrix, start_r, start_c, end_r, end_c): if start_r == end_r: while start_c <= end_c: print(matrix[start_r][start_c], end=' ') start_c += 1 elif start_c == end_c: while start_r <= end_r: print(matrix[start_r][start_c], end=' ') start_r += 1 else: tmp_c = start_c tmp_r = start_r while tmp_c != end_c: print(matrix[tmp_r][tmp_c], end=' ') tmp_c += 1 while tmp_r != end_r: print(matrix[tmp_r][tmp_c], end=' ') tmp_r += 1 while tmp_c != start_c: print(matrix[tmp_r][tmp_c], end=' ') tmp_c -= 1 while tmp_r != start_r: print(matrix[tmp_r][tmp_c], end=' ') tmp_r -= 1
Example 5
Source File: score.py From fnc-1-baseline with Apache License 2.0 | 6 votes |
def print_confusion_matrix(cm): lines = [] header = "|{:^11}|{:^11}|{:^11}|{:^11}|{:^11}|".format('', *LABELS) line_len = len(header) lines.append("-"*line_len) lines.append(header) lines.append("-"*line_len) hit = 0 total = 0 for i, row in enumerate(cm): hit += row[i] total += sum(row) lines.append("|{:^11}|{:^11}|{:^11}|{:^11}|{:^11}|".format(LABELS[i], *row)) lines.append("-"*line_len) print('\n'.join(lines))
Example 6
Source File: scenarios.py From molecule with MIT License | 6 votes |
def print_matrix(self): msg = "Test matrix" LOG.info(msg) tree = tuple( ( "", [ (scenario.name, [(action, []) for action in scenario.sequence]) for scenario in self.all ], ) ) tf = tree_format.format_tree( tree, format_node=operator.itemgetter(0), get_children=operator.itemgetter(1), ) LOG.out(tf) LOG.out("")
Example 7
Source File: generate.py From multi-categorical-gans with BSD 3-Clause "New" or "Revised" License | 6 votes |
def print_matrix_stats(matrix, num_samples, num_features): num_ones = matrix.sum() num_positions = num_samples * num_features num_ones_per_row = np.asarray(matrix.sum(axis=1)).ravel() num_ones_per_column = np.asarray(matrix.sum(axis=0)).ravel() print("Min:", matrix.min()) print("Max:", matrix.max()) print("Rows:", matrix.shape[0]) print("Columns:", matrix.shape[1]) print("Mean ones per row:", num_ones_per_row.mean()) print("Mean ones per column:", num_ones_per_column.mean()) print("Total ones:", num_ones) print("Total positions:", num_positions) print("Total ratio of ones:", num_ones / num_positions) print("Empty rows:", np.sum(num_ones_per_row == 0)) print("Full rows:", np.sum(num_ones_per_row == num_features)) print("Empty columns:", np.sum(num_ones_per_column == 0)) print("Full columns:", np.sum(num_ones_per_column == num_samples))
Example 8
Source File: converters.py From transitionMatrix with Apache License 2.0 | 6 votes |
def print_matrix(A, format_type='Standard', accuracy=2): """ Pretty print a matrix :param format_type: formatting options (Standard, Percent) :type format_type: str :param accuracy: number of decimals to display :type accuracy: int """ for s_in in range(A.shape[0]): for s_out in range(A.shape[1]): if format_type is 'Standard': format_string = "{0:." + str(accuracy) + "f}" print(format_string.format(A[s_in, s_out]) + ' ', end='') elif format_type is 'Percent': print("{0:.2f}%".format(100 * A[s_in, s_out]) + ' ', end='') print('')
Example 9
Source File: track4-metrics.py From dfc2019 with MIT License | 6 votes |
def print_matrix(mat): """ Prints the confusion matrix to terminal in a human readable manner :param mat: Confusion matrix generated by this software :return: nothing """ across = "T" ALL_LABELS = LABELS + ['OTHER'] for label in ALL_LABELS: across += "{:>9} ".format("P({})".format(label)) print(across) print('-' * len(across)) for label in LABELS: across = "{:<3}".format(label) for label_inner in ALL_LABELS: i = LABEL_INDEXES[label] j = -1 if label_inner is 'OTHER' else LABEL_INDEXES[label_inner] across += "{:>9}|".format(mat[i][j]) print(across) print()
Example 10
Source File: evaluate.py From ccg2lambda with Apache License 2.0 | 6 votes |
def print_confusion_matrix(gold_id_labels, sys_id_labels): gold_ids = gold_id_labels.keys() gold_labels = [gold_id_labels[i] for i in gold_ids] sys_labels = [sys_id_labels.get(i, 'unknown') for i in gold_ids] c = ConfusionMatrix(gold_labels, sys_labels) print('Confusion matrix:\n{0}'.format(c)) true_positives = c.get('yes', 'yes') + c.get('no', 'no') true_negatives = c.get('unknown', 'unknown') false_positives = c.get('unknown', 'yes') + c.get('unknown', 'no') + c.get('no', 'yes') + c.get('yes', 'no') false_negatives = c.get('yes', 'unknown') + c.get('no', 'unknown') print('Precision : {0:.4f}'.format( float(true_positives) / (true_positives + false_positives))) print('Recall : {0:.4f}'.format( float(true_positives) / (true_positives + false_negatives))) print('True positives : {0}'.format(true_positives)) print('True negatives : {0}'.format(true_negatives)) print('False positives: {0}'.format(false_positives)) print('False negatives: {0}'.format(false_negatives))
Example 11
Source File: _wheel.py From steam-vr-wheel with MIT License | 5 votes |
def print_matrix(matrix): l = [] for i in range(3): ll = [] for j in range(4): ll.append(matrix[j]) l.append(ll) print(l)
Example 12
Source File: model.py From bugbug with Mozilla Public License 2.0 | 5 votes |
def print_labeled_confusion_matrix(confusion_matrix, labels, is_multilabel=False): confusion_matrix_table = confusion_matrix.tolist() # Don't show the Not classified row in the table output if "__NOT_CLASSIFIED__" in labels and not is_multilabel: confusion_matrix_table.pop(labels.index("__NOT_CLASSIFIED__")) if not is_multilabel: confusion_matrix_table = [confusion_matrix_table] for num, table in enumerate(confusion_matrix_table): if is_multilabel: print(f"label: {labels[num]}") table_labels = [0, 1] else: table_labels = labels confusion_matrix_header = [] for i in range(len(table[0])): confusion_matrix_header.append( f"{table_labels[i]} (Predicted)" if table_labels[i] != "__NOT_CLASSIFIED__" else "Not classified" ) for i in range(len(table)): table[i].insert(0, f"{table_labels[i]} (Actual)") print( tabulate(table, headers=confusion_matrix_header, tablefmt="fancy_grid"), end="\n\n", )
Example 13
Source File: print_metrix.py From oh-my-python with MIT License | 5 votes |
def print_matrix(matrix): r = [] entry = 0 length = len(matrix[0]) if matrix else 0 width = len(matrix) while entry * 2 < length or entry * 2 < width: print_circle(matrix, entry, length, width, r) entry += 1 print(r) return r
Example 14
Source File: constraint_satisfaction.py From bii-server with MIT License | 5 votes |
def print_in_matrix_form(matrix): ret_str = '' for row in matrix: for elem in row: ret_str += str(elem) else: ret_str += '\n' ret_str += "\n" return ret_str
Example 15
Source File: 19-顺时针打印矩阵.py From awesome-algorithm with GNU General Public License v3.0 | 5 votes |
def PrintMatrixInCircle(self, matrix, columns, rows,start,result): endX = columns - 1 - start endY = rows - 1 - start # 从左到右打印一行 for i in range(start, endX+1): #number = matrix[start][i] result.append(matrix[start][i]) # 从上到下打印一行 if start < endY: for i in range(start+1, endY+1): #number = matrix[i][endX] result.append(matrix[i][endX]) # 从右到左打印一行 if start < endX and start < endY: for i in range(endX-1, start-1, -1): #number = matrix[endY][i] result.append(matrix[endY][i]) # 从下到上打印一行 if start < endX and start < endY-1: for i in range(endY-1, start, -1): #number = matrix[i][start] result.append(matrix[i][start])
Example 16
Source File: audioTrainTest.py From pyAudioAnalysis with Apache License 2.0 | 5 votes |
def print_confusion_matrix(cm, class_names): """ This function prints a confusion matrix for a particular classification task. ARGUMENTS: cm: a 2-D np array of the confusion matrix (cm[i,j] is the number of times a sample from class i was classified in class j) class_names: a list that contains the names of the classes """ if cm.shape[0] != len(class_names): print("printConfusionMatrix: Wrong argument sizes\n") return for c in class_names: if len(c) > 4: c = c[0:3] print("\t{0:s}".format(c), end="") print("") for i, c in enumerate(class_names): if len(c) > 4: c = c[0:3] print("{0:s}".format(c), end="") for j in range(len(class_names)): print("\t{0:.2f}".format(100.0 * cm[i][j] / np.sum(cm)), end="") print("")
Example 17
Source File: benchmark.py From vamb with MIT License | 5 votes |
def print_matrix(self, rank, file=_sys.stdout): """Prints the recall/precision number of bins to STDOUT.""" if rank >= len(self.counters): raise IndexError("Taxonomic rank out of range") print('\tRecall', file=file) print('Prec.', '\t'.join([str(r) for r in self.recalls]), sep='\t', file=file) for min_precision in self.precisions: row = [self.counters[rank][(min_recall, min_precision)] for min_recall in self.recalls] print(min_precision, '\t'.join([str(i) for i in row]), sep='\t', file=file)
Example 18
Source File: gamelevel.py From collection with MIT License | 5 votes |
def print_matrix(m, is_all_char = False): mlen = 0 for line in m: for n in line: s = len(str(n)) mlen = max(mlen, s) for line in m: text = '' for n in line: result = str(n).rjust(mlen) + ' ' if is_all_char: result = str(n)[:1] text += result print text return 0
Example 19
Source File: predict_util.py From kaggle-dr with MIT License | 5 votes |
def print_confusion_matrix(M): K = M.shape[0] print("Confusion Matrix") left_margins = [" T\P |", "-----|"] header = left_margins[0] + "".join([" %4d |" % klass for klass in range(K)]) spacer = left_margins[1] + "".join(["------|" for klass in range(K)]) print header print spacer for pred_klass, true_klass in enumerate(xrange(K)): row = (" %3d |" % true_klass) + "".join([" %4d |" % entry for entry in M[pred_klass]]) print row print spacer
Example 20
Source File: tree_kernels.py From Semantic-Texual-Similarity-Toolkits with MIT License | 5 votes |
def printKernelMatrix(self,dataset): if not isinstance(dataset, tree.Dataset): print("ERROR: the first Parameter must be a Dataset object") return ne = len(dataset) for i in range(ne): for j in range(i,ne): print("%d %d %.2f" % (i, j, self.kernel(dataset.getExample(i), dataset.getExample(j))))
Example 21
Source File: classifier.py From tornado with MIT License | 5 votes |
def print_confusion_matrix(self): for real_class in self.CLASSES: for predicted_class in self.CLASSES: print(self.__CONFUSION_MATRIX[real_class][predicted_class], end="\t") print()
Example 22
Source File: bit_score.py From EdwardsLab with MIT License | 5 votes |
def print_matrix(matf, pb, verbose=False): """ Print a matrix version of the pairwise bitscores :param matf: the matrix file to write :param pb: the pairwise bitscores :param verbose: more output :return: """ if verbose: sys.stderr.write(f"{bcolors.GREEN}Creating scores{bcolors.ENDC}\n") allkeys = list(pb.keys()) with open(matf + ".mat", 'w') as out: out.write("\t".join([""] + allkeys)) out.write("\n") for p in allkeys: out.write(p) for q in allkeys: if p == q: out.write("\t0") elif q in pb[p]: out.write(f"\t{1-pb[p][q]}") else: out.write("\t1") out.write("\n")
Example 23
Source File: 19-顺时针打印矩阵.py From awesome-algorithm with GNU General Public License v3.0 | 5 votes |
def printMatrix(self, matrix): if not matrix: return [] rows = len(matrix) columns = len(matrix[0]) start = 0 result = [] while rows > start * 2 and columns > start * 2: self.PrintMatrixInCircle(matrix, columns, rows, start,result) start += 1 return result
Example 24
Source File: utils_model.py From HistoGAN with GNU General Public License v3.0 | 5 votes |
def print_conf_matrix(confusion_matrix, classes): first_line = " " + " ".join(['{:5s}'.format(_class) for _class in classes]) print(first_line) for row, _class in zip(confusion_matrix, classes): row_pretty = '{:3s}'.format(_class) + " ".join(['{:.3f}'.format(number) for number in row]) print(row_pretty) #random rotation function #credits to Naofumi Tomita
Example 25
Source File: cmUtilities.py From credit-risk-modelling with GNU General Public License v3.0 | 5 votes |
def printMatrix(R,myString): N,M = R.shape for n in range(0,N): for m in range(0,M): if m!=(M-1): print(myString % (R[n,m]) + " & ", end=" ") else: print(myString % (R[n,m]) + "\\\\", end="\n")
Example 26
Source File: munkres.py From SARosPerceptionKitti with MIT License | 5 votes |
def print_matrix(matrix, msg=None): """ Convenience function: Displays the contents of a matrix of integers. :Parameters: matrix : list of lists Matrix to print msg : str Optional message to print before displaying the matrix """ import math if msg is not None: print msg # Calculate the appropriate format width. width = 0 for row in matrix: for val in row: width = max(width, int(math.log10(val)) + 1) # Make the format string format = '%%%dd' % width # Print the matrix for row in matrix: sep = '[' for val in row: sys.stdout.write(sep + format % val) sep = ', ' sys.stdout.write(']\n') # --------------------------------------------------------------------------- # Main # ---------------------------------------------------------------------------
Example 27
Source File: combine_distance_matrices.py From Bacsort with GNU General Public License v3.0 | 5 votes |
def print_matrix(matrix, assemblies): print('Printing matrix to stdout', end='', file=sys.stderr, flush=True) print(len(assemblies)) for i, a1 in enumerate(assemblies): print(a1, end='') for a2 in assemblies: print('\t%.6f' % matrix[(a1, a2)], end='') print('') if i % 100 == 0: print('.', end='', file=sys.stderr, flush=True) print(' done\n', file=sys.stderr, flush=True)
Example 28
Source File: es_spark_rect_mm.py From qbox-blog-code with Apache License 2.0 | 5 votes |
def print_matrix(A, M, N): matrix = [[0 for j in range(N)] for i in range(M)] for result in A: row = result[0][0] col = result[0][1] matrix[row-1][col-1] = result[1] for i in range(M): print(','.join([str(matrix[i][j]) for j in range(N)]) + ',')
Example 29
Source File: render.py From g-tensorflow-models with Apache License 2.0 | 5 votes |
def print_matrix(f, mat): for i in range(4): for j in range(4): f.write("%lf " % mat[i][j]) f.write("\n")
Example 30
Source File: print.py From mapillary_vistas with MIT License | 5 votes |
def print_confusion_matrix(labels, confusion_matrix, percent=False): max_length = get_max_length(labels) print('') print('') print('') header = "{:>{ml}} |".format("", ml=max_length+1) for label in labels: header += "{:>{ml}} |".format(label["name"], ml=max_length) print(header) for index, label in enumerate(labels): current_line = "{:>{ml}}: |".format(label["name"], ml=max_length) divider = float(np.sum(confusion_matrix[index, :])) for inner_index, _ in enumerate(labels): if percent: if divider == 0: metric = float('nan') else: metric = confusion_matrix[index, inner_index] / divider value = "{:.2%}".format(metric) else: value = "{:d}".format(confusion_matrix[index, inner_index]) current_line += "{:>{ml}} |".format(value, ml=max_length) print(current_line) print()
Example 31
Source File: q1.py From algorithm_qa with MIT License | 5 votes |
def print_matrix(cls, matrix): start_r = 0 start_c = 0 end_r = len(matrix) - 1 end_c = len(matrix[0]) - 1 while start_r <= end_r and start_c <= end_c: cls.print_cycle_of_matrix(matrix, start_r, start_c, end_r, end_c) start_c += 1 start_r += 1 end_r -= 1 end_c -= 1
Example 32
Source File: pycm_obj.py From pycm with MIT License | 5 votes |
def print_normalized_matrix( self, one_vs_all=False, class_name=None, sparse=False): """ Print normalized confusion matrix. :param one_vs_all : One-Vs-All mode flag :type one_vs_all : bool :param class_name : target class name for One-Vs-All mode :type class_name : any valid type :param sparse : sparse mode printing flag :type sparse : bool :return: None """ classes = self.classes table = self.table normalized_table = self.normalized_table if one_vs_all: [classes, table] = one_vs_all_func( classes, table, self.TP, self.TN, self.FP, self.FN, class_name) normalized_table = normalized_table_calc(classes, table) if sparse is True: if self.sparse_normalized_matrix is None: self.sparse_normalized_matrix = sparse_matrix_calc( classes, normalized_table) print(sparse_table_print(self.sparse_normalized_matrix)) else: print(table_print(classes, normalized_table)) if len(classes) >= CLASS_NUMBER_THRESHOLD: warn(CLASS_NUMBER_WARNING, RuntimeWarning)
Example 33
Source File: cf.py From Seq2Seq_Upgrade_TensorFlow with Apache License 2.0 | 5 votes |
def print_matrix_info(x_embed,y): print 'the size of x embed is ', x_embed.nbytes print 'the size of y is ', y.nbytes print 'the shape of x embed ', x_embed.shape print 'the shape of y ', y.shape
Example 34
Source File: reward_confusion.py From training_results_v0.5 with Apache License 2.0 | 5 votes |
def print_confusion_matrix(title, cm): print("=" * 30) print(title) print("=" * 30) print(cm) print("=" * 30) print()
Example 35
Source File: Graph.py From Python with MIT License | 5 votes |
def print_matrix(self): """ To print the adjecency matrix """ for i in self.adj_mat: for j in i: print(j,end=" ") print("")
Example 36
Source File: 16_DS_Part_2.py From Python with MIT License | 5 votes |
def printAdjMatrix(self): if len(self.adjMatrix) == 0: print('Please fill the Adjacency Matrix') return print('Given Adjacency Matrix :') for row in self.adjMatrix: print(row)
Example 37
Source File: SchedMatrix.py From bart with Apache License 2.0 | 5 votes |
def print_matrix(self): """Print the correlation matrix""" # pylint fails to recognize numpy members. # pylint: disable=no-member np.set_printoptions(precision=5) np.set_printoptions(suppress=False) np.savetxt(sys.stdout, self._matrix, "%5.5f") # pylint: enable=no-member
Example 38
Source File: classification_demo.py From Deep-Learning-with-TensorFlow-Second-Edition with MIT License | 5 votes |
def print_and_plot_confusion_matrix(cm, classes, normalize=False, title='Confusion matrix', cmap=plt.cm.Blues): """ This function prints and plots the confusion matrix. Normalization can be applied by setting `normalize=True`. """ plt.imshow(cm, interpolation='nearest', cmap=cmap) plt.title(title) plt.colorbar() tick_marks = np.arange(len(classes)) plt.xticks(tick_marks, classes, rotation=45) plt.yticks(tick_marks, classes) if normalize: cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis] print("Normalized confusion matrix") else: print('Confusion matrix, without normalization') thresh = cm.max() / 2. for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])): plt.text(j, i, cm[i, j], horizontalalignment="center", color="white" if cm[i, j] > thresh else "black") plt.tight_layout() plt.ylabel('True label') plt.xlabel('Predicted label') return cm # Plot non-normalized confusion matrix
Example 39
Source File: translate.py From DL4MT with BSD 3-Clause "New" or "Revised" License | 5 votes |
def print_matrix(hyp, file): # each target word has corresponding alignment weights for target_word_alignment in hyp: # each source hidden state has a corresponding weight for w in target_word_alignment: print >> file, w, print >> file, "" print >> file, ""
Example 40
Source File: classification_inference.py From sciwing with MIT License | 5 votes |
def print_confusion_matrix(self) -> None: """ Prints the confusion matrix for the test dataset """ self.metrics_calculator.print_confusion_metrics( predicted_probs=self.output_analytics["all_pred_probs"], labels=self.output_analytics["true_labels_indices"].unsqueeze(1), )
Example 41
Source File: crc.py From valentyusb with BSD 3-Clause "New" or "Revised" License | 5 votes |
def print_matrix(crc_width, cols_nin, cols_min): """ >>> crc_width = 5 >>> data_width = 4 >>> poly_list = [0, 0, 1, 0, 1] >>> _, cols_nin, cols_min = build_matrix(poly_list, data_width) >>> print_matrix(crc_width, cols_nin, cols_min) 0 d[ 0], , , d[ 3], , c[ 1], , , c[ 4] 1 , d[ 1], , , , , c[ 2], , 2 d[ 0], , d[ 2], d[ 3], , c[ 1], , c[ 3], c[ 4] 3 , d[ 1], , d[ 3], , , c[ 2], , c[ 4] 4 , , d[ 2], , c[ 0], , , c[ 3], """ for i in range(crc_width): text_xor = [] for j, use in enumerate(cols_nin[i]): if use: text_xor.append('d[%2i]' % j) else: text_xor.append(' ') for j, use in enumerate(cols_min[i]): if use: text_xor.append('c[%2i]' % j) else: text_xor.append(' ') print("{:4d} {}".format(i, ", ".join("{:>5s}".format(x) for x in text_xor).rstrip()))
Example 42
Source File: micro-jpeg-visualizer.py From micro-jpeg-visualizer with MIT License | 5 votes |
def PrintMatrix( m): for j in range(8): for i in range(8): print("%2f" % m[i+j*8]), print print
Example 43
Source File: stats_metrics.py From fanci with GNU General Public License v3.0 | 5 votes |
def print_cummulative_conf_matrix(self): """ Prints the cumulated confusion matrix for all added runs :return: """ cumu_cm = self.cummulative_conf_matrix() log.info('Confusion matrix\n' + pretty_print_cm(cumu_cm.astype(int), ('Benign', 'Malicious')))
Example 44
Source File: copy_transform.py From algorithms with MIT License | 5 votes |
def print_matrix(matrix, name): print('{}:\n['.format(name)) for row in matrix: print(' {}'.format(row)) print(']\n')
Example 45
Source File: munkres.py From MOTSFusion with MIT License | 5 votes |
def print_matrix(matrix, msg=None): """ Convenience function: Displays the contents of a matrix of integers. :Parameters: matrix : list of lists Matrix to print msg : str Optional message to print before displaying the matrix """ import math if msg is not None: print(msg) # Calculate the appropriate format width. width = 0 for row in matrix: for val in row: width = max(width, int(math.log10(val)) + 1) # Make the format string format = '%%%dd' % width # Print the matrix for row in matrix: sep = '[' for val in row: sys.stdout.write(sep + format % val) sep = ', ' sys.stdout.write(']\n') # --------------------------------------------------------------------------- # Main # ---------------------------------------------------------------------------
Example 46
Source File: yap_log.py From yap with Apache License 2.0 | 5 votes |
def print_matrix(dict, file): """ Called within the pass_fail_matrix() function. Input dict with sample name/command name if applicable with stagewise fail/pass dict and write path as input. prints the stagewise matrix to file. """ normal_stage_arr = ['PREPROCESS', 'ALIGNMENT', 'POSTPROCESS'] # Stages of the matrix/sample compare_stage_arr = ['CUFFDIFF', 'CUFFCOMPARE', 'CUFFMERGE', 'MACS2'] # Multi-sample hence printed after. head_str = '\t' + '\t'.join(normal_stage_arr) + '\n' normal_str = "" compare_str = "" for i in sorted(dict.keys()): if sorted(dict[i].keys()) == sorted(normal_stage_arr): normal_str += i + "\t" for j in range(len(normal_stage_arr)): if j != len(normal_stage_arr) - 1: normal_str += dict[i][normal_stage_arr[j]] + "\t" else: normal_str += dict[i][normal_stage_arr[j]] + "\n" elif set(dict[i].keys()).issubset(set(compare_stage_arr)): for j in dict[i].keys(): compare_str += i + ": " + dict[i][j] + "\n" yap_file_io.write_data(head_str + normal_str, file) if compare_str != '': yap_file_io.write_data("\n\n" + compare_str, file)
Example 47
Source File: translate.py From DL4MT with BSD 3-Clause "New" or "Revised" License | 5 votes |
def print_matrix_json(hyp, source, target, sid, tid, file): source.append("</s>") target.append("</s>") links = [] for ti, target_word_alignment in enumerate(hyp): for si, w in enumerate(target_word_alignment): links.append((target[ti], source[si], str(w), sid, tid)) json.dump(links, file, ensure_ascii=False, indent=2)
Example 48
Source File: fill.py From labs with MIT License | 5 votes |
def print_matrix(matrix): """Prints matrix to stdout """ for row in matrix: row_values = "".join(row) print("|%s|" % row_values) print('\n')
Example 49
Source File: rotateMatrix180Deg.py From Python-Interview-Problems-for-Practice with MIT License | 5 votes |
def printMatrix(ipMat, size): for i in range(size): for j in range(size): print(ipMat[i][j], end=" ") print('\n')
Example 50
Source File: training.py From OpenCV-3-x-with-Python-By-Example with MIT License | 5 votes |
def print_confusion_matrix(confusion_matrix): expected_model = confusion_matrix.keys() print ('\t\t', '\t'.join([expected_type.ljust(15) for expected_type in expected_model])) for expected_type in expected_model: values = [] for predicted_values in confusion_matrix.values(): for predicted_model, value in predicted_values.items(): if predicted_model == expected_type: values.append(str(value).ljust(10)) print('%s\t\t%s' % (expected_type.ljust(15), '\t'.join(values)))
Example 51
Source File: weights.py From trackml-library with MIT License | 5 votes |
def print_order_weight_matrix(prefix=''): print(prefix, 'order weight matrix (weights in percent):', sep='') print(prefix, 'nhits | ihit', sep='') print(prefix, ' |', sep='', end='') for i in range(len(ORDER_MATRIX[1:][0])): print(' {:2d}'.format(i), end='') print() print(prefix, '------+' + len(ORDER_MATRIX[1:][0]) * 3 * '-', sep='') for nhits, row in enumerate(ORDER_MATRIX[1:], start=1): print(prefix, ' {: 3d} |'.format(nhits), sep='', end='') for ihit in range(nhits): print(' {:2.0f}'.format(100 * row[ihit]), end='') print()
Example 52
Source File: evaluator.py From knowledge-net with MIT License | 5 votes |
def printPredictionsMatrix(predictionsMatrix): print("\n ------ Predictions Matrix ------") print('%-30s%-15s%-15s%-15s' % ("Property" , "TP", "FP", "FN")) print('%-30s%-15s%-15s%-15s' % ("--------" , "--", "--", "--")) tp_total = 0 fp_total = 0 fn_total = 0 for p in predictionsMatrix: values = predictionsMatrix[p] tp_total+=predictionsMatrix[p]["TP"] fp_total+=predictionsMatrix[p]["FP"] fn_total+=predictionsMatrix[p]["FN"] print('%-30s%-15i%-15i%-15i' % (p , values["TP"], values["FP"], values["FN"])) print('%-30s%-15i%-15i%-15i' % ("#global" , tp_total, fp_total, fn_total))
Example 53
Source File: munkres.py From uois with GNU General Public License v3.0 | 5 votes |
def print_matrix(matrix, msg=None): """ Convenience function: Displays the contents of a matrix of integers. :Parameters: matrix : list of lists Matrix to print msg : str Optional message to print before displaying the matrix """ import math if msg is not None: print(msg) # Calculate the appropriate format width. width = 0 for row in matrix: for val in row: width = max(width, int(math.log10(val)) + 1) # Make the format string format = '%%%dd' % width # Print the matrix for row in matrix: sep = '[' for val in row: sys.stdout.write(sep + format % val) sep = ', ' sys.stdout.write(']\n')