Customize Consent Preferences

We use cookies to help you navigate efficiently and perform certain functions. You will find detailed information about all cookies under each consent category below.

The cookies that are categorized as "Necessary" are stored on your browser as they are essential for enabling the basic functionalities of the site. ... 

Always Active

Necessary cookies are required to enable the basic features of this site, such as providing secure log-in or adjusting your consent preferences. These cookies do not store any personally identifiable data.

No cookies to display.

Functional cookies help perform certain functionalities like sharing the content of the website on social media platforms, collecting feedback, and other third-party features.

No cookies to display.

Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics such as the number of visitors, bounce rate, traffic source, etc.

No cookies to display.

Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.

No cookies to display.

Advertisement cookies are used to provide visitors with customized advertisements based on the pages you visited previously and to analyze the effectiveness of the ad campaigns.

No cookies to display.

Creating a Neural Network to Invent the Conversion Formula from Hours to Minutes Using Python and TensorFlow

Tiempo de lectura: 3 minutos

Reading time: 3 minutes

Today I’m going to show you how to create a small neural network capable of predicting the conversion formula from hours to minutes.

To create this Artificial Intelligence, we’re going to use TensorFlow, a library created by Google that will make things easier for us. To install it, we run:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
python3 -m pip install tensorflow
python3 -m pip install tensorflow
python3 -m pip install tensorflow

Now we create a new file and name it “speed.py”.

Let’s start by adding the dependencies:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
import tensorflow as tf
import numpy as np
import tensorflow as tf import numpy as np
import tensorflow as tf
import numpy as np

Now we create some sample training data. These may not be the best training data, but they will suffice for the example.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
# training data: hours and minutes (output), supervised training
hours = np.array([1.0, 2.0, 3.0, 4.0, 4.5, 5.0, 10.0, 23.0, 15.0, 24.0, 1.5, 1.2,
3.3, 5.3, 100.0, 12.3, 3.4], dtype=float)
minutes = np.array([60.0, 120.0, 180.0, 240.0, 270.0, 300.0, 600.0, 1380.0, 900.0, 1440.0, 90.0, 72.0,
198.0, 318.0, 6000.0, 738.0, 204.0], dtype=float)
# training data: hours and minutes (output), supervised training hours = np.array([1.0, 2.0, 3.0, 4.0, 4.5, 5.0, 10.0, 23.0, 15.0, 24.0, 1.5, 1.2, 3.3, 5.3, 100.0, 12.3, 3.4], dtype=float) minutes = np.array([60.0, 120.0, 180.0, 240.0, 270.0, 300.0, 600.0, 1380.0, 900.0, 1440.0, 90.0, 72.0, 198.0, 318.0, 6000.0, 738.0, 204.0], dtype=float)
# training data: hours and minutes (output), supervised training
hours = np.array([1.0, 2.0, 3.0, 4.0, 4.5, 5.0, 10.0, 23.0, 15.0, 24.0, 1.5, 1.2,
                  3.3, 5.3, 100.0, 12.3, 3.4], dtype=float)
minutes = np.array([60.0, 120.0, 180.0, 240.0, 270.0, 300.0, 600.0, 1380.0, 900.0, 1440.0, 90.0, 72.0,
                   198.0, 318.0, 6000.0, 738.0, 204.0], dtype=float)

We create two arrays, one for hours and one for the equivalent in minutes. Since this is supervised training, we will train the system by providing input data (hours) and the corresponding expected output data (minutes).

If we want to improve the Neural Network, we will need to add more data. The more data we add, the better.

Now let’s create the learning model.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
# Create the model, use 0.1 as the learning rate and mean squared error as the loss function
modelo.compile(
optimizer=tf.keras.optimizers.Adam(0.1),
loss='mean_squared_error'
)
# Create the model, use 0.1 as the learning rate and mean squared error as the loss function modelo.compile( optimizer=tf.keras.optimizers.Adam(0.1), loss='mean_squared_error' )
# Create the model, use 0.1 as the learning rate and mean squared error as the loss function
modelo.compile(
    optimizer=tf.keras.optimizers.Adam(0.1),
    loss='mean_squared_error'
)

First, we add the Adam optimizer with a learning rate of 0.1 (it increments the node indices by 0.1).

In addition, we use mean squared error as the loss function.

Now we need to train our Artificial Intelligence.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
# Train the model
print("Training the model...")
modelo_entrenado = modelo.fit(horas, minutos, epochs=1000, verbose=False)
print("Model trained successfully")
# Train the model print("Training the model...") modelo_entrenado = modelo.fit(horas, minutos, epochs=1000, verbose=False) print("Model trained successfully")
# Train the model
print("Training the model...")
modelo_entrenado = modelo.fit(horas, minutos, epochs=1000, verbose=False)
print("Model trained successfully")

