Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Chapter 6: resizing notebook giving error: #11

Open
andysingal opened this issue Jun 4, 2023 · 1 comment
Open

Chapter 6: resizing notebook giving error: #11

andysingal opened this issue Jun 4, 2023 · 1 comment

Comments

@andysingal
Copy link

Hi,
I was running code:

import tensorflow_hub as hub
import os
# Load compressed models from tensorflow_hub
os.environ['TFHUB_MODEL_LOAD_FORMAT'] = 'COMPRESSED'

preproc_layers = tf.keras.Sequential([
    tf.keras.layers.Lambda(lambda img:
                           tf.image.resize_with_pad(
                               img, 2*IMG_HEIGHT, 2*IMG_WIDTH),
                           input_shape=(None, None, 3)),
    tf.keras.layers.experimental.preprocessing.CenterCrop(
        height=IMG_HEIGHT, width=IMG_WIDTH)
    ])

def apply_preproc(img, label):
    # add to a batch, call preproc, remove from batch
    x = tf.expand_dims(img, 0)
    x = preproc_layers(x)
    x = tf.squeeze(x, 0)
    return x, label

# parameterize to the values in the previous cell
def train_and_evaluate(batch_size = 32,
                       lrate = 0.001,
                       l1 = 0.,
                       l2 = 0.,
                       num_hidden = 16):
  regularizer = tf.keras.regularizers.l1_l2(l1, l2)

  train_dataset = tf.data.TFRecordDataset(
    [filename for filename in tf.io.gfile.glob(
        'gs://practical-ml-vision-book/flowers_tfr/train-*')
    ],
    compression_type='GZIP'
  ).map(parse_tfr).map(apply_preproc).batch(batch_size)

  eval_dataset = tf.data.TFRecordDataset(
    [filename for filename in tf.io.gfile.glob(
        'gs://practical-ml-vision-book/flowers_tfr/valid-*')
    ],
    compression_type='GZIP'
  ).map(parse_tfr).map(apply_preproc).batch(batch_size)

  layers = [
      hub.KerasLayer(
          "https://tfhub.dev/google/tf2-preview/mobilenet_v2/feature_vector/4",
          input_shape=(IMG_HEIGHT, IMG_WIDTH, IMG_CHANNELS),
          trainable=False,
          name='mobilenet_embedding'),
      tf.keras.layers.Dense(num_hidden,
                            kernel_regularizer=regularizer, 
                            activation=tf.keras.activations.relu,
                            name='dense_hidden'),
      tf.keras.layers.Dense(len(CLASS_NAMES), 
                            kernel_regularizer=regularizer,
                            activation='softmax',
                            name='flower_prob')
  ]

  model = tf.keras.Sequential(layers, name='flower_classification')
  model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=lrate),
                loss=tf.keras.losses.SparseCategoricalCrossentropy(
                    from_logits=False),
                metrics=['accuracy'])
  print(model.summary())
  history = model.fit(train_dataset, validation_data=eval_dataset, epochs=10)
  training_plot(['loss', 'accuracy'], history)
  return model

and got the following error:

ValueError Traceback (most recent call last)
in <cell line: 1>()
----> 1 model = train_and_evaluate()

20 frames
/usr/local/lib/python3.10/dist-packages/tensorflow/python/framework/ops.py in _create_c_op(graph, node_def, inputs, control_inputs, op_def, extract_traceback)
1971 except errors.InvalidArgumentError as e:
1972 # Convert to ValueError for backwards compatibility.
-> 1973 raise ValueError(e.message)
1974
1975 # Record the current Python stack trace as the creating stacktrace of this

ValueError: in user code:

File "<ipython-input-29-30d7b53cf7ed>", line 19, in apply_preproc  *
    x = tf.squeeze(x, 0)

ValueError: Can not squeeze dim[0], expected a dimension of 1, got 224 for '{{node Squeeze}} = Squeeze[T=DT_FLOAT, squeeze_dims=[0]](sequential_5/center_crop_3/cond/Identity)' with input shapes: [224,224,?].

Even though the code is good in your book but contains several errors.

I hope you can assist in fixing the error.
Thanks,
Ankush Singal

@hariharan382
Copy link

hi can you say what notebook are you using?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants