MSDN Community

Getting Started with TensorFlow

Welcome to the TensorFlow Getting Started guide. In this tutorial, you’ll set up your environment, build your first model, and run inference—all using TensorFlow 2.x.

Install TensorFlow

Table of Contents

Prerequisites

You should have the following installed before you begin:

Setup Environment

We recommend using a virtual environment to keep dependencies isolated.

python -m venv tf-env
source tf-env/bin/activate   # On Windows use `tf-env\Scripts\activate`
pip install --upgrade pip
pip install tensorflow

Hello World Model

Let’s create a minimal TensorFlow program that adds two numbers.

import tensorflow as tf

# Define constant tensors
a = tf.constant(2)
b = tf.constant(3)

# Perform addition
c = tf.add(a, b)

print("Result:", c.numpy())

The above script should output Result: 5.

Training a Simple Model

We’ll train a linear regression model on a synthetic dataset.

import tensorflow as tf
import numpy as np

# Generate synthetic data
X = np.random.rand(1000, 1)
y = 3 * X + 2 + np.random.randn(1000, 1) * 0.05

# Build a simple sequential model
model = tf.keras.Sequential([
    tf.keras.layers.Dense(1, input_shape=(1,))
])

model.compile(optimizer='sgd', loss='mse')
model.fit(X, y, epochs=50, verbose=0)

# Print learned parameters
weights = model.layers[0].get_weights()
print(f"Learned weight: {weights[0][0][0]:.2f}, bias: {weights[1][0]:.2f}")

Running Inference

After training, use the model to predict new values.

# Predict for a new input
new_X = np.array([[0.5]])
prediction = model.predict(new_X)
print(f"Prediction for 0.5: {prediction[0][0]:.2f}")

Next Steps

Continue exploring TensorFlow with the following tutorials: