感谢您阅读我的问题
我有这样的数据。 19个输入数据和1个标签
我已经尝试过mnist,tensorboard示例和csv批量加载示例。 现在我正在尝试将它们混合在一起。
加载csv数据并批量处理。 只学习1层并检查成本。 这就是我想做的一切
这是我的代码
import tensorflow as tf
with tf.name_scope("input") as scope:
x = tf.placeholder(tf.float32, [None, 19])
with tf.name_scope("weight") as scope:
W = tf.Variable(tf.zeros([19, 1]))
with tf.name_scope("bias") as scope:
b = tf.Variable(tf.zeros([1]))
with tf.name_scope("layer1") as scope:
y = tf.nn.relu(tf.matmul(x, W) + b)
w_hist = tf.summary.histogram("weight", W)
b_hist = tf.summary.histogram("bias", b)
y_hist = tf.summary.histogram("y", y)
with tf.name_scope("y_") as scope:
y_ = tf.placeholder(tf.float32, [None, 1])
with tf.name_scope("cost") as scope:
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1]))
cost_sum = tf.summary.scalar("cost",cross_entropy)
with tf.name_scope("train") as scope:
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)
def read_my_file_format(filename_queue):
reader = tf.TextLineReader(skip_header_lines=1)
_, value = reader.read(filename_queue)
record_defaults = [[1], [1], [1], [1], [1],[1], [1], [1], [1], [1],[1], [1], [1], [1], [1],[1], [1], [1], [1], [1]]
record_defaults = [tf.constant([1], dtype=tf.float32),
tf.constant([1], dtype=tf.float32),
tf.constant([1], dtype=tf.float32),
tf.constant([1], dtype=tf.float32),
tf.constant([1], dtype=tf.float32),
tf.constant([1], dtype=tf.float32),
tf.constant([1], dtype=tf.float32),
tf.constant([1], dtype=tf.float32),
tf.constant([1], dtype=tf.float32),
tf.constant([1], dtype=tf.float32),
tf.constant([1], dtype=tf.float32),
tf.constant([1], dtype=tf.float32),
tf.constant([1], dtype=tf.float32),
tf.constant([1], dtype=tf.float32),
tf.constant([1], dtype=tf.float32),
tf.constant([1], dtype=tf.float32),
tf.constant([1], dtype=tf.float32),
tf.constant([1], dtype=tf.float32),
tf.constant([1], dtype=tf.float32),
tf.constant([1], dtype=tf.float32)]
col1, col2, col3, col4, col5, col6, col7, col8, col9, col10, col11, col12, col13, col14, col15 ,col16, col17, col18, col19, col20 = tf.decode_csv(value, record_defaults=record_defaults)
features = tf.pack([col1, col2, col3, col4, col5, col6, col7, col8, col9, col10, col11, col12, col13, col14, col15 ,col16, col17, col18, col19])
label = tf.pack([col20])
return features, label
def input_pipeline(batch_size, num_epochs=None):
min_after_dequeue = 10000
capacity = min_after_dequeue + 3 * batch_size
filename_queue = tf.train.string_input_producer(["sampledata1999_2008.csv"], num_epochs=num_epochs, shuffle=True)
example, label = read_my_file_format(filename_queue)
example_batch, label_batch = tf.train.shuffle_batch([example, label],
batch_size=batch_size,
capacity=capacity,
min_after_dequeue=min_after_dequeue)
return example_batch, label_batch
examples, labels = input_pipeline(100,1)
init_op = tf.group(tf.global_variables_initializer(), tf.local_variables_initializer())
sess = tf.Session()
# Initialize the variables (like the epoch counter).
sess.run(init_op)
merged = tf.summary.merge_all()
trainwriter =tf.summary.FileWriter("./board/custom", sess.graph)
# Start input enqueue threads.
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(sess=sess, coord=coord)
try:
i = 0;
while not coord.should_stop():
i = i + 1
example_batch, label_batch = sess.run([examples, labels])
sess.run(train_step, feed_dict={x: example_batch, y_: label_batch})
if i % 100 == 0:
summary = sess.run(merged, feed_dict={x: example_batch, y_: label_batch})
trainwriter.add_summary(summary,i)
print(example_batch)
except tf.errors.OutOfRangeError:
print('Done training -- epoch limit reached')
finally:
# When done, ask the threads to stop.
coord.request_stop()
# Wait for threads to finish.
coord.join(threads)
sess.close()
我检查批量数据是否正确输入到cross_entropy。 但如果我使用这些
if i % 100 == 0:
summary = sess.run(merged, feed_dict={x: example_batch, y_: label_batch})
trainwriter.add_summary(summary,i)
print(example_batch)
我收到了这样的错误消息
---------------------------------------------------------------------------
InvalidArgumentError Traceback (most recent call last)
C:\Program Files\Anaconda3\envs\tensorflow_env\lib\site-packages\tensorflow\python\client\session.py in _do_call(self, fn, *args)
1020 try:
-> 1021 return fn(*args)
1022 except errors.OpError as e:
C:\Program Files\Anaconda3\envs\tensorflow_env\lib\site-packages\tensorflow\python\client\session.py in _run_fn(session, feed_dict, fetch_list, target_list, options, run_metadata)
1002 feed_dict, fetch_list, target_list,
-> 1003 status, run_metadata)
1004
C:\Program Files\Anaconda3\envs\tensorflow_env\lib\contextlib.py in __exit__(self, type, value, traceback)
65 try:
---> 66 next(self.gen)
67 except StopIteration:
C:\Program Files\Anaconda3\envs\tensorflow_env\lib\site-packages\tensorflow\python\framework\errors_impl.py in raise_exception_on_not_ok_status()
468 compat.as_text(pywrap_tensorflow.TF_Message(status)),
--> 469 pywrap_tensorflow.TF_GetCode(status))
470 finally:
InvalidArgumentError: Nan in summary histogram for: weight_1
[[Node: weight_1 = HistogramSummary[T=DT_FLOAT, _device="/job:localhost/replica:0/task:0/cpu:0"](weight_1/tag, weight/Variable/read)]]
During handling of the above exception, another exception occurred:
InvalidArgumentError Traceback (most recent call last)
<ipython-input-1-d641bed636e8> in <module>()
104 example_batch, label_batch = sess.run([examples, labels])
105 sess.run(train_step, feed_dict={x: example_batch, y_: label_batch})
--> 106 summary = sess.run(merged, feed_dict={x: example_batch, y_: label_batch})
107 writer.add_summary(summary,i)
108 print(example_batch)
C:\Program Files\Anaconda3\envs\tensorflow_env\lib\site-packages\tensorflow\python\client\session.py in run(self, fetches, feed_dict, options, run_metadata)
764 try:
765 result = self._run(None, fetches, feed_dict, options_ptr,
--> 766 run_metadata_ptr)
767 if run_metadata:
768 proto_data = tf_session.TF_GetBuffer(run_metadata_ptr)
C:\Program Files\Anaconda3\envs\tensorflow_env\lib\site-packages\tensorflow\python\client\session.py in _run(self, handle, fetches, feed_dict, options, run_metadata)
962 if final_fetches or final_targets:
963 results = self._do_run(handle, final_targets, final_fetches,
--> 964 feed_dict_string, options, run_metadata)
965 else:
966 results = []
C:\Program Files\Anaconda3\envs\tensorflow_env\lib\site-packages\tensorflow\python\client\session.py in _do_run(self, handle, target_list, fetch_list, feed_dict, options, run_metadata)
1012 if handle is None:
1013 return self._do_call(_run_fn, self._session, feed_dict, fetch_list,
-> 1014 target_list, options, run_metadata)
1015 else:
1016 return self._do_call(_prun_fn, self._session, handle, feed_dict,
C:\Program Files\Anaconda3\envs\tensorflow_env\lib\site-packages\tensorflow\python\client\session.py in _do_call(self, fn, *args)
1032 except KeyError:
1033 pass
-> 1034 raise type(e)(node_def, op, message)
1035
1036 def _extend_graph(self):
InvalidArgumentError: Nan in summary histogram for: weight_1
[[Node: weight_1 = HistogramSummary[T=DT_FLOAT, _device="/job:localhost/replica:0/task:0/cpu:0"](weight_1/tag, weight/Variable/read)]]
Caused by op 'weight_1', defined at:
File "C:\Program Files\Anaconda3\envs\tensorflow_env\lib\runpy.py", line 184, in _run_module_as_main
"__main__", mod_spec)
File "C:\Program Files\Anaconda3\envs\tensorflow_env\lib\runpy.py", line 85, in _run_code
exec(code, run_globals)
File "C:\Program Files\Anaconda3\envs\tensorflow_env\lib\site-packages\ipykernel\__main__.py", line 3, in <module>
app.launch_new_instance()
File "C:\Program Files\Anaconda3\envs\tensorflow_env\lib\site-packages\traitlets\config\application.py", line 658, in launch_instance
app.start()
File "C:\Program Files\Anaconda3\envs\tensorflow_env\lib\site-packages\ipykernel\kernelapp.py", line 474, in start
ioloop.IOLoop.instance().start()
File "C:\Program Files\Anaconda3\envs\tensorflow_env\lib\site-packages\zmq\eventloop\ioloop.py", line 177, in start
super(ZMQIOLoop, self).start()
File "C:\Program Files\Anaconda3\envs\tensorflow_env\lib\site-packages\tornado\ioloop.py", line 887, in start
handler_func(fd_obj, events)
File "C:\Program Files\Anaconda3\envs\tensorflow_env\lib\site-packages\tornado\stack_context.py", line 275, in null_wrapper
return fn(*args, **kwargs)
File "C:\Program Files\Anaconda3\envs\tensorflow_env\lib\site-packages\zmq\eventloop\zmqstream.py", line 440, in _handle_events
self._handle_recv()
File "C:\Program Files\Anaconda3\envs\tensorflow_env\lib\site-packages\zmq\eventloop\zmqstream.py", line 472, in _handle_recv
self._run_callback(callback, msg)
File "C:\Program Files\Anaconda3\envs\tensorflow_env\lib\site-packages\zmq\eventloop\zmqstream.py", line 414, in _run_callback
callback(*args, **kwargs)
File "C:\Program Files\Anaconda3\envs\tensorflow_env\lib\site-packages\tornado\stack_context.py", line 275, in null_wrapper
return fn(*args, **kwargs)
File "C:\Program Files\Anaconda3\envs\tensorflow_env\lib\site-packages\ipykernel\kernelbase.py", line 276, in dispatcher
return self.dispatch_shell(stream, msg)
File "C:\Program Files\Anaconda3\envs\tensorflow_env\lib\site-packages\ipykernel\kernelbase.py", line 228, in dispatch_shell
handler(stream, idents, msg)
File "C:\Program Files\Anaconda3\envs\tensorflow_env\lib\site-packages\ipykernel\kernelbase.py", line 390, in execute_request
user_expressions, allow_stdin)
File "C:\Program Files\Anaconda3\envs\tensorflow_env\lib\site-packages\ipykernel\ipkernel.py", line 196, in do_execute
res = shell.run_cell(code, store_history=store_history, silent=silent)
File "C:\Program Files\Anaconda3\envs\tensorflow_env\lib\site-packages\ipykernel\zmqshell.py", line 501, in run_cell
return super(ZMQInteractiveShell, self).run_cell(*args, **kwargs)
File "C:\Program Files\Anaconda3\envs\tensorflow_env\lib\site-packages\IPython\core\interactiveshell.py", line 2717, in run_cell
interactivity=interactivity, compiler=compiler, result=result)
File "C:\Program Files\Anaconda3\envs\tensorflow_env\lib\site-packages\IPython\core\interactiveshell.py", line 2821, in run_ast_nodes
if self.run_code(code, result):
File "C:\Program Files\Anaconda3\envs\tensorflow_env\lib\site-packages\IPython\core\interactiveshell.py", line 2881, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-1-d641bed636e8>", line 17, in <module>
w_hist = tf.summary.histogram("weight", W)
File "C:\Program Files\Anaconda3\envs\tensorflow_env\lib\site-packages\tensorflow\python\summary\summary.py", line 205, in histogram
tag=scope.rstrip('/'), values=values, name=scope)
File "C:\Program Files\Anaconda3\envs\tensorflow_env\lib\site-packages\tensorflow\python\ops\gen_logging_ops.py", line 139, in _histogram_summary
name=name)
File "C:\Program Files\Anaconda3\envs\tensorflow_env\lib\site-packages\tensorflow\python\framework\op_def_library.py", line 759, in apply_op
op_def=op_def)
File "C:\Program Files\Anaconda3\envs\tensorflow_env\lib\site-packages\tensorflow\python\framework\ops.py", line 2240, in create_op
original_op=self._default_original_op, op_def=op_def)
File "C:\Program Files\Anaconda3\envs\tensorflow_env\lib\site-packages\tensorflow\python\framework\ops.py", line 1128, in __init__
self._traceback = _extract_stack()
InvalidArgumentError (see above for traceback): Nan in summary histogram for: weight_1
[[Node: weight_1 = HistogramSummary[T=DT_FLOAT, _device="/job:localhost/replica:0/task:0/cpu:0"](weight_1/tag, weight/Variable/read)]]
我的代码有什么问题?
答案 0 :(得分:0)
您的代码有一个问题是权重的初始化......您应该给它们随机权重(否则您的网络将无法学习)。摘要说明你的权重中有NaN(不是数字)。尝试运行W.eval()以查看权重矩阵的确切含义!