R语言加权logistic回归代码
时间: 2023-10-12 11:05:38 浏览: 301
以下是一个基于R语言的加权logistic回归代码示例,用于分析二元分类问题,其中使用了权重矩阵来调整样本权重:
# 训练集和测试集数据
train_data <- read.csv("train_data.csv")
test_data <- read.csv("test_data.csv")
# 创建权重矩阵
weights <- matrix(rep(1, nrow(train_data)), nrow = nrow(train_data), ncol = 1)
weights[train_data$class == 1,] <- 0.5
# 拟合加权logistic回归模型
model <- glm(class ~ ., data = train_data, family = "binomial", weights = weights)
# 在训练集和测试集上进行预测
train_preds <- predict(model, train_data, type = "response")
test_preds <- predict(model, test_data, type = "response")
# 计算模型性能指标
train_acc <- mean((train_data$class == 1 & train_preds >= 0.5) |
(train_data$class == 0 & train_preds < 0.5))
test_acc <- mean((test_data$class == 1 & test_preds >= 0.5) |
(test_data$class == 0 & test_preds < 0.5))
print(paste("训练集准确率:", train_acc))
print(paste("测试集准确率:", test_acc))
阅读全文