The provided Python code demonstrates the implementation of a simple neural network using TensorFlow. The network utilizes the MNIST dataset, which involves classifying handwritten digits from 0 to 9. The model is constructed with a flatten layer to reshape the input data, followed by a dense layer with ReLU activation, dropout layer for regularization purposes, and a final dense layer with softmax activation for multi-class classification. The model is compiled with the Adam optimizer and sparse categorical cross-entropy loss. The code proceeds to train the model using the training data and evaluate its performance using the test data.
Write a simple neural network in python
Certainly! Here’s an example of a simple neural network implemented in Python using the TensorFlow library:
import tensorflow as tf
from tensorflow.keras.datasets import mnist
# Load the MNIST dataset
(X_train, y_train), (X_test, y_test) = mnist.load_data()
# Preprocess the data
X_train = X_train / 255.0
X_test = X_test / 255.0
# Create a simple neural network model
model = tf.keras.models.Sequential([
tf.keras.layers.Flatten(input_shape=(28, 28)),
tf.keras.layers.Dense(128, activation='relu'),
tf.keras.layers.Dropout(0.2),
tf.keras.layers.Dense(10, activation='softmax')
])
# Compile the model
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
# Train the model
model.fit(X_train, y_train, epochs=5, validation_data=(X_test, y_test))
# Evaluate the model
loss, accuracy = model.evaluate(X_test, y_test)
print(f'Test loss: {loss}')
print(f'Test accuracy: {accuracy}')
This simple neural network uses the MNIST dataset, where images of handwritten digits are classified into their respective digits (0-9). The model consists of a flatten layer to convert the 2D image data into 1D, followed by a dense layer with ReLU activation, dropout layer for regularization, and a final dense layer with softmax activation for multi-class classification. The model is compiled with the adam optimizer and sparse categorical cross-entropy loss. Finally, the model is trained using the training data and evaluated using the test data.