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

运行神经网络代码时Jupyter内核崩溃问题求助

问题:Keras模型编译时Jupyter内核崩溃

可正常运行的前置代码

import numpy as np
import cv2
import os
import matplotlib.pyplot as plt
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.preprocessing import image
from tensorflow.keras.optimizers import RMSprop

img = image.load_img("image_location_here")

train = ImageDataGenerator(rescale=1/255)
validation = ImageDataGenerator(rescale=1/255)

train_dataset = train.flow_from_directory(
    'image_location_here', 
    target_size=(50,50),  
    batch_size=3,
    class_mode='binary'
)

validation_dataset = validation.flow_from_directory(
    'image_location_here', 
    target_size=(50,50),
    batch_size=3,
    class_mode='binary'     
)

train_dataset.class_indices
train_dataset.classes

崩溃触发代码

运行以下代码时Jupyter内核直接崩溃:

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

已更新Anaconda至最新版本,多次重启环境后问题仍存在。

问题根源与修复方案

原代码的模型定义存在多处语法错误:

  1. model = tf.keras.models.Sequential仅将Sequential类赋值给变量,未实例化模型;
  2. 后续的层定义都是孤立代码行,未被添加到模型结构中;
  3. 存在拼写错误:metrices应为metrics;
  4. 原代码中validation_dataset错误调用train.flow_from_directory,应改为validation.flow_from_directory。

修复后的完整模型定义与编译代码如下:

import tensorflow as tf

# 正确实例化Sequential模型并添加层
model = tf.keras.models.Sequential([
    tf.keras.layers.Conv2D(16, (3,3), activation='relu', input_shape=(50,50,3)),
    tf.keras.layers.MaxPool2D(2,2),
    tf.keras.layers.Conv2D(32, (3,3), activation='relu'),
    tf.keras.layers.MaxPool2D(2,2),
    tf.keras.layers.Conv2D(64, (3,3), activation='relu'),
    tf.keras.layers.MaxPool2D(2,2),
    tf.keras.layers.Flatten(),
    tf.keras.layers.Dense(128, activation='relu'),
    tf.keras.layers.Dense(1, activation='sigmoid')
])

# 正确编译模型(修正拼写错误)
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 00:10:49