Swiftorial Logo
Home
Swift Lessons
Tutorials
Learn More
Career
Resources

TensorFlow Basics

Introduction to TensorFlow

TensorFlow is an open-source machine learning framework developed by Google. It is widely used for various applications such as image recognition, natural language processing, and more. TensorFlow allows you to build and deploy machine learning models easily.

Installing TensorFlow

To get started with TensorFlow, you need to install it. You can install TensorFlow using pip:

pip install tensorflow

Once the installation is complete, you can verify it by importing TensorFlow in Python:

import tensorflow as tf

Basic Operations in TensorFlow

TensorFlow allows you to perform a variety of mathematical operations. Let's start with some basic operations:

import tensorflow as tf

# Create two constants
a = tf.constant(2)
b = tf.constant(3)

# Perform basic operations
add = tf.add(a, b)
sub = tf.subtract(a, b)
mul = tf.multiply(a, b)
div = tf.divide(a, b)

# Execute the operations
print("Addition: ", add.numpy())
print("Subtraction: ", sub.numpy())
print("Multiplication: ", mul.numpy())
print("Division: ", div.numpy())

Addition: 5

Subtraction: -1

Multiplication: 6

Division: 0.6666667

TensorFlow Variables

Variables in TensorFlow are used to hold and update parameters. You can create a variable using tf.Variable:

# Create a variable with an initial value
var = tf.Variable(0)
print("Initial value:", var.numpy())

# Update the variable
var.assign_add(5)
print("Updated value:", var.numpy())

Initial value: 0

Updated value: 5

Creating a Simple Neural Network

Let's create a simple neural network using TensorFlow's high-level Keras API. This example will demonstrate how to build, compile, and train a neural network model.

from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense

# Create a simple neural network model
model = Sequential([
Dense(10, activation='relu', input_shape=(4,)),
Dense(10, activation='relu'),
Dense(3, activation='softmax')
])

# Compile the model
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])

# Display the model summary
model.summary()

Model: "sequential"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
dense (Dense) (None, 10) 50
dense_1 (Dense) (None, 10) 110
dense_2 (Dense) (None, 3) 33
=================================================================
Total params: 193
Trainable params: 193
Non-trainable params: 0
_________________________________________________________________

Training the Model

To train the model, you will need some data. For this example, we will use random data to demonstrate the training process:

import numpy as np

# Generate random data
X_train = np.random.rand(100, 4)
y_train = np.random.randint(3, size=100)

# Train the model
model.fit(X_train, y_train, epochs=10)

Epoch 1/10
4/4 [==============================] - 1s 3ms/step - loss: 1.1319 - accuracy: 0.3100
Epoch 2/10
4/4 [==============================] - 0s 3ms/step - loss: 1.1105 - accuracy: 0.3600
Epoch 3/10
4/4 [==============================] - 0s 2ms/step - loss: 1.0965 - accuracy: 0.3900
Epoch 4/10
4/4 [==============================] - 0s 3ms/step - loss: 1.0866 - accuracy: 0.4600
Epoch 5/10
4/4 [==============================] - 0s 3ms/step - loss: 1.0788 - accuracy: 0.4600
Epoch 6/10
4/4 [==============================] - 0s 3ms/step - loss: 1.0711 - accuracy: 0.4700
Epoch 7/10
4/4 [==============================] - 0s 2ms/step - loss: 1.0641 - accuracy: 0.4600
Epoch 8/10
4/4 [==============================] - 0s 2ms/step - loss: 1.0575 - accuracy: 0.4600
Epoch 9/10
4/4 [==============================] - 0s 3ms/step - loss: 1.0516 - accuracy: 0.4600
Epoch 10/10
4/4 [==============================] - 0s 3ms/step - loss: 1.0462 - accuracy: 0.4600