Here we indicate that it should perform 1000 iterations on each value and not print the log (verbose=False).

Once trained, we can make predictions.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
# Make a prediction
print("How many minutes are 9 hours?")
resultado = modelo.predict([9.0])
print("9 hours are " + str(resultado) + " minutes")
# Make a prediction print("How many minutes are 9 hours?") resultado = modelo.predict([9.0]) print("9 hours are " + str(resultado) + " minutes")
# Make a prediction
print("How many minutes are 9 hours?")
resultado = modelo.predict([9.0])
print("9 hours are " + str(resultado) + " minutes")

The complete code looks like this:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
# Neural network that converts hours to minutes
import tensorflow as tf
import numpy as np
# Training data
hours = np.array([1.0, 2.0, 3.0, 4.0, 4.5, 5.0, 10.0, 23.0, 15.0, 24.0, 1.5, 1.2,
3.3, 5.3, 100.0, 12.3, 3.4], dtype=float)
minutes = np.array([60.0, 120.0, 180.0, 240.0, 270.0, 300.0, 600.0, 1380.0, 900.0, 1440.0, 90.0, 72.0,
198.0, 318.0, 6000.0, 738.0, 204.0], dtype=float)
# Create twoneurons: one for the input layer and one for the output layer.
layer = tf.keras.layers.Dense(units=1, input_shape=[1])
model = tf.keras.Sequential([layer])
Create the model, use 0.1 as the learning rate and mean squared error as the loss function
model.compile(
optimizer=tf.keras.optimizers.Adam(0.1),
loss='mean_squared_error'
)
Train the model
print("Training the model...")
trained_model = model.fit(hours, minutes, epochs=1000, verbose=False)
print("Model trained successfully")
Make a prediction
print("How many minutes are 9 hours?")
result = model.predict([9.0])
print("9 hours are " + str(result) + " minutes")
Complete code:
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># Neural network that converts hours to minutes
import tensorflow as tf
import numpy as np
# Training data
hours = np.array([1.0, 2.0, 3.0, 4.0, 4.5, 5.0, 10.0, 23.0, 15.0, 24.0, 1.5, 1.2,
3.3, 5.3, 100.0, 12.3, 3.4], dtype=float)
minutes = np.array([60.0, 120.0, 180.0, 240.0, 270.0, 300.0, 600.0, 1380.0, 900.0, 1440.0, 90.0, 72.0,
198.0, 318.0, 6000.0, 738.0, 204.0], dtype=float)
# Create two neurons: one for the input layer and one for the output layer
layer = tf.keras.layers.Dense(units=1, input_shape=[1])
model = tf.keras.Sequential([layer])
# Create the model, use 0.1 as the learning rate and mean squared error as the loss function
model.compile(
optimizer=tf.keras.optimizers.Adam(0.1),
loss='mean_squared_error'
)
# Train the model
print("Training the model...")
trained_model = model.fit(hours, minutes, epochs=1000, verbose=False)
print("Model trained successfully")
# Make a prediction
print("How many minutes are 9 hours?")
result = model.predict([9.0])
print("9 hours are " + str(result) + " minutes")</pre>
<p>When executed, it predicts the following:</p>
<div class="wp-block-image">
<figure class="aligncenter size-full"><img data-recalc-dims="1" decoding="async" loading="lazy" width="554" height="102" src="https://i0.wp.com/devcodelight.com/wp-content/uploads/2023/01/imagen-1.png?resize=554%2C102&ssl=1" alt="" class="wp-image-2718" srcset="https://devcodelight.com/wp-content/uploads/2023/01/imagen-1.png 554w, https://devcodelight.com/wp-content/uploads/2023/01/imagen-1-300x55.png 300w, https://devcodelight.com/wp-content/uploads/2023/01/imagen-1-228x42.png 228w" sizes="auto, (max-width: 554px) 100vw, 554px"></figure>
</div>
<p>Our Neural Network predicts that 9 hours are 551.87854 minutes, but we know that in reality it is 540 minutes. It is close to the correct solution, but this demonstrates that it needs more training data.<br>
Training data is the most important part of an artificial intelligence network. We need to find reliable and abundant data to achieve optimal results. </p>
<div class="saboxplugin-wrap" itemtype="http://schema.org/Person" itemscope="" itemprop="author"><div class="saboxplugin-tab"><div class="saboxplugin-gravatar"><img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/devcodelight.com/wp-content/uploads/2023/07/cropped-light_logo-5.png?resize=100%2C100&ssl=1" width="100" height="100" alt="" itemprop="image"></div><div class="saboxplugin-authorname"><a href="https://devcodelight.com/en/author/courstube/" class="vcard author" rel="author"><span class="fn">DevCodeLight</span></a></div><div class="saboxplugin-desc"><div itemprop="description"></div></div><div class="clearfix"></div></div></div><div class="post-views content-post post-5381 entry-meta load-static">
<span class="post-views-icon dashicons dashicons-chart-bar"></span> <span class="post-views-label">Post Views:</span> <span class="post-views-count">0</span>
</div> <div class="wpulike wpulike-robeen "><div class="wp_ulike_general_class wp_ulike_is_not_liked"><button type="button" aria-label="Like Button" data-ulike-id="5381" data-ulike-nonce="a132afe7ef" data-ulike-type="post" data-ulike-template="wpulike-robeen" data-ulike-display-likers="0" data-ulike-likers-style="popover" class="wp_ulike_btn wp_ulike_put_image wp_post_btn_5381"></button><span class="count-box wp_ulike_counter_up" data-ulike-counter-value="0">0</span> </div></div>
<div class="sharedaddy sd-sharing-enabled"><div class="robots-nocontent sd-block sd-social sd-social-icon-text sd-sharing"><h3 class="sd-title">Comparte esto:</h3><div class="sd-content"><ul><li class="share-facebook"><a rel="nofollow noopener noreferrer" data-shared="sharing-facebook-5381" class="share-facebook sd-button share-icon" href="https://devcodelight.com/en/creating-a-neural-network-to-invent-the-conversion-formula-from-hours-to-minutes-using-python-and-tensorflow/?share=facebook" target="_blank" title="Click to share on Facebook"><span>Facebook</span></a></li><li class="share-x"><a rel="nofollow noopener noreferrer" data-shared="sharing-x-5381" class="share-x sd-button share-icon" href="https://devcodelight.com/en/creating-a-neural-network-to-invent-the-conversion-formula-from-hours-to-minutes-using-python-and-tensorflow/?share=x" target="_blank" title="Click to share on X"><span>X</span></a></li><li class="share-end"></li></ul></div></div></div>
<div id="jp-relatedposts" class="jp-relatedposts">
<h3 class="jp-relatedposts-headline"><em>Related</em></h3>
</div>
# Neural network that converts hours to minutes import tensorflow as tf import numpy as np # Training data hours = np.array([1.0, 2.0, 3.0, 4.0, 4.5, 5.0, 10.0, 23.0, 15.0, 24.0, 1.5, 1.2, 3.3, 5.3, 100.0, 12.3, 3.4], dtype=float) minutes = np.array([60.0, 120.0, 180.0, 240.0, 270.0, 300.0, 600.0, 1380.0, 900.0, 1440.0, 90.0, 72.0, 198.0, 318.0, 6000.0, 738.0, 204.0], dtype=float) # Create twoneurons: one for the input layer and one for the output layer. layer = tf.keras.layers.Dense(units=1, input_shape=[1]) model = tf.keras.Sequential([layer]) Create the model, use 0.1 as the learning rate and mean squared error as the loss function model.compile( optimizer=tf.keras.optimizers.Adam(0.1), loss='mean_squared_error' ) Train the model print("Training the model...") trained_model = model.fit(hours, minutes, epochs=1000, verbose=False) print("Model trained successfully") Make a prediction print("How many minutes are 9 hours?") result = model.predict([9.0]) print("9 hours are " + str(result) + " minutes") Complete code: <pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># Neural network that converts hours to minutes import tensorflow as tf import numpy as np # Training data hours = np.array([1.0, 2.0, 3.0, 4.0, 4.5, 5.0, 10.0, 23.0, 15.0, 24.0, 1.5, 1.2, 3.3, 5.3, 100.0, 12.3, 3.4], dtype=float) minutes = np.array([60.0, 120.0, 180.0, 240.0, 270.0, 300.0, 600.0, 1380.0, 900.0, 1440.0, 90.0, 72.0, 198.0, 318.0, 6000.0, 738.0, 204.0], dtype=float) # Create two neurons: one for the input layer and one for the output layer layer = tf.keras.layers.Dense(units=1, input_shape=[1]) model = tf.keras.Sequential([layer]) # Create the model, use 0.1 as the learning rate and mean squared error as the loss function model.compile( optimizer=tf.keras.optimizers.Adam(0.1), loss='mean_squared_error' ) # Train the model print("Training the model...") trained_model = model.fit(hours, minutes, epochs=1000, verbose=False) print("Model trained successfully") # Make a prediction print("How many minutes are 9 hours?") result = model.predict([9.0]) print("9 hours are " + str(result) + " minutes")</pre> <p>When executed, it predicts the following:</p> <div class="wp-block-image"> <figure class="aligncenter size-full"><img data-recalc-dims="1" decoding="async" loading="lazy" width="554" height="102" src="https://i0.wp.com/devcodelight.com/wp-content/uploads/2023/01/imagen-1.png?resize=554%2C102&ssl=1" alt="" class="wp-image-2718" srcset="https://devcodelight.com/wp-content/uploads/2023/01/imagen-1.png 554w, https://devcodelight.com/wp-content/uploads/2023/01/imagen-1-300x55.png 300w, https://devcodelight.com/wp-content/uploads/2023/01/imagen-1-228x42.png 228w" sizes="auto, (max-width: 554px) 100vw, 554px"></figure> </div> <p>Our Neural Network predicts that 9 hours are 551.87854 minutes, but we know that in reality it is 540 minutes. It is close to the correct solution, but this demonstrates that it needs more training data.<br> Training data is the most important part of an artificial intelligence network. We need to find reliable and abundant data to achieve optimal results. </p> <div class="saboxplugin-wrap" itemtype="http://schema.org/Person" itemscope="" itemprop="author"><div class="saboxplugin-tab"><div class="saboxplugin-gravatar"><img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/devcodelight.com/wp-content/uploads/2023/07/cropped-light_logo-5.png?resize=100%2C100&ssl=1" width="100" height="100" alt="" itemprop="image"></div><div class="saboxplugin-authorname"><a href="https://devcodelight.com/en/author/courstube/" class="vcard author" rel="author"><span class="fn">DevCodeLight</span></a></div><div class="saboxplugin-desc"><div itemprop="description"></div></div><div class="clearfix"></div></div></div><div class="post-views content-post post-5381 entry-meta load-static"> <span class="post-views-icon dashicons dashicons-chart-bar"></span> <span class="post-views-label">Post Views:</span> <span class="post-views-count">0</span> </div> <div class="wpulike wpulike-robeen "><div class="wp_ulike_general_class wp_ulike_is_not_liked"><button type="button" aria-label="Like Button" data-ulike-id="5381" data-ulike-nonce="a132afe7ef" data-ulike-type="post" data-ulike-template="wpulike-robeen" data-ulike-display-likers="0" data-ulike-likers-style="popover" class="wp_ulike_btn wp_ulike_put_image wp_post_btn_5381"></button><span class="count-box wp_ulike_counter_up" data-ulike-counter-value="0">0</span> </div></div> <div class="sharedaddy sd-sharing-enabled"><div class="robots-nocontent sd-block sd-social sd-social-icon-text sd-sharing"><h3 class="sd-title">Comparte esto:</h3><div class="sd-content"><ul><li class="share-facebook"><a rel="nofollow noopener noreferrer" data-shared="sharing-facebook-5381" class="share-facebook sd-button share-icon" href="https://devcodelight.com/en/creating-a-neural-network-to-invent-the-conversion-formula-from-hours-to-minutes-using-python-and-tensorflow/?share=facebook" target="_blank" title="Click to share on Facebook"><span>Facebook</span></a></li><li class="share-x"><a rel="nofollow noopener noreferrer" data-shared="sharing-x-5381" class="share-x sd-button share-icon" href="https://devcodelight.com/en/creating-a-neural-network-to-invent-the-conversion-formula-from-hours-to-minutes-using-python-and-tensorflow/?share=x" target="_blank" title="Click to share on X"><span>X</span></a></li><li class="share-end"></li></ul></div></div></div> <div id="jp-relatedposts" class="jp-relatedposts"> <h3 class="jp-relatedposts-headline"><em>Related</em></h3> </div>
# Neural network that converts hours to minutes
import tensorflow as tf
import numpy as np

