Skip to content

Instantly share code, notes, and snippets.

Created October 28, 2017 22:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/c816eb15daf949543e96dd2c64174670 to your computer and use it in GitHub Desktop.
Save anonymous/c816eb15daf949543e96dd2c64174670 to your computer and use it in GitHub Desktop.
from keras.models import Sequential
from keras.layers import Dense
import numpy
import sklearn.datasets
import matplotlib
matplotlib.use("TkAgg")
import matplotlib.pyplot as plt
numpy.random.seed(7)
# -----------------------------------------------------------------------------
# generate sinus.
# -----------------------------------------------------------------------------
T = 1000
X = numpy.array(range(T))
Y = numpy.sin(3.5 * numpy.pi * X / T)
# -----------------------------------------------------------------------------
# Draw training data
# -----------------------------------------------------------------------------
plt.scatter(X, Y, s = 10)
plt.show()
# -----------------------------------------------------------------------------
# Build Keras model (my keras uses TensorFlow backend)
# -----------------------------------------------------------------------------
input_dim = 1
model = Sequential()
model.add(Dense(10, input_dim = input_dim, activation='tanh'))
model.add(Dense(90, activation='tanh'))
model.add(Dense(10, activation='tanh'))
model.add(Dense(10, activation='tanh'))
model.add(Dense(10, activation='tanh'))
model.add(Dense(10, activation='tanh'))
model.add(Dense(10, activation='tanh'))
model.add(Dense(10, activation='tanh'))
model.add(Dense(10, activation='tanh'))
model.add(Dense(10, activation='tanh'))
model.add(Dense(10, activation='tanh'))
model.add(Dense(1, activation='tanh'))
# -----------------------------------------------------------------------------
# Comile and fit
# -----------------------------------------------------------------------------
model.compile(loss='mean_squared_error', optimizer='adam', metrics=['accuracy'])
model.fit(X, Y, epochs=50, batch_size=10)
# -----------------------------------------------------------------------------
# Evalute
# -----------------------------------------------------------------------------
scores = model.evaluate(X, Y)
print("-" * 100)
print("\n%s: %.2f%%" % (model.metrics_names[0], scores[0]*100))
# -----------------------------------------------------------------------------
# Compare prediction vs groundtruth
# -----------------------------------------------------------------------------
pred = model.predict(X)
x_plot = X
plt.scatter(x_plot, pred, s = 1, c = 'r')
plt.scatter(x_plot, Y, s = 1, c = 'b')
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment