You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

机器学习与TensorFlow项目中Graph Execution Error问题求助

TensorFlow图像分类项目Graph Execution Error排查求助

我是一名学生,在基于TensorFlow的图像分类项目中遇到Graph Execution Error,无法定位问题所在。以下是我的项目代码及报错信息,若需要代码细节补充我会配合,恳请各位提供排查思路。

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from tensorflow.keras.preprocessing.image import ImageDataGenerator

train_idg= ImageDataGenerator(rescale = 1/255,
                           shear_range=0.2,
                           zoom_range=0.2,
                           horizontal_flip = False,
                           vertical_flip = True,
                           )

train_data = train_idg.flow_from_directory('rps_train',
                                       target_size=(64,64))
                                       #,class_mode='binary')
#Found 2520 images belonging to 3 classes.

test_idg = ImageDataGenerator(1./255,
                         shear_range=0.2,
                         zoom_range=0.2,
                         horizontal_flip = False,
                         vertical_flip = True,
                           )
test_data=test_idg.flow_from_directory('rps_test',
                                   target_size=(64,64))
                                   #,class_mode='binary')

from tensorflow.keras.models import Sequential
from tensorflow.keras import layers

model = Sequential()

model.add(layers.Conv2D(filters=64,
                    kernel_size=3,
                    input_shape=[64,64,3],
                    activation='relu'))

model.add(layers.MaxPool2D(strides=3))

model.add(layers.Conv2D(filters=32,
                     kernel_size=3,
                     activation='relu'))

model.add(layers.MaxPool2D(strides=3))

model.add(layers.Flatten())
model.add(layers.Dense(units=64, activation='relu'))
model.add(layers.Dense(units=64, activation='softmax'))

model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'] )

model.fit(x=train_data, validation_data=test_data, epochs=10,batch_size=50)

运行时出现以下报错:

Epoch 1/10
---------------------------------------------------------------------------
InvalidArgumentError                      Traceback (most recent call last)
Input In [29], in <cell line: 1>()
----> 1 model.fit(x=train_data, validation_data=test_data, epochs=10,batch_size=50)

File ~\anaconda3\lib\site-packages\keras\utils\traceback_utils.py:70, in 
filter_traceback.<locals>.error_handler(*args, **kwargs)
     67     filtered_tb = _process_traceback_frames(e.__traceback__)
     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

File ~\anaconda3\lib\site-packages\tensorflow\python\eager\execute.py:54, in 
quick_execute(op_name, num_outputs, inputs, attrs, ctx, name)

 52 try:
     53   ctx.ensure_initialized()
---> 54   tensors = pywrap_tfe.TFE_Py_Execute(ctx._handle, device_name, op_name,
     55                                       inputs, attrs, num_outputs)
     56 except core._NotOkStatusException as e:
     57   if name is not None:

InvalidArgumentError: Graph execution error:

Detected at node 'gradient_tape/binary_crossentropy/logistic_loss/mul/BroadcastGradientArgs' defined at (most recent call last):

排查思路与修正方案

  • 损失函数与分类体系不匹配:你的数据集是3类,但存在两处核心错误:
    • 最后一层Dense设为64单元+softmax,完全不符合3分类需求,应改为units=3
    • 使用了二分类专用的binary_crossentropy,需替换为多分类损失:
      • 若在flow_from_directory中指定class_mode='categorical',损失函数选categorical_crossentropy
      • 若指定class_mode='sparse',损失函数选sparse_categorical_crossentropy
  • ImageDataGenerator参数错误:test_idg的写法有误,1./255未指定rescale参数,会被误识别为featurewise_center参数值,导致图像预处理逻辑错误。修正为:
    test_idg = ImageDataGenerator(rescale=1./255,
                                 shear_range=0.2,
                                 zoom_range=0.2,
                                 horizontal_flip = False,
                                 vertical_flip = True)
    
  • MaxPool2D参数缺失:仅指定strides=3但未设置pool_size,默认pool_size=(2,2)会导致strides大于池化窗口,可能引发特征图尺寸异常。建议显式设置:
    model.add(layers.MaxPool2D(pool_size=(3,3), strides=3))
    
  • batch_size参数冲突:flow_from_directory默认batch_size为32,model.fit中又设置了batch_size=50,会引发数据批次处理冲突,建议只在flow_from_directory中指定batch_size,或删除model.fit中的batch_size参数

内容的提问来源于stack exchange,提问作者Wildo_Baggins311

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 03:00:56