我正在尝试使用Keras创建一个简单的图像分类神经网络,但无法弄清楚为什么在model.fit中出现错误!
我的图像形状是(300,300,3),为了简单起见,我将其转换为(27000,)(我是机器学习的初学者,如果我在某个地方出错了,请纠正我;)
from keras.models import Sequential
from keras.layers import Dense, Activation, Flatten
import numpy as np
import matplotlib.pyplot as plt
import random
model = Sequential()
model.add(Dense(512, input_shape=(270000,), activation='relu')) #For image with shape (300,300,3)
model.add(Dense(256, activation='relu'))
model.add(Dense(1, activation='relu'))
dataset = []
i = 1
while i <= 3:
n = 1000
while n:
temp_img = plt.imread('finger_dataset/' + str(i) + '/' + str(n) + '.png')
dataset.append([temp_img, i])
n -= 1
i += 1
random.shuffle(dataset)
i = 0
X_train = []
y_train = []
while i < len(dataset):
X_train.append(dataset[i][0])
y_train.append(dataset[i][1])
i+=1
X_train = np.array(X_train)
y_train = np.array(y_train)
X_train = X_train.reshape((len(X_train), -1))
y_train = y_train.reshape((-1,1))
model.compile(optimizer='sgd', loss='mse', metrics=['accuracy'])
model.fit(X_train, y_train, epochs=100, batch_size=512, shuffle=True)
运行 model.fit(....)后出现的错误是
---------------------------------------------------------------------------
InvalidArgumentError Traceback (most recent call last)
c:\users\aakash\appdata\local\programs\python\python36\lib\site-packages\tensorflow_core\python\client\session.py in _do_call(self, fn, *args)
1364 try:
-> 1365 return fn(*args)
1366 except errors.OpError as e:
c:\users\aakash\appdata\local\programs\python\python36\lib\site-packages\tensorflow_core\python\client\session.py in _run_fn(feed_dict, fetch_list, target_list, options, run_metadata)
1349 return self._call_tf_sessionrun(options, feed_dict, fetch_list,
-> 1350 target_list, run_metadata)
1351
c:\users\aakash\appdata\local\programs\python\python36\lib\site-packages\tensorflow_core\python\client\session.py in _call_tf_sessionrun(self, options, feed_dict, fetch_list, target_list, run_metadata)
1442 fetch_list, target_list,
-> 1443 run_metadata)
1444
InvalidArgumentError: Cannot parse tensor from proto: dtype: DT_FLOAT
tensor_shape {
dim {
size: 270000
}
dim {
size: 512
}
}
float_val: 0
[[{{node training/SGD/moment_0}}]]
During handling of the above exception, another exception occurred:
InvalidArgumentError Traceback (most recent call last)
<ipython-input-10-fef3f263c0f5> in <module>
----> 1 model.fit(X_train, y_train, epochs=100, batch_size=512, shuffle=True)
c:\users\aakash\appdata\local\programs\python\python36\lib\site-packages\keras\engine\training.py in fit(self, x, y, batch_size, epochs, verbose, callbacks, validation_split, validation_data, shuffle, class_weight, sample_weight, initial_epoch, steps_per_epoch, validation_steps, validation_freq, max_queue_size, workers, use_multiprocessing, **kwargs)
1211 else:
1212 fit_inputs = x + y + sample_weights
-> 1213 self._make_train_function()
1214 fit_function = self.train_function
1215
c:\users\aakash\appdata\local\programs\python\python36\lib\site-packages\keras\engine\training.py in _make_train_function(self)
331 updates=updates + metrics_updates,
332 name='train_function',
--> 333 **self._function_kwargs)
334
335 def _make_test_function(self):
c:\users\aakash\appdata\local\programs\python\python36\lib\site-packages\keras\backend\tensorflow_backend.py in function(inputs, outputs, updates, **kwargs)
3004 def function(inputs, outputs, updates=None, **kwargs):
3005 if _is_tf_1():
-> 3006 v1_variable_initialization()
3007 return tf_keras_backend.function(inputs, outputs,
3008 updates=updates,
c:\users\aakash\appdata\local\programs\python\python36\lib\site-packages\keras\backend\tensorflow_backend.py in v1_variable_initialization()
418
419 def v1_variable_initialization():
--> 420 session = get_session()
421 with session.graph.as_default():
422 variables = tf.global_variables()
c:\users\aakash\appdata\local\programs\python\python36\lib\site-packages\keras\backend\tensorflow_backend.py in get_session()
383 '`get_session` is not available when '
384 'TensorFlow is executing eagerly.')
--> 385 return tf_keras_backend.get_session()
386
387
c:\users\aakash\appdata\local\programs\python\python36\lib\site-packages\tensorflow_core\python\keras\backend.py in get_session(op_input_list)
484 if not _MANUAL_VAR_INIT:
485 with session.graph.as_default():
--> 486 _initialize_variables(session)
487 return session
488
c:\users\aakash\appdata\local\programs\python\python36\lib\site-packages\tensorflow_core\python\keras\backend.py in _initialize_variables(session)
908 v._keras_initialized = True
909 if uninitialized_vars:
--> 910 session.run(variables_module.variables_initializer(uninitialized_vars))
911
912
c:\users\aakash\appdata\local\programs\python\python36\lib\site-packages\tensorflow_core\python\client\session.py in run(self, fetches, feed_dict, options, run_metadata)
954 try:
955 result = self._run(None, fetches, feed_dict, options_ptr,
--> 956 run_metadata_ptr)
957 if run_metadata:
958 proto_data = tf_session.TF_GetBuffer(run_metadata_ptr)
c:\users\aakash\appdata\local\programs\python\python36\lib\site-packages\tensorflow_core\python\client\session.py in _run(self, handle, fetches, feed_dict, options, run_metadata)
1178 if final_fetches or final_targets or (handle and feed_dict_tensor):
1179 results = self._do_run(handle, final_targets, final_fetches,
-> 1180 feed_dict_tensor, options, run_metadata)
1181 else:
1182 results = []
c:\users\aakash\appdata\local\programs\python\python36\lib\site-packages\tensorflow_core\python\client\session.py in _do_run(self, handle, target_list, fetch_list, feed_dict, options, run_metadata)
1357 if handle is None:
1358 return self._do_call(_run_fn, feeds, fetches, targets, options,
-> 1359 run_metadata)
1360 else:
1361 return self._do_call(_prun_fn, handle, feeds, fetches)
c:\users\aakash\appdata\local\programs\python\python36\lib\site-packages\tensorflow_core\python\client\session.py in _do_call(self, fn, *args)
1382 '\nsession_config.graph_options.rewrite_options.'
1383 'disable_meta_optimizer = True')
-> 1384 raise type(e)(node_def, op, message)
1385
1386 def _extend_graph(self):
InvalidArgumentError: Cannot parse tensor from proto: dtype: DT_FLOAT
tensor_shape {
dim {
size: 270000
}
dim {
size: 512
}
}
float_val: 0
[[node training/SGD/moment_0 (defined at c:\users\aakash\appdata\local\programs\python\python36\lib\site-packages\tensorflow_core\python\framework\ops.py:1748) ]]
Original stack trace for 'training/SGD/moment_0':
File "c:\users\aakash\appdata\local\programs\python\python36\lib\runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "c:\users\aakash\appdata\local\programs\python\python36\lib\runpy.py", line 85, in _run_code
exec(code, run_globals)
File "c:\users\aakash\appdata\local\programs\python\python36\lib\site-packages\ipykernel_launcher.py", line 16, in <module>
app.launch_new_instance()
File "c:\users\aakash\appdata\local\programs\python\python36\lib\site-packages\traitlets\config\application.py", line 658, in launch_instance
app.start()
File "c:\users\aakash\appdata\local\programs\python\python36\lib\site-packages\ipykernel\kernelapp.py", line 505, in start
self.io_loop.start()
File "c:\users\aakash\appdata\local\programs\python\python36\lib\site-packages\tornado\platform\asyncio.py", line 132, in start
self.asyncio_loop.run_forever()
File "c:\users\aakash\appdata\local\programs\python\python36\lib\asyncio\base_events.py", line 422, in run_forever
self._run_once()
File "c:\users\aakash\appdata\local\programs\python\python36\lib\asyncio\base_events.py", line 1434, in _run_once
handle._run()
File "c:\users\aakash\appdata\local\programs\python\python36\lib\asyncio\events.py", line 145, in _run
self._callback(*self._args)
File "c:\users\aakash\appdata\local\programs\python\python36\lib\site-packages\tornado\ioloop.py", line 758, in _run_callback
ret = callback()
File "c:\users\aakash\appdata\local\programs\python\python36\lib\site-packages\tornado\stack_context.py", line 300, in null_wrapper
return fn(*args, **kwargs)
File "c:\users\aakash\appdata\local\programs\python\python36\lib\site-packages\tornado\gen.py", line 1233, in inner
self.run()
File "c:\users\aakash\appdata\local\programs\python\python36\lib\site-packages\tornado\gen.py", line 1147, in run
yielded = self.gen.send(value)
File "c:\users\aakash\appdata\local\programs\python\python36\lib\site-packages\ipykernel\kernelbase.py", line 357, in process_one
yield gen.maybe_future(dispatch(*args))
File "c:\users\aakash\appdata\local\programs\python\python36\lib\site-packages\tornado\gen.py", line 326, in wrapper
yielded = next(result)
File "c:\users\aakash\appdata\local\programs\python\python36\lib\site-packages\ipykernel\kernelbase.py", line 267, in dispatch_shell
yield gen.maybe_future(handler(stream, idents, msg))
File "c:\users\aakash\appdata\local\programs\python\python36\lib\site-packages\tornado\gen.py", line 326, in wrapper
yielded = next(result)
File "c:\users\aakash\appdata\local\programs\python\python36\lib\site-packages\ipykernel\kernelbase.py", line 534, in execute_request
user_expressions, allow_stdin,
File "c:\users\aakash\appdata\local\programs\python\python36\lib\site-packages\tornado\gen.py", line 326, in wrapper
yielded = next(result)
File "c:\users\aakash\appdata\local\programs\python\python36\lib\site-packages\ipykernel\ipkernel.py", line 294, in do_execute
res = shell.run_cell(code, store_history=store_history, silent=silent)
File "c:\users\aakash\appdata\local\programs\python\python36\lib\site-packages\ipykernel\zmqshell.py", line 536, in run_cell
return super(ZMQInteractiveShell, self).run_cell(*args, **kwargs)
File "c:\users\aakash\appdata\local\programs\python\python36\lib\site-packages\IPython\core\interactiveshell.py", line 2819, in run_cell
raw_cell, store_history, silent, shell_futures)
File "c:\users\aakash\appdata\local\programs\python\python36\lib\site-packages\IPython\core\interactiveshell.py", line 2845, in _run_cell
return runner(coro)
File "c:\users\aakash\appdata\local\programs\python\python36\lib\site-packages\IPython\core\async_helpers.py", line 67, in _pseudo_sync_runner
coro.send(None)
File "c:\users\aakash\appdata\local\programs\python\python36\lib\site-packages\IPython\core\interactiveshell.py", line 3020, in run_cell_async
interactivity=interactivity, compiler=compiler, result=result)
File "c:\users\aakash\appdata\local\programs\python\python36\lib\site-packages\IPython\core\interactiveshell.py", line 3191, in run_ast_nodes
if (yield from self.run_code(code, result)):
File "c:\users\aakash\appdata\local\programs\python\python36\lib\site-packages\IPython\core\interactiveshell.py", line 3267, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-10-fef3f263c0f5>", line 1, in <module>
model.fit(X_train, y_train, epochs=100, batch_size=512, shuffle=True)
File "c:\users\aakash\appdata\local\programs\python\python36\lib\site-packages\keras\engine\training.py", line 1213, in fit
self._make_train_function()
File "c:\users\aakash\appdata\local\programs\python\python36\lib\site-packages\keras\engine\training.py", line 316, in _make_train_function
loss=self.total_loss)
File "c:\users\aakash\appdata\local\programs\python\python36\lib\site-packages\keras\legacy\interfaces.py", line 91, in wrapper
return func(*args, **kwargs)
File "c:\users\aakash\appdata\local\programs\python\python36\lib\site-packages\keras\optimizers.py", line 202, in get_updates
for (i, shape) in enumerate(shapes)]
File "c:\users\aakash\appdata\local\programs\python\python36\lib\site-packages\keras\optimizers.py", line 202, in <listcomp>
for (i, shape) in enumerate(shapes)]
File "c:\users\aakash\appdata\local\programs\python\python36\lib\site-packages\keras\backend\tensorflow_backend.py", line 963, in zeros
v = tf.zeros(shape=shape, dtype=dtype, name=name)
File "c:\users\aakash\appdata\local\programs\python\python36\lib\site-packages\tensorflow_core\python\ops\array_ops.py", line 2350, in zeros
output = fill(shape, constant(zero, dtype=dtype), name=name)
File "c:\users\aakash\appdata\local\programs\python\python36\lib\site-packages\tensorflow_core\python\ops\array_ops.py", line 171, in fill
result = gen_array_ops.fill(dims, value, name=name)
File "c:\users\aakash\appdata\local\programs\python\python36\lib\site-packages\tensorflow_core\python\ops\gen_array_ops.py", line 3602, in fill
"Fill", dims=dims, value=value, name=name)
File "c:\users\aakash\appdata\local\programs\python\python36\lib\site-packages\tensorflow_core\python\framework\op_def_library.py", line 794, in _apply_op_helper
op_def=op_def)
File "c:\users\aakash\appdata\local\programs\python\python36\lib\site-packages\tensorflow_core\python\util\deprecation.py", line 507, in new_func
return func(*args, **kwargs)
File "c:\users\aakash\appdata\local\programs\python\python36\lib\site-packages\tensorflow_core\python\framework\ops.py", line 3357, in create_op
attrs, op_def, compute_device)
File "c:\users\aakash\appdata\local\programs\python\python36\lib\site-packages\tensorflow_core\python\framework\ops.py", line 3426, in _create_op_internal
op_def=op_def)
File "c:\users\aakash\appdata\local\programs\python\python36\lib\site-packages\tensorflow_core\python\framework\ops.py", line 1748, in __init__
self._traceback = tf_stack.extract_stack()
1
答案 0 :(得分:0)
如果您使用的是tensorflow == 2.0或2.2 尝试
loss_fn=tf.keras.losses.MeanSquaredError(reduction=losses_utils.ReductionV2.AUTO, name='mean_squared_error')
model.compile(optimizer='sgd', loss=loss_fn, metrics=['accuracy'])
它对我有用...尝试一下... 而且我也是新来的,所以和平