Skip to main content
Practice

Reference AI Training Code Example - Part 2

This time, let's create a slightly more complex AI model compared to the last lesson.

In this session, you will learn how to make an AI predict the square of the input value plus 1, instead of simply doubling the given value. For example, if the input value is 2, the result will be 5 (the square of 2 is 4, plus 1).


Code Explanation

Let's step through the code to see what each part does.

Importing Necessary Tools for AI Learning
import tensorflow as tf
import numpy as np

This is the process of importing the necessary tools for AI learning. tensorflow is a tool for building AI models, and numpy is a tool for handling numbers.


Preparing Data
x_train = np.array([1.0, 2.0, 3.0, 4.0, 5.0], dtype=np.float32)
y_train = np.array([2.0, 5.0, 10.0, 17.0, 26.0], dtype=np.float32)

We prepare example data to show to the AI.

x_train is the input value, and y_train is the corresponding result value. Each result value is the square of the input value plus 1.


Defining the Model
model = tf.keras.Sequential([
tf.keras.layers.Dense(50, activation='relu', input_shape=[1]),
tf.keras.layers.Dense(50, activation='relu'),
tf.keras.layers.Dense(1)
])

This part constructs the structure of the AI model. It is more complex than before. In the first layer, 50 neurons are used with an activation function called relu.

In the second layer, 50 neurons are used again with the relu activation function. The final layer uses a single neuron.

This setup allows the AI to learn more complex patterns.


Compiling the Model
model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=0.01), loss='mean_squared_error')

Here, we configure how the AI will learn. We use the Adam optimizer with a learning rate of 0.01.

The loss function is set as mean_squared_error, which calculates the difference between the predicted values and the actual values.


Training the Model
history = model.fit(x_train, y_train, epochs=4, verbose=0)

Now, we actually train the AI. The entire dataset is repeated for 4 epochs.


Printing the Loss
print(f"Final Loss: {history.history['loss'][-1]:.4f}")

After training, we print the final loss value. The smaller this number is, the better the AI has learned the data.


Testing Predictions
x_test = np.array([2.0, 5.0, 8.0], dtype=np.float32)
predictions = model.predict(x_test, verbose=0)

print("\nPrediction Results:")
for x, pred in zip(x_test, predictions):
print(f"x = {x:.1f}, Predicted Value = {pred[0]:.2f}")

Here, we output the AI's predictions for new input values (2, 5, 8).


Comparing Actual and Predicted Values
print("\nComparing Actual and Predicted Values:")
for x, y in zip(x_train, y_train):
pred = model.predict(np.array([x]), verbose=0)[0][0]
print(f"x = {x:.1f}, Actual Value = {y:.2f}, Predicted Value = {pred:.2f}")

Finally, we compare the AI's predicted values with actual values for the training data.


Click the Execute Code button in your practice environment to train the AI yourself!


Training AI with Code

This code may seem slightly more complex than before, but the basic principle remains the same. The AI learns patterns from the given data and uses those patterns to respond to new situations.

In reality, AI systems handle much more complex and diverse data. If you want to learn more about AI programming, it is recommended to start learning Python basics.

Want to learn more?

Join CodeFriends Plus membership or enroll in a course to start your journey.