Iris Data Classification in R: SVM Guide
In R language, there are multiple methods to classify iris data, with the most commonly used being training models using machine learning algorithms to predict the species of iris flowers. Below is a simple example demonstrating how to classify iris data using the Support Vector Machine (SVM) algorithm.
# 导入iris数据集
data(iris)
# 将数据集划分为训练集和测试集
set.seed(123)
train_indices <- sample(1:nrow(iris), 0.7 * nrow(iris))
train_data <- iris[train_indices, ]
test_data <- iris[-train_indices, ]
# 训练支持向量机模型
library(e1071)
svm_model <- svm(Species ~ ., data = train_data, kernel = "linear")
# 使用模型对测试集进行预测
predictions <- predict(svm_model, test_data)
# 计算准确率
accuracy <- sum(predictions == test_data$Species) / nrow(test_data)
cat("Accuracy:", accuracy)
In the above code, the iris dataset is first imported, then the dataset is split into a training set and a testing set. Next, the svm() function is used to train a support vector machine model, with Species as the target variable and the remaining columns as the feature variables. Finally, the trained model is used to predict the test set and calculate the accuracy.
In addition to the support vector machine algorithm, other machine learning algorithms like decision trees and random forests can also be used to classify the iris dataset. By adjusting parameters and trying different algorithms, the most suitable model for the dataset can be found.