微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

将 Inception 应用于图像分类但得到类型错误

如何解决将 Inception 应用于图像分类但得到类型错误

目前内窥镜技术正逐步进入从诊断阶段到手术治疗阶段,而国内市场几乎被国外内窥镜公司垄断,因此内窥镜的研究对发展具有重要意义。家用医疗设备。

在这里,我尝试使用 InceptionV3 方法运行图像分类,但随后收到如下错误消息 ---

runfile('C:/Users/MDIC/Desktop/Image Classification with Inception.py',wdir='C:/Users/MDIC/Desktop')
Traceback (most recent call last):

  File "<ipython-input-16-10cce949c165>",line 1,in <module>
    runfile('C:/Users/MDIC/Desktop/Image Classification with Inception.py',wdir='C:/Users/MDIC/Desktop')

  File "C:\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py",line 786,in runfile
    execfile(filename,namespace)

  File "C:\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py",line 110,in execfile
    exec(compile(f.read(),filename,'exec'),namespace)

  File "C:/Users/MDIC/Desktop/Image Classification with Inception.py",line 33,in <module>
    print('total training esophagus images:',len(os.listdir(train_esophagus_dir)))

TypeError: listdir: path should be string,bytes,os.pathLike or None,not list

我的整个编程代码如下------

# Importing the necessary libraries
from matplotlib import pyplot as plt
from tensorflow.keras import layers
from tensorflow.keras import Model
from tensorflow.keras.applications.inception_v3 import InceptionV3
from tensorflow.keras.optimizers import RMSprop
from tensorflow.keras.preprocessing.image import img_to_array,load_img
from tensorflow.keras.preprocessing.image import ImageDataGenerator
import matplotlib.image as mpimg
import numpy as np
import os
import random
import tensorflow

# Set directory where training and validation images are placed
base_dir = 'data'

train_dir = os.path.join(base_dir,'train')
# Directory with training pictures
train_esophagus_dir = os.path.join(train_dir,'esophagus')
train_noesophagus_dir = os.path.join(train_dir,'noesophagus')

validation_dir = os.path.join(base_dir,'validation')
# Directory with validation pictures
validation_esophagus_dir = os.path.join(validation_dir,'esophagus')
validation_noesophagus_dir = os.path.join(validation_dir,'noesophagus')

# Understanding diretory from inside
train_esophagus_dir = os.listdir(train_esophagus_dir)
train_noesophagus_dir = os.listdir(train_noesophagus_dir)

print('total training esophagus images:',len(os.listdir(train_esophagus_dir)))
print('total training noesophagus images:',len(os.listdir(train_noesophagus_dir)))
print('total validation esophagus images:',len(os.listdir(validation_esophagus_dir)))
print('total validation noesophagus images:',len(os.listdir(validation_noesophagus_dir)))

# Understanding directory from inside
train_esophagus_fnames = os.listdir(train_esophagus_dir)
train_noesophagus_fnames = os.listdir(train_noesophagus_dir)

print("Printing five esophagus images name in train_esophagus_dir:",train_esophagus_fnames[:5])
print("Printing five noesophagus images name in train_noesophagus_dir:",train_noesophagus_fnames[:5])

# Visualising images randomly to check if everything is working
# Parameters for gragh; will output images in a 4x4 configuration
ncols = 5
nrows = 5
# Index for iterating over images
pic_index = 0 

# Set up matplotlib figure,and size it to fit 4x4 pics
fig =plt.gcf()
fig.set_size_inches(ncols*5,nrows*5)
pic_index += 10
next_esophagus_pix = [os.path.join(train_esophagus_dir,fname)
                 for fname in train_esophagus_fnames[pic_index-10:pic_index]]
next_noesophagus_pix = [os.path.join(train_noesophagus_dir,fname)
                 for fname in train_noesophagus_fnames[pic_index-10:pic_index]]

