mrdbourke / tensorflow-deep-learning

All course materials for the Zero to Mastery Deep Learning with TensorFlow course.
https://dbourke.link/ZTMTFcourse
MIT License
5.14k stars 2.53k forks source link

Issue with Tensorflow: Import "tensorflow.keras" could not be resolved #381

Open kelixirr opened 2 years ago

kelixirr commented 2 years ago

Hi, I am trying to use image augmentation and getting this issue. Although codes are running, data is not being augmented. Do you think this is some bug in Tensorflow?

Here is the code from Video 165

import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
from tensorflow.keras.layers.experimental import preprocessing

# Create a data augmentation stage with horizontal flipping, rotations, zooms
data_augmentation = keras.Sequential([
  preprocessing.RandomFlip("horizontal"),
  preprocessing.RandomRotation(0.2),
  preprocessing.RandomZoom(0.2),
  preprocessing.RandomHeight(0.2),
  preprocessing.RandomWidth(0.2),
], name ="data_augmentation")
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import os
import random
target_class = random.choice(train_data_1_percent.class_names) # choose a random class
target_dir = "10_food_classes_1_percent/train/" + target_class # create the target directory
random_image = random.choice(os.listdir(target_dir)) # choose a random image from target directory
random_image_path = target_dir + "/" + random_image # create the choosen random image path
img = mpimg.imread(random_image_path) # read in the chosen target image
plt.imshow(img) # plot the target image
plt.title(f"Original random image from class: {target_class}")
plt.axis(False); # turn off the axes

# Augment the image
augmented_img = data_augmentation(tf.expand_dims(img, axis=0)) # data augmentation model requires shape (None, height, width, 3)
plt.figure()
plt.imshow(tf.squeeze(augmented_img)/255.) # requires normalization after augmentation
plt.title(f"Augmented random image from class: {target_class}")
plt.axis(False);

The output of the plt.imshow() is same for both img and augmented_img.

undisputedcoder commented 2 years ago

@kelixirr Did you include data_augmentation in your Sequential model as a layer?

mrdbourke commented 2 years ago

Hello @kelixirr,

Can try running it with:

training=True

For example,

augmented_img = data_augmentation(img, training=True)

See more of an example here: https://github.com/mrdbourke/tensorflow-deep-learning/discussions/369#discussion-4003365