A neural network helps a computer learn patterns from data to make decisions or predictions.
First neural network in TensorFlow
Start learning this pattern below
Jump into concepts and practice - no test required
import tensorflow as tf from tensorflow.keras import layers, models model = models.Sequential([ layers.Dense(units=10, activation='relu', input_shape=(784,)), layers.Dense(units=1, activation='sigmoid') ]) model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy']) model.fit(x_train, y_train, epochs=5)
Sequential means layers are stacked one after another.
Dense is a fully connected layer where each input connects to each output.
model = models.Sequential([
layers.Dense(5, activation='relu', input_shape=(3,)),
layers.Dense(1, activation='sigmoid')
])model.compile(optimizer='sgd', loss='mean_squared_error', metrics=['mse'])
model.fit(x_train, y_train, epochs=10, batch_size=32)
This program creates a tiny dataset where the output is 1 if the sum of inputs is greater than or equal to 1, else 0. It builds a small neural network with one hidden layer, trains it, and shows predictions and accuracy.
import tensorflow as tf from tensorflow.keras import layers, models import numpy as np # Create simple data: inputs are 2 numbers, output is 1 if sum >= 1 else 0 x_train = np.array([[0,0],[0,1],[1,0],[1,1]], dtype=float) y_train = np.array([0,1,1,1], dtype=float) # Build model model = models.Sequential([ layers.Dense(4, activation='relu', input_shape=(2,)), 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=20, verbose=0) # Predict on training data predictions = model.predict(x_train) # Print predictions rounded to 2 decimals for i, pred in enumerate(predictions): print(f"Input: {x_train[i]}, Prediction: {pred[0]:.2f}, Actual: {y_train[i]}") # Print final accuracy final_acc = history.history['accuracy'][-1] print(f"Final training accuracy: {final_acc:.2f}")
Use relu activation to help the network learn complex patterns.
sigmoid activation is good for outputs between 0 and 1, like yes/no.
Training for more epochs usually improves accuracy but watch out for overfitting.
A neural network learns from data by adjusting connections between layers.
Start with a simple model: input layer, one hidden layer, and output layer.
Use compile to set how the model learns and fit to train it.
Practice
compile method in a TensorFlow neural network model?Solution
Step 1: Understand the role of
Thecompilecompilemethod prepares the model for training by specifying how it learns, including the optimizer, loss function, and metrics.Step 2: Differentiate from other methods
Adding layers is done before compiling, training is done withfit, and predictions usepredict.Final Answer:
To set the optimizer, loss function, and metrics for training -> Option AQuick Check:
compile sets training details = A [OK]
- Confusing compile with fit (training)
- Thinking compile adds layers
- Mixing compile with prediction
Solution
Step 1: Recall correct TensorFlow syntax for adding layers
The correct way is to usetf.keras.layers.Densewith units first, then activation as a named argument.Step 2: Check each option
model.add(tf.keras.layers.Dense(10, activation='relu')) matches the correct syntax. model.add(Dense(activation='relu', 10)) has wrong argument order. model.add(tf.layers.Dense(activation='relu', units=10)) uses deprecatedtf.layers. model.add(tf.keras.Dense(10, activation='relu')) misseslayersin the path.Final Answer:
model.add(tf.keras.layers.Dense(10, activation='relu')) -> Option CQuick Check:
Correct layer syntax = D [OK]
- Wrong argument order in Dense layer
- Using deprecated tf.layers instead of tf.keras.layers
- Missing 'layers' in the import path
model = tf.keras.Sequential() model.add(tf.keras.layers.Dense(5, input_shape=(3,), activation='relu')) model.add(tf.keras.layers.Dense(2, activation='softmax')) print(model.output_shape)
Solution
Step 1: Understand input and output shapes
The input shape is (3,), first layer outputs 5 units, second layer outputs 2 units.Step 2: Determine final output shape
The model output shape is (None, 2) where None is batch size, 2 is output units.Final Answer:
(None, 2) -> Option BQuick Check:
Output units = 2 means shape (None, 2) [OK]
- Confusing input shape with output shape
- Ignoring batch size dimension None
- Mixing layer units and input dimensions
model = tf.keras.Sequential() model.add(tf.keras.layers.Dense(10, activation='relu')) model.compile(optimizer='adam', loss='mse') model.summary() model.fit(x_train, y_train, epochs=5)
Solution
Step 1: Check layer definition
The first Dense layer lacks an input shape, which is required for the model to know input dimensions.Step 2: Verify other parts
Loss 'mse' and optimizer 'adam' are valid. Batch size is optional in fit.Final Answer:
Missing input shape in the first layer -> Option DQuick Check:
Input shape needed in first layer = C [OK]
- Skipping input_shape in first layer
- Thinking batch_size is mandatory in fit
- Confusing loss and optimizer names
model = tf.keras.Sequential([ tf.keras.layers.Flatten(input_shape=(28,28)), tf.keras.layers.Dense(64, activation='relu'), tf.keras.layers.Dense(3, activation='softmax') ]) model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
Solution
Step 1: Analyze model layers
Flatten converts 2D image to 1D, Dense with 64 units and ReLU is hidden layer, final Dense with 3 units and softmax outputs class probabilities.Step 2: Check compile settings
Optimizer 'adam' is good, loss 'sparse_categorical_crossentropy' fits multi-class with integer labels, metrics include accuracy.Final Answer:
Correct setup for multi-class classification -> Option AQuick Check:
Softmax + sparse_categorical_crossentropy = B [OK]
- Using sigmoid for multi-class output
- Using MSE loss for classification
- Skipping Flatten for image input