# Training data
hours = np.array([1.0, 2.0, 3.0, 4.0, 4.5, 5.0, 10.0, 23.0, 15.0, 24.0, 1.5, 1.2,
                  3.3, 5.3, 100.0, 12.3, 3.4], dtype=float)
minutes = np.array([60.0, 120.0, 180.0, 240.0, 270.0, 300.0, 600.0, 1380.0, 900.0, 1440.0, 90.0, 72.0,
                   198.0, 318.0, 6000.0, 738.0, 204.0], dtype=float)

# Create twoneurons: one for the input layer and one for the output layer.
layer = tf.keras.layers.Dense(units=1, input_shape=[1])
model = tf.keras.Sequential([layer])
Create the model, use 0.1 as the learning rate and mean squared error as the loss function
model.compile(
optimizer=tf.keras.optimizers.Adam(0.1),
loss='mean_squared_error'
)
Train the model
print("Training the model...")
trained_model = model.fit(hours, minutes, epochs=1000, verbose=False)
print("Model trained successfully")
Make a prediction
print("How many minutes are 9 hours?")
result = model.predict([9.0])
print("9 hours are " + str(result) + " minutes")
Complete code:
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
# Neural network that converts hours to minutes
import tensorflow as tf
import numpy as np
# Training data
hours = np.array([1.0, 2.0, 3.0, 4.0, 4.5, 5.0, 10.0, 23.0, 15.0, 24.0, 1.5, 1.2,
3.3, 5.3, 100.0, 12.3, 3.4], dtype=float)
minutes = np.array([60.0, 120.0, 180.0, 240.0, 270.0, 300.0, 600.0, 1380.0, 900.0, 1440.0, 90.0, 72.0,
198.0, 318.0, 6000.0, 738.0, 204.0], dtype=float)
# Create two neurons: one for the input layer and one for the output layer
layer = tf.keras.layers.Dense(units=1, input_shape=[1])
model = tf.keras.Sequential([layer])
# Create the model, use 0.1 as the learning rate and mean squared error as the loss function
model.compile(
optimizer=tf.keras.optimizers.Adam(0.1),
loss='mean_squared_error'
)
# Train the model
print("Training the model...")
trained_model = model.fit(hours, minutes, epochs=1000, verbose=False)
print("Model trained successfully")
# Make a prediction
print("How many minutes are 9 hours?")
result = model.predict([9.0])
print("9 hours are " + str(result) + " minutes")
# Neural network that converts hours to minutes import tensorflow as tf import numpy as np # Training data hours = np.array([1.0, 2.0, 3.0, 4.0, 4.5, 5.0, 10.0, 23.0, 15.0, 24.0, 1.5, 1.2, 3.3, 5.3, 100.0, 12.3, 3.4], dtype=float) minutes = np.array([60.0, 120.0, 180.0, 240.0, 270.0, 300.0, 600.0, 1380.0, 900.0, 1440.0, 90.0, 72.0, 198.0, 318.0, 6000.0, 738.0, 204.0], dtype=float) # Create two neurons: one for the input layer and one for the output layer layer = tf.keras.layers.Dense(units=1, input_shape=[1]) model = tf.keras.Sequential([layer]) # Create the model, use 0.1 as the learning rate and mean squared error as the loss function model.compile( optimizer=tf.keras.optimizers.Adam(0.1), loss='mean_squared_error' ) # Train the model print("Training the model...") trained_model = model.fit(hours, minutes, epochs=1000, verbose=False) print("Model trained successfully") # Make a prediction print("How many minutes are 9 hours?") result = model.predict([9.0]) print("9 hours are " + str(result) + " minutes")
# Neural network that converts hours to minutes
import tensorflow as tf
import numpy as np

