To kick off our exploration into SVM with a practical example, we'll begin by setting up our coding environment. This involves importing necessary libraries, loading the dataset we're going to use, and then focusing on preparing our data by splitting it into training and testing sets. Given that SVM, especially with the RBF kernel, is computationally intensive, we will use a subset of the data for educational purposes. This smaller dataset size will help us grasp the concepts and run through the exercises more quickly without a significant wait time for the model to train. Let's dive into the code:
# Importing necessary libraries
import pandas as pd
from math import sqrt
from sklearn import svm
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error
from sklearn.datasets import fetch_california_housing
# Loading the California Housing dataset
housing_data = fetch_california_housing()
# Creating a dataframe and reducing the data to the first 1000 samples for faster processing
housing_df = pd.DataFrame(housing_data.data[:1000], columns=housing_data.feature_names)
housing_df['MedHouseVal'] = housing_data.target[:1000]
# Data Splitting
X = housing_df[housing_data.feature_names]
y = housing_df['MedHouseVal']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)
In this setup, by selecting only the first 1000 datapoints from our dataset, we aptly reduce the computational overhead. This helps in significantly accelerating the training process, making it more feasible for an educational setting. The test_size=0.2 parameter remains, meaning we reserve 20% of our subset of the data for testing our model, maintaining a robust evaluation process. This decision creates a balanced foundation for creating, training, and evaluating our SVM model in the forthcoming sections, without spending excessive time on the training phase.