I am trying to build a model for crop identification and keep getting this error:
import tensorflow as tf
import tensorflow_hub as hub
#Read crop details
import pandas as pd
crop_details_csv = pd.read_excel('/content/drive/MyDrive/Crop Identification/Crop_details.xlsx')
crop_details_csv.head()
#Get imamges filepaths
filename = ['drive/MyDrive/Crop Identification/Train2/' + fname for fname in crop_details_csv['path']]
import numpy as np
labels = crop_details_csv['croplabel']
labels=np.array(labels)
#if len(labels)==len(filename):
#print('Yes')
#else:
#print('NO')
unique_labels = np.unique(labels)
unique_labels
boolean_labels = [label == unique_labels for label in labels]#turn labels to numbers
#Split our data and creating Validation set
x = filename
y = boolean_labels
#Get validation set
from sklearn.model_selection import train_test_split
x_train,x_val,y_train,y_val=train_test_split(x,y,test_size=0.2,random_state=42)
#Turn Images to tensors
image_size=224
def preprocess_image(image_path,image_size=image_size):
#read an image file
image= tf.io.read_file(image_path)
#turn image into numerical tensors with RGB
image = tf.image.decode_jpeg(image,channels=3)
#convert color values from 0-255 to 0-1 #Normaliization
image = tf.image.convert_image_dtype(image,tf.float32)
#resize image to 224,224
image = tf.image.resize(image,size=[image_size,image_size])
return image
#Turn Data into batches
#Returns tuple (image,label)
def get_image_label(image_path,label):
image = preprocess_image(image_path)
return image,label
Batch_size=32
def create_batches(x,y=None,batch_size=Batch_size,valid_data=False,test_data=False):
if test_data:#test data has no labels
data= tf.data.Dataset.from_tensor_slices((tf.constant(x)))#no labels
data_batch = data.map(preprocess_image).batch(Batch_size)
return data_batch
elif valid_data:#no shuffling for valid data
data= tf.data.Dataset.from_tensor_slices((tf.constant(x),(tf.constant(y))))
data_batch = data.map(get_image_label).batch(Batch_size)
return data_batch
else:
data= tf.data.Dataset.from_tensor_slices((tf.constant(x),(tf.constant(y))))
data= data.shuffle(buffer_size=len(x))#shuffle for training data
data= data.map(get_image_label)
data_batch=data.batch(Batch_size)
return data_batch
train_data=create_batches(x_train,y_train)
val_data=create_batches(x_val,y_val,valid_data=True)
input_shape=[None,image_size,image_size,3]#batch ,height ,width , color channels
output_shape= len(unique_labels)
model_URL = "https://tfhub.dev/google/imagenet/mobilenet_v2_035_128/classification/5"
def create_model(input_shape=input_shape,output_shape=output_shape,model_URL=model_URL):
#model layers setup
model = tf.keras.Sequential([hub.KerasLayer(model_URL),#input layer
tf.keras.layers.Dense(units=output_shape,activation='softmax')])#output layer
#compile model
model.compile(loss=tf.keras.losses.CategoricalCrossentropy(),
optimizer=tf.keras.optimizers.Adam(),
metrics=['accuracy'])
#Build model
model.build(input_shape)
return model
model = create_model()
-----------------------------------------------------------------
----------
ValueError Traceback (most recent call last)
<ipython-input-14-0fd4f47c95c0> in <module>()
----> 1 model = create_model()
2 model.summary()
5 frames
/usr/local/lib/python3.7/dist-packages/tensorflow/python/autograph/impl/api.py in wrapper(*args, **kwargs)
697 except Exception as e: # pylint:disable=broad-except
698 if hasattr(e, 'ag_error_metadata'):
--> 699 raise e.ag_error_metadata.to_exception(e)
700 else:
701 raise
ValueError: Exception encountered when calling layer "keras_layer" (type KerasLayer).
in user code:
File "/usr/local/lib/python3.7/dist-packages/tensorflow_hub/keras_layer.py", line 237, in call *
result = smart_cond.smart_cond(training,
ValueError: Could not find matching concrete function to call loaded from the SavedModel. Got:
Positional arguments (4 total):
* Tensor("inputs:0", shape=(224, 224, 3), dtype=float32)
* False
* False
* 0.99
Keyword arguments: {}
Expected these arguments to match one of the following 4 option(s):
Option 1:
Positional arguments (4 total):
* TensorSpec(shape=(None, 128, 128, 3), dtype=tf.float32, name='inputs')
* True
* True
* TensorSpec(shape=(), dtype=tf.float32, name='batch_norm_momentum')
Keyword arguments: {}
Option 2:
Positional arguments (4 total):
* TensorSpec(shape=(None, 128, 128, 3), dtype=tf.float32, name='inputs')
* True
* False
* TensorSpec(shape=(), dtype=tf.float32, name='batch_norm_momentum')
Keyword arguments: {}
Option 3:
Positional arguments (4 total):
* TensorSpec(shape=(None, 128, 128, 3), dtype=tf.float32, name='inputs')
* False
* True
* TensorSpec(shape=(), dtype=tf.float32, name='batch_norm_momentum')
Keyword arguments: {}
Option 4:
Positional arguments (4 total):
* TensorSpec(shape=(None, 128, 128, 3), dtype=tf.float32, name='inputs')
* False
* False
* TensorSpec(shape=(), dtype=tf.float32, name='batch_norm_momentum')
Keyword arguments: {}
Call arguments received:
• inputs=tf.Tensor(shape=(224, 224, 3), dtype=float32)
• training=None