Machine learning can be used to predict result in complicated case. However, in order to understand how it works lets build the simplest model: a model which predict the double of the input (1 -> 2).
The data
f(x) = 2x
Inputs of the model must be must be in [0, 1].
x_train = [number/200 for number in list(range(150))]
y_train = [number * 2 for number in x_train]
x_val = [number/200 for number in list(range(150, 200))]
y_val = [number * 2 for number in x_val]
x_test = [number/200 for number in list(range(0, 200, 10))]
The model
Since we predict numerical value, we use MAE (Mean absolute error).
inputs = tf.keras.Input(shape=1, name="input_layer"
outputs = tf.keras.layers.Dense(1, activation="relu", name="output_layer")(inputs)
model = tf.keras.Model(inputs = inputs, outputs = outputs)model.compile(optimizer=tf.optimizers.Adam(learning_rate=0.3), loss=tf.keras.losses.MAE, metrics=["MAE"])
model.fit(x_train, y_train, batch_size=32, epochs=300, validation_data=(x_val, y_val))
Then we can check our trained model weights.
print(model.get_weights())
We find something near 2.
Prediction
prediction = model.predict(x_test)
Check the results
from matplotlib import pyplot as pltfig, (ax1, ax2) = plt.subplots(1, 2)
fig.suptitle('Comparison')
ax1.set_title('Prediction')
ax1.plot(x_test, prediction)
ax2.set_title('Dataset')
ax2.plot(x_val, y_val)
ax2.plot(x_train, y_train)
plt.legend(["Validation", "Train"], loc ="lower right")
plt.show()