DL record
DL record
Date:
WEEK – 3
3a) Design a neural Network for classifying news wires (Multi class classification) using
Reuters dataset.
Aim: To design a neural Network for classifying news wires (Multi class classification) using
Reuters dataset.
Description:
Multiclass Classification is the classification of samples in more than two classes. Classifying
samples into precisely two categories is colloquially referred to as Binary Classification. This
piece will design a neural network to classify newsreels from the Reuters dataset, published
by Reuters in 1986, into forty-six mutually exclusive classes using the Python library Keras.
This problem is a typical example of a single-label, multiclass classification problem.
Program:
import matplotlib.pyplot as plt
# Compile, train, and evaluate model
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
history = model.fit(train_data, train_labels, epochs=5,
validation_data=(test_data, test_labels))
test_loss, test_acc = model.evaluate(test_data, test_labels)
# Plot loss & accuracy
for metric in ['loss', 'accuracy']:
plt.plot(history.history[metric], label='Train')
plt.plot(history.history[f'val_{metric}'], label='Validation')
plt.title(f'Model {metric.capitalize()}')
plt.xlabel('Epoch')
plt.legend()
plt.show()
print('Test accuracy:', test_acc)
Output:
Output:
m = VGG16(weights='imagenet')
x = np.random.rand(1, 224, 224, 3) * 255
x = preprocess_input(x)
p = m.predict(x)
d = decode_predictions(p, top=3)[0]
Output:
m = Sequential([
Conv2D(32, (3,3), activation='relu', input_shape=(32,32,3)),
MaxPooling2D((2,2)),
Conv2D(64, (3,3), activation='relu'), MaxPooling2D((2,2)),
Flatten(),
Dense(128, activation='relu'), Dropout(0.2), Dense(10,
activation='softmax')
])
m.compile(optimizer='adam', loss='categorical_crossentropy',
metrics=['accuracy'])
m.fit(a, b, batch_size=32, epochs=3, validation_data=(c, d))
print(f'Test accuracy: {m.evaluate(c, d)[1]:.2f}')
Output:
Output:
# Build model
model = Sequential([
Embedding(10000, 8, input_length=20),
Flatten(),
Dense(1, activation='sigmoid')
])
Output:
Output:
# Prepare data
X_train, X_test, y_train, y_test =
train_test_split(df.drop(columns='AHD'), df['AHD'], test_size=0.3,
random_state=23)
X_train, X_test = StandardScaler().fit_transform(X_train),
StandardScaler().fit_transform(X_test)
Output:
# Train model
Model.fit(data, estimator=MaximumLikelihoodEstimator)
d_infer = VariableElimination(Model) # Inference
q = d_infer.query(variables=['AHD'], evidence={'Chol': 200})
print(q)
Output:
# Make predictions
y_pred = rf.predict(X_test)
# Evaluate accuracy
print(f"Random Forest Accuracy: {accuracy_score(y_test, y_pred):.4f}")
Output:
# Generate dataset
X, y = make_classification(n_samples=1000, n_features=20,
random_state=42)
X_train, X_test, y_train, y_test = train_test_split(X, y,
test_size=0.2, random_state=42)
# Predictions
y_pred = gbm.predict(X_test)
# Accuracy
print(f"PyTorch-based Gradient Boosting Accuracy:
{accuracy_score(y_test, y_pred):.4f}")
Output: