Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

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)

Code Block
languagepy
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

...

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


Run it Locally

You may need to update pip3, etc... 

Code Block
$pip3 install --user --upgrade pip


Install tensorflow

Code Block
$ pip3 install --user --upgrade tensorflow


Run code

> python3 <file>


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



References