import keras
import math
import numpy as np
# create a dataset
data = np.arange(0.001, 100, 0.00025)
np.random.shuffle(data)
# take a sample for testing purposes
split_data = np.array_split(data, 4)
x_train = np.concatenate((split_data[0], split_data[1], split_data[2]))
x_test = split_data[3]
split_data = None # wipe my temp variable
y_train = np.reciprocal(np.sqrt(x_train))
y_test = np.reciprocal(np.sqrt(x_test))
# set up a model / topology or whatever
model = keras.models.Sequential([
keras.layers.Input(shape=(1,)),
keras.layers.Dense(32, activation='relu'),
keras.layers.Dense(16, activation='relu'),
keras.layers.Dense(16, activation='relu'),
keras.layers.Dense(1, activation='exponential')
])
# define a loss function
loss_fn = keras.losses.MeanSquaredLogarithmicError()
model.dropout = keras.layers.Dropout(0.0)
# compile the model, with the loss function
model.compile(optimizer='adam',
loss=loss_fn,
metrics=['mean_absolute_percentage_error'],
auto_scale_loss=True)
# adjust the model to minimise loss
model.fit(x_train, y_train, validation_data=(x_test, y_test), epochs=3)
# evaluate the model's performance
# for the purposes of this, I think 1 colour channel is fine
model.evaluate(x_test, y_test, verbose=2)
while True: # bad bad bad error management, but good enough. Don't want it to hard crash after spending ages training.
try:
value = float(input("Enter test value: ").strip())
prediction = model.predict(np.reshape(value, (1)))
print("1 / sqrt({0}) ≈ {1}".format(value, prediction))
except KeyboardInterrupt:
break # (effectively just exit, but without importing sys)
except:
print("Invalid value! Please retry")
post a comment