ValueError:找不到匹配的具体函数来调用从 SavedModel 加载的函数

kim*_*kim 5 python classification machine-learning keras tensorflow

我正在尝试建立一个作物识别模型,但不断收到此错误:

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

小智 0

我能够使用农业作物图像数据集复制该错误。您必须将图像大小从 224 更改为 128,因为mobilenet_v2_035_128模型采用的输入大小为(128, 128, 3)

请参阅此要点以获取工作代码。谢谢你!