Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
https-deeplearning-ai

Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.

GitHub Repository: https-deeplearning-ai/tensorflow-1-public
Path: blob/main/C1/W1/assignment/C1W1_Assignment.ipynb
Views: 2336
Kernel: Python 3 (ipykernel)

Week 1 Assignment: Housing Prices

In this exercise you'll build a neural network that predicts the price of a house according to a simple formula.

Imagine that house pricing is as easy as:

A house has a base cost of 50k, and every additional bedroom adds a cost of 50k. This will make a 1 bedroom house cost 100k, a 2 bedroom house cost 150k etc.

How would you create a neural network that learns this relationship so that it would predict a 7 bedroom house as costing close to 400k etc.

Hint: Your network might work better if you scale the house price down. You don't have to give the answer 400...it might be better to create something that predicts the number 4, and then your answer is in the 'hundreds of thousands' etc.

TIPS FOR SUCCESSFUL GRADING OF YOUR ASSIGNMENT:

  • All cells are frozen except for the ones where you need to submit your solutions or when explicitly mentioned you can interact with it.

  • You can add new cells to experiment but these will be omitted by the grader, so don't rely on newly created cells to host your solution code, use the provided places for this.

  • You can add the comment # grade-up-to-here in any graded cell to signal the grader that it must only evaluate up to that point. This is helpful if you want to check if you are on the right track even if you are not done with the whole assignment. Be sure to remember to delete the comment afterwards!

  • Avoid using global variables unless you absolutely have to. The grader tests your code in an isolated environment without running all cells from the top. As a result, global variables may be unavailable when scoring your submission. Global variables that are meant to be used will be defined in UPPERCASE.

  • To submit your notebook, save it and then click on the blue submit button at the beginning of the page.

import numpy as np import tensorflow as tf
import unittests

Exercise 1: create_training_data

Your first task is to create the data that your model will be trained on. Use the scenario presented at the top of this notebook where a 1-bedroom house costs 100k, and increases by 50k for each additional bedroom.

To generate the training data (aka the features and the targets), you will use numpy to create a one-dimensional tensor with the number of bedrooms and another one-dimensional tensor with the corresponding price in hundreds of thousands of dollars (e.g. 1.0 means 100k). In this case, the number of bedrooms will be the features, which the network will try to map to the target of the prices. These tensors (or numpy arrays) should have six elements which will be the values (number of bedrooms and price in hundreds of thousands) for houses with 1 up to 6 bedrooms.

Hints:

  • Even if the number of bedrooms can be thought of as an integer, define these values as floats to account for scenarios such as half a bedroom.

  • The price should also be a float since currency is tipically defined as such.

# GRADED FUNCTION: create_training_data def create_training_data(): """Creates the data that will be used for training the model. Returns: (numpy.ndarray, numpy.ndarray): Arrays that contain info about the number of bedrooms and price in hundreds of thousands for 6 houses. """ ### START CODE HERE ### # Define feature and target tensors with the values for houses with 1 up to 6 bedrooms. # For this exercise, please arrange the values in ascending order (i.e. 1, 2, 3, and so on). # Hint: Remember to explictly set the dtype as float when defining the numpy arrays n_bedrooms = None price_in_hundreds_of_thousands = None ### END CODE HERE ### return n_bedrooms, price_in_hundreds_of_thousands
features, targets = create_training_data() print(f"Features have shape: {features.shape}") print(f"Targets have shape: {targets.shape}")

Expected Output:

Features have shape: (6,) Targets have shape: (6,)
# Test your code! unittests.test_create_training_data(create_training_data)

Exercise 2: define_and_compile_model

Your second task is to define the architecture of your model and compile it.

For this particular task your model should be made up of a single dense layer with 1 unit and when compiling it, use:

  • Stochastic Gradient Descent as the optimizer

  • Mean Squared Error as the loss function

Remember that the training data is one-dimensional, so use this information when defining the shape of the Input.

In case you need some extra help, be sure to check the docs for tf.keras.Input and tf.keras.layers.Dense

# GRADED FUNCTION: define_and_compile_model def define_and_compile_model(): """Returns the compiled (but untrained) model. Returns: tf.keras.Model: The model that will be trained to predict house prices. """ ### START CODE HERE ### # Define your model model = tf.keras.Sequential([ # Define the Input with the appropriate shape None, # Define the Dense layer None ]) # Compile your model model.compile(optimizer=None, loss=None) ### END CODE HERE ### return model
untrained_model = define_and_compile_model() untrained_model.summary()

Expected Output:

Model: "sequential" ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━┓ ┃ Layer (type) ┃ Output Shape ┃ Param # ┃ ┡━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━┩ │ dense (Dense) │ (None, 1) │ 2 │ └─────────────────────────────────┴────────────────────────┴───────────────┘ Total params: 2 (8.00 B) Trainable params: 2 (8.00 B) Non-trainable params: 0 (0.00 B)
# Test your code! unittests.test_define_and_compile_model(define_and_compile_model)

Exercise 3: train_model

With your model and the training data ready now it is time to train your model. You will feed this training data into the model so it can learn the relationship between the number of bedrooms and the price of the houses. For this you will use Tensorflow model's fit method.

After training you will test your network with a 7-bedroom house to see if it is able to accurately predict its price.

# GRADED FUNCTION: train_model def train_model(): """Returns the trained model. Returns: tf.keras.Model: The trained model that will predict house prices. """ ### START CODE HERE ### # Define feature and target tensors with the values for houses with 1 up to 6 bedrooms # Hint: Remember you already coded a function that does this! n_bedrooms, price_in_hundreds_of_thousands = None # Define a compiled (but untrained) model # Hint: Remember you already coded a function that does this! model = None # Train your model for 500 epochs by feeding the training data model.fit(None, None, epochs=None) ### END CODE HERE ### return model

Now that you have a function that returns a compiled and trained model when invoked, use it to get the model to predict the price of houses:

# Get your trained model trained_model = train_model()

Expected Output:

Values of loss function don't need to be exact to these values

Epoch 1/500 1/1 [==============================] - 0s 409ms/step - loss: 14.7905 Epoch 2/500 1/1 [==============================] - 0s 5ms/step - loss: 6.8536 Epoch 3/500 1/1 [==============================] - 0s 7ms/step - loss: 3.1801 ... ... ... 1/1 [==============================] - 0s 12ms/step - loss: 1.0113e-07 Epoch 500/500 1/1 [==============================] - 0s 12ms/step - loss: 1.0038e-07

Now that your model has finished training it is time to test it out! You can do so by running the next cell.

new_n_bedrooms = np.array([7.0]) predicted_price = trained_model.predict(new_n_bedrooms, verbose=False).item() print(f"Your model predicted a price of {predicted_price:.2f} hundreds of thousands of dollars for a {int(new_n_bedrooms.item())} bedrooms house")

Expected Output:

Values of loss function don't need to be exact to these values

Your model predicted a price of 4.03 hundreds of thousands of dollars for a 7 bedrooms house

The price doesn't need to exactly match this one but it should be close to 4.

# Test your code! unittests.test_trained_model(trained_model)

If everything went as expected you should see a prediction value very close to 4. If not, try adjusting your code before submitting the assignment. Notice that you can play around with the value of new_n_bedrooms to get different predictions. In general you should see that the network was able to learn the linear relationship between n_bedrooms and price_in_hundreds_of_thousands, so if you use a value of 8.0 you should get a prediction close to 4.5 and so on.

Congratulations on finishing this week's assignment!

You have successfully coded a neural network that learned the linear relationship between two variables. Nice job!

Keep it up!