找不到可以处理输入的数据适配器:<class 'NoneType'>、<class 'NoneType'>
Failed to find data adapter that can handle input: <class 'NoneType'>, <class 'NoneType'>
我在这里遇到了问题:
关于代码:我在这里创建一个模型。第一步是使用 Sequential() 初始化模型。之后,我们将数据展平并添加额外的 3 个(或更多)隐藏层。
import pandas as pd
import numpy as np
import itertools
import keras
from sklearn import metrics
from sklearn.metrics import confusion_matrix
from keras.preprocessing.image import ImageDataGenerator, img_to_array, load_img
from keras.models import Sequential
from keras import optimizers
from keras.preprocessing import image
from keras.layers import Dropout, Flatten, Dense
from keras import applications
from keras.utils.np_utils import to_categorical
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
%matplotlib inline
import math
import datetime
import time
import tensorflow as tf
img_width, img_height = 224, 224
#Create a bottleneck file
top_model_weights_path = 'model_.h5'
train_data_dir = 'data/train'
#validation_data_dir = ‘data/validation’
test_data_dir = 'data/test'
epochs = 7 #this has been changed after multiple model run
# batch size used by flow_from_directory and predict_generator
batch_size = 50
VGG16 = tf.keras.applications.VGG16(include_top=False, weights='imagenet')
datagen = ImageDataGenerator(rescale=1. / 255)
start = datetime.datetime.now()
generator = datagen.flow_from_directory(
train_data_dir,
target_size=(img_width, img_height),
batch_size=batch_size,
class_mode=None,
shuffle=False)
nb_train_samples = len(generator.filenames)
num_classes = len(generator.class_indices)
predict_size_train = int(math.ceil(nb_train_samples / batch_size))
bottleneck_features_train = VGG16.predict_generator(generator, predict_size_train)
np.save('bottleneck_features_train.npy', bottleneck_features_train)
end= datetime.datetime.now()
elapsed= end-start
print ('Time: ', elapsed)
generator_top = datagen.flow_from_directory(
train_data_dir,
target_size=(img_width, img_height),
batch_size=batch_size,
class_mode='categorical',
shuffle=False)
nb_train_samples = len(generator_top.filenames)
num_classes = len(generator_top.class_indices)
# load the bottleneck features saved earlier
train_data = np.load('bottleneck_features_train.npy')
# get the class labels for the training data, in the original order
train_labels = generator_top.classes
# convert the training labels to categorical vectors
train_labels = to_categorical(train_labels, num_classes=num_classes)
start = datetime.datetime.now()
model = Sequential()
model.add(Flatten(input_shape=train_data.shape[1:]))
model.add(Dense(100, activation=keras.layers.LeakyReLU(alpha=0.3)))
model.add(Dropout(0.5))
model.add(Dense(50, activation=keras.layers.LeakyReLU(alpha=0.3)))
model.add(Dropout(0.3))
model.add(Dense(num_classes, activation='softmax'))
model.compile(loss='categorical_crossentropy',
optimizer=tf.keras.optimizers.RMSprop(lr=1e-4),
metrics=['acc'])
history = model.fit(train_data, train_labels,
epochs=7,
batch_size=batch_size,
validation_data=(validation_data, validation_labels))
model.save_weights(top_model_weights_path)
(eval_loss, eval_accuracy) = model.evaluate(
validation_data, validation_labels, batch_size=batch_size, verbose=1)
print("[INFO] accuracy: {:.2f}%".format(eval_accuracy * 100))
print("[INFO] Loss: {}".format(eval_loss))
end= datetime.datetime.now()
elapsed= end-start
print ('Time: ', elapsed)
我的错误是:
ValueError: Failed to find data adapter that can handle input: <class 'NoneType'>, <class 'NoneType'>
我该如何解决这个问题:我需要知道如何解决这个错误。我试过了还是没解决。
我喜欢这个。这工作正常。请尝试这样做。
import cv2
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
from sklearn.metrics import confusion_matrix
import itertools
import os, glob
from tqdm import tqdm
from efficientnet.tfkeras import EfficientNetB4
img_path = '.\Data\test\PNEUMONIA\PNEUMONIA.jpg'
model_path = '.\model.h5'
# labels used while training
labels = {0: 'NORMAL', 1: 'PNEUMONIA', 2: 'COVID'}
# loading the model
model = tf.keras.models.load_model(model_path, compile=False)
# model allowable image dimensions
img_width, img_height = 224, 224
# loading the image
image = cv2.imread(img_path)
# resizing the image
image = cv2.resize(image, (img_width, img_height))
# coverting BGR to RGB format
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
# adding a new axis [batch axis]
image = image[np.newaxis, ...]
# rescale image from [0,255] to [0,1]
image = image / 255.
# predicting the output
prediction = model.predict(image)
# squeeze/remove an extra axis
prediction = np.squeeze(prediction)
for i in labels:
print(labels[i], ':', prediction[i])
# picking the class with max. score
prediction = np.argmax(prediction)
# selecting the class with max. score
output = labels[prediction]
#print('Prediction:',output)
print()
print('The image which you entered, prediction is:',output)
我在这里遇到了问题:
关于代码:我在这里创建一个模型。第一步是使用 Sequential() 初始化模型。之后,我们将数据展平并添加额外的 3 个(或更多)隐藏层。
import pandas as pd
import numpy as np
import itertools
import keras
from sklearn import metrics
from sklearn.metrics import confusion_matrix
from keras.preprocessing.image import ImageDataGenerator, img_to_array, load_img
from keras.models import Sequential
from keras import optimizers
from keras.preprocessing import image
from keras.layers import Dropout, Flatten, Dense
from keras import applications
from keras.utils.np_utils import to_categorical
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
%matplotlib inline
import math
import datetime
import time
import tensorflow as tf
img_width, img_height = 224, 224
#Create a bottleneck file
top_model_weights_path = 'model_.h5'
train_data_dir = 'data/train'
#validation_data_dir = ‘data/validation’
test_data_dir = 'data/test'
epochs = 7 #this has been changed after multiple model run
# batch size used by flow_from_directory and predict_generator
batch_size = 50
VGG16 = tf.keras.applications.VGG16(include_top=False, weights='imagenet')
datagen = ImageDataGenerator(rescale=1. / 255)
start = datetime.datetime.now()
generator = datagen.flow_from_directory(
train_data_dir,
target_size=(img_width, img_height),
batch_size=batch_size,
class_mode=None,
shuffle=False)
nb_train_samples = len(generator.filenames)
num_classes = len(generator.class_indices)
predict_size_train = int(math.ceil(nb_train_samples / batch_size))
bottleneck_features_train = VGG16.predict_generator(generator, predict_size_train)
np.save('bottleneck_features_train.npy', bottleneck_features_train)
end= datetime.datetime.now()
elapsed= end-start
print ('Time: ', elapsed)
generator_top = datagen.flow_from_directory(
train_data_dir,
target_size=(img_width, img_height),
batch_size=batch_size,
class_mode='categorical',
shuffle=False)
nb_train_samples = len(generator_top.filenames)
num_classes = len(generator_top.class_indices)
# load the bottleneck features saved earlier
train_data = np.load('bottleneck_features_train.npy')
# get the class labels for the training data, in the original order
train_labels = generator_top.classes
# convert the training labels to categorical vectors
train_labels = to_categorical(train_labels, num_classes=num_classes)
start = datetime.datetime.now()
model = Sequential()
model.add(Flatten(input_shape=train_data.shape[1:]))
model.add(Dense(100, activation=keras.layers.LeakyReLU(alpha=0.3)))
model.add(Dropout(0.5))
model.add(Dense(50, activation=keras.layers.LeakyReLU(alpha=0.3)))
model.add(Dropout(0.3))
model.add(Dense(num_classes, activation='softmax'))
model.compile(loss='categorical_crossentropy',
optimizer=tf.keras.optimizers.RMSprop(lr=1e-4),
metrics=['acc'])
history = model.fit(train_data, train_labels,
epochs=7,
batch_size=batch_size,
validation_data=(validation_data, validation_labels))
model.save_weights(top_model_weights_path)
(eval_loss, eval_accuracy) = model.evaluate(
validation_data, validation_labels, batch_size=batch_size, verbose=1)
print("[INFO] accuracy: {:.2f}%".format(eval_accuracy * 100))
print("[INFO] Loss: {}".format(eval_loss))
end= datetime.datetime.now()
elapsed= end-start
print ('Time: ', elapsed)
我的错误是:
ValueError: Failed to find data adapter that can handle input: <class 'NoneType'>, <class 'NoneType'>
我该如何解决这个问题:我需要知道如何解决这个错误。我试过了还是没解决。
我喜欢这个。这工作正常。请尝试这样做。
import cv2
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
from sklearn.metrics import confusion_matrix
import itertools
import os, glob
from tqdm import tqdm
from efficientnet.tfkeras import EfficientNetB4
img_path = '.\Data\test\PNEUMONIA\PNEUMONIA.jpg'
model_path = '.\model.h5'
# labels used while training
labels = {0: 'NORMAL', 1: 'PNEUMONIA', 2: 'COVID'}
# loading the model
model = tf.keras.models.load_model(model_path, compile=False)
# model allowable image dimensions
img_width, img_height = 224, 224
# loading the image
image = cv2.imread(img_path)
# resizing the image
image = cv2.resize(image, (img_width, img_height))
# coverting BGR to RGB format
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
# adding a new axis [batch axis]
image = image[np.newaxis, ...]
# rescale image from [0,255] to [0,1]
image = image / 255.
# predicting the output
prediction = model.predict(image)
# squeeze/remove an extra axis
prediction = np.squeeze(prediction)
for i in labels:
print(labels[i], ':', prediction[i])
# picking the class with max. score
prediction = np.argmax(prediction)
# selecting the class with max. score
output = labels[prediction]
#print('Prediction:',output)
print()
print('The image which you entered, prediction is:',output)