Related
i am getting this error when i run a simple neural network model using MNIST dataset.
Heres my model
customNN = Sequential()
# input layer
customNN.add(Dense(4, activation = "relu",input_shape = (28,28)))
# Hidden layer
customNN.add(Dense(16,activation = "relu"))
customNN.add(Dense(32,activation = "relu"))
customNN.add(Dense(64,activation = "relu"))
customNN.add(Dense(100,activation = "relu"))
customNN.add(Dense(128,activation = "relu"))
# flatten() function is used to get a copy of an given array collapsed into one dimension.
customNN.add(Flatten())
# output layer
customNN.add(Dense(10,activation = "softmax"))
when i compile it successfully done with MNIST dataset
customNN.compile(optimizer="adam", loss= "categorical_crossentropy", metrics=["accuracy"])
customNN.fit(xtrain,ytrain, epochs=10)
import cv2
def input_prepare(img):
img = np.asarray(img) # convert to array
img = cv2.resize(img, (28, 28 )) # resize to target shape
img = cv2.bitwise_not(img) # [optional] turned bg to black - {bitwise_not} turns 1's into 0's and 0's into 1's
img = img / 255 # normalize
img = img.reshape(1, 784) # reshape it to input placeholder shape
return img
img = cv2.imread('4.jpg')
orig = img.copy() # save for plotting later on
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # gray scaling
img = input_prepare(img)
pred = customNN.predict(img)
plt.imshow(cv2.cvtColor(orig, cv2.COLOR_BGR2RGB))
plt.title(np.argmax(pred, axis=1))
plt.show()
But when i run this code i am getting the following error
---------------------------------------------------------------------------
InvalidArgumentError Traceback (most recent call last)
<ipython-input-29-509e1856bd1e> in <module>
16
17
---> 18 pred = customNN.predict(img)
19 plt.imshow(cv2.cvtColor(orig, cv2.COLOR_BGR2RGB))
20 plt.title(np.argmax(pred, axis=1))
D:\anaconda3\lib\site-packages\keras\utils\traceback_utils.py in error_handler(*args, **kwargs)
68 # To get the full stack trace, call:
69 # `tf.debugging.disable_traceback_filtering()`
---> 70 raise e.with_traceback(filtered_tb) from None
71 finally:
72 del filtered_tb
D:\anaconda3\lib\site-packages\tensorflow\python\eager\execute.py in quick_execute(op_name, num_outputs, inputs, attrs, ctx, name)
51 ctx.ensure_initialized()
52 tensors = pywrap_tfe.TFE_Py_Execute(ctx._handle, device_name, op_name,
---> 53 inputs, attrs, num_outputs)
54 except core._NotOkStatusException as e:
55 if name is not None:
InvalidArgumentError: Graph execution error:
Detected at node 'sequential/dense/Tensordot/GatherV2_1' defined at (most recent call last):
File "D:\anaconda3\lib\runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "D:\anaconda3\lib\runpy.py", line 85, in _run_code
exec(code, run_globals)
File "D:\anaconda3\lib\site-packages\ipykernel_launcher.py", line 16, in <module>
app.launch_new_instance()
File "C:\Users\Deadpool\AppData\Roaming\Python\Python37\site-packages\traitlets\config\application.py", line 1041, in launch_instance
app.start()
File "D:\anaconda3\lib\site-packages\ipykernel\kernelapp.py", line 583, in start
self.io_loop.start()
File "C:\Users\Deadpool\AppData\Roaming\Python\Python37\site-packages\tornado\platform\asyncio.py", line 215, in start
self.asyncio_loop.run_forever()
File "D:\anaconda3\lib\asyncio\base_events.py", line 541, in run_forever
self._run_once()
File "D:\anaconda3\lib\asyncio\base_events.py", line 1786, in _run_once
handle._run()
File "D:\anaconda3\lib\asyncio\events.py", line 88, in _run
self._context.run(self._callback, *self._args)
File "C:\Users\Deadpool\AppData\Roaming\Python\Python37\site-packages\tornado\ioloop.py", line 687, in <lambda>
lambda f: self._run_callback(functools.partial(callback, future))
File "C:\Users\Deadpool\AppData\Roaming\Python\Python37\site-packages\tornado\ioloop.py", line 740, in _run_callback
ret = callback()
File "C:\Users\Deadpool\AppData\Roaming\Python\Python37\site-packages\tornado\gen.py", line 821, in inner
self.ctx_run(self.run)
File "C:\Users\Deadpool\AppData\Roaming\Python\Python37\site-packages\tornado\gen.py", line 782, in run
yielded = self.gen.send(value)
File "D:\anaconda3\lib\site-packages\ipykernel\kernelbase.py", line 361, in process_one
yield gen.maybe_future(dispatch(*args))
File "C:\Users\Deadpool\AppData\Roaming\Python\Python37\site-packages\tornado\gen.py", line 234, in wrapper
yielded = ctx_run(next, result)
File "D:\anaconda3\lib\site-packages\ipykernel\kernelbase.py", line 268, in dispatch_shell
yield gen.maybe_future(handler(stream, idents, msg))
File "C:\Users\Deadpool\AppData\Roaming\Python\Python37\site-packages\tornado\gen.py", line 234, in wrapper
yielded = ctx_run(next, result)
File "D:\anaconda3\lib\site-packages\ipykernel\kernelbase.py", line 541, in execute_request
user_expressions, allow_stdin,
File "C:\Users\Deadpool\AppData\Roaming\Python\Python37\site-packages\tornado\gen.py", line 234, in wrapper
yielded = ctx_run(next, result)
File "D:\anaconda3\lib\site-packages\ipykernel\ipkernel.py", line 300, in do_execute
res = shell.run_cell(code, store_history=store_history, silent=silent)
File "D:\anaconda3\lib\site-packages\ipykernel\zmqshell.py", line 536, in run_cell
return super(ZMQInteractiveShell, self).run_cell(*args, **kwargs)
File "D:\anaconda3\lib\site-packages\IPython\core\interactiveshell.py", line 2976, in run_cell
raw_cell, store_history, silent, shell_futures, cell_id
File "D:\anaconda3\lib\site-packages\IPython\core\interactiveshell.py", line 3030, in _run_cell
return runner(coro)
File "D:\anaconda3\lib\site-packages\IPython\core\async_helpers.py", line 78, in _pseudo_sync_runner
coro.send(None)
File "D:\anaconda3\lib\site-packages\IPython\core\interactiveshell.py", line 3258, in run_cell_async
interactivity=interactivity, compiler=compiler, result=result)
File "D:\anaconda3\lib\site-packages\IPython\core\interactiveshell.py", line 3473, in run_ast_nodes
if (await self.run_code(code, result, async_=asy)):
File "D:\anaconda3\lib\site-packages\IPython\core\interactiveshell.py", line 3553, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-29-509e1856bd1e>", line 18, in <module>
pred = customNN.predict(img)
File "D:\anaconda3\lib\site-packages\keras\utils\traceback_utils.py", line 65, in error_handler
return fn(*args, **kwargs)
File "D:\anaconda3\lib\site-packages\keras\engine\training.py", line 2350, in predict
tmp_batch_outputs = self.predict_function(iterator)
File "D:\anaconda3\lib\site-packages\keras\engine\training.py", line 2137, in predict_function
return step_function(self, iterator)
File "D:\anaconda3\lib\site-packages\keras\engine\training.py", line 2123, in step_function
outputs = model.distribute_strategy.run(run_step, args=(data,))
File "D:\anaconda3\lib\site-packages\keras\engine\training.py", line 2111, in run_step
outputs = model.predict_step(data)
File "D:\anaconda3\lib\site-packages\keras\engine\training.py", line 2079, in predict_step
return self(x, training=False)
File "D:\anaconda3\lib\site-packages\keras\utils\traceback_utils.py", line 65, in error_handler
return fn(*args, **kwargs)
File "D:\anaconda3\lib\site-packages\keras\engine\training.py", line 561, in __call__
return super().__call__(*args, **kwargs)
File "D:\anaconda3\lib\site-packages\keras\utils\traceback_utils.py", line 65, in error_handler
return fn(*args, **kwargs)
File "D:\anaconda3\lib\site-packages\keras\engine\base_layer.py", line 1132, in __call__
outputs = call_fn(inputs, *args, **kwargs)
File "D:\anaconda3\lib\site-packages\keras\utils\traceback_utils.py", line 96, in error_handler
return fn(*args, **kwargs)
File "D:\anaconda3\lib\site-packages\keras\engine\sequential.py", line 413, in call
return super().call(inputs, training=training, mask=mask)
File "D:\anaconda3\lib\site-packages\keras\engine\functional.py", line 511, in call
return self._run_internal_graph(inputs, training=training, mask=mask)
File "D:\anaconda3\lib\site-packages\keras\engine\functional.py", line 668, in _run_internal_graph
outputs = node.layer(*args, **kwargs)
File "D:\anaconda3\lib\site-packages\keras\utils\traceback_utils.py", line 65, in error_handler
return fn(*args, **kwargs)
File "D:\anaconda3\lib\site-packages\keras\engine\base_layer.py", line 1132, in __call__
outputs = call_fn(inputs, *args, **kwargs)
File "D:\anaconda3\lib\site-packages\keras\utils\traceback_utils.py", line 96, in error_handler
return fn(*args, **kwargs)
File "D:\anaconda3\lib\site-packages\keras\layers\core\dense.py", line 244, in call
outputs = tf.tensordot(inputs, self.kernel, [[rank - 1], [0]])
Node: 'sequential/dense/Tensordot/GatherV2_1'
indices[0] = 2 is not in [0, 2)
[[{{node sequential/dense/Tensordot/GatherV2_1}}]] [Op:__inference_predict_function_82024]
Cannot figure out whats the problem? i am newbie in DL and trying to improve. any help to find out the problem is highly appreciated
thanks
i have tried a new image to detect the handwriting, but shows error
I get following error, when I am trying to trigger DAG which is using custom BaseOperator.
here is the error,
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x80 in position 0: invalid start byte
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 2446, in wsgi_app
response = self.full_dispatch_request()
File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 1951, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 1820, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/usr/local/lib/python3.7/site-packages/flask/_compat.py", line 39, in reraise
raise value
File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 1949, in full_dispatch_request
rv = self.dispatch_request()
File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 1935, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/usr/local/lib/python3.7/site-packages/flask_admin/base.py", line 69, in inner
return self._run_view(f, *args, **kwargs)
File "/usr/local/lib/python3.7/site-packages/flask_admin/base.py", line 368, in _run_view
return fn(self, *args, **kwargs)
File "/usr/local/lib/python3.7/site-packages/flask_login/utils.py", line 258, in decorated_view
return func(*args, **kwargs)
File "/usr/local/lib/python3.7/site-packages/airflow/www/utils.py", line 290, in wrapper
return f(*args, **kwargs)
File "/usr/local/lib/python3.7/site-packages/airflow/www/utils.py", line 337, in wrapper
return f(*args, **kwargs)
File "/usr/local/lib/python3.7/site-packages/airflow/utils/db.py", line 74, in wrapper
return func(*args, **kwargs)
File "/usr/local/lib/python3.7/site-packages/airflow/www/views.py", line 1213, in trigger
external_trigger=True
File "/usr/local/lib/python3.7/site-packages/airflow/utils/db.py", line 74, in wrapper
return func(*args, **kwargs)
File "/usr/local/lib/python3.7/site-packages/airflow/models/dag.py", line 1659, in create_dagrun
session=session)
File "/usr/local/lib/python3.7/site-packages/airflow/utils/db.py", line 70, in wrapper
return func(*args, **kwargs)
File "/usr/local/lib/python3.7/site-packages/airflow/models/dag.py", line 1346, in create_dagrun
run.refresh_from_db()
File "/usr/local/lib/python3.7/site-packages/airflow/utils/db.py", line 74, in wrapper
return func(*args, **kwargs)
File "/usr/local/lib/python3.7/site-packages/airflow/models/dagrun.py", line 109, in refresh_from_db
DR.run_id == self.run_id
File "/usr/local/lib/python3.7/site-packages/sqlalchemy/orm/query.py", line 3347, in one
ret = self.one_or_none()
File "/usr/local/lib/python3.7/site-packages/sqlalchemy/orm/query.py", line 3316, in one_or_none
ret = list(self)
File "/usr/local/lib/python3.7/site-packages/sqlalchemy/orm/query.py", line 3389, in __iter__
return self._execute_and_instances(context)
File "/usr/local/lib/python3.7/site-packages/sqlalchemy/orm/query.py", line 3414, in _execute_and_instances
result = conn.execute(querycontext.statement, self._params)
File "/usr/local/lib/python3.7/site-packages/sqlalchemy/engine/base.py", line 982, in execute
return meth(self, multiparams, params)
File "/usr/local/lib/python3.7/site-packages/sqlalchemy/sql/elements.py", line 293, in _execute_on_connection
return connection._execute_clauseelement(self, multiparams, params)
File "/usr/local/lib/python3.7/site-packages/sqlalchemy/engine/base.py", line 1101, in _execute_clauseelement
distilled_params,
File "/usr/local/lib/python3.7/site-packages/sqlalchemy/engine/base.py", line 1250, in _execute_context
e, statement, parameters, cursor, context
File "/usr/local/lib/python3.7/site-packages/sqlalchemy/engine/base.py", line 1478, in _handle_dbapi_exception
util.reraise(*exc_info)
File "/usr/local/lib/python3.7/site-packages/sqlalchemy/util/compat.py", line 153, in reraise
raise value
File "/usr/local/lib/python3.7/site-packages/sqlalchemy/engine/base.py", line 1246, in _execute_context
cursor, statement, parameters, context
File "/usr/local/lib/python3.7/site-packages/sqlalchemy/engine/default.py", line 588, in do_execute
cursor.execute(statement, parameters)
File "/usr/local/lib/python3.7/site-packages/mysql/connector/cursor_cext.py", line 272, in execute
self._handle_result(result)
File "/usr/local/lib/python3.7/site-packages/mysql/connector/cursor_cext.py", line 163, in _handle_result
self._handle_resultset()
File "/usr/local/lib/python3.7/site-packages/mysql/connector/cursor_cext.py", line 651, in _handle_resultset
self._rows = self._cnx.get_rows()[0]
File "/usr/local/lib/python3.7/site-packages/mysql/connector/connection_cext.py", line 318, in get_rows
else self._cmysql.fetch_row()
SystemError: <method 'fetch_row' of '_mysql_connector.MySQL' objects> returned a result with an error set
My Code is as follows:
from airflow.plugins_manager import AirflowPlugin
from airflow.utils.decorators import apply_defaults
class TestOperator(BaseOperator):
template_fields = ('param1')
ui_color = '#A7E6A7'
#apply_defaults
def __init__(self,param1,*args, **kwargs):
self.param1 = param1
super(TestOperator, self).__init__(*args, **kwargs)
def execute(self):
print ('welcome to airflow')
class TestOperatorPlugin(AirflowPlugin):
name = "TestOperator_plugin"
operators = [TestOperator]
--here is Dag,
from TestOperator import TestOperator
from airflow import DAG
from datetime import datetime
prog_args = {
'depends_on_past': False, 'param1' : 'testOne'
}
testMYDAG = DAG('TestMYDAG', start_date = datetime(2020, 2, 18) , description='TestMYDAG', default_args = prog_args, schedule_interval=None)
testOp = TestOperator(task_id='test_dag', dag=testMYDAG )
testOp
Team, I had resolved issue by adding encoding scheme to utf-8 in airflow.cfg file, Also, it needs to be appended to sql_alchemy_connection string.
I have Tried my CSV data to tfrecords format and read tfrecords file.
but I can't read tfrecord file.
first I had converted CSV file to tfrecords file.
My CSV Data is this
1,2,3,4,5,1
2,3,4,5,6,2
3,4,5,6,7,3
4,5,6,7,8,4
Column 1~5 is features and column 6 is label
I converted this CSV file using this code
import pandas as pd
import tensorflow as tf
import argparse
import os
import sys
FLAGS = None
name = 'test'
filename = name + '.tfrecords'
print('Writing', filename)
writer = tf.python_io.TFRecordWriter(filename)
for row in csv:
features, label = row[:-1], row[-1]
print(features)
print(label)
example = tf.train.Example()
example.features.feature['features'].int64_list.value.extend(features)
example.features.feature['label'].int64_list.value.append(label)
writer.write(example.SerializeToString())
writer.close()
and then I Got a tfrecords file. (test.tfrecords)
My problem is that I can't read this tfrecords file.
I had tried this code and I got a Error message.
def read_and_decode(filename_queue):
reader = tf.TFRecordReader()
_, serialized_example = reader.read(filename_queue)
features = tf.parse_single_example(
serialized_example,
# Defaults are not specified since both keys are required.
features={
'features': tf.FixedLenFeature([], tf.string),
'label': tf.FixedLenFeature([], tf.int64)
})
image = tf.decode_raw(features['features'], tf.int64)
label = tf.cast(features['label'], tf.int32)
return image, label
def get_all_records(FILE):
with tf.Session() as sess:
filename_queue = tf.train.string_input_producer([ FILE ])
image, label = read_and_decode(filename_queue)
init_op = tf.global_variables_initializer()
sess.run(init_op)
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(coord=coord)
for i in range(100):
example, l = sess.run([image, label])
print (example,l)
coord.request_stop()
coord.join(threads)
get_all_records('test.tfrecords')
this is Error message
INFO:tensorflow:Error reported to Coordinator: <class 'tensorflow.python.framework.errors_impl.CancelledError'>, Run call was cancelled
---------------------------------------------------------------------------
InvalidArgumentError Traceback (most recent call last)
C:\Program Files\Anaconda3\envs\tf\lib\site-packages\tensorflow\python\client\session.py in _do_call(self, fn, *args)
1021 try:
-> 1022 return fn(*args)
1023 except errors.OpError as e:
C:\Program Files\Anaconda3\envs\tf\lib\site-packages\tensorflow\python\client\session.py in _run_fn(session, feed_dict, fetch_list, target_list, options, run_metadata)
1003 feed_dict, fetch_list, target_list,
-> 1004 status, run_metadata)
1005
C:\Program Files\Anaconda3\envs\tf\lib\contextlib.py in __exit__(self, type, value, traceback)
65 try:
---> 66 next(self.gen)
67 except StopIteration:
C:\Program Files\Anaconda3\envs\tf\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: Name: <unknown>, Key: features, Index: 0. Data types don't match. Data type: int64Expected type: string
[[Node: ParseSingleExample/ParseExample/ParseExample = ParseExample[Ndense=2, Nsparse=0, Tdense=[DT_STRING, DT_INT64], dense_shapes=[[], []], sparse_types=[], _device="/job:localhost/replica:0/task:0/cpu:0"](ParseSingleExample/ExpandDims, ParseSingleExample/ParseExample/ParseExample/names, ParseSingleExample/ParseExample/ParseExample/dense_keys_0, ParseSingleExample/ParseExample/ParseExample/dense_keys_1, ParseSingleExample/ParseExample/Const, ParseSingleExample/ParseExample/Const_1)]]
[[Node: ParseSingleExample/ParseExample/ParseExample/_3 = _Recv[client_terminated=false, recv_device="/job:localhost/replica:0/task:0/gpu:0", send_device="/job:localhost/replica:0/task:0/cpu:0", send_device_incarnation=1, tensor_name="edge_13_ParseSingleExample/ParseExample/ParseExample", tensor_type=DT_INT64, _device="/job:localhost/replica:0/task:0/gpu:0"]()]]
During handling of the above exception, another exception occurred:
InvalidArgumentError Traceback (most recent call last)
<ipython-input-6-0bf78295d664> in <module>()
----> 1 get_all_records('test.tfrecords')
<ipython-input-5-afbcd262993d> in get_all_records(FILE)
8 threads = tf.train.start_queue_runners(coord=coord)
9 for i in range(100):
---> 10 example, l = sess.run([image, label])
11 print (example,l)
12 coord.request_stop()
C:\Program Files\Anaconda3\envs\tf\lib\site-packages\tensorflow\python\client\session.py in run(self, fetches, feed_dict, options, run_metadata)
765 try:
766 result = self._run(None, fetches, feed_dict, options_ptr,
--> 767 run_metadata_ptr)
768 if run_metadata:
769 proto_data = tf_session.TF_GetBuffer(run_metadata_ptr)
C:\Program Files\Anaconda3\envs\tf\lib\site-packages\tensorflow\python\client\session.py in _run(self, handle, fetches, feed_dict, options, run_metadata)
963 if final_fetches or final_targets:
964 results = self._do_run(handle, final_targets, final_fetches,
--> 965 feed_dict_string, options, run_metadata)
966 else:
967 results = []
C:\Program Files\Anaconda3\envs\tf\lib\site-packages\tensorflow\python\client\session.py in _do_run(self, handle, target_list, fetch_list, feed_dict, options, run_metadata)
1013 if handle is None:
1014 return self._do_call(_run_fn, self._session, feed_dict, fetch_list,
-> 1015 target_list, options, run_metadata)
1016 else:
1017 return self._do_call(_prun_fn, self._session, handle, feed_dict,
C:\Program Files\Anaconda3\envs\tf\lib\site-packages\tensorflow\python\client\session.py in _do_call(self, fn, *args)
1033 except KeyError:
1034 pass
-> 1035 raise type(e)(node_def, op, message)
1036
1037 def _extend_graph(self):
InvalidArgumentError: Name: <unknown>, Key: features, Index: 0. Data types don't match. Data type: int64Expected type: string
[[Node: ParseSingleExample/ParseExample/ParseExample = ParseExample[Ndense=2, Nsparse=0, Tdense=[DT_STRING, DT_INT64], dense_shapes=[[], []], sparse_types=[], _device="/job:localhost/replica:0/task:0/cpu:0"](ParseSingleExample/ExpandDims, ParseSingleExample/ParseExample/ParseExample/names, ParseSingleExample/ParseExample/ParseExample/dense_keys_0, ParseSingleExample/ParseExample/ParseExample/dense_keys_1, ParseSingleExample/ParseExample/Const, ParseSingleExample/ParseExample/Const_1)]]
[[Node: ParseSingleExample/ParseExample/ParseExample/_3 = _Recv[client_terminated=false, recv_device="/job:localhost/replica:0/task:0/gpu:0", send_device="/job:localhost/replica:0/task:0/cpu:0", send_device_incarnation=1, tensor_name="edge_13_ParseSingleExample/ParseExample/ParseExample", tensor_type=DT_INT64, _device="/job:localhost/replica:0/task:0/gpu:0"]()]]
Caused by op 'ParseSingleExample/ParseExample/ParseExample', defined at:
File "C:\Program Files\Anaconda3\envs\tf\lib\runpy.py", line 184, in _run_module_as_main
"__main__", mod_spec)
File "C:\Program Files\Anaconda3\envs\tf\lib\runpy.py", line 85, in _run_code
exec(code, run_globals)
File "C:\Program Files\Anaconda3\envs\tf\lib\site-packages\ipykernel\__main__.py", line 3, in <module>
app.launch_new_instance()
File "C:\Program Files\Anaconda3\envs\tf\lib\site-packages\traitlets\config\application.py", line 658, in launch_instance
app.start()
File "C:\Program Files\Anaconda3\envs\tf\lib\site-packages\ipykernel\kernelapp.py", line 474, in start
ioloop.IOLoop.instance().start()
File "C:\Program Files\Anaconda3\envs\tf\lib\site-packages\zmq\eventloop\ioloop.py", line 177, in start
super(ZMQIOLoop, self).start()
File "C:\Program Files\Anaconda3\envs\tf\lib\site-packages\tornado\ioloop.py", line 887, in start
handler_func(fd_obj, events)
File "C:\Program Files\Anaconda3\envs\tf\lib\site-packages\tornado\stack_context.py", line 275, in null_wrapper
return fn(*args, **kwargs)
File "C:\Program Files\Anaconda3\envs\tf\lib\site-packages\zmq\eventloop\zmqstream.py", line 440, in _handle_events
self._handle_recv()
File "C:\Program Files\Anaconda3\envs\tf\lib\site-packages\zmq\eventloop\zmqstream.py", line 472, in _handle_recv
self._run_callback(callback, msg)
File "C:\Program Files\Anaconda3\envs\tf\lib\site-packages\zmq\eventloop\zmqstream.py", line 414, in _run_callback
callback(*args, **kwargs)
File "C:\Program Files\Anaconda3\envs\tf\lib\site-packages\tornado\stack_context.py", line 275, in null_wrapper
return fn(*args, **kwargs)
File "C:\Program Files\Anaconda3\envs\tf\lib\site-packages\ipykernel\kernelbase.py", line 276, in dispatcher
return self.dispatch_shell(stream, msg)
File "C:\Program Files\Anaconda3\envs\tf\lib\site-packages\ipykernel\kernelbase.py", line 228, in dispatch_shell
handler(stream, idents, msg)
File "C:\Program Files\Anaconda3\envs\tf\lib\site-packages\ipykernel\kernelbase.py", line 390, in execute_request
user_expressions, allow_stdin)
File "C:\Program Files\Anaconda3\envs\tf\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\tf\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\tf\lib\site-packages\IPython\core\interactiveshell.py", line 2717, in run_cell
interactivity=interactivity, compiler=compiler, result=result)
File "C:\Program Files\Anaconda3\envs\tf\lib\site-packages\IPython\core\interactiveshell.py", line 2827, in run_ast_nodes
if self.run_code(code, result):
File "C:\Program Files\Anaconda3\envs\tf\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-6-0bf78295d664>", line 1, in <module>
get_all_records('test.tfrecords')
File "<ipython-input-5-afbcd262993d>", line 4, in get_all_records
image, label = read_and_decode(filename_queue)
File "<ipython-input-4-a06d5222e475>", line 9, in read_and_decode
'label': tf.FixedLenFeature([], tf.int64)
File "C:\Program Files\Anaconda3\envs\tf\lib\site-packages\tensorflow\python\ops\parsing_ops.py", line 595, in parse_single_example
dense_types, dense_defaults, dense_shapes, name)
File "C:\Program Files\Anaconda3\envs\tf\lib\site-packages\tensorflow\python\ops\parsing_ops.py", line 669, in _parse_single_example_raw
name=name)
File "C:\Program Files\Anaconda3\envs\tf\lib\site-packages\tensorflow\python\ops\parsing_ops.py", line 544, in _parse_example_raw
name=name)
File "C:\Program Files\Anaconda3\envs\tf\lib\site-packages\tensorflow\python\ops\gen_parsing_ops.py", line 167, in _parse_example
dense_shapes=dense_shapes, name=name)
File "C:\Program Files\Anaconda3\envs\tf\lib\site-packages\tensorflow\python\framework\op_def_library.py", line 763, in apply_op
op_def=op_def)
File "C:\Program Files\Anaconda3\envs\tf\lib\site-packages\tensorflow\python\framework\ops.py", line 2395, in create_op
original_op=self._default_original_op, op_def=op_def)
File "C:\Program Files\Anaconda3\envs\tf\lib\site-packages\tensorflow\python\framework\ops.py", line 1264, in __init__
self._traceback = _extract_stack()
InvalidArgumentError (see above for traceback): Name: <unknown>, Key: features, Index: 0. Data types don't match. Data type: int64Expected type: string
[[Node: ParseSingleExample/ParseExample/ParseExample = ParseExample[Ndense=2, Nsparse=0, Tdense=[DT_STRING, DT_INT64], dense_shapes=[[], []], sparse_types=[], _device="/job:localhost/replica:0/task:0/cpu:0"](ParseSingleExample/ExpandDims, ParseSingleExample/ParseExample/ParseExample/names, ParseSingleExample/ParseExample/ParseExample/dense_keys_0, ParseSingleExample/ParseExample/ParseExample/dense_keys_1, ParseSingleExample/ParseExample/Const, ParseSingleExample/ParseExample/Const_1)]]
[[Node: ParseSingleExample/ParseExample/ParseExample/_3 = _Recv[client_terminated=false, recv_device="/job:localhost/replica:0/task:0/gpu:0", send_device="/job:localhost/replica:0/task:0/cpu:0", send_device_incarnation=1, tensor_name="edge_13_ParseSingleExample/ParseExample/ParseExample", tensor_type=DT_INT64, _device="/job:localhost/replica:0/task:0/gpu:0"]()]]
What's wrong is this?
The error occurs because in the program where you wrote the data, you created the "features" feature with type int64:
example.features.feature['features'].int64_list.value.extend(features)
...whereas in the program where you try to read the data, you specify that the "features" feature has type tf.string:
features = tf.parse_single_example(
...
features={
'features': tf.FixedLenFeature([], tf.string),
...
})
The solution most likely to work is to change the call to tf.parse_single_example() in your reading program to match the true type of the data:
features = tf.parse_single_example(
serialized_example,
features={
'features': tf.FixedLenFeature([], tf.int64),
'label': tf.FixedLenFeature([], tf.int64)
})
Here is the error log i get this error when i try to create a new user when i do:
u = User (...)
Error log:
Traceback (most recent call last)
File "/usr/lib/python3.6/site-packages/flask/app.py", line 1994, in __call__
return self.wsgi_app(environ, start_response)
File "/usr/lib/python3.6/site-packages/flask/app.py", line 1985, in wsgi_app
response = self.handle_exception(e)
File "/usr/lib/python3.6/site-packages/flask/app.py", line 1540, in handle_exception
reraise(exc_type, exc_value, tb)
File "/usr/lib/python3.6/site-packages/flask/_compat.py", line 33, in reraise
raise value
File "/usr/lib/python3.6/site-packages/flask/app.py", line 1982, in wsgi_app
response = self.full_dispatch_request()
File "/usr/lib/python3.6/site-packages/flask/app.py", line 1614, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/usr/lib/python3.6/site-packages/flask/app.py", line 1517, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/usr/lib/python3.6/site-packages/flask/_compat.py", line 33, in reraise
raise value
File "/usr/lib/python3.6/site-packages/flask/app.py", line 1612, in full_dispatch_request
rv = self.dispatch_request()
File "/usr/lib/python3.6/site-packages/flask/app.py", line 1598, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/home/quechon/PycharmProjects/untitled3/myapp/login/routes.py", line 66, in _register_process
timecreated=datetime.datetime.utcnow()
File "<string>", line 4, in __init__
File "/usr/lib/python3.6/site-packages/sqlalchemy/orm/state.py", line 414, in _initialize_instance
manager.dispatch.init_failure(self, args, kwargs)
File "/usr/lib/python3.6/site-packages/sqlalchemy/util/langhelpers.py", line 60, in __exit__
compat.reraise(exc_type, exc_value, exc_tb)
File "/usr/lib/python3.6/site-packages/sqlalchemy/util/compat.py", line 186, in reraise
raise value
File "/usr/lib/python3.6/site-packages/sqlalchemy/orm/state.py", line 411, in _initialize_instance
return manager.original_init(*mixed[1:], **kwargs)
File "/home/quechon/PycharmProjects/untitled3/myapp/models.py", line 80, in __init__
self.follow(self)
File "/home/quechon/PycharmProjects/untitled3/myapp/models.py", line 47, in follow
if not self.is_following(user):
File "/home/quechon/PycharmProjects/untitled3/myapp/models.py", line 57, in is_following
return self.followed.filter_by(followed_id=user.id).first() is not None
File "/usr/lib/python3.6/site-packages/sqlalchemy/orm/query.py", line 1517, in filter_by
return self.filter(sql.and_(*clauses))
File "<string>", line 2, in filter
File "/usr/lib/python3.6/site-packages/sqlalchemy/orm/base.py", line 198, in generate
self = args[0]._clone()
File "/usr/lib/python3.6/site-packages/sqlalchemy/orm/dynamic.py", line 278, in _clone
orm_util.instance_str(instance), self.attr.key))
sqlalchemy.orm.exc.DetachedInstanceError: Parent instance <User at 0x7fe2ac0e6e80> is not bound to a Session, and no contextual session is established; lazy load operation of attribute 'followed' cannot proceed
This is the model:
class User(db.Model):
__tablename__ = 'user'
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(100), unique=True)
email = db.Column(db.String(100))
password = db.Column(db.Binary)
profilepic = db.Column(db.String)
timecreated = db.Column(db.DateTime)
#picture = db.relationship('Picture', backref='owner', lazy='dynamic')
comment = db.relationship('Comment', backref='user', lazy='dynamic')
post = db.relationship('Post', backref='user', lazy='dynamic')
followed = db.relationship('Follow', foreign_keys=[Follow.follower_id],
backref=db.backref('follower', lazy='joined'),
lazy='dynamic',
cascade='all, delete-orphan')
followers = db.relationship('Follow',
foreign_keys=[Follow.followed_id],
backref=db.backref('followed', lazy='joined'),
lazy='dynamic',
cascade='all, delete-orphan')
def follow(self, user):
if not self.is_following(user):
f = Follow(follower=self, followed=user)
db.session.add(f)
def unfollow(self, user):
f = self.followed.filter_by(followed_id=user.id).first()
if f:
db.session.delete(f)
def is_following(self, user):
return self.followed.filter_by(followed_id=user.id).first() is not None
def is_followed_by(self, user):
return self.followers.filter_by(follower_id=user.id).first() is not None
#property
def followed_posts(self):
return Post.query.join(Follow.followed_id == Post.user_id)\
.filter(Follow.follower_id == self.id)
def is_authenticated(self):
return True
def is_active(self):
return True
def is_anonymous(self):
return False
def get_id(self):
return str(self.id)
def __init__(self, **kwargs):
self.follow(self)
def __repr__(self):
return f'<id - {self.id} | - {self.username}>'
I would like to know why that happened and how to avoid this error next time
The only thing i found online about was to use lazy='subquery' instead of lazy='dynamic' but using that wont allow my query to use filter_by attribute.
It looks like you are trying to interact with your flask app via the interactive shell. You can do this using the command line interface (CLI).
See docs:
http://flask.pocoo.org/docs/0.12/shell/
sometimes execute query and got this error:
ct = db.session.query(CIType).filter(
CIType.type_name == key).first() or \
db.session.query(CIType).filter(CIType.type_id == key).first()
full error info
2016-08-11 14:27:26,177 ERROR /usr/lib/python2.6/site-packages/flask/app.py 1306 - Exception on /api/v0.1/projects/search-indexer-rafael/product [GET]
Traceback (most recent call last):
File "/usr/lib/python2.6/site-packages/flask/app.py", line 1687, in wsgi_app
response = self.full_dispatch_request()
File "/usr/lib/python2.6/site-packages/flask/app.py", line 1360, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/usr/lib/python2.6/site-packages/flask/app.py", line 1358, in full_dispatch_request
rv = self.dispatch_request()
File "/usr/lib/python2.6/site-packages/flask/app.py", line 1344, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/data/webapps/cmdb-api/core/special.py", line 175, in get_project_product
product = ProjectManager().get_for_product(project_name)
File "/data/webapps/cmdb-api/lib/special/project.py", line 18, in __init__
self.ci_type = CITypeCache.get("project")
File "/data/webapps/cmdb-api/models/cmdb.py", line 458, in get
ct = db.session.query(CIType).filter(
File "/usr/lib64/python2.6/site-packages/sqlalchemy/orm/scoping.py", line 149, in do
def do(self, *args, **kwargs):
File "/usr/lib64/python2.6/site-packages/sqlalchemy/util/_collections.py", line 903, in __call__
item = dict.get(self, key)
File "/usr/lib/python2.6/site-packages/flask_sqlalchemy.py", line 201, in __init__
bind=db.engine,
File "/usr/lib/python2.6/site-packages/flask_sqlalchemy.py", line 754, in engine
return self.get_engine(self.get_app())
File "/usr/lib/python2.6/site-packages/flask_sqlalchemy.py", line 771, in get_engine
return connector.get_engine()
File "/usr/lib/python2.6/site-packages/flask_sqlalchemy.py", line 451, in get_engine
self._engine = rv = sqlalchemy.create_engine(info, **options)
File "/usr/lib64/python2.6/site-packages/sqlalchemy/engine/__init__.py", line 344, in create_engine
of 0 indicates no limit; to disable pooling, set ``poolclass`` to
File "/usr/lib64/python2.6/site-packages/sqlalchemy/engine/strategies.py", line 50, in create
File "/usr/lib64/python2.6/site-packages/sqlalchemy/engine/url.py", line 116, in get_dialect
return self.get_dialect().driver
File "/usr/lib64/python2.6/site-packages/sqlalchemy/util/langhelpers.py", line 170, in load
fn.__func__.__doc__ = doc
File "/usr/lib64/python2.6/site-packages/sqlalchemy/dialects/__init__.py", line 33, in _auto_fn
try:
File "/usr/lib64/python2.6/site-packages/sqlalchemy/dialects/mysql/__init__.py", line 8, in <module>
from . import base, mysqldb, oursql, \
File "/usr/lib64/python2.6/site-packages/sqlalchemy/dialects/mysql/base.py", line 681, in <module>
class _MatchType(sqltypes.Float, sqltypes.MatchType):
AttributeError: 'module' object has no attribute 'MatchType'
code
#special.route("/api/v0.1/projects/<string:project_name>/product",
methods=["GET"])
def get_project_product(project_name):
product = ProjectManager().get_for_product(project_name)
return jsonify(product=product)
...
goto
class ProjectManager(object):
def __init__(self):
self.ci_type = CITypeCache.get("project")
...
then
class CITypeCache(object):
#classmethod
def get(cls, key):
if key is None:
return
ct = cache.get("CIType::ID::%s" % key) or \
cache.get("CIType::Name::%s" % key)
if ct is None:
ct = db.session.query(CIType).filter(
CIType.type_name == key).first() or \
db.session.query(CIType).filter(CIType.type_id == key).first()
if ct is not None:
CITypeCache.set(ct)
return ct
The sqlalchemy's version is SQLAlchemy-1.0.8-py2.6.egg-info
and after many same error, I can't catch this error any more. What's the reason of this error?
I assume CIType.type_name and CIType.type_id have different data types (perhaps string and numeric types). It may lead to situation when:
db.session.query(CIType).filter(CIType.type_name == key).first()
is valid expression but:
db.session.query(CIType).filter(CIType.type_id == key).first()
produces error because of type mismatch. You need to convert key to the type_id column type in this expression.
The second expression is calculated when first expression returns no results. As written in Python documentation:
The expression x or y first evaluates x; if x is true, its value is returned; otherwise, y is evaluated and the resulting value is returned.
For example:
>>> a = 1 or 2 + '2'
>>> print a
1
>>> a = 0 or 2 + '2'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'