Reputation: 11
I did transfer learning to VGG16 model in order to classify images to cat or dog and here is portion of the code snippet:
prediction_layer = tf.keras.layers.Dense(1)
prediction_batch = prediction_layer(feature_batch_average)
def manual_preprocess_input(x, data_format=None):
if data_format is None:
data_format = tf.keras.backend.image_data_format()
if data_format == 'channels_first':
# If channels are first, move them to the last dimension
x = tf.transpose(x, perm=[0, 2, 3, 1])
# Mean subtraction (ImageNet means in BGR order)
mean = [103.939, 116.779, 123.68]
x = x - tf.constant(mean, dtype=x.dtype)
# Zero-centering by subtracting 127.5
x = x / 127.5
return x
inputs = tf.keras.Input(shape=(224, 224, 3))
x = data_augmentation(inputs)
x = manual_preprocess_input(
x
)
x = base_model(x, training=False)
x = global_average_layer(x)
x = tf.keras.layers.Dropout(0.2)(x)
outputs = prediction_layer(x)
model = tf.keras.Model(inputs, outputs)
And here is the view code where I loaded my model:
def testSkinCancer(request):
model = tf.keras.models.load_model(
os.getcwd()+r'\media\my_model.keras', safe_mode=False)
print(">>> model loaded")
if not request.FILES:
return HttpResponseBadRequest(json.dumps({'error': 'No image uploaded'}))
# Access the uploaded image directly
uploaded_image = request.FILES['image']
username = request.POST['username']
user = User.objects.get(username=username)
# Save the image to the database
image_model = SkinImage.objects.create(user=user, image=uploaded_image)
img_path = r'images/{0}'.format(uploaded_image)
img = keras.utils.load_img(img_path, target_size=(224, 224))
x = keras.utils.img_to_array(img)
x = np.expand_dims(x, axis=0)
predictions = model.predict(x)
# You can perform additional processing here (e.g., resize, convert format)
# Optionally, return a response to the client
response_data = {'message': 'Image uploaded successfully'}
return JsonResponse(response_data)
Then I saved it using model.save('my_model.keras')
, then I loaded in a Django view but the problem is whenever I load it and make post request to the view, in the line where I load the model I encounter this error:
TypeError: Could not deserialize class 'Functional' because its parent module keras.src.models.functional cannot be imported.
What is the problem and how to resolve it?
Upvotes: 1
Views: 1257