DEV Community

Ricky
Ricky

Posted on

Training a simple neural network

A simple problem for training and testing a neural network is classifying the famous Iris dataset. The Iris dataset consists of 150 samples from three species of Iris flowers (Iris setosa, Iris virginica, and Iris versicolor). Each sample has four features: sepal length, sepal width, petal length, and petal width. The goal is to train a neural network to classify the Iris species based on these features.

Here's a step-by-step example using Python and popular libraries like NumPy and scikit-learn:

a. Load the Iris dataset:

You can load the Iris dataset from scikit-learn, a popular machine learning library in Python.

   from sklearn import datasets

   iris = datasets.load_iris()
   X = iris.data  # Features
   y = iris.target  # Target labels
Enter fullscreen mode Exit fullscreen mode

b. Data Preprocessing:

You may need to preprocess the data, such as scaling features, splitting the dataset into training and testing sets, and one-hot encoding the target labels (if using neural networks).

c. Build and Train the Neural Network:

You can use deep learning libraries like TensorFlow or PyTorch to build and train your neural network. Here's an example using TensorFlow and Keras:

   import tensorflow as tf
   from tensorflow import keras

   model = keras.Sequential([
       keras.layers.Dense(8, activation='relu', input_shape=(4,)),
       keras.layers.Dense(3, activation='softmax')
   ])

   model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
   model.fit(X_train, y_train, epochs=100)
Enter fullscreen mode Exit fullscreen mode

d. Evaluate the Model:

After training the model, you can evaluate its performance on the test set:

   test_loss, test_accuracy = model.evaluate(X_test, y_test)
   print(f'Test accuracy: {test_accuracy}')
Enter fullscreen mode Exit fullscreen mode

This example demonstrates a simple neural network for classifying the Iris dataset, which is a classic introductory problem for machine learning. You can modify the neural network architecture, hyperparameters, or try different datasets as you become more comfortable with neural networks.

Top comments (0)