Let’s create a basic Neural Network with TensorFlow

What is a Neural Network?

tensorflow-ar21-1024x512 Let’s create a basic Neural Network with TensorFlow

With that said.. let’s create one using TensorFlow.

pip install numpy matplotlib tensorflow
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
# Define the number of neurons for each layer
input_layer = 2
hidden_layer = 3
output_layer = 1
# Define the architecture of the neural network
model = tf.keras.models.Sequential([
    tf.keras.layers.Dense(hidden_layer, input_shape=(input_layer,), activation='relu'),
    tf.keras.layers.Dense(output_layer, activation='sigmoid')
])
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
# Generate some random data
X = np.random.rand(1000, input_layer)
y = np.random.randint(2, size=(1000, output_layer))
model.fit(X, y, epochs=100)
loss, accuracy = model.evaluate(X, y)
print('Loss:', loss)
print('Accuracy:', accuracy)

How to use your shiny new Neural Network

# Generate new data for prediction
X_new = np.random.rand(5, input_layer)
# Use the neural network to make predictions
predictions = model.predict(X_new)# Print the predictions
print(predictions)
# Use the neural network to make binary predictions
binary_predictions = model.predict_classes(X_new)
# Print the binary predictions
print(binary_predictions)

Here’s another example of how to use this Neural Network

import numpy as np
import tensorflow as tf
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
# Load the Iris dataset
iris = load_iris()# Split the dataset into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(iris.data, iris.target, test_size=0.2, random_state=42)# Define the architecture of the neural network
model = tf.keras.models.Sequential([
    tf.keras.layers.Dense(10, input_shape=(4,), activation='relu'),
    tf.keras.layers.Dense(1, activation='sigmoid')
])# Compile the model
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])# Train the model
model.fit(X_train, y_train, epochs=50, batch_size=10)# Evaluate the model on the testing set
loss, accuracy = model.evaluate(X_test, y_test)
print('Loss:', loss)
print('Accuracy:', accuracy)
Founder & CEO

Lyron Foster is a Prolific Multinational Serial Entrepreneur, Blogger, Author, IT Trainer, Polyglot Coder, Real Estate Investor and Technologist.