0
0
TensorFlowml~5 mins

Keras as TensorFlow's high-level API

Choose your learning style9 modes available
Introduction

Keras makes building and training neural networks simple and fast. It is easy to use and helps you focus on your ideas, not the complex code.

You want to quickly create a neural network for image recognition.
You need an easy way to try different model designs without deep coding.
You want to train a model on your data with minimal setup.
You are learning machine learning and want clear, simple code.
You want to use TensorFlow but prefer a friendlier interface.
Syntax
TensorFlow
import tensorflow as tf
from tensorflow import keras

input_size = 20
model = keras.Sequential([
    keras.layers.Dense(units=10, activation='relu', input_shape=(input_size,)),
    keras.layers.Dense(units=1, activation='sigmoid')
])

model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
model.fit(x_train, y_train, epochs=5)

Keras is part of TensorFlow and accessed via tensorflow.keras.

The Sequential model stacks layers in order.

Examples
A simple model with one hidden layer and an output layer for 10 classes.
TensorFlow
model = keras.Sequential([
    keras.layers.Dense(64, activation='relu', input_shape=(100,)),
    keras.layers.Dense(10, activation='softmax')
])
Compile the model with stochastic gradient descent and mean squared error loss.
TensorFlow
model.compile(optimizer='sgd', loss='mean_squared_error')
Train the model for 10 passes over the data with batches of 32 samples.
TensorFlow
model.fit(x_train, y_train, epochs=10, batch_size=32)
Sample Model

This program creates a small neural network using Keras inside TensorFlow. It trains on random data for 3 rounds and prints predictions for 5 samples.

TensorFlow
import tensorflow as tf
from tensorflow import keras
import numpy as np

# Create dummy data
x_train = np.random.random((100, 20))
y_train = np.random.randint(2, size=(100, 1))

# Build model
model = keras.Sequential([
    keras.layers.Dense(16, activation='relu', input_shape=(20,)),
    keras.layers.Dense(1, activation='sigmoid')
])

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

# Train model
history = model.fit(x_train, y_train, epochs=3, batch_size=10, verbose=2)

# Make predictions
predictions = model.predict(x_train[:5])
print('Predictions:', predictions.flatten())
OutputSuccess
Important Notes

Keras hides many complex details, so you can build models quickly.

Use model.compile to set how the model learns and measures success.

Training with model.fit shows progress and updates model weights.

Summary

Keras is a simple way to build neural networks inside TensorFlow.

It uses easy-to-understand code to create layers and train models.

You can quickly try ideas and get results without deep coding.