You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 3 Current »

Create your first ML model

Consider the following sets of numbers. Can you see the relationship between them?

X:

-1

0

1

2

3

4

Y:

-2

1

4

7

10

13

As you look at them, you might notice that the value of X is increasing by 1 as you read left to right and the corresponding value of Y is increasing by 3. You probably think that Y equals 3X plus or minus something. Then, you'd probably look at the 0 on X and see that Y is 1, and you'd come up with the relationship Y=3X+1.

That's almost exactly how you would use code to train a model to spot the patterns in the data!

Now, look at the code to do it.

How would you train a neural network to do the equivalent task? Using data! By feeding it with a set of X‘s and a set of Y‘s, it should be able to figure out the relationship between them.


Code (Python)

import tensorflow as tf
import numpy as np
from tensorflow import keras

model = tf.keras.Sequential([keras.layers.Dense(units=1, input_shape=[1])])

model.compile(optimizer='sgd', loss='mean_squared_error')

xs = np.array([-1.0, 0.0, 1.0, 2.0, 3.0, 4.0], dtype=float)
ys = np.array([-2.0, 1.0, 4.0, 7.0, 10.0, 13.0], dtype=float)

model.fit(xs, ys, epochs=500)

print(model.predict([10.0]))


Run it in Colaboratory

Browse to https://colab.research.google.com/notebooks/welcome.ipynb

Past in your code and click run.


Output

Epoch 1/500
1/1 [==============================] - 0s 217ms/step - loss: 110.2153
....
Epoch 500/500
1/1 [==============================] - 0s 4ms/step - loss: 2.2867e-06
[[30.995588]]

For 10, the prediction is 30.995588

which is close to the expected Y= 3X+1 = 3*10 + 1  = 31


Run it Locally

You may need to update pip3, etc... 

$pip3 install --user --upgrade pip


Install tensorflow

$ pip3 install --user --upgrade tensorflow


Run code

> python3 <file>


$ python3 simplePredict.py
...
Epoch 500/500
1/1 [==============================] - 0s 640us/step - loss: 1.7887e-06
[[31.003902]]



References

  • No labels