for i,img_path in enumerate(next_esophagus_pix + next_noesophagus_pix):
# Set up subplot; subplot indices start at 1
    sp = plt.subplot(ncols,nrows,i + 1)
# Do not show axes (or gridlines)
    sp.axis('Off')
    img = mpimg.imread(img_path)
    plt.imshow(img)
plt.show()

# Loading InceptionV3 model,loading its weight,and freezing its layers
local_weights_file = os.getcwd()+'/inception_v3_weights_tf_dim_ordering_tf_kernels_notop.h5//'

pre_trained_model = InceptionV3(input_shape = (150,150,3),include_top = False,weights = None)

pre_trained_model.load_weights(local_weights_file)

for layer in pre_trained_model.layers:
    layer.trainable = False

pre_trained_model.summary()

# Customising InceptionV3 model for own need
last_layer = pre_trained_model.get_layer('mixed7')
print("Last layer taken from InceptionV3 output shape: ",last_layer.output_shape)

last_output = last_layer.output
# Flatten the output layer to 1 dimension
x = layers.Flatten()(last_output)
# Add a fully connected layer with 1024 hidden units and ReLU activation 
x = layers.Dense(1024,activation = 'relu')(x)
# Add a dropout rate of 0.2
x = layers.Dropout(0.2)(x)
# Add a final sigmoid layer for classification
x = layers.Dense(1,activation = 'sigmoid')(x)

model = Model(pre_trained_model.input,x)

# Compiling the model
model.compile(optimizer = RMSprop(lr=0.0001),loss = 'binary_crossentropy',metrics = ['acc'])

# Data augmentation using ImageDataGenerator
train_datagen = ImageDataGenerator(rescale = 1.0/255,height_shift_range = 0.2,width_shift_range = 0.2,rotation_range = 40,shear_range = 0.2,zoom_range = 0.2,horizontal_flip = True)

# Note that the validation data should not be augmented
test_datagen = ImageDataGenerator(rescale = 1.0/255.)

# Loading images directly from directory
# Flow training images in bateches of 20 using train_datagen generator
train_generator = train_datagen.flow_from_directory(train_dir,batch_size = 20,class_mode = 'binary',target_size = (150,150))

# Flow validation images in bateches of 20 using test_datagen generator
validation_generator = test_datagen.flow_from_directory(validation_dir,150))

# Fitting the model
history = model.fit_generator(
        train_generator,epochs = 2,steps_per_epoch = 100,validation_data = validation_generator,validation_steps = 50,verbose = 2)

# Evluating the model
acc = history.history['acc']
val_acc = history.history['val_acc']
loss = history.history['loss']
val_loss = history.history['val_loss']

epochs = range(len(acc))

plt.plot(epochs,acc,'r',label='Training accuracy')
plt.plot(epochs,val_acc,'g',label='Validation accuracy')
plt.title('Training and validation accuracy')
plt.legend(loc=0)
plt.figure()
plt.show()

# Visualising middle layers of neural networks
successive_outputs = [layer.output for layer in model.layers[1:5]]
# The input of InceptionV3 model
visualization_model = Model(inputs = model.input,outputs = successive_outputs)

img_path = os.path.join(train_esophagus_dir,random.choice(train_esophagus_fnames))
# This is a PIL image
img = load_img(img_path,target_size=(150,150))  
# Numpy array with shape (150,3)
x = img_to_array(img)  
# Numpy array with shape (1,3)
x = x.reshape((1,) + x.shape)  
# Rescale by 1/255
x /= 255 

successive_feature_maps = visualization_model.predict(x)
layer_names = [layer.name for layer in visualization_model.layers]

# Now let display representations for say convolution number 32
print("Total number of layers saved:",len(successive_feature_maps))
# Taking layer 1 activations array
layer_activation = successive_feature_maps[0]
# visualising 1st convolution
CONVOLUTION_NUM = 1 
plt.imshow(layer_activation[0,:,CONVOLUTION_NUM],cmap='inferno')

请尽快帮我

非常感谢

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。