<jupyter_start><jupyter_text><jupyter_code>#@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.<jupyter_output><empty_output><jupyter_text>**Things to Note:**1. When coding the `class myCallback`, Python 3 will run into an error```pythonTypeError: '>' not supported between instances of 'NoneType' and 'float'```when using the code```pythonif(logs.get('accuracy')>0.99):```For Python 3, use the following equivalent code line```pythonif logs.get('accuracy') is not None and logs.get('accuracy') > 0.99:```2. You can run the notebook using TensorFlow 2.5.0<jupyter_code>#!pip install tensorflow==2.5.0
# this is used in downloading data from the google drive
#!pip install gdown<jupyter_output><empty_output><jupyter_text>Below is code with a link to a happy or sad dataset which contains 80 images, 40 happy and 40 sad. Create a convolutional neural network that trains to 100% accuracy on these images,  which cancels training upon hitting training accuracy of >.999Hint -- it will work best with 3 convolutional layers.<jupyter_code>import tensorflow as tf
import os
import zipfile

!gdown --id 1NvV6VhmrfU8JDZNoEbwJxwx_6dhyN5bf 

zip_ref = zipfile.ZipFile("./happy-or-sad.zip", 'r')
zip_ref.extractall("./h-or-s")
zip_ref.close()
# GRADED FUNCTION: train_happy_sad_model
def train_happy_sad_model():
    # Please write your code only where you are indicated.
    # please do not remove # model fitting inline comments.

    DESIRED_ACCURACY = 0.999

    class myCallback(tf.keras.callbacks.Callback): # YOUR CODE HERE):
        
        # YOUR CODE START HERE
        
        def on_epoch_end(self, epoch, logs={}):
            if logs.get('accuracy') is not None and logs.get('accuracy') > DESIRED_ACCURACY:
                print("\nReached 99.9% accuracy so cancelling training!")
                self.model.stop_training = True
         
        
        # YOUR CODE END HERE
        
    callbacks = myCallback()
    
    # This Code Block should Define and Compile the Model. Please assume the images are 150 X 150 in your implementation.
    model = tf.keras.models.Sequential([
    tf.keras.layers.Conv2D(16, (3,3), activation='relu', input_shape=(150, 150, 3)), # YOUR CODE HERE,
    tf.keras.layers.MaxPooling2D(2, 2), # YOUR CODE HERE,
    tf.keras.layers.Conv2D(32, (3,3), activation='relu'), # YOUR CODE HERE,
    tf.keras.layers.MaxPooling2D(2,2), # YOUR CODE HERE,
    tf.keras.layers.Conv2D(32, (3,3), activation='relu'), # YOUR CODE HERE
    tf.keras.layers.MaxPooling2D(2,2), # YOUR CODE HERE
    tf.keras.layers.Flatten(), # YOUR CODE HERE
    tf.keras.layers.Dense(512, activation='relu'), # YOUR CODE HERE
    tf.keras.layers.Dense(1, activation='sigmoid') # YOUR CODE HERE
    ])

    from tensorflow.keras.optimizers import RMSprop

    model.compile(loss='binary_crossentropy', # YOUR CODE HERE,
                  optimizer=RMSprop(learning_rate=0.001), # YOUR CODE HERE,
                  metrics=['accuracy']) # YOUR CODE HERE)
    
    # This code block should create an instance of an ImageDataGenerator called train_datagen 
    # And a train_generator by calling train_datagen.flow_from_directory

    from tensorflow.keras.preprocessing.image import ImageDataGenerator

    train_datagen = ImageDataGenerator(rescale=1/255) # YOUR CODE HERE

    # Please use a target_size of 150 X 150.
    train_generator = train_datagen.flow_from_directory( "./h-or-s", # YOUR CODE HERE
                                                        target_size=(150, 150), # YOUR CODE HERE
                                                        batch_size=10, # YOUR CODE HERE
                                                        class_mode='binary') # YOUR CODE HERE
    # Expected output: 'Found 80 images belonging to 2 classes'

    # This code block should call model.fit_generator and train for
    # a number of epochs.
    # model fitting
    history = model.fit(train_generator, # YOUR CODE HERE,
                        steps_per_epoch=8, # YOUR CODE HERE,
                        epochs=15, # YOUR CODE HERE,
                        verbose=1, # YOUR CODE HERE,
                        callbacks=[callbacks] # YOUR CODE HERE,
                       )
    
    return history.history['accuracy'][-1]
train_happy_sad_model()<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.09507853403141361, 'fraction_numerical': 0.02429319371727749, 'mean_word_length': 2.943848059454996, 'pattern_counts': {'":': 0, '<': 13, '<?xml version=': 0, '>': 18, 'https://': 1, 'lorem ipsum': 0, 'www.': 1, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 7, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '3', 'dir': 'jupyter-structured-clean-dedup', 'id': '205118', 'license': 'MIT', 'n_tokens_mistral': 1517, 'n_tokens_neox': 1361, 'n_words': 454, 'path': 'C1/W4/assignment/C1_W4_Assignment_Solution.ipynb', 'repo_name': 'aiwithqasim/TensorFlow-Ceritfication', 'size': '4775'}