# Training data
hours = np.array([1.0, 2.0, 3.0, 4.0, 4.5, 5.0, 10.0, 23.0, 15.0, 24.0, 1.5, 1.2,
                  3.3, 5.3, 100.0, 12.3, 3.4], dtype=float)
minutes = np.array([60.0, 120.0, 180.0, 240.0, 270.0, 300.0, 600.0, 1380.0, 900.0, 1440.0, 90.0, 72.0,
                   198.0, 318.0, 6000.0, 738.0, 204.0], dtype=float)

# Create two neurons: one for the input layer and one for the output layer
layer = tf.keras.layers.Dense(units=1, input_shape=[1])
model = tf.keras.Sequential([layer])

# Create the model, use 0.1 as the learning rate and mean squared error as the loss function
model.compile(
    optimizer=tf.keras.optimizers.Adam(0.1),
    loss='mean_squared_error'
)

# Train the model
print("Training the model...")
trained_model = model.fit(hours, minutes, epochs=1000, verbose=False)
print("Model trained successfully")

# Make a prediction
print("How many minutes are 9 hours?")
result = model.predict([9.0])
print("9 hours are " + str(result) + " minutes")

When executed, it predicts the following:

Our Neural Network predicts that 9 hours are 551.87854 minutes, but we know that in reality it is 540 minutes. It is close to the correct solution, but this demonstrates that it needs more training data.
Training data is the most important part of an artificial intelligence network. We need to find reliable and abundant data to achieve optimal results.

0

Leave a Comment