Solution and implementation for QC1 from Artificial Neural Network (ann).
!pip install tensorflow scikit-learn matplotlib -q
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
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)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
)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()history = model.fit(
X_train, y_train,
epochs=50,
batch_size=8,
validation_split=0.2
)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))plt.plot(history.history['accuracy'], label='train acc')
plt.plot(history.history['val_accuracy'], label='val acc')
plt.legend()
plt.title("Accuracy")
plt.show()# 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])