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

构建CNN模型时遇NameError:scipy未定义问题求助

问题:Keras模型训练阶段触发NameError: name 'scipy' is not defined错误

已安装scipy并完成导入,Python版本3.9,TensorFlow版本2.15.0,模型编译阶段运行正常,但执行model.fit()时触发该错误。

环境信息

  • Python:3.9
  • TensorFlow:2.15.0
  • 已安装并导入scipy

报错代码

from tensorflow.keras.preprocessing.image import ImageDataGenerator 
import scipy

# 设置随机种子
tf.random.set_seed(99)

# 数据预处理(将像素值归一化到0-1区间)
train_data_gen = ImageDataGenerator(rescale=1.0/255)
test_data_gen = ImageDataGenerator(rescale=1.0/255)

# 数据目录路径
train_data_path = 'pizza_steak/train/'
test_data_path = 'pizza_steak/test/'

# 自动生成数据与标签
train_data = train_data_gen.flow_from_directory(
    directory = train_data_path,
    batch_size = 32, # 每个批次包含32个训练样本
    target_size = (224,224), # 调整图片尺寸至224x224
    class_mode = 'binary',
    seed = 42
)

test_data = test_data_gen.flow_from_directory(
    directory = test_data_path ,
    batch_size = 32,
    target_size = (224,224),
    class_mode = 'binary',
    seed = 42
)

# 构建CNN模型
model_1 = tf.keras.Sequential([
    tf.keras.layers.Conv2D(filters=10,
                           kernel_size = 3,
                           activation = 'relu',
                           input_shape = (224,224,3)), # 输入尺寸与图片预处理后的尺寸一致
    
    tf.keras.layers.Conv2D(10, 3, activation='relu'),
    tf.keras.layers.MaxPool2D(pool_size=2,
                              padding = 'valid'),

    tf.keras.layers.Conv2D(10, 3, activation='relu'),
    tf.keras.layers.Conv2D(10,3, activation='relu'),
    tf.keras.layers.MaxPool2D(2),
    tf.keras.layers.Flatten(),
    tf.keras.layers.Dense(1, activation = 'sigmoid')

])

# 编译模型
model_1.compile(
    loss = "binary_crossentropy",
    optimizer = tf.keras.optimizers.Adam(),
    metrics = ["accuracy"]
)

# 训练模型(报错触发位置)
model_1.fit(train_data, 
            epochs=5,
            steps_per_epoch = len(train_data),
            validation_data = test_data,
            validation_steps = len(test_data))

# 无需手动传入X和y,flow_from_directory已自动生成

解决方案

  • 确认scipy安装在当前运行的Python环境:执行pip list | grep scipy(Linux/macOS)或pip list | findstr scipy(Windows),检查是否存在scipy条目
  • 安装与当前环境兼容的scipy版本:针对Python3.9和TensorFlow2.15.0,推荐安装scipy==1.10.1,执行命令pip install scipy==1.10.1
  • 验证导入是否生效:在代码开头添加print(scipy.__version__),运行后查看是否正常打印版本号,排除导入失败的隐性问题
  • 检查虚拟环境:如果使用了虚拟环境,确保安装scipy和运行代码时处于同一个虚拟环境中

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 04:44:55