Ex 7
Ex 7
import pandas as pd
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout
from tensorflow.keras.utils import to_categorical
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler, LabelEncoder
# Load the dataset
def load_data(csv_file):
data = pd.read_csv(csv_file)
X = data.iloc[:, 1:-1].values # Assuming features are in all columns except the first and
last
y = data.iloc[:, -1].values # Assuming labels are in the last column
return X, y
# Load the data
csv_file = 'UrbanSound8K.csv' # Replace with the path to your CSV file
X, y = load_data(csv_file)
# Normalize the features
scaler = StandardScaler()
X = scaler.fit_transform(X)
# Convert labels to numerical format
label_encoder = LabelEncoder()
y_encoded = label_encoder.fit_transform(y)
# Convert labels to categorical
num_classes = len(np.unique(y_encoded))
y_categorical = to_categorical(y_encoded, num_classes=num_classes)
# Split the dataset into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X, y_categorical, test_size=0.2,
random_state=42)
# Define a simple neural network model
model = Sequential([
Dense(128, activation='relu', input_shape=(X_train.shape[1],)),
Dropout(0.5),
Dense(64, activation='relu'),
Dropout(0.5),
Dense(num_classes, activation='softmax')
])
# Compile the model
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
# Train the model
history = model.fit(X_train, y_train, epochs=10, batch_size=32, validation_data=(X_test,
y_test))
# Evaluate the model
test_loss, test_acc = model.evaluate(X_test, y_test)
print(f'Test Accuracy: {test_acc:.4f}')
# Make predictions (example)
def predict(features):
features = scaler.transform([features])
prediction = model.predict(features)
predicted_class_index = np.argmax(prediction)
predicted_class = label_encoder.inverse_transform([predicted_class_index])[0]
return predicted_class
# Example prediction (replace with actual feature values)
example_features = X_test[0] # Using a sample from test data
predicted_class = predict(example_features)
print(f'Predicted Class: {predicted_class}')