weixin_45904768
2021-04-29 18:35 浏览 27

TensorFlow关于垃圾分类的一段简单代码问题

import numpy as np
from tensorflow import keras
from tensorflow.keras.preprocessing import image
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.applications.mobilenet_v2 import MobileNetV2
import tensorflow as tf
import os
os.environ['CUDA_VISIBLE_DEVICES'] = '/gpu:0'
target_size = 96
base_model = MobileNetV2(weights='imagenet', include_top=False, input_shape=(target_size,target_size,3))

model = keras.Sequential([
        base_model,
        keras.layers.GlobalAveragePooling2D(),
        keras.layers.Dropout(0.5),
        keras.layers.Dense(1024, activation='relu'),
        keras.layers.Dense(5) 
])
train_path = 'C:/Users/11500/Desktop/ai人工智能导论/垃圾分类data/垃圾分类/training/'
test_path = 'C:/Users/11500/Desktop/ai人工智能导论/垃圾分类data/垃圾分类/test/'
    
train_data = ImageDataGenerator(
    rescale=1./225, #数值归一化
)
    
test_data = ImageDataGenerator(
    rescale=1./225, #数值归一化
)

train_generator = train_data.flow_from_directory(
    train_path,
    target_size=(target_size, target_size),
    batch_size=4,
    class_mode='categorical',
    seed=0)

test_generator = train_data.flow_from_directory(
    test_path,
    target_size=(target_size, target_size),
    batch_size=4,
    class_mode='categorical',
    seed=0)

labels = train_generator.class_indices
print(labels)
labels = dict((v, k) for k, v in labels.items())
print(labels)



def scheduler(epoch, lr):
    '''
        学习率调整策略函数:
        可以尝试在不同的epoch之间使用不同的学习率
    '''
    if epoch < 2:
        return lr
    else:
        return lr * 0.1

lr_callback = keras.callbacks.LearningRateScheduler(schedule=scheduler, verbose=1)

#模型保存策略
root = '.eckpointsapter01'
folder = 'chapter01'
name = 'mobilenet'
ckpt_callback = keras.callbacks.ModelCheckpoint(
    filepath = os.path.join(root, folder, name + '-ep{epoch:03d}-loss{loss:.3f}-val_accuracy{val_accuracy:.3f}.h5'),
    monitor='val_loss',  #monitor:需要监视的值
    save_weights_only=False, # 保存整个模型
    save_best_only=False, 
    mode='auto',
    period=1, #保存模型的间隔数,1表示每个epoch训练结束后都会保存一个模型
)


callback = [ckpt_callback, lr_callback]

SGD = keras.optimizers.SGD(lr=0.001, momentum=0.9)
loss = keras.losses.CategoricalCrossentropy(from_logits=True)
model.compile(optimizer=SGD, loss=loss,  metrics=['accuracy'])

model.fit_generator(
    generator = train_generator,
    epochs = 4,
    steps_per_epoch = len(train_generator),
    validation_data = test_generator,
    validation_steps = len(test_generator),
    callbacks=callback
)

我的代码如上:

报错如下:

事先自己新建好了这三个文件夹 

求问,哪里出问题了? 

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

相关推荐