Skip to main content
Practice

Reference AI Training Code Example - Part 1

So far, you've learned about the fine-tuning process without writing a single line of code, but to actually fine-tune, you'll need to write a comprehensive and detailed program.

The most widely used language in AI programming is Python. Python’s concise and readable syntax, combined with abundant learning resources and libraries (tools), makes it the most utilized language in the artificial intelligence field.

The code introduced in the practice screen uses one of the popular AI libraries, TensorFlow, to train a simple AI model.

You don’t need to understand the code deeply; it serves as a reference to grasp how the AI training process unfolds at the code level.


AI Training Objective

The AI model to be trained will learn the relationship between input and output numbers.

For example, when numbers like 1, 2, 3, 4, 5 are given as input, the AI will learn to produce corresponding output values like 2, 4, 6, 8, 10.

As you may have guessed, this is the result of multiplying the input by 2.


Code Explanation

Let's now look at the actual code and break down what each part does.

Importing Tools for AI Training
import tensorflow as tf
import numpy as np

This part is about importing the tools needed for AI training. tensorflow is a tool for creating AI models, and numpy is a tool for handling numbers.


Data Preparation
x = np.array([1, 2, 3, 4, 5])
y = np.array([2, 4, 6, 8, 10])

Here, we prepare example data to show the AI. x is the input values, and y is the corresponding output values.


Model Creation
model = tf.keras.Sequential([
tf.keras.layers.Dense(1, input_shape=[1])
])

This part constructs the structure of the AI model. It's a very simple setup that takes one input value and produces one output value.


Model Compilation
model.compile(optimizer='sgd', loss='mean_squared_error')

The compilation process prepares the AI to start learning by setting up the learning method and how the learning results are measured.

Here, we set up how the AI will learn. optimizer refers to the learning method, while loss refers to how we'll measure how well the AI has learned.


Model Training
model.fit(x, y, epochs=4)

Now, we actually train the AI. epochs=4 means that the entire dataset will be used for training 4 times.


Prediction
print(model.predict(np.array([6])))

Lastly, we give a new value 6 to the trained AI and ask for its prediction.

If the AI was trained correctly, it should output a value close to 12.


Click the Run Code button in the practice environment and train the AI yourself!

Want to learn more?

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