Skip to content

Instantly share code, notes, and snippets.

@bitsnaps
Last active November 11, 2021 09:05
Show Gist options
  • Save bitsnaps/c2d86f1e4bf1ca9bb78f2ba913f14cc6 to your computer and use it in GitHub Desktop.
Save bitsnaps/c2d86f1e4bf1ca9bb78f2ba913f14cc6 to your computer and use it in GitHub Desktop.
keras (tensorflow) simplest linear model example
# Simplest linear model with keras 2.1.3 (using tensorflow backed) it worked with python 3.5
import numpy as np
import keras
model = keras.Sequential( [keras.layers.Dense(units=1, input_shape=[1])] )
model.compile(optimizer='sgd', loss='mean_squared_error')
# y = 2x - 1
xs = np.array([-1.0, 0.0, 1.0, 2.0, 3.0, 4.0])
ys = np.array([-3.0, -1.0, 1.0, 3.0, 5.0, 7.0])
# verbose: can be either 1, 2 or 0 for no output.
# you can increase the epochs for better accuracy
model.fit(xs, ys, epochs=500, verbose=0)
# In newer version of tf you can just pass an array (instead of np.array) to predit()
print(model.predict(np.array([5.0]))) # ~= [[8.99...]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment