This exercise involves a series of steps to build, train, and evaluate a neural network model using a dataset related to advertising. Below, I'll guide you through these steps in a sequential manner using Python, along with some popular libraries such as pandas, scikit-learn, and TensorFlow/Keras.
Steps to follow
1. Download the Data
First, create a CSV file from the snippet you provided or load it if accessible through a URL.
python
import pandas as pd
# Assuming the data snippet is saved in a file called 'advertising.csv'
data = pd.read_csv('advertising.csv')
print(data.head())
2. Split the Data into Training and Test Sets
python
from sklearn.model_selection import train_test_split
# Features and target
X = data[['TV', 'Radio', 'Newspaper']]
y = data['Sales']
# Split the data
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
3. Define the Neural Network Architecture
We will use Keras from TensorFlow to define and train our neural network model.
python
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
# Initialize the model
model = Sequential()
# Add layers
model.add(Dense(64, input_dim=3, activation='relu')) # Input layer and first hidden layer
model.add(Dense(32, activation='relu')) # Second hidden layer
model.add(Dense(1)) # Output layer for regression
# Compile the model
model.compile(optimizer='adam', loss='mean_squared_error', metrics=['mean_absolute_error'])
# Display the model summary
model.summary()
4. Train the Model
python
# Train the model
history = model.fit(X_train, y_train, epochs=100, validation_split=0.2, verbose=1)
5. Evaluate the Model
After training, we will evaluate its performance on the test set.
python
import matplotlib.pyplot as plt
# Evaluate on test data
test_loss, test_mae = model.evaluate(X_test, y_test)
print(f"Test MAE: {test_mae}")
# Make predictions
predictions = model.predict(X_test)
# Plot training & validation MAE values
plt.plot(history.history['mean_absolute_error'])
plt.plot(history.history['val_mean_absolute_error'])
plt.title('Model mean_absolute_error')
plt.ylabel('MAE')
plt.xlabel('Epoch')
plt.legend(['Train', 'Validation'], loc='upper left')
plt.show()
# Compare predictions with actual values
comparison = pd.DataFrame({'Actual': y_test, 'Predicted': predictions.flatten()})
print(comparison.head())
Summary of the Steps
Download the data: Load the data into a pandas DataFrame.
Split the data: Use train_test_split from scikit-learn to split the data into training and test sets.
Define the model architecture: Use Keras' Sequential API to build the model. Add input, hidden, and output layers.
Compile the model: Define the optimizer, loss function, and metrics.
Train the model: Use the fit method to train the model with a specified number of epochs.
Evaluate the model: Use the evaluate and predict methods to assess the model's performance and make predictions on the test data.
Comparison with Previous Models
To compare this neural network model with the model from Atelier N°1 (which might be a simpler model like linear regression), you would typically look at metrics such as Mean Absolute Error (MAE) or Mean Squared Error (MSE) on the test set. Here, both training and evaluation are done using mean_absolute_error.
Make sure libraries like TensorFlow, pandas, scikit-learn, and matplotlib are installed in your Python environment.
To provide the performance of the neural network model on the given dataset, we can follow the steps outlined previously. Specifically, after training the model, we evaluate it on the test dataset and calculate relevant performance metrics like Mean Absolute Error (MAE). Here's a complete example of how to execute these steps and assess the model's performance:
Complete Code to Train and Evaluate the Neural Network Model
python
import pandas as pd
from sklearn.model_selection import train_test_split
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
import matplotlib.pyplot as plt
# Load the data
data = pd.read_csv('advertising.csv')
print(data.head())
# Split the data into features and target variable
X = data[['TV', 'Radio', 'Newspaper']]
y = data['Sales']
# Split the data into training and test sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# Build the neural network model
model = Sequential()
model.add(Dense(64, input_dim=3, activation='relu')) # First hidden layer
model.add(Dense(32, activation='relu')) # Second hidden layer
model.add(Dense(1)) # Output layer for regression
# Compile the model
model.compile(optimizer='adam', loss='mean_squared_error', metrics=['mean_absolute_error'])
# Display the model summary
model.summary()
# Train the model
history = model.fit(X_train, y_train, epochs=100, validation_split=0.2, verbose=1)
# Evaluate the model
test_loss, test_mae = model.evaluate(X_test, y_test)
print(f"Test MAE: {test_mae}")
# Make predictions
predictions = model.predict(X_test)
# Plot training & validation MAE values
plt.plot(history.history['mean_absolute_error'])
plt.plot(history.history['val_mean_absolute_error'])
plt.title('Model mean_absolute_error')
plt.ylabel('MAE')
plt.xlabel('Epoch')
plt.legend(['Train', 'Validation'], loc='upper left')
plt.show()
# Compare predictions with actual values
comparison = pd.DataFrame({'Actual': y_test.values, 'Predicted': predictions.flatten()})
print(comparison.head())
Explanation and Output
Loading and Splitting the Data: The dataset is loaded and split into training and test sets.
Building the Neural Network Model: A Sequential model is created with two hidden layers containing 64 and 32 neurons, respectively, both using ReLU activation.
Training the Model: The model is compiled with Adam optimizer and mean squared error loss, and trained for 100 epochs.
Evaluating the Model: The test set's mean absolute error (MAE) is computed to evaluate the model's performance.
Visualizing Training Progress: The training and validation MAE over epochs is plotted.
Comparing Predictions: A DataFrame is created to compare the model's predictions with the actual sales values from the test set.
Performance Metrics
After running the script, the output should display the test MAE, which provides an assessment of the model's performance on unseen data. Here is a sample output:
python
Test MAE: 1.237
This means the average absolute error in predicting sales using the test dataset is approximately 1.237 units (adjust the exact figure based on your dataset splitting and random state).
Comparing With Previous Models
To conclude the comparison with the model from Atelier N°1, you should compare the MAE value obtained above with the MAE (or other relevant metrics) of the previous model. If the previous model achieved an MAE of, say, 1.7, then the neural network model with an MAE of 1.237 indicates an improvement.
Remember to adjust the performance metrics and analysis based on specific results from running the complete script on your system, as actual numbers may vary.