Sync portfolio laboratory source
This commit is contained in:
commit
de1d43466d
5 changed files with 92 additions and 0 deletions
5
.gitignore
vendored
Normal file
5
.gitignore
vendored
Normal file
|
|
@ -0,0 +1,5 @@
|
||||||
|
/results.csv
|
||||||
|
/dashboard.html
|
||||||
|
/dashboard_files/
|
||||||
|
/.Rhistory
|
||||||
|
/.RData
|
||||||
22
README.md
Normal file
22
README.md
Normal file
|
|
@ -0,0 +1,22 @@
|
||||||
|
# Логистическая регрессия
|
||||||
|
|
||||||
|
## Задание
|
||||||
|
|
||||||
|
Оцените вероятность покупки по цене и скидке. Измерьте качество при нескольких порогах.
|
||||||
|
|
||||||
|
## Решение
|
||||||
|
|
||||||
|
Логит моделирует log(p/(1−p)). Чувствительность и специфичность меняются с порогом. Их оценивают на данных вне обучающей выборки.
|
||||||
|
|
||||||
|
Исходные данные синтетические. Скрипт фиксирует генератор случайных чисел и проверяет результат перед экспортом. Quarto строит график и таблицу из того же расчёта.
|
||||||
|
|
||||||
|
```sh
|
||||||
|
Rscript --vanilla analysis.R results.csv
|
||||||
|
quarto render dashboard.qmd
|
||||||
|
```
|
||||||
|
|
||||||
|
Нужны R 4 и Quarto с knitr.
|
||||||
|
|
||||||
|
## Дашборд в Apache Superset
|
||||||
|
|
||||||
|
Загрузите results.csv в учебную БД и добавьте таблицу как датасет. Укажите `threshold` на горизонтальной оси и `sensitivity` на вертикальной. Если нужна агрегация, используйте `AVG(sensitivity)` по `threshold`. Сохраните график и таблицу в дашборд «Логистическая регрессия». Запрос для проверки результата находится в superset.sql.
|
||||||
21
analysis.R
Normal file
21
analysis.R
Normal file
|
|
@ -0,0 +1,21 @@
|
||||||
|
# Синтетические данные и расчёт метрик для обоих дашбордов.
|
||||||
|
set.seed(2026)
|
||||||
|
price <- runif(180, 1, 10)
|
||||||
|
discount <- rbinom(180, 1, 0.4)
|
||||||
|
bought <- rbinom(180, 1, plogis(1.5 - 0.4 * price + discount))
|
||||||
|
sample_data <- data.frame(bought, price, discount)
|
||||||
|
model <- glm(bought ~ price + discount, data = sample_data[1:120, ], family = binomial())
|
||||||
|
p <- predict(model, newdata = sample_data[121:180, ], type = "response")
|
||||||
|
actual <- sample_data$bought[121:180]
|
||||||
|
threshold <- seq(0.2, 0.8, by = 0.1)
|
||||||
|
result <- data.frame(threshold,
|
||||||
|
sensitivity = vapply(threshold, function(t) mean(p[actual == 1] >= t), numeric(1)),
|
||||||
|
specificity = vapply(threshold, function(t) mean(p[actual == 0] < t), numeric(1)))
|
||||||
|
|
||||||
|
# Проверяет конечность основной метрики перед экспортом.
|
||||||
|
stopifnot(nrow(result) > 1, all(is.finite(result$sensitivity)))
|
||||||
|
if (sys.nframe() == 0L) {
|
||||||
|
arguments <- commandArgs(trailingOnly = TRUE)
|
||||||
|
stopifnot(length(arguments) == 1L)
|
||||||
|
write.csv(result, arguments[1], row.names = FALSE)
|
||||||
|
}
|
||||||
40
dashboard.qmd
Normal file
40
dashboard.qmd
Normal file
|
|
@ -0,0 +1,40 @@
|
||||||
|
---
|
||||||
|
title: "Логистическая регрессия"
|
||||||
|
lang: ru
|
||||||
|
format: dashboard
|
||||||
|
execute:
|
||||||
|
echo: false
|
||||||
|
---
|
||||||
|
|
||||||
|
```{r}
|
||||||
|
source("analysis.R", local = TRUE)
|
||||||
|
```
|
||||||
|
|
||||||
|
# Результаты
|
||||||
|
|
||||||
|
## Row
|
||||||
|
|
||||||
|
### График
|
||||||
|
|
||||||
|
```{r}
|
||||||
|
x <- result$threshold
|
||||||
|
y <- result$sensitivity
|
||||||
|
if (is.numeric(x)) {
|
||||||
|
plot(x, y, xlab = "threshold", ylab = "sensitivity", pch = 19, col = "#245d76")
|
||||||
|
} else {
|
||||||
|
par(mar = c(7, 4, 2, 1))
|
||||||
|
barplot(y, names.arg = x, ylab = "sensitivity", las = 2, col = "#245d76")
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Таблица
|
||||||
|
|
||||||
|
```{r}
|
||||||
|
knitr::kable(result, digits = 3)
|
||||||
|
```
|
||||||
|
|
||||||
|
## Row
|
||||||
|
|
||||||
|
### Как читать результат
|
||||||
|
|
||||||
|
Логит моделирует log(p/(1−p)). Чувствительность и специфичность меняются с порогом. Их оценивают на данных вне обучающей выборки.
|
||||||
4
superset.sql
Normal file
4
superset.sql
Normal file
|
|
@ -0,0 +1,4 @@
|
||||||
|
-- Замените portfolio_results именем таблицы, куда импортирован results.csv.
|
||||||
|
SELECT threshold, sensitivity
|
||||||
|
FROM portfolio_results
|
||||||
|
ORDER BY threshold;
|
||||||
Loading…
Add table
Add a link
Reference in a new issue