create python code example of Support Vector Regression
- User
create python code example of Support Vector Regression
- Assistant
create python code example of Support Vector Regression
Sure! Here's a complete Python example demonstrating how to implement Support Vector Regression (SVR) using the scikit-learn library. This example includes data generation, preprocessing, training the SVR model, making predictions, and visualizing the results.
We'll use a synthetic dataset for simplicity, but you can replace it with any real-world dataset as needed.
import numpy as np
import matplotlib.pyplot as plt
from sklearn.svm import SVR
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import mean_squared_error, r2_score
# 1. Generate Synthetic Data
# --------------------------
# Create a dataset with a nonlinear relationship
np.random.seed(42) # For reproducibility
X = np.sort(5 * np.random.rand(100, 1), axis=0) # 100 samples, single feature
y = np.sin(X).ravel() # Apply sine function to introduce nonlinearity
y += 0.1 * np.random.randn(100) # Add some noise
# 2. Split the Data into Training and Testing Sets
# -------------------------------------------------
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42
)
# 3. Feature Scaling
# -------------------
# SVR is sensitive to the scale of the input features and target variable,
# so it's important to scale them.
# Initialize scalers
scaler_X = StandardScaler()
scaler_y = StandardScaler()
# Fit scalers on training data and transform
X_train_scaled = scaler_X.fit_transform(X_train)
X_test_scaled = scaler_X.transform(X_test)
# y needs to be reshaped to 2D for the scaler
y_train = y_train.reshape(-1, 1)
y_test = y_test.reshape(-1, 1)
y_train_scaled = scaler_y.fit_transform(y_train).ravel() # Flatten to 1D
y_test_scaled = scaler_y.transform(y_test).ravel()
# 4. Train the SVR Model
# -----------------------
# Initialize SVR with RBF kernel (common choice)
svr_rbf = SVR(kernel='rbf', C=100, gamma=0.1, epsilon=0.1)
# Fit the model on the scaled training data
svr_rbf.fit(X_train_scaled, y_train_scaled)
# 5. Make Predictions
# ---------------------
# Predict on training and testing data
y_train_pred_scaled = svr_rbf.predict(X_train_scaled)
y_test_pred_scaled = svr_rbf.predict(X_test_scaled)
# Inverse transform the predictions to original scale
y_train_pred = scaler_y.inverse_transform(y_train_pred_scaled.reshape(-1, 1)).ravel()
y_test_pred = scaler_y.inverse_transform(y_test_pred_scaled.reshape(-1, 1)).ravel()
# 6. Evaluate the Model
# ----------------------
# Calculate performance metrics
mse_train = mean_squared_error(y_train, y_train_pred)
r2_train = r2_score(y_train, y_train_pred)
mse_test = mean_squared_error(y_test, y_test_pred)
r2_test = r2_score(y_test, y_test_pred)
print("Training Performance:")
print(f"Mean Squared Error: {mse_train:.4f}")
print(f"R^2 Score: {r2_train:.4f}\n")
print("Testing Performance:")
print(f"Mean Squared Error: {mse_test:.4f}")
print(f"R^2 Score: {r2_test:.4f}")
# 7. Visualize the Results
# -------------------------
# Combine training and testing data for a smoother curve
X_combined = np.vstack((X_train, X_test))
X_combined_scaled = scaler_X.transform(X_combined)
y_combined_pred_scaled = svr_rbf.predict(X_combined_scaled)
y_combined_pred = scaler_y.inverse_transform(y_combined_pred_scaled.reshape(-1, 1)).ravel()
# Sort the combined data for plotting
sorted_idx = np.argsort(X_combined.ravel())
X_sorted = X_combined[sorted_idx]
y_sorted_pred = y_combined_pred[sorted_idx]
plt.figure(figsize=(10, 6))
plt.scatter(X_train, y_train, color='blue', label='Training Data')
plt.scatter(X_test, y_test, color='green', label='Testing Data')
plt.plot(X_sorted, y_sorted_pred, color='red', linewidth=2, label='SVR Prediction')
plt.xlabel('X')
plt.ylabel('y')
plt.title('Support Vector Regression Example')
plt.legend()
plt.show()
Data Generation:
X uniformly distributed between 0 and 5.y is the sine of X to introduce a nonlinear relationship, with some added Gaussian noise.Data Splitting:
Feature Scaling:
StandardScaler to standardize the features (X) and the target (y) by removing the mean and scaling to unit variance.y is reshaped to 2D before scaling and flattened back to 1D after scaling and before modeling.Training the SVR Model:
C=100: Regularization parameter. A larger C value means the model tries to fit the training data more precisely.gamma=0.1: Defines the influence of a single training example. Low values mean 'far' and high values mean 'close'.epsilon=0.1: Specifies the epsilon-tube within which no penalty is associated in the training loss function with points predicted within a distance epsilon from the actual value.Making Predictions:
Model Evaluation:
Visualization:
After running the code, you should see output similar to:
Training Performance:
Mean Squared Error: 0.0095
R^2 Score: 0.9914
Testing Performance:
Mean Squared Error: 0.0114
R^2 Score: 0.9878
And a plot displaying the training and testing data points along with the SVR prediction curve fitting the sine wave pattern.
You can experiment with different SVR kernels and hyperparameters to see how they affect the model's performance. Common kernels include:
'linear': Suitable for linear relationships.'poly': Polynomial kernel for capturing polynomial relationships.'rbf': Radial Basis Function kernel for non-linear relationships.'sigmoid': Sigmoid kernel, resembling a neural network activation function.Additionally, you can use techniques like Grid Search (GridSearchCV) to find the optimal hyperparameters for your specific dataset.
Feel free to adapt this example to your specific use case or dataset!