I'm having an error running my fruit detection model. Do you have any idea why? You can see the error after the code. How can I fix this problem? I need this for a school project, so i would be happy about fast answers :))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import os
for dirname, _, filenames in os.walk('C:\\Users\\XX\\Desktop\\XX\\2. Semester\\Data Science\\archive'):
for filename in filenames:
print(os.path.join(dirname, filename))
from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D, Activation, Dropout, Flatten, Dense
from tensorflow.keras.preprocessing.image import ImageDataGenerator, img_to_array, load_img
train_path = "C:\\Users\\XX\\Desktop\\XX\\2. Semester\\Data Science\\archive\\train_zip\\train"
test_path = "C:\\Users\\XX\\Desktop\\XX\\2. Semester\\Data Science\\archive\\test_zip\\test"
img = load_img(train_path "\\litchi\\280_100.jpg")
plt.imshow(img)
plt.axis("on")
plt.show()
img = img_to_array(img)
img.shape
model = Sequential()
model.add(Conv2D(128, 3, activation="relu", input_shape=(100,100,3)))
model.add(MaxPooling2D())
model.add(Conv2D(64, 3, activation="relu"))
model.add(Conv2D(32, 3, activation="relu"))
model.add(MaxPooling2D())
model.add(Dropout(0.50))
model.add(Flatten())
model.add(Dense(5000, activation = "relu"))
model.add(Dense(1000, activation = "relu"))
model.add(Dense(131, activation = "softmax"))
model.summary()
model.compile(loss="categorical_crossentropy", optimizer="SGD", metrics=["accuracy"])
train_datagen = ImageDataGenerator(rescale=1. / 255,
shear_range=0.3,
horizontal_flip=True,
vertical_flip=False,
zoom_range=0.3
)
test_datagen = ImageDataGenerator(rescale=1. / 255)
train_generator = train_datagen.flow_from_directory(train_path,
target_size=(100, 100),
batch_size=32,
color_mode="rgb",
class_mode="categorical")
test_generator = test_datagen.flow_from_directory(test_path,
target_size=(100, 100),
batch_size=32,
color_mode="rgb",
class_mode="categorical")
hist = model.fit_generator(generator = train_generator,
steps_per_epoch = 50,
epochs = 50,
validation_data = test_generator,
validation_steps = 50)
from keras.models import load_model
model.save("Fruitmodel.h5")
import tensorflow as tf
probability_model = tf.keras.Sequential([model,
tf.keras.layers.Softmax()])
test_generator.classes[1460]
predictions = probability_model.predict(test_generator)
b=predictions[8]
print(b)
np.argmax(b)
import os
folder = 'C:\\Users\\XX\\Desktop\\XX\\2. Semester\\Data Science\\archive\\test_zip\\test'
sub_folders = [name for name in os.listdir(folder) if os.path.isdir(os.path.join(folder, name))]
print(sub_folders[3]) ```
# Error: InvalidArgumentError: Graph execution error #
```Detected at node 'categorical_crossentropy/softmax_cross_entropy_with_logits' defined at (most recent call last):
File "C:\Users\Janine\anaconda3\lib\runpy.py", line 197, in _run_module_as_main
return _run_code(code, main_globals, None,
File "C:\Users\Janine\anaconda3\lib\runpy.py", line 87, in _run_code
exec(code, run_globals)
File "C:\Users\Janine\anaconda3\lib\site-packages\spyder_kernels\console\__main__.py", line 23, in <module>
start.main()
File "C:\Users\Janine\anaconda3\lib\site-packages\spyder_kernels\console\start.py", line 328, in main
kernel.start()
File "C:\Users\Janine\anaconda3\lib\site-packages\ipykernel\kernelapp.py", line 677, in start
self.io_loop.start()
File "C:\Users\Janine\anaconda3\lib\site-packages\tornado\platform\asyncio.py", line 199, in start
self.asyncio_loop.run_forever()
File "C:\Users\Janine\anaconda3\lib\asyncio\base_events.py", line 601, in run_forever
self._run_once()
File "C:\Users\Janine\anaconda3\lib\asyncio\base_events.py", line 1905, in _run_once
handle._run()
File "C:\Users\Janine\anaconda3\lib\asyncio\events.py", line 80, in _run
self._context.run(self._callback, *self._args)
File "C:\Users\Janine\anaconda3\lib\site-packages\ipykernel\kernelbase.py", line 471, in dispatch_queue
await self.process_one()
File "C:\Users\Janine\anaconda3\lib\site-packages\ipykernel\kernelbase.py", line 460, in process_one
await dispatch(*args)
File "C:\Users\Janine\anaconda3\lib\site-packages\ipykernel\kernelbase.py", line 367, in dispatch_shell
await result
File "C:\Users\Janine\anaconda3\lib\site-packages\ipykernel\kernelbase.py", line 662, in execute_request
reply_content = await reply_content
File "C:\Users\Janine\anaconda3\lib\site-packages\ipykernel\ipkernel.py", line 360, in do_execute
res = shell.run_cell(code, store_history=store_history, silent=silent)
File "C:\Users\Janine\anaconda3\lib\site-packages\ipykernel\zmqshell.py", line 532, in run_cell
return super().run_cell(*args, **kwargs)
File "C:\Users\Janine\anaconda3\lib\site-packages\IPython\core\interactiveshell.py", line 2863, in run_cell
result = self._run_cell(
File "C:\Users\Janine\anaconda3\lib\site-packages\IPython\core\interactiveshell.py", line 2909, in _run_cell
return runner(coro)
File "C:\Users\Janine\anaconda3\lib\site-packages\IPython\core\async_helpers.py", line 129, in _pseudo_sync_runner
coro.send(None)
File "C:\Users\Janine\anaconda3\lib\site-packages\IPython\core\interactiveshell.py", line 3106, in run_cell_async
has_raised = await self.run_ast_nodes(code_ast.body, cell_name,
File "C:\Users\Janine\anaconda3\lib\site-packages\IPython\core\interactiveshell.py", line 3309, in run_ast_nodes
if await self.run_code(code, result, async_=asy):
File "C:\Users\Janine\anaconda3\lib\site-packages\IPython\core\interactiveshell.py", line 3369, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "C:\Users\Janine\AppData\Local\Temp\ipykernel_14720\1719248090.py", line 1, in <cell line: 1>
runfile('C:/Users/Janine/Desktop/DHBW/2. Semester/Projekt.py', wdir='C:/Users/Janine/Desktop/DHBW/2. Semester')
File "C:\Users\Janine\anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 577, in runfile
exec_code(file_code, filename, ns_globals, ns_locals,
File "C:\Users\Janine\anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 465, in exec_code
exec(compiled, ns_globals, ns_locals)
File "C:\Users\Janine\Desktop\DHBW\2. Semester\Projekt.py", line 59, in <module>
hist = model.fit_generator(generator = train_generator,
File "C:\Users\Janine\anaconda3\lib\site-packages\keras\engine\training.py", line 2260, in fit_generator
return self.fit(
File "C:\Users\Janine\anaconda3\lib\site-packages\keras\utils\traceback_utils.py", line 64, in error_handler
return fn(*args, **kwargs)
File "C:\Users\Janine\anaconda3\lib\site-packages\keras\engine\training.py", line 1409, in fit
tmp_logs = self.train_function(iterator)
File "C:\Users\Janine\anaconda3\lib\site-packages\keras\engine\training.py", line 1051, in train_function
return step_function(self, iterator)
File "C:\Users\Janine\anaconda3\lib\site-packages\keras\engine\training.py", line 1040, in step_function
outputs = model.distribute_strategy.run(run_step, args=(data,))
File "C:\Users\Janine\anaconda3\lib\site-packages\keras\engine\training.py", line 1030, in run_step
outputs = model.train_step(data)
File "C:\Users\Janine\anaconda3\lib\site-packages\keras\engine\training.py", line 890, in train_step
loss = self.compute_loss(x, y, y_pred, sample_weight)
File "C:\Users\Janine\anaconda3\lib\site-packages\keras\engine\training.py", line 948, in compute_loss
return self.compiled_loss(
File "C:\Users\Janine\anaconda3\lib\site-packages\keras\engine\compile_utils.py", line 201, in __call__
loss_value = loss_obj(y_t, y_p, sample_weight=sw)
File "C:\Users\Janine\anaconda3\lib\site-packages\keras\losses.py", line 139, in __call__
losses = call_fn(y_true, y_pred)
File "C:\Users\Janine\anaconda3\lib\site-packages\keras\losses.py", line 243, in call
return ag_fn(y_true, y_pred, **self._fn_kwargs)
File "C:\Users\Janine\anaconda3\lib\site-packages\keras\losses.py", line 1787, in categorical_crossentropy
return backend.categorical_crossentropy(
File "C:\Users\Janine\anaconda3\lib\site-packages\keras\backend.py", line 5134, in categorical_crossentropy
return tf.nn.softmax_cross_entropy_with_logits(
Node: 'categorical_crossentropy/softmax_cross_entropy_with_logits'
logits and labels must be broadcastable: logits_size=[32,131] labels_size=[32,3]
[[{{node categorical_crossentropy/softmax_cross_entropy_with_logits}}]] [Op:__inference_train_function_2419]```
CodePudding user response:
Actual error is this:
logits and labels must be broadcastable: logits_size=[32,131] labels_size=[32,3]
Try to change this line:
model.add(Dense(131, activation = "softmax"))
to this:
model.add(Dense(3, activation = "softmax"))