"This notebook calculates a logistic regression using Keras. It's basically meant to show the principles of Keras.\n",
"\n",
"### Background\n",
"\n",
"The Space Shuttle Challenger exploded 73 second after liftoff on January 28th, 1986. The disaster claimed the lives of all seven astronauts on board, including school teacher Christa McAuliffe.\n",
"\n",
"The details surrounding this disaster were very involved. For the purposes of this analysis, it is sufficient to point out that engineers that manufactured the large boosters that launched the rocket were aware of the possible failures that could happen during cold temperatures. They tried to prevent the launch, but were ultimately ignored and disaster ensued.\n",
"\n",
"The main concern of engineers in launching the Challenger was the evidence that the large O-rings sealing the several sections of the boosters could fail in cold temperatures.\n",
"\n",
"\n",
"### Datset\n",
"\n",
"We investigate the data set of the challenger flight with broken O-rings (`Y=1`) versus start temperature."
"The lowest temperature of any of the 23 prior launches (before the Challenger explosion) was 53° F. This is evident in the data set shown below. Engineers prior to the Challenger launch suggested that the launch not be attempted below 53°. The “evidence” that the o-rings could fail below 53° was based on a simple conclusion that since the launch at 53° experienced two o-ring failures, it seemed unwise to launch below that temperature. In the following analysis we demonstrate more fully how dangerous it was to launch on this specific day where the outside temperature at the time of the launch was 31°.\n",
"\n",
"The `Broken O-rings` column in the data set below records whether O-rings experienced failures during that particular launch - if they did, the value for `Broken O-rings` is 1. The `Temperature [F]` column lists the outside temperature at the time of launch.\n",
"\n",
"### Goal of Analysis\n",
"\n",
"We investigate the data set of the challenger flight with broken O-rings (`Y=1`) vs start temperature.§"
]
},
{
...
...
%% Cell type:markdown id: tags:
# Exercise 1 : Conversion from Celsius to Fahrenheit (Simple Regression Analysis)
%% Cell type:markdown id: tags:
The problem we will solve is to convert from Celsius to Fahrenheit, where the approximate formula is:
$$ f = c \times 1.8 + 32 $$
Of course, it would be simple enough to create a conventional Python function that directly performs this calculation, but that wouldn't be machine learning.
Instead, we will give TensorFlow some sample Celsius values (0, 8, 15, 22, 38) and their corresponding Fahrenheit values (32, 46, 59, 72, 100).
Then, we will train a model that figures out the above formula through the training process. This is a _simple regression analysis_ problem.
%% Cell type:markdown id: tags:
## Import dependencies
First, import TensorFlow. Here, we're calling it `tf` for ease of use. We also tell it to only display errors.
Next, import [NumPy](http://www.numpy.org/) as `np`. Numpy helps us to represent our data as highly performant lists.
As we saw before, supervised Machine Learning is all about figuring out an algorithm given a set of inputs and outputs. Since the task in this Codelab is to create a model that can give the temperature in Fahrenheit when given the degrees in Celsius, we create two lists `celsius_q` and `fahrenheit_a` that we can use to train our model.
-**Feature** — The input(s) to our model. In this case, a single value — the degrees in Celsius.
-**Labels/response variable** — The output our model predicts. In this case, a single value — the degrees in Fahrenheit. In a classification setting, we would predict labels (discrete classes), in a regression setting, we predict a continuous response variable, such as Fahrenheit.
-**Example** — A pair of inputs/outputs used during training. In our case a pair of values from `celsius_q` and `fahrenheit_a` at a specific index, such as `(22,72)`.
%% Cell type:markdown id: tags:
## 1. Define the Network
Next create the model. We will use simplest possible model we can, a Dense network. Since the problem is straightforward, this network will require only a single layer, with a single neuron.
### Build a layer
We'll call the layer `l0` and create it by instantiating `tf.keras.layers.Dense` with the following configuration:
*`input_shape=[1]` — This specifies that the input to this layer is a single value. That is, the shape is a one-dimensional array with one member. Since this is the first (and only) layer, that input shape is the input shape of the entire model. The single value is a floating point number, representing degrees Celsius.
*`units=1` — This specifies the number of neurons in the layer. The number of neurons defines how many internal variables the layer has to try to learn how to solve the problem (more later). Since this is the final layer, it is also the size of the model's output — a single float value representing degrees Fahrenheit. (In a multi-layered network, the size and shape of the layer would need to match the `input_shape` of the next layer.)
%% Cell type:code id: tags:
``` python
l0=tf.keras.layers.Dense(units=1,input_shape=[1])
```
%% Cell type:markdown id: tags:
### Assemble layers into the model
Once layers are defined, they need to be assembled into a model. The Sequential model definition takes a list of layers as argument, specifying the calculation order from the input to the output.
This model has just a single layer, l0.
%% Cell type:code id: tags:
``` python
model=<---------YourCodehere-------------->
```
%% Cell type:markdown id: tags:
## 2. Compile the network, with loss and optimizer functions
Before training, the model has to be compiled. When compiled for training, the model is given:
-**Loss function** — A way of measuring how far off predictions are from the desired outcome. (The measured difference is called the "loss".)
-**Optimizer function** — A way of adjusting internal values in order to reduce the loss.
%% Cell type:markdown id: tags:
model.compile(loss='mean_squared_error',
optimizer=tf.keras.optimizers.Adam(0.1))
%% Cell type:markdown id: tags:
These are used during training (`model.fit()`, below) to first calculate the loss at each point, and then improve it. In fact, the act of calculating the current loss of a model and then improving it is precisely what training is.
During training, the optimizer function is used to calculate adjustments to the model's internal variables. The goal is to adjust the internal variables until the model (which is really a math function) mirrors the actual equation for converting Celsius to Fahrenheit.
TensorFlow uses numerical analysis to perform this tuning, and all this complexity is hidden from you so we will not go into the details here. What is useful to know about these parameters are:
The loss function ([mean squared error](https://en.wikipedia.org/wiki/Mean_squared_error)) and the optimizer ([Adam](https://machinelearningmastery.com/adam-optimization-algorithm-for-deep-learning/)) used here are standard for simple models like this one, but many others are available. It is not important to know how these specific functions work at this point.
One part of the Optimizer you may need to think about when building your own models is the learning rate (`0.1` in the code above). This is the step size taken when adjusting values in the model. If the value is too small, it will take too many iterations to train the model. Too large, and accuracy goes down. Finding a good value often involves some trial and error, but the range is usually within 0.001 (default), and 0.1
%% Cell type:markdown id: tags:
## 3. Fit the model
Train the model by calling the `fit` method.
During training, the model takes in Celsius values, performs a calculation using the current internal variables (called "weights") and outputs values which are meant to be the Fahrenheit equivalent. Since the weights are initially set randomly, the output will not be close to the correct value. The difference between the actual output and the desired output is calculated using the loss function, and the optimizer function directs how the weights should be adjusted.
This cycle of calculate, compare, adjust is controlled by the `fit` method. The first argument is the inputs, the second argument is the desired outputs. The `epochs` argument specifies how many times this cycle should be run, and the `verbose` argument controls how much output the method produces.
## 4. Evaluate the Model - Display training statistics
The `fit` method returns a history object. We can use this object to plot how the loss of our model goes down after each training epoch. A high loss means that the Fahrenheit degrees the model predicts is far from the corresponding value in `fahrenheit_a`.
We'll use [Matplotlib](https://matplotlib.org/) to visualize this (you could use another tool). As you can see, our model improves very quickly at first, and then has a steady, slow improvement until it is very near "perfect" towards the end.
%% Cell type:code id: tags:
``` python
importmatplotlib.pyplotasplt
plt.xlabel('Epoch Number')
plt.ylabel("Loss Magnitude")
plt.plot(history.history['loss'])
```
%% Cell type:markdown id: tags:
## 5. Use the model to predict values
Now you have a model that has been trained to learn the relationship between `celsius_q` and `fahrenheit_a`. You can use the predict method to have it calculate the Fahrenheit degrees for a previously unknown Celsius degrees.
So, for example, if the Celsius value is 100, what do you think the Fahrenheit result will be? Take a guess before you run this code.
%% Cell type:code id: tags:
``` python
print(model.predict(<----yourcodehere---->))
```
%% Cell type:markdown id: tags:
The correct answer is $100 \times 1.8 + 32 = 212$, so our model is doing really well.
### To review
* We created a model with a Dense layer
* We trained it with 3500 examples (7 pairs, over 500 epochs).
Our model tuned the variables (weights) in the Dense layer until it was able to return the correct Fahrenheit value for any Celsius value. (Remember, 100 Celsius was not part of our training data.)
%% Cell type:markdown id: tags:
## Looking at the layer weights
Finally, let's print the internal variables of the Dense layer.
%% Cell type:code id: tags:
``` python
print("These are the layer variables: {}".format(l0.get_weights()))
```
%% Cell type:markdown id: tags:
The first variable is close to ~1.8 and the second to ~32. These values (1.8 and 32) are the actual variables in the real conversion formula.
This is really close to the values in the conversion formula. We'll explain this in an upcoming video where we show how a Dense layer works, but for a single neuron with a single input and a single output, the internal math looks the same as [the equation for a line](https://en.wikipedia.org/wiki/Linear_equation#Slope%E2%80%93intercept_form), $y = mx + b$, which has the same form as the conversion equation, $f = 1.8c + 32$.
Since the form is the same, the variables should converge on the standard values of 1.8 and 32, which is exactly what happened.
With additional neurons, additional inputs, and additional outputs, the formula becomes much more complex, but the idea is the same.
### A little experiment
Just for fun, what if we created more Dense layers with different units, which therefore also has more variables?
print("Model predicts that 100 degrees Celsius is: {} degrees Fahrenheit".format(model.predict([100.0])))
print("These are the l0 variables: {}".format(l0.get_weights()))
print("These are the l1 variables: {}".format(l1.get_weights()))
print("These are the l2 variables: {}".format(l2.get_weights()))
```
%% Cell type:markdown id: tags:
As you can see, this model is also able to predict the corresponding Fahrenheit value really well. But when you look at the variables (weights) in the `l0` and `l1` layers, they are nothing even close to ~1.8 and ~32. The added complexity hides the "simple" form of the conversion equation.
%% Cell type:markdown id: tags:
# Exercise 2 : O-Rings seen with Logistic Regression
%% Cell type:markdown id: tags:
This notebook calculates a logistic regression using Keras. It's basically meant to show the principles of Keras.
### Background
The Space Shuttle Challenger exploded 73 second after liftoff on January 28th, 1986. The disaster claimed the lives of all seven astronauts on board, including school teacher Christa McAuliffe.
The details surrounding this disaster were very involved. For the purposes of this analysis, it is sufficient to point out that engineers that manufactured the large boosters that launched the rocket were aware of the possible failures that could happen during cold temperatures. They tried to prevent the launch, but were ultimately ignored and disaster ensued.
The main concern of engineers in launching the Challenger was the evidence that the large O-rings sealing the several sections of the boosters could fail in cold temperatures.
### Datset
We investigate the data set of the challenger flight with broken O-rings (`Y=1`) versus start temperature.
The lowest temperature of any of the 23 prior launches (before the Challenger explosion) was 53° F. This is evident in the data set shown below. Engineers prior to the Challenger launch suggested that the launch not be attempted below 53°. The “evidence” that the o-rings could fail below 53° was based on a simple conclusion that since the launch at 53° experienced two o-ring failures, it seemed unwise to launch below that temperature. In the following analysis we demonstrate more fully how dangerous it was to launch on this specific day where the outside temperature at the time of the launch was 31°.
The `Broken O-rings` column in the data set below records whether O-rings experienced failures during that particular launch - if they did, the value for `Broken O-rings` is 1. The `Temperature [F]` column lists the outside temperature at the time of launch.
### Goal of Analysis
We investigate the data set of the challenger flight with broken O-rings (`Y=1`) vs start temperature.§
If we have more than one data point, which we usually do, we have to apply the equation above to each of the N data points. In this case we can used a vectorized version with $x=(x_1,x_2,\ldots,x_N)$ and $y=(y_1,y_2,\ldots,y_N$)
%% Cell type:markdown id: tags:
### Numpy code
This numpy code, shows the calculation for one value using numpy (like a single forward pass)
<tensorflow.python.keras.callbacks.History at 0x14081c048>
%% Cell type:code id: tags:
``` python
plt.plot(data[:,0],data[:,1],'o')
plt.axis([40,85,-0.1,1.2])
x_pred=np.linspace(40,85)
x_pred=np.resize(x_pred,[len(x_pred),1])
y_pred=<----yourcodehere---->
plt.plot(x_pred,y_pred)
```
%% Cell type:markdown id: tags:
# Exercise 3 : MNIST and Multinomial Logistic Regression
%% Cell type:markdown id: tags:
In this exercise we use multinomial logistic regression to predict the handwritten digits of the MNIST dataset.
%% Cell type:markdown id: tags:
## TODO : read MNIST data and compute validation accuracy for a multinomial logistic regression model, see [Multinomial Logistic Regression](https://en.wikipedia.org/wiki/Multinomial_logistic_regression)
If there are several labels, then we use `categorical_crossentropy` as loss function and the output layer should be a `softmax` layer.
The prices are typically between 10000 and 50000 USD. If that sounds cheap, remember
that this was the mid-1970s, and these prices aren’t adjusted for inflation.
%% Cell type:markdown id: tags:
### Preparing the data
It would be problematic to feed into a neural network values that all take wildly different ranges. The model might be able to automatically adapt to such heterogeneous data, but it would definitely make learning more difficult. A widespread best practice for dealing with such data is to do feature-wise normalization: for each feature in the input data (a column in the input data matrix), we subtract the mean of the feature and divide by the standard deviation, so that the feature is centered around 0 and has a unit standard deviation. This is easily done in NumPy.
%% Cell type:markdown id: tags:
### Normalizing the data
%% Cell type:code id: tags:
``` python
mean=train_data.mean(axis=0)
train_data-=mean
std=train_data.std(axis=0)
train_data/=std
test_data-=mean
test_data/=std
```
%% Cell type:markdown id: tags:
Note that the quantities used for normalizing the test data are computed using the
training data. You should never use any quantity computed on the test data in your
workflow, even for something as simple as data normalization.
%% Cell type:markdown id: tags:
### TODO: Building your model
Because so few samples are available, we’ll use a very small model with two intermediate layers, each with 64 units, each followed by a `relu` activation function. In general, the less training data you have, the worse overfitting will be, and using a small model is one way to mitigate overfitting.
The model ends with a single unit and no activation (it will be a linear layer). This is a
typical setup for scalar regression (a regression where you’re trying to predict a single
continuous value). Applying an activation function would constrain the range the output
can take; for instance, if you applied a sigmoid activation function to the last layer,
the model could only learn to predict values between 0 and 1. Here, because the last
layer is purely linear, the model is free to learn to predict values in any range.
Note that we compile the model with the `mse` loss function — _mean squared error_, the
square of the difference between the predictions and the targets. This is a widely used
loss function for regression problems.
We’re also monitoring a new metric during training: _mean absolute error_ (`MAE`). It’s the
absolute value of the difference between the predictions and the targets. For instance, an
MAE of 0.5 on this problem would mean your predictions are off by 500 on average.
%% Cell type:markdown id: tags:
### Validating your approach using K-fold validation
To evaluate our model while we keep adjusting its parameters (such as the number of
epochs used for training), we could split the data into a training set and a validation set, as we did in the previous examples. But because we have so few data points, the validation set would end up being very small (for instance, about 100 examples). As a consequence, the validation scores might change a lot depending on which data points we chose for validation and which we chose for training: the validation scores might have a high variance with regard to the validation split. This would prevent us from reliably evaluating our model.
The best practice in such situations is to use $K$-fold cross-validation. It consists of splitting the available data into K partitions (typically $K = 4$ or $5$), instantiating $K$ identical models, and training each one on $K - 1$ partitions while evaluating on the remaining partition. The validation score for the model used is then the average of the $K$ validation scores obtained. In terms of code, this is straightforward.
%% Cell type:markdown id: tags:
#### K-fold validation
%% Cell type:code id: tags:
``` python
importnumpyasnp
fromtensorflowimportkeras
fromtensorflow.kerasimportlayers
k=4
num_val_samples=len(train_data)//k
num_epochs=100
all_scores=[]
foriinrange(k):
print(f"Processing fold #{i}")
# Prepares the validation data: data from partition k
Running this with `num_epochs = 100` yields the following results:
%% Cell type:code id: tags:
``` python
all_scores
```
%% Output
[1.9184445142745972,
2.4037296772003174,
2.4944815635681152,
2.4431681632995605]
%% Cell type:code id: tags:
``` python
np.mean(all_scores)
```
%% Output
2.3149559795856476
%% Cell type:markdown id: tags:
The different runs do indeed show rather different validation scores, from 1.9 to 2.49.
The average (2.3) is a much more reliable metric than any single score—that’s the
entire point of K-fold cross-validation. In this case, we’re off by 2310 USD on average, which is significant considering that the prices range from 10000 to 50000.
Let’s try training the model a bit longer: 500 epochs. To keep a record of how well
the model does at each epoch, we’ll modify the training loop to save the per-epoch
validation score log for each fold.
%% Cell type:markdown id: tags:
#### Saving the validation logs at each fold
%% Cell type:code id: tags:
``` python
num_epochs=500
all_mae_histories=[]
foriinrange(k):
print(f"Processing fold #{i}")
# Prepares the validation data: data from partition #k
When calling `predict()` on our binary classification model, we retrieved a scalar score between 0 and 1 for each input sample. With our multiclass classification model, we retrieved a probability distribution over all classes for each sample. Now, with this scalar regression model, `predict()` returns the model’s guess for the sample’s price in thousands of dollars:
"This notebook calculates a logistic regression using Keras. It's basically meant to show the principles of Keras.\n",
"\n",
"### Background\n",
"\n",
"The Space Shuttle Challenger exploded 73 second after liftoff on January 28th, 1986. The disaster claimed the lives of all seven astronauts on board, including school teacher Christa McAuliffe.\n",
"\n",
"The details surrounding this disaster were very involved. For the purposes of this analysis, it is sufficient to point out that engineers that manufactured the large boosters that launched the rocket were aware of the possible failures that could happen during cold temperatures. They tried to prevent the launch, but were ultimately ignored and disaster ensued.\n",
"\n",
"The main concern of engineers in launching the Challenger was the evidence that the large O-rings sealing the several sections of the boosters could fail in cold temperatures.\n",
"\n",
"\n",
"### Datset\n",
"\n",
"We investigate the data set of the challenger flight with broken O-rings (`Y=1`\n",
") vs start temperature."
"The lowest temperature of any of the 23 prior launches (before the Challenger explosion) was 53° F. This is evident in the data set shown below. Engineers prior to the Challenger launch suggested that the launch not be attempted below 53°. The “evidence” that the o-rings could fail below 53° was based on a simple conclusion that since the launch at 53° experienced two o-ring failures, it seemed unwise to launch below that temperature. In the following analysis we demonstrate more fully how dangerous it was to launch on this specific day where the outside temperature at the time of the launch was 31°.\n",
"\n",
"The `Broken O-rings` column in the data set below records whether O-rings experienced failures during that particular launch - if they did, the value for `Broken O-rings` is 1. The `Temperature [F]` column lists the outside temperature at the time of launch.\n",
"\n",
"### Goal of Analysis\n",
"\n",
"We investigate the data set of the challenger flight with broken O-rings (`Y=1`) vs start temperature."
]
},
{
...
...
%% Cell type:markdown id: tags:
# Exercise 1 : Conversion from Celsius to Fahrenheit (Simple Regression Analysis)
%% Cell type:markdown id: tags:
The problem we will solve is to convert from Celsius to Fahrenheit, where the approximate formula is:
$$ f = c \times 1.8 + 32 $$
Of course, it would be simple enough to create a conventional Python function that directly performs this calculation, but that wouldn't be machine learning.
Instead, we will give TensorFlow some sample Celsius values (0, 8, 15, 22, 38) and their corresponding Fahrenheit values (32, 46, 59, 72, 100).
Then, we will train a model that figures out the above formula through the training process. This is a _simple regression analysis_ problem.
%% Cell type:markdown id: tags:
## Import dependencies
First, import TensorFlow. Here, we're calling it `tf` for ease of use. We also tell it to only display errors.
Next, import [NumPy](http://www.numpy.org/) as `np`. Numpy helps us to represent our data as highly performant lists.
As we saw before, supervised Machine Learning is all about figuring out an algorithm given a set of inputs and outputs. Since the task in this exercise is to create a model that can give the temperature in Fahrenheit when given the degrees in Celsius, we create two lists `celsius_q` and `fahrenheit_a` that we can use to train our model.
-**Feature** — The input(s) to our model. In this case, a single value — the degrees in Celsius.
-**Labels/response variable** — The output our model predicts. In this case, a single value — the degrees in Fahrenheit. In a classification setting, we would predict labels (discrete classes), in a regression setting, we predict a continuous response variable, such as Fahrenheit.
-**Example** — A pair of inputs/outputs used during training. In our case a pair of values from `celsius_q` and `fahrenheit_a` at a specific index, such as `(22,72)`.
%% Cell type:markdown id: tags:
## 1. Define the Network
Next create the model. We will use the simplest possible model we can, a Dense network. Since the problem is straightforward, this network will require only a single layer, with a single neuron.
### Build a layer
We'll call the layer `l0` and create it by instantiating `tf.keras.layers.Dense` with the following configuration:
*`input_shape=[1]` — This specifies that the input to this layer is a single value. That is, the shape is a one-dimensional array with one member. Since this is the first (and only) layer, that input shape is the input shape of the entire model. The single value is a floating point number, representing degrees Celsius.
*`units=1` — This specifies the number of units in the layer. The number of units defines how many internal variables the layer has to try to learn how to solve the problem (more later). Since this is the final layer, it is also the size of the model's output — a single float value representing degrees Fahrenheit. (In a multi-layered network, the size and shape of the layer would need to match the `input_shape` of the next layer.)
%% Cell type:code id: tags:
``` python
l0=tf.keras.layers.Dense(units=1,input_shape=[1])
```
%% Cell type:markdown id: tags:
### Assemble layers into the model
Once layers are defined, they need to be assembled into a model. The Sequential model definition takes a list of layers as argument, specifying the calculation order from the input to the output.
## 2. Compile the network, with loss and optimizer functions
Before training, the model has to be compiled. When compiled for training, the model is given:
-**Loss function** — A way of measuring how far off predictions are from the desired outcome. (The measured difference is called the "loss".)
-**Optimizer function** — A way of adjusting internal values in order to reduce the loss.
%% Cell type:code id: tags:
``` python
model.compile(loss='mean_squared_error',
optimizer=tf.keras.optimizers.Adam(0.1))
```
%% Cell type:markdown id: tags:
These are used during training (`model.fit()`, below) to first calculate the loss at each point, and then improve it. In fact, the act of calculating the current loss of a model and then improving it is precisely what training is.
During training, the optimizer function is used to calculate adjustments to the model's internal variables. The goal is to adjust the internal variables until the model (which is really a math function) mirrors the actual equation for converting Celsius to Fahrenheit.
`TensorFlow` uses numerical analysis to perform this tuning, and all this complexity is hidden from you so we will not go into the details here. What is useful to know about these parameters are:
The loss function ([mean squared error](https://en.wikipedia.org/wiki/Mean_squared_error)) and the optimizer ([Adam](https://machinelearningmastery.com/adam-optimization-algorithm-for-deep-learning/)) used here are standard for simple models like this one, but many others are available. It is not important to know how these specific functions work at this point.
One part of the Optimizer you may need to think about when building your own models is the learning rate (`0.1` in the code above). This is the step size taken when adjusting values in the model. If the value is too small, it will take too many iterations to train the model. Too large, and accuracy goes down. Finding a good value often involves some trial and error, but the range is usually within 0.001 (default), and 0.1
%% Cell type:markdown id: tags:
## 3. Fit the model
Train the model by calling the `fit` method.
During training, the model takes in Celsius values, performs a calculation using the current internal variables (called "weights") and outputs values which are meant to be the Fahrenheit equivalent. Since the weights are initially set randomly, the output will not be close to the correct value. The difference between the actual output and the desired output is calculated using the loss function, and the optimizer function directs how the weights should be adjusted.
This cycle of calculate, compare, adjust is controlled by the `fit` method. The first argument is the inputs, the second argument is the desired outputs. The `epochs` argument specifies how many times this cycle should be run, and the `verbose` argument controls how much output the method produces.
## 4. Evaluate the Model - Display training statistics
The `fit` method returns a history object. We can use this object to plot how the loss of our model goes down after each training epoch. A high loss means that the Fahrenheit degrees the model predicts is far from the corresponding value in `fahrenheit_a`.
We'll use [Matplotlib](https://matplotlib.org/) to visualize this (you could use another tool). As you can see, our model improves very quickly at first, and then has a steady, slow improvement until it is very near "perfect" towards the end.
%% Cell type:code id: tags:
``` python
importmatplotlib.pyplotasplt
plt.xlabel('Epoch Number')
plt.ylabel("Loss Magnitude")
plt.plot(history.history['loss'])
```
%% Output
[<matplotlib.lines.Line2D at 0x7ff9ec12a190>]
%% Cell type:markdown id: tags:
## 5. Use the model to predict values
Now you have a model that has been trained to learn the relationship between `celsius_q` and `fahrenheit_a`. You can use the predict method to have it calculate the Fahrenheit degrees for a previously unknown Celsius degrees.
So, for example, if the Celsius value is 100, what do you think the Fahrenheit result will be? Take a guess before you run this code.
%% Cell type:code id: tags:
``` python
print(model.predict([100.0]))
```
%% Output
[[211.31021]]
%% Cell type:markdown id: tags:
The correct answer is $100 \times 1.8 + 32 = 212$, so our model is doing really well.
### To review
* We created a model with a Dense layer
* We trained it with 3500 examples (7 pairs, over 500 epochs).
Our model tuned the variables (weights) in the Dense layer until it was able to return the correct Fahrenheit value for any Celsius value. (Remember, 100 Celsius was not part of our training data.)
%% Cell type:markdown id: tags:
## Looking at the layer weights
Finally, let's print the internal variables of the Dense layer.
%% Cell type:code id: tags:
``` python
print("These are the layer variables: {}".format(model.get_weights()))
```
%% Output
These are the layer variables: [array([[1.8242955]], dtype=float32), array([28.880667], dtype=float32)]
%% Cell type:markdown id: tags:
The first variable is close to ~1.8 and the second to ~32. These values (1.8 and 32) are the actual variables in the real conversion formula.
This is really close to the values in the conversion formula. We can show how a Dense layer works, but for a single neuron with a single input and a single output, the internal math looks the same as [the equation for a line](https://en.wikipedia.org/wiki/Linear_equation#Slope%E2%80%93intercept_form), $y = mx + b$, which has the same form as the conversion equation, $f = 1.8c + 32$.
Since the form is the same, the variables should converge on the standard values of 1.8 and 32, which is exactly what happened.
With additional neurons, additional inputs, and additional outputs, the formula becomes much more complex, but the idea is the same.
### A little experiment
Just for fun, what if we created more Dense layers with different units, which therefore also has more variables?
As you can see, this model is also able to predict the corresponding Fahrenheit value really well. But when you look at the variables (weights) in the `l0` and `l1` layers, they are nothing even close to ~1.8 and ~32. The added complexity hides the "simple" form of the conversion equation.
%% Cell type:markdown id: tags:
# Exercise 2 : O-Rings seen with Logistic Regression
%% Cell type:markdown id: tags:
This notebook calculates a logistic regression using Keras. It's basically meant to show the principles of Keras.
### Background
The Space Shuttle Challenger exploded 73 second after liftoff on January 28th, 1986. The disaster claimed the lives of all seven astronauts on board, including school teacher Christa McAuliffe.
The details surrounding this disaster were very involved. For the purposes of this analysis, it is sufficient to point out that engineers that manufactured the large boosters that launched the rocket were aware of the possible failures that could happen during cold temperatures. They tried to prevent the launch, but were ultimately ignored and disaster ensued.
The main concern of engineers in launching the Challenger was the evidence that the large O-rings sealing the several sections of the boosters could fail in cold temperatures.
### Datset
We investigate the data set of the challenger flight with broken O-rings (`Y=1`
) vs start temperature.
The lowest temperature of any of the 23 prior launches (before the Challenger explosion) was 53° F. This is evident in the data set shown below. Engineers prior to the Challenger launch suggested that the launch not be attempted below 53°. The “evidence” that the o-rings could fail below 53° was based on a simple conclusion that since the launch at 53° experienced two o-ring failures, it seemed unwise to launch below that temperature. In the following analysis we demonstrate more fully how dangerous it was to launch on this specific day where the outside temperature at the time of the launch was 31°.
The `Broken O-rings` column in the data set below records whether O-rings experienced failures during that particular launch - if they did, the value for `Broken O-rings` is 1. The `Temperature [F]` column lists the outside temperature at the time of launch.
### Goal of Analysis
We investigate the data set of the challenger flight with broken O-rings (`Y=1`) vs start temperature.
If we have more than one data point, which we usually do, we have to apply the equation above to each of the N data points. In this case we can use a vectorized version with $x=(x_1,x_2,\ldots,x_N)$ and $y=(y_1,y_2,\ldots,y_N$)
%% Cell type:markdown id: tags:
### Numpy code
This numpy code, shows the calculation for one value using `NumPy` (like a single forward pass)
The value of the cross-entropy loss function could be decreased from 0.9094435 to 0.4416346251964569
%% Cell type:markdown id: tags:
# Exercise 3 : MNIST and Multinomial Logistic Regression
%% Cell type:markdown id: tags:
In this exercise we use multinomial logistic regression to predict the number of the handwritten digits of the MNIST dataset.
%% Cell type:markdown id: tags:
## TODO : read MNIST data and compute validation accuracy for a multinomial logistic regression model, see [Multinomial Logistic Regression](https://en.wikipedia.org/wiki/Multinomial_logistic_regression)
If there are several labels, then we use `categorical_crossentropy` as loss function and the output layer should be a `softmax` layer.
The prices are typically between 10000 and 50000 USD. If that sounds cheap, remember
that this was the mid-1970s, and these prices aren’t adjusted for inflation.
%% Cell type:markdown id: tags:
### Preparing the data
It would be problematic to feed into a neural network values that all take wildly different ranges. The model might be able to automatically adapt to such heterogeneous data, but it would definitely make learning more difficult. A widespread best practice for dealing with such data is to do feature-wise normalization: for each feature in the input data (a column in the input data matrix), we subtract the mean of the feature and divide by the standard deviation, so that the feature is centered around 0 and has a unit standard deviation. This is easily done in NumPy.
%% Cell type:markdown id: tags:
### Normalizing the data
%% Cell type:code id: tags:
``` python
mean=train_data.mean(axis=0)
train_data-=mean
std=train_data.std(axis=0)
train_data/=std
test_data-=mean
test_data/=std
```
%% Cell type:markdown id: tags:
Note that the quantities used for normalizing the test data are computed using the
training data. You should never use any quantity computed on the test data in your
workflow, even for something as simple as data normalization.
%% Cell type:markdown id: tags:
### Building your model
Because so few samples are available, we’ll use a very small model with two intermediate layers, each with 64 units. In general, the less training data you have, the worse overfitting will be, and using a small model is one way to mitigate overfitting.
The model ends with a single unit and no activation (it will be a linear layer). This is a
typical setup for scalar regression (a regression where you’re trying to predict a single
continuous value). Applying an activation function would constrain the range the output
can take; for instance, if you applied a sigmoid activation function to the last layer,
the model could only learn to predict values between 0 and 1. Here, because the last
layer is purely linear, the model is free to learn to predict values in any range.
Note that we compile the model with the `mse` loss function — _mean squared error_, the
square of the difference between the predictions and the targets. This is a widely used
loss function for regression problems.
We’re also monitoring a new metric during training: _mean absolute error_ (`MAE`). It’s the
absolute value of the difference between the predictions and the targets. For instance, an
MAE of 0.5 on this problem would mean your predictions are off by 500 on average.
%% Cell type:markdown id: tags:
### Validating your approach using K-fold validation
To evaluate our model while we keep adjusting its parameters (such as the number of
epochs used for training), we could split the data into a training set and a validation set, as we did in the previous examples. But because we have so few data points, the validation set would end up being very small (for instance, about 100 examples). As a consequence, the validation scores might change a lot depending on which data points we chose for validation and which we chose for training: the validation scores might have a high variance with regard to the validation split. This would prevent us from reliably evaluating our model.
The best practice in such situations is to use $K$-fold cross-validation. It consists of splitting the available data into K partitions (typically $K = 4$ or $5$), instantiating $K$ identical models, and training each one on $K - 1$ partitions while evaluating on the remaining partition. The validation score for the model used is then the average of the $K$ validation scores obtained. In terms of code, this is straightforward.
%% Cell type:markdown id: tags:
#### K-fold validation
%% Cell type:code id: tags:
``` python
importnumpyasnp
fromtensorflowimportkeras
fromtensorflow.kerasimportlayers
k=4
num_val_samples=len(train_data)//k
num_epochs=100
all_scores=[]
foriinrange(k):
print(f"Processing fold #{i}")
# Prepares the validation data: data from partition k
Running this with `num_epochs = 100` yields the following results:
%% Cell type:code id: tags:
``` python
all_scores
```
%% Output
[1.9184445142745972,
2.4037296772003174,
2.4944815635681152,
2.4431681632995605]
%% Cell type:code id: tags:
``` python
np.mean(all_scores)
```
%% Output
2.3149559795856476
%% Cell type:markdown id: tags:
The different runs do indeed show rather different validation scores, from 1.9 to 2.49.
The average (2.3) is a much more reliable metric than any single score—that’s the
entire point of K-fold cross-validation. In this case, we’re off by 2310 USD on average, which is significant considering that the prices range from 10000 to 50000.
Let’s try training the model a bit longer: 500 epochs. To keep a record of how well
the model does at each epoch, we’ll modify the training loop to save the per-epoch
validation score log for each fold.
%% Cell type:markdown id: tags:
#### Saving the validation logs at each fold
%% Cell type:code id: tags:
``` python
num_epochs=500
all_mae_histories=[]
foriinrange(k):
print(f"Processing fold #{i}")
# Prepares the validation data: data from partition #k
We’re still off by a bit under 2800 USD. It’s an improvement! Just like with the two previous tasks, you can try varying the number of layers in the model, or the number of units per layer, to see if you can squeeze out a lower test error.
%% Cell type:markdown id: tags:
### Generating predictions on new data
When calling `predict()` on our binary classification model, we retrieved a scalar score between 0 and 1 for each input sample. With our multiclass classification model, we retrieved a probability distribution over all classes for each sample. Now, with this scalar regression model, `predict()` returns the model’s guess for the sample’s price in thousands of dollars:
%% Cell type:code id: tags:
``` python
predictions=model.predict(test_data)
predictions[0]
```
%% Output
array([8.708372], dtype=float32)
%% Cell type:markdown id: tags:
The first house in the test set is predicted to have a price of about 8700 USD.