Skip to content

Instantly share code, notes, and snippets.

@philipobiorah
Created April 3, 2019 23:26
Show Gist options
  • Save philipobiorah/108e79dc538c083c75f0f1ba7d369c12 to your computer and use it in GitHub Desktop.
Save philipobiorah/108e79dc538c083c75f0f1ba7d369c12 to your computer and use it in GitHub Desktop.
To convert from Celsius to Fahrenheit using Tensorflow
import tensorflow as tf
import numpy as np
#create numpy array and initialize with values
celsius_q = np.array([-40, -10, 0, 8, 15, 22, 38], dtype=float)
fahrenheit_a = np.array([-40, 14, 32, 46, 59, 72, 100], dtype=float)
#looping through the celcius input array
for i, c in enumerate(celsius_q):
print("{} degrees Celsius = {} degrees Fahrenheit".format(c, fahrenheit_a[i]))
#bulidng a layer l0
# input_shape=[1] —
# This specifies that the input to this layer is a single value.
# That is, the shape is a one-dimensional array with one member.
# Since this is the first (and only) layer, that input shape is the
# input shape of the entire model. The single value is a floating point number, representing degrees Celsius.
#
# units=1 — This specifies the number of neurons in the layer.
# The number of neurons defines how many internal variables the layer
# has to try to learn how to solve the problem (more later)
l0 = tf.keras.layers.Dense(units=1, input_shape=[1])
#assemble layers into the model
model = tf.keras.Sequential([l0])
#compile the model
model.compile(loss='mean_squared_error', optimizer=tf.keras.optimizers.Adam(0.1))
#train the model
history = model.fit(celsius_q, fahrenheit_a, epochs=500, verbose=False)
print("Finished training the model")
#use the trained model to predict
print(model.predict([100]))
#looking at the layer weights
print("These are the layer variables: {}".format(l0.get_weights()))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment