DEV Community

The Practical Developer
The Practical Developer

Posted on Originally published at practicaldevblog.blogspot.com

TensorFlow Explained: Machine Learning, From Tensors to Training

Introduction

Machine learning sounds like magic until you see the machinery: numbers flow through operations, a model adjusts its parameters, and error goes down. TensorFlow, released by Google in 2015, is the library that packages that machinery: it represents data as tensors, multi-dimensional arrays, and gives you the tools to build, train, and ship models, from a laptop experiment to a phone app.

Tensors, Keras, and the road to production

TensorFlow rests on a few distinctive ideas:

  • Tensors first: data is a tensor, an array with shape and type, and every operation, from addition to a neural network layer, works on tensors.
  • Keras, the friendly front door: the high-level Keras API lets you stack layers into a model in a few lines, while TensorFlow underneath handles the maths.
  • Eager by default, graphs when needed: run operations immediately while experimenting, then compile a model into an efficient graph for training and serving.
  • An ecosystem around the model: TensorFlow Lite runs models on phones, TensorFlow.js runs them in the browser, and serving tools take a trained model into production.

A tiny example shows the shape, a model that learns the line y = 2x + 1 from four examples:

import numpy as np
import tensorflow as tf

xs = np.array([0.0, 1.0, 2.0, 3.0], dtype=np.float32)
ys = np.array([1.0, 3.0, 5.0, 7.0], dtype=np.float32)

model = tf.keras.Sequential([
    tf.keras.layers.Input(shape=(1,)),
    tf.keras.layers.Dense(units=1)
])
model.compile(optimizer='sgd', loss='mean_squared_error')
model.fit(xs, ys, epochs=100, verbose=0)
print(model.predict(np.array([4.0], dtype=np.float32)))
Enter fullscreen mode Exit fullscreen mode

Input(shape=(1,)) says each example is one number, Dense(units=1) adds a single output neuron, compile picks the optimiser and the loss, and fit trains for 100 passes over the data. Predicting for 4.0 gives a value near 9.0, not exactly, because training improves gradually rather than solving the equation outright.

The honest trade

TensorFlow trades simplicity for scale: it is a large library with a learning curve, small models are often easier in a smaller library like scikit-learn, and debugging a training run takes patience. When to reach for it: for neural networks, especially ones headed for production or mobile; a smaller library when the model is a simple regression or classifier.

A model, not magic

TensorFlow is machine learning from tensors to training: data as arrays, models as stacked layers, and an ecosystem that carries a trained model onto phones, browsers, and servers. It trades a gentle learning curve for serious scale, and for neural networks that need to ship, that scale is the reason it endures.

Top comments (0)