故事一:监督学习——猫咪分类
R代码示例:
# 加载必要的库
library(ggplot2)
library(caret)
# 生成一些模拟数据
set.seed(123)
data <- data.frame(
Length = rnorm(100, mean = 50, sd = 10),
Weight = rnorm(100, mean = 10, sd = 2),
Breed = factor(rep(c('Persian', 'Maine Coon', 'British Shorthair'), length.out = 100))
)
# 可视化数据
ggplot(data, aes(x = Length, y = Weight, color = Breed)) +
geom_point() +
labs(title = "猫咪品种分类", x = "长度", y = "重量")
# 划分训练集和测试集
set.seed(123)
trainIndex <- createDataPartition(data$Breed, p = 0.8, list = FALSE)
trainData <- data[trainIndex,]
testData <- data[-trainIndex,]
# 训练模型
model <- train(Breed ~ Length + Weight, data = trainData, method = "rpart")
# 预测
predictions <- predict(model, testData)
# 结果
confusionMatrix(predictions, testData$Breed)
## Confusion Matrix and Statistics
##
## Reference
## Prediction British Shorthair Maine Coon Persian
## British Shorthair 2 3 3
## Maine Coon 1 3 2
## Persian 3 0 1
##
## Overall Statistics
##
## Accuracy : 0.3333
## 95% CI : (0.1334, 0.5901)
## No Information Rate : 0.3333
## P-Value [Acc > NIR] : 0.5878
##
## Kappa : 0
##
## Mcnemar's Test P-Value : 0.3916
##
## Statistics by Class:
##
## Class: British Shorthair Class: Maine Coon Class: Persian
## Sensitivity 0.3333 0.5000 0.16667
## Specificity 0.5000 0.7500 0.75000
## Pos Pred Value 0.2500 0.5000 0.25000
## Neg Pred Value 0.6000 0.7500 0.64286
## Prevalence 0.3333 0.3333 0.33333
## Detection Rate 0.1111 0.1667 0.05556
## Detection Prevalence 0.4444 0.3333 0.22222
## Balanced Accuracy 0.4167 0.6250 0.45833
这个代码展示了如何使用监督学习的方法来分类猫咪的品种。我们用猫咪的长度和重量作为特征,来训练一个模型,并用这个模型来预测新的猫咪照片的品种。
故事二:非监督学习——顾客分群
现在,想象一下你是一个市场分析师,你想要了解你的顾客群体。你收集了大量关于顾客消费行为的数据,但这些数据没有明确的标签(比如顾客类型)。你希望通过分析这些数据,找出顾客的不同群体。这就是一个非监督学习的问题,因为你没有事先的标签,只能通过数据本身来发现规律。
# 加载必要的库
library(ggplot2)
library(cluster)
# 生成一些模拟数据
set.seed(123)
data <- data.frame(
AnnualIncome = rnorm(100, mean = 50000, sd = 10000),
SpendingScore = rnorm(100, mean = 50, sd = 10)
)
# 执行K均值聚类
set.seed(123)
kmeans_result <- kmeans(data, centers = 3)
# 将聚类结果添加到数据中
data$Cluster <- as.factor(kmeans_result$cluster)
# 可视化聚类结果
ggplot(data, aes(x = AnnualIncome, y = SpendingScore, color = Cluster)) +
geom_point() +
labs(title = "顾客分群", x = "年收入", y = "消费评分")
总结
监督学习:有明确的标签,用这些标签来训练模型。例如,猫咪分类。 非监督学习:没有明确的标签,通过数据本身发现规律。例如,顾客分群。
感谢关注!