Google Colab中TensorFlow代码目录找不到报错及代码问题求助
解决Google Colab中图像分类代码的NotFoundError及其他问题
核心问题分析与修复步骤
1. 路径错误:Zip文件无法直接作为数据集目录
tf.keras.preprocessing.image_dataset_from_directory要求传入解压后的文件夹路径,而非压缩包路径。同时路径中的空格无需转义,需去掉多余的\符号。先解压Zip文件再指向文件夹:
# 解压Zip文件到指定目录 import zipfile zip_ref = zipfile.ZipFile("/content/gdrive/MyDrive/Colab Notebooks/Pointing_dogs.zip", 'r') zip_ref.extractall("/content/gdrive/MyDrive/Colab Notebooks/Pointing_dogs") zip_ref.close() # 指向解压后的文件夹 proj_path = "/content/gdrive/MyDrive/Colab Notebooks/Pointing_dogs" proj_path = pathlib.Path(proj_path)
2. 数据集函数名与参数错误
验证集的函数名写错(少了directory后缀),且参数里的"proj_path"是字符串常量,需改为变量proj_path:
# 修正后的验证集代码 ds_validation = tf.keras.preprocessing.image_dataset_from_directory( proj_path, labels="inferred", label_mode="int", color_mode="grayscale", # 和模型输入通道匹配 batch_size=batch_size, image_size=(img_height, img_width), shuffle=True, seed=123, validation_split=0.2, subset="validation", )
3. 输入通道与图像模式不匹配
模型输入定义为单通道灰度图(28, 28, 1),但代码中color_mode设为"rgb"(3通道),会导致维度不匹配错误。需将训练集和验证集的color_mode统一改为"grayscale",或把模型输入改为(28,28,3)(根据图像实际类型选择)。
4. 移除无用的自定义循环
代码中存在一段空的训练循环,会占用资源且与后续model.fit功能重复,直接删除即可:
# 删除这段无用代码 # for epochs in range(10): # for x, y in ds_train: # # train here # pass
完整修正后的代码
import os import zipfile os.environ["TF_CPP_MIN_LOG_LEVEL"] = "2" import tensorflow as tf import pathlib from google.colab import drive drive.mount('/content/gdrive') from tensorflow import keras from tensorflow.keras import layers from tensorflow.keras.preprocessing.image import ImageDataGenerator img_height = 28 img_width = 28 batch_size = 2 # 解压Zip文件(仅当目录不存在时执行) zip_path = "/content/gdrive/MyDrive/Colab Notebooks/Pointing_dogs.zip" extract_path = "/content/gdrive/MyDrive/Colab Notebooks/Pointing_dogs" if not os.path.exists(extract_path): with zipfile.ZipFile(zip_path, 'r') as zip_ref: zip_ref.extractall(extract_path) # 指向解压后的文件夹 proj_path = pathlib.Path(extract_path) # 模型输入为单通道(匹配grayscale模式),若为RGB则改为(28,28,3) model = keras.Sequential( [ layers.Input((28, 28, 1)), layers.Conv2D(16, 3, padding="same"), layers.Conv2D(32, 3, padding="same"), layers.MaxPooling2D(), layers.Flatten(), layers.Dense(10), ] ) # 训练集 ds_train = tf.keras.preprocessing.image_dataset_from_directory( proj_path, labels="inferred", label_mode="int", color_mode="grayscale", batch_size=batch_size, image_size=(img_height, img_width), shuffle=True, seed=123, validation_split=0.2, subset="training", ) # 验证集 ds_validation = tf.keras.preprocessing.image_dataset_from_directory( proj_path, labels="inferred", label_mode="int", color_mode="grayscale", batch_size=batch_size, image_size=(img_height, img_width), shuffle=True, seed=123, validation_split=0.2, subset="validation", ) # 数据增强 def augment(x, y): image = tf.image.random_brightness(x, max_delta=0.05) return image, y ds_train = ds_train.map(augment) # 编译与训练(加入验证集监控) model.compile( optimizer=keras.optimizers.Adam(), loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True), metrics=["accuracy"], ) model.fit(ds_train, validation_data=ds_validation, epochs=2, verbose=2)
内容的提问来源于stack exchange,提问作者Jazaic Divina
相关产品推荐
相关产品推荐

