Group C

QC1: 1. How to Train a Neural Network with TensorFlow/Pytorch and evaluation of logistic regression using tensorflow

Neural Network Training

Solution and implementation for QC1 from Artificial Neural Network (ann).

C1_neural_network.ipynb Download
Code Cell [In]
!pip install tensorflow scikit-learn matplotlib -q
Code Cell [In]
import tensorflow as tf
from tensorflow import keras
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import accuracy_score, confusion_matrix, classification_report
import numpy as np
import matplotlib.pyplot as plt
Code Cell [In]
data = load_iris()
X = data.data
y = data.target

print("Feature shape:", X.shape)
print("Classes:", np.unique(y))
print("Class names:", data.target_names)
Code Cell [In]
scaler = StandardScaler()
X = scaler.fit_transform(X)

X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, random_state=42
)
Code Cell [In]
model = keras.Sequential([
    keras.layers.Dense(3, activation='softmax', input_shape=(X.shape[1],))
])

model.compile(
    optimizer='adam',
    loss='sparse_categorical_crossentropy',
    metrics=['accuracy']
)

model.summary()
Code Cell [In]
history = model.fit(
    X_train, y_train,
    epochs=50,
    batch_size=8,
    validation_split=0.2
)
Code Cell [In]
loss, accuracy = model.evaluate(X_test, y_test)
print("Test Accuracy:", accuracy)

y_pred = model.predict(X_test)
y_pred_classes = np.argmax(y_pred, axis=1)

print("\nConfusion Matrix:")
print(confusion_matrix(y_test, y_pred_classes))

print("\nClassification Report:")
print(classification_report(y_test, y_pred_classes))
Code Cell [In]
plt.plot(history.history['accuracy'], label='train acc')
plt.plot(history.history['val_accuracy'], label='val acc')
plt.legend()
plt.title("Accuracy")
plt.show()
Code Cell [In]
# Example input: [sepal length, sepal width, petal length, petal width]
sample = np.array([[5.1, 3.5, 1.4, 0.2]])

# Apply same scaling
sample = scaler.transform(sample)

prediction = model.predict(sample)
class_index = np.argmax(prediction)

print("Raw probabilities:", prediction)
print("Predicted class:", data.target_names[class_index])

Other Questions in Artificial Neural Network

See All Available Questions
Download