# Load necessary library
library(ggplot2)
library(e1071) # For SVM
# Set random seed for reproducibility
set.seed(123)
# Generate synthetic data
n <- 100
dosage <- runif(n, 0, 1) # Dosages between 0 and 1
cured <- ifelse(dosage > 0.3 & dosage < 0.7, 1, 0) # Cured in the "just right" range
# Create a data frame
data <- data.frame(dosage = dosage, cured = as.factor(cured))
# Plot the original data
ggplot(data, aes(x = dosage, y = cured, color = cured)) +
geom_point(size = 3) +
labs(title = "Drug Dosage vs. Cure Status",
x = "Dosage",
y = "Cure Status (0 = Not Cured, 1 = Cured)") +
scale_color_manual(values = c("red", "green")) +
theme_minimal()

# Transform data: Add dosage^2 as a new dimension
data$dosage_sq <- data$dosage^2
# Train a support vector machine
svm_model <- svm(cured ~ dosage + dosage_sq, data = data, kernel = "linear", cost = 1)
# Generate a grid of points to visualize decision boundary
grid <- expand.grid(
dosage = seq(0, 1, length.out = 100),
dosage_sq = seq(0, 1, length.out = 100)
)
# Predict classifications on the grid
grid$cured <- predict(svm_model, grid)
# Plot the transformed data and decision boundary
ggplot(data, aes(x = dosage, y = dosage_sq, color = cured)) +
geom_point(size = 3) +
geom_contour(data = grid, aes(x = dosage, y = dosage_sq, z = as.numeric(cured)),
breaks = 0.5, color = "blue") +
labs(title = "Support Vector Classifier in Transformed Space",
x = "Dosage",
y = "Dosage^2") +
scale_color_manual(values = c("red", "green")) +
theme_minimal()
## Warning: `stat_contour()`: Zero contours were generated
## Warning in min(x): no non-missing arguments to min; returning Inf
## Warning in max(x): no non-missing arguments to max; returning -Inf
