TensorFlow FileWriter not writing to file

2024/11/15 8:24:29

I am training a simple TensorFlow model. The training aspect works fine, but no logs are being written to /tmp/tensorflow_logs and I'm not sure why. Could anyone provide some insight? Thank you

# import MNIST
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)import tensorflow as tf# set parameters
learning_rate = 0.01
training_iteration = 30
batch_size = 100
display_step = 2# TF graph input
x = tf.placeholder("float", [None, 784])
y = tf.placeholder("float", [None, 10])# create a model# set model weights
# 784 is the dimension of a flattened MNIST image
W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))with tf.name_scope("Wx_b") as scope:# construct linear modelmodel = tf.nn.softmax(tf.matmul(x, W) + b) #softmax# add summary ops to collect data
w_h = tf.summary.histogram("weights", W)
b_h = tf.summary.histogram("biases", b)with tf.name_scope("cost_function") as scope:# minimize error using cross entropycost_function = -tf.reduce_sum(y*tf.log(model))# create a summary to monitor the cost functiontf.summary.scalar("cost_function", cost_function)with tf.name_scope("train") as scope:# gradient descentoptimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost_function)init = tf.global_variables_initializer()# merge all summaries into a single operator
merged_summary_op = tf.summary.merge_all()# launch the graph
with tf.Session() as sess:sess.run(init)# set the logs writer to the folder /tmp/tensorflow_logssummary_writer = tf.summary.FileWriter('/tmp/tensorflow_logs', graph=sess.graph)# training cyclefor iteration in range(training_iteration):avg_cost = 0.total_batch = int(mnist.train.num_examples/batch_size)# loop over all batchesfor i in range(total_batch):batch_xs, batch_ys = mnist.train.next_batch(batch_size)# fit training using batch datasess.run(optimizer, feed_dict={x: batch_xs, y: batch_ys})# compute the average lossavg_cost += sess.run(cost_function, feed_dict={x: batch_xs, y: batch_ys})/total_batch# write logs for each iterationsummary_str = sess.run(merged_summary_op, feed_dict={x: batch_xs, y: batch_ys})summary_writer.add_summary(summary_str, iteration*total_batch + i)# display logs per iteration stepif iteration % display_step == 0:print("Iteration:", '%04d' % (iteration + 1), "cost= ", "{:.9f}".format(avg_cost))print("Tuning completed!")# test the modelpredictions = tf.equal(tf.argmax(model, 1), tf.argmax(y, 1))# calculate accuracyaccuracy = tf.reduce_mean(tf.cast(predictions, "float"))print("Accuracy:", accuracy.eval({x: mnist.test.images, y: mnist.test.labels}))print("Success!")
Answer

A combination of changing the file path from /temp/... to temp/... and adding summary_writer.flush() and summary_writer.close() made the logs be written successfully.

https://en.xdnf.cn/q/71797.html

Related Q&A

python time.strftime %z is always zero instead of timezone offset

>>> import time >>> t=1440935442 >>> time.strftime("%Y/%m/%d-%H:%M:%S %z",time.gmtime(t)) 2015/08/30-11:50:42 +0000 >>> time.strftime("%Y/%m/%d-%H:%M:…

Python: Nested for loops or next statement

Im a rookie hobbyist and I nest for loops when I write python, like so:dict = {key1: {subkey/value1: value2} ... keyn: {subkeyn/valuen: valuen+1}}for key in dict:for subkey/value in key:do it to itIm a…

How to install cython an Anaconda 64 bits with Windows 10?

Its all in the title, does someone have a step by step method to install cython and run it on Anaconda 64 bits on Windows 10? I search for hours and there are a lot of tutorials... For things that I w…

Using DictWriter to write a CSV when the fields are not known beforehand

I am parsing a large piece of text into dictionaries, with the end objective of creating a CSV file with the keys as column headers. csv.DictWriter(csvfile, fieldnames, restval=, extrasaction=raise, di…

How to Save io.BytesIO pdfrw PDF into Django FileField

What I am trying to do is basically:Get PDF from URL Modify it via pdfrw Store it in memory as a BytesIO obj Upload it into a Django FileField via Model.objects.create(form=pdf_file, name="Some n…

Which python static checker can catch forgotten await problems?

Code: from typing import AsyncIterableimport asyncioasync def agen() -> AsyncIterable[str]:print(agen start)yield 1yield 2async def agenmaker() -> AsyncIterable[str]:print(agenmaker start)return …

Tkinter : Syntax highlighting for Text widget

Can anyone explain how to add syntax highlighting to a Tkinter Text widget ?Every time the program finds a matching word, it would color that word to how I want. Such as : Color the word tkinter in pi…

how to use pkgutils.get_data with csv.reader in python?

I have a python module that has a variety of data files, (a set of csv files representing curves) that need to be loaded at runtime. The csv module works very well # curvefile = "ntc.10k.csv"…

How to make celery retry using the same worker?

Im just starting out with celery in a Django project, and am kinda stuck at this particular problem: Basically, I need to distribute a long-running task to different workers. The task is actually broke…

Make an AJAX call to pass drop down value to the python script

I want to pass the selected value from dropdown which contains names of databases and pass it to the python script in the background which connects to the passed database name. Following is the ajax co…