The following code is a simple linear regression model, fit y = 2 * x, tensorboard created folder in the current folder
. 1 Import OS 2 Import IO . 3 Import Time . 4 Import numpy AS NP . 5 Import matplotlib.pyplot AS PLT . 6 Import tensorflow AS TF . 7 . 8 Sess = tf.Session () . 9 # Create summary_writer, the write tensorboard tensorboard summary folder 10 summary_writer tf.summary.FileWriter = ( ' tensorboard ' , tf.get_default_graph ()) . 11 # ensure summary_writer folder exists written Tensorflo 12 is IF Not os.path.exists ( 'tensorboard ' ): 13 is os.makdirs ( ' tensorboard ' ) 14 15 # Set model parameters 16 the batch_size = 50 . 17 Generations 100 = 18 is x_data = np.arange (1000) / 10 . 19 true_slope = 2 . 20 is y_data true_slope + * = x_data np.random.normal (LOC = 0.0, Scale = 25, size = 1000 ) 21 is 22 is # divided data into training and test sets 23 is train_ix np.random.choice = (len (x_data), int size = (len (x_data ) * 0.9), Replace = False) 24 # Print ( 'train_ix', train_ix.shape) 25 test_ix = np.setdiff1d(np.arange(1000), train_ix) 26 x_data_train, y_data_train = x_data[train_ix], y_data[train_ix] 27 # print('x_data_train', x_data_train.shape) 28 # print('y_data_train', y_data_train.shape) 29 x_data_test, y_data_test = x_data[test_ix], y_data[test_ix] 30 # print('x_data_test', x_data_test.shape) 31 # print('y_data_test', y_data_test.shape) 32 # print(y_data_test) 33 # 创建占位符,变量,模型操作,损失和优化函数 34 x_graph_input = tf.placeholder(tf.float32, [None]) 35 y_graph_input = tf.placeholder(tf.float32, [None]) 36 m = tf.Variable(tf.random_normal([1], dtype=tf.float32), name='Slope') 37 output = tf.multiply(m, x_graph_input, name='Batch_Multiplication') 38 residuals = output - y_graph_input 39 l2_loss = tf.reduce_mean(tf.abs(residuals), name='L2_Loss') 40 my_optim = tf.train.GradientDescentOptimizer(0.01) 41 train_step = my_optim.minimize(l2_loss) 42 43 # 创建tensorboard 操作汇总一个标量值 44 is with tf.name_scope ( ' Slope_Estimate ' ): 45 tf.summary.scalar ( ' Slope_Estimate ' , tf.squeeze (m)) 46 is 47 # another aggregate data is added tensorboard summary histogram 48 with tf.name_scope ( ' Loss_and_Residuals ' ): 49 tf.summary.histogram ( ' Histogram_Error ' , l2_loss) 50 tf.summary.histogram ( ' Histogram_Residuals ' , residuals) 51 is 52 is # summarized data 53 is summary_op = tf.summary.merge_all() 54 init = tf.global_variables_initializer() 55 sess.run(init) 56 57 # 训练线性回归模型 58 for i in range(generations): 59 batch_indices = np.random.choice(len(x_data_train), size=batch_size) 60 x_batch = x_data_train[batch_indices] 61 y_batch = y_data_train[batch_indices] 62 # print(y_batch.shape) 63 _, train_loss, summary = sess.run([train_step, l2_loss, summary_op], 64 feed_dict={x_graph_input: x_batch, y_graph_input: y_batch}) 65 66 67 test_loss, test_resids = sess.run([l2_loss, residuals], feed_dict = {x_graph_input: x_data_test, y_graph_input: y_data_test}) 68 if (i + 1) % 10 == 0: 69 print('generation {} of {}. Train Loss: {:.3}, Test Loss: {:.3}.'.format(i + 1, generations, train_loss, test_loss)) 70 log_writer = tf.summary.FileWriter('tensorboard') 71 log_writer.add_summary(summary, i) 72 73 # 创建函数输出protobuff格式的图像 74 def get_linear_plot(slope): 75 linear_prediction = x_data + slope 76 plt.plot(x_data, y_data, 'b.', label='data') 77 plt.plot(x_data, linear_prediction, 'r--', linewidth=3, label='predicted line') 78 plt.legend(loc='upper left') 79 buf = io.BytesIO() 80 plt.savefig(buf, format='png') 81 buf.seek(0) 82 return buf 83 84 85 slope = sess.run(m) 86 plot_buf = get_linear_plot(slope[0]) 87 image = tf.image.decode_png(plot_buf.getvalue(), channels=4) 88 image = tf.expand_dims(image, 0) 89 image_summary_op = tf.summary.image('Linear_Plot', image) 90 image_summary = sess.run(image_summary_op) 91 log_writer.add_summary(image_summary, i) 92 log_writer.close()
Entering cmd folder in the current mode, the input tensorboard --logdir = tensorboard --host = 127.0.0.1
Access 127.0.0.1:6006 to enter tensorboard
Note: If written as --logdir = 'tensorboard' will not be displayed
It may also be input directly pycharm tensorboard --logdir console = tensorboard --host = 127.0.0.1