PYTHON ALTERNATIVES TO THE SHINY TEACHING APP Prepared for Sara Brumbaugh / Ceres Analytics, October 6, 2026 START IN FIVE STEPS 1. Extract the entire ZIP into one folder. Do not run files from inside the ZIP. Keep the eleven lesson scripts, input_data.py, model_tools.py and data folder together. Each lesson runs on its own; none imports another lesson. Clustering is deliberately a three-step workflow using saved CSV files. 2. Use Python 3.10 or later with pip. In a terminal opened in the extracted Python_Analytics_Teaching folder, install the six libraries once: python -m pip install -r requirements.txt Windows may require 'py' instead of 'python'; macOS/Linux may require 'python3'. An existing JupyterHub/Colab Python environment can also be used. No R installation is required. Installation needs internet access. 3. Open linear_ols.py in your editor. The SETTINGS block at the beginning has the filename, dependent variable (Y), explanatory variables (Xs), sorting variable, and holdout count. Defaults already match a supplied example. Leave them unchanged for your first run. 4. Run: python linear_ols.py In Spyder or another editor, use its Run command with the correct interpreter. In Jupyter, with the notebook in the extracted folder, run a cell containing: %run linear_ols.py This runs the existing script without copying its contents into a notebook. In Colab, upload the ZIP and extract it, install requirements, then %cd into Python_Analytics_Teaching before using %run. Do not import the scripts just to run them: importing is intentionally side-effect free. 5. Read the printed model summary. Open outputs/linear_ols to see coefficients, metrics, a predictions CSV and saved PNG plots. Each lesson has its own output folder, so an OLS run does not overwrite your tree results. Re-running the SAME lesson overwrites that lesson's outputs. THE ELEVEN LESSONS File Purpose / default example linear_ols.py OLS regression / Product1 quarterly sales linear_stepwise.py Bidirectional F-test selection / quarterly sales linear_all_subsets.py Exhaustive subsets / quarterly sales linear_lasso.py Lasso, cross-validation and optional OLS refit / sales cluster_ward.py STEP 1: build a Ward tree / wine customers cluster_evaluate.py STEP 2: compare k=2 through k=8 / saved wine tree cluster_assign.py STEP 3: attach membership for selected k / saved tree logistic_regression.py Binomial logistic regression / Challenger launches logistic_stepwise.py Bidirectional likelihood-ratio selection / Challenger tree_classification.py Binary classification tree / telecom churn tree_regression.py Numeric regression tree / quarterly sales Run the eight supervised lessons in any order. Run the three clustering lessons in this order: python cluster_ward.py python cluster_evaluate.py python cluster_assign.py All three clustering scripts must use the same WORKFLOW_FOLDER setting. Choose N_CLUSTERS in cluster_assign.py after inspecting cluster_evaluation.csv and silhouette_by_k.png. The supplied default assignment uses k=2, like Shiny; the example evaluation suggests considering k=3. Cluster numbers are labels, not a ranking of customers. Changing the input or clustering variables means re-running STEP 1 before the later steps. Steps 2 and 3 use the saved snapshot, not a newly edited copy of the original data. HOW TO USE YOUR OWN COMMA- OR TAB-DELIMITED FILE input_data.py contains the shared read_data(filename, delimiter=None) function. All eleven lessons ultimately read tables through this function, or use saved CSV workflow state. The first line of a student file must contain unique column headings. A row is one observation; a column is one variable. A CSV should quote text containing commas. A tab-delimited file may have .txt or .tsv extension. UTF-8 with or without a byte-order mark is supported. Excel should export CSV UTF-8 or tab-delimited text, not .xlsx, for this reader. Example settings for a file of house prices: DATA_FILE = 'data/houses.csv' DELIMITER = None Y_COLUMN = 'Sale price' X_COLUMNS = ['Area', 'Age', 'Neighborhood'] CATEGORICAL_COLUMNS = ['Neighborhood'] SORT_BY = None HOLDOUT_COUNT = 0 Text predictor columns are automatically categorical. List a numeric category code in CATEGORICAL_COLUMNS to prevent its being treated as a quantity. Do not include IDs, phone numbers, or the dependent variable in X_COLUMNS. Use original headings exactly; spaces, apostrophes and '?' are supported. To see headings yourself: from input_data import read_data table = read_data('data/churn.csv') print(table.columns.tolist()) print(table.head()) DATA_FILE is resolved relative to the lesson script, independent of the terminal's current directory. Absolute paths also work. On Windows, use a raw string such as r'C:\Users\Sara\Documents\houses.csv' to avoid backslash escape problems. Outputs are also resolved beside the scripts. Missing values: blank, NA, N/A and NaN mean missing. Infinite numeric values are treated as missing during model preparation. A literal string 'NULL' is not automatically missing. Missing values in columns you did not select have no effect. A selected predictor with missing data prevents that row from being used for training or prediction. A missing response does not prevent a forecast if predictors are complete. Excluded rows remain visible in predictions.csv. The output-only '_source_row' column numbers source rows starting at 1; reserve that heading for the scripts. No input file is overwritten by any lesson. CATEGORICAL VARIABLES For regression/logistic/tree Xs, dummy columns compare each category with the first alphabetically sorted training category. Encoding decisions use training rows only. An unseen category in a holdout/future row cannot be scored; the script announces this and leaves its prediction blank. The console prints reference categories, and model summaries include the original-variable map. Encoded names retain the original variable/level (e.g. 'x4: Intl Plan = yes'). Categorical regression terms enter/leave as a group in stepwise/all-subsets. Lasso penalizes dummy columns individually. Clustering requires numeric Xs; do not include OldGroup, OldGroupNum or CustomerID in the wine predictors. REGRESSION AND FORECASTS HOLDOUT_COUNT = 4 reserves the last four OBSERVED Y rows after SORT_BY sorting. These rows never enter estimation or variable selection. Future rows with missing Y are a separate group: the supplied sales file has 43 observed quarters and five future quarters. With four holdouts, there are 39 training quarters, four holdouts, and five forecasts. Forecasts require supplied future X values; the scripts do not forecast the X variables themselves. OLS fits an intercept and every nonconstant selected X. linear_stepwise.py begins with an intercept-only model, adds terms by partial F tests, and removes terms that fail the stay threshold. The app's SLE=0.15 / SLS=0.05 are preserved. Because SLE exceeds SLS, an X can qualify to enter and immediately fail to stay. A repeated-model check stops cycling and prints an explanation. For conventional threshold ordering, try SLE=0.05, SLS=0.10. Review selection_history.csv. linear_all_subsets.py examines every original-variable combination, including intercept-only. MAX_CANDIDATES defaults to 12, like Shiny's X selection limit. The number of fits grows exponentially. Select 'AIC', 'BIC', or 'adjRsq'. AIC/BIC are minimized; adjusted R-squared is maximized. TOP_N_PER_SIZE controls the best models displayed for EACH subset size. all_models.csv retains every estimable candidate. Rank-deficient combinations are announced and skipped. All models use exactly the same complete training rows so scores are comparable. R-like OLS AIC/BIC here include the estimated residual variance parameter. linear_lasso.py minimizes squared error plus an absolute-coefficient penalty. Scaling uses training-fold means and standard deviations. The intercept is not penalized. 'lambda.min' minimizes mean fold validation MSE; 'lambda.1se' chooses the largest penalty within one standard error of that minimum. Both choices are reported. LAMBDA_MIN/MAX and N_LAMBDAS define a positive log-spaced grid. Expand the grid if the minimum is at an endpoint. Cross-validation normally uses ten random folds with seed 9, as a close conceptual counterpart to cv.glmnet. For forecasting over time, CV_METHOD='time' uses forward-only splits; choose fewer CV_FOLDS for small data. PREDICTION_MODEL='OLS' refits only nonzero encoded columns. Lasso outputs original-unit coefficients and a path/CV plot. Conventional OLS p-values from an optional selected-model refit ignore the selection process. metrics.csv separates training and holdout results. MAE and RMSE are in Y units; MAPE is a percentage and excludes zero actual Y. Forecast rows have no scoring metrics because their actual Y is not yet known. Training results alone do not measure generalization. Regression predictions and plots are saved even if there are no holdouts. LOGISTIC REGRESSION AND CLASSIFICATION TREES These scripts use TWO observed response classes, reflecting the app's binary probability/ROC workflow. POSITIVE_CLASS determines which is 1. yes/true/1 and no/false/0 are recognized case-insensitively, including the telecom trailing period. For other labels, set POSITIVE_CLASS to the desired positive label. PROBABILITY_CUTOFF=0.5 classifies probability >=0.5 as positive. Change the cutoff and rerun to see the precision/recall tradeoff. Confusion matrices have actual classes in rows and predicted classes in columns, both in 0,1 order. Logistic regression is UNPENALIZED, like glm(..., family='binomial'), with an intercept. It reports coefficient inference, odds ratios, McFadden pseudo R², probabilities, confusion matrix, sensitivity, specificity, precision and ROC/AUC. Stepwise logistic uses likelihood-ratio tests (LRT), not coefficient Wald tests and not AIC selection. Perfect separation and convergence problems raise clear errors instead of reporting a usable finite model. Extremely sparse data can still make inference unreliable: simplify the predictors in that case. Logistic TEST_FRACTION is an optional extension: 0.2 reserves a stratified 20% random holdout. Shiny has no corresponding logistic holdout setting. Tree HOLDOUT_PERCENT uses 20 for 20%, matching the CLASSIFICATION tree's Shiny setting. Both default to zero to match the app. RANDOM_SEED makes splits repeatable. ROC/AUC describes probabilities independently of the chosen cutoff. For a telecom logistic example, change: DATA_FILE = 'data/churn.csv' Y_COLUMN = 'Churn?' X_COLUMNS = ['Day Mins', 'CustServ Calls', "Int'l Plan"] POSITIVE_CLASS = 1 TEST_FRACTION = 0.2 The default Challenger predictors deliberately exclude distress_ct (which DEFINES isDistress), launch_id (an ID), and o_ring_ct (constant). Including a variable derived from the outcome would reveal the answer to the model. DECISION TREES MIN_SPLIT and MIN_BUCKET map to scikit-learn's min_samples_split and min_samples_leaf. MAX_DEPTH limits the fitted tree; PLOT_MAX_DEPTH only limits the picture. The app defaults (5, 2, 3) are retained. Regression trees minimize squared error and classification trees use Gini impurity. Tree rules and feature importance are saved alongside predictions and a colored decision_tree.png. IMPORTANT: rpart's tree_CP and Python's CCP_ALPHA are different parameters on different scales. The supplied CCP_ALPHA=0.001 is a Python starting value, NOT a faithful numeric translation of R's cp=0.001. Tune it against holdouts; exact R trees cannot be expected. R uses categorical subset splits and can use surrogate splits for missing predictors. These Python trees use dummy columns, binary splits on those columns, and exclude rows with missing selected Xs. CLUSTER QUALITY STATISTICS Ward clustering uses Euclidean distance after centering/scaling. To match agnes(stand=TRUE), the scale is MEAN ABSOLUTE DEVIATION FROM THE MEAN, not standard deviation and not median absolute deviation. STANDARDIZE=False uses raw data. Constant clustering variables raise an error so students can remove them. Step 2 saves all the clusEval measures: WBRatio, AvgSilWidth, PearsonGamma, Dunn, AvgBetween and AvgWithin, plus each cluster's size, diameter and mean distance to other clusters. The wide Shiny-style table is also included. Average within distance weights cluster averages by observation counts, excluding singletons, as in fpc::cluster.stats. Between distance averages cross-cluster point pairs. Dunn is minimum between-point separation divided by maximum cluster diameter. Pearson gamma correlates pair distance with the different-cluster indicator. Undefined statistics are blank rather than presented as reliable scores. Step 3 writes memberships, mean profiles, and sizes. Rows missing clustering Xs have blank membership, preserving their original IDs. Numeric group labels and tie-breaking can differ from R; compare which observations are grouped together. The linkage/retained/distances CSVs and settings.json are workflow state, NOT a special input dataset format students need to learn. Student inputs remain text. Large Ward analyses require quadratic memory; MAX_OBSERVATIONS guards against accidentally allocating huge distance matrices. Steps 2 and 3 deliberately reuse step 1's snapshot rather than recomputing the hierarchy. DATA FILES AND CONVERSION quarterlySales.csv: copied from the supplied timestamped CSV, with a simpler filename; 48 rows, 9 columns. The five future Product1/2/3 values are missing. churn.csv: supplied CSV unchanged; 3,333 rows, 21 columns. Spaces/punctuation in its headings are retained. The reader does not rename them to R's dotted names. clusterData_forWine.txt: supplied tab-delimited file unchanged; 32 rows, 6 columns. challengerLaunch.csv: converted from challengerLaunch.RDS; 23 rows, 6 columns. Its logical isDistress column is written as True/False; no R reader is required. Duplicate RDS files are omitted from this package. Quarterly sales, wine, churn, and myChurn were checked against the corresponding text values (numeric tolerance 1e-8). The two churn RDS variants differ in headings and logical encoding, not in observations. tempData.RData contains saved R functions and a random seed, not another tabular dataset, and is omitted. The app's optional mtcars example is an R built-in dataset, not one of the uploaded nine dataset files; it is not bundled here. No student runtime reads RDS or RData files or sources remote code. HOW CLOSE ARE THE PYTHON AND R RESULTS? This is a translation of the eleven requested analysis workflows, not the Shiny UI or the app's unrelated exploratory plots. R's OLS/binomial models have direct Python counterparts. Selection tests and original-variable grouping are retained. Identical results are not guaranteed: different random-number generators, standardization/CV details, numerical tolerances, ties and tree implementations can change results. Lasso uses fold-specific scaling to avoid validation leakage and an explicit Python penalty grid, unlike glmnet's automatically generated path. Therefore even seed=9 does not reproduce R's lambda or CV folds exactly. No live R/Shiny-versus-Python numerical parity run was possible in this workspace. Support modules keep file handling and reporting in one place. Students can focus on model settings and the model workflow in each lesson. Keep both modules beside the scripts; there is no package installation or sys.path editing. TROUBLESHOOTING 'ModuleNotFoundError': install requirements into the SAME interpreter that runs the script. A notebook can use %pip install -r requirements.txt, then restart its kernel if necessary. 'Unknown columns': print the file's headings and match case, spaces and spelling. The CSV Churn? is NOT the RDS Churn, and "Int'l Plan" is NOT Intl.Plan. 'Rank-deficient model': remove redundant Xs (e.g., both minutes and their exactly proportional charges, or every category dummy plus the intercept). 'Too few training rows': reduce Xs/holdouts/CV folds or use a larger dataset. 'Stepwise stopped at a repeated model': inspect history; adjust SLE/SLS as above. 'Missing cluster files': run cluster_ward.py and check WORKFLOW_FOLDER in all three scripts. Re-run step 1 after changing source data. Charts do not pop up automatically: this is intentional so the same scripts work in JupyterHub and on servers. Open the saved PNGs. Outputs are reusable CSV/TXT, not serialized Python models. example_results contains the supplied-data default runs so an instructor can inspect expected files before installing anything. DOCUMENTATION REFERENCES pandas text-file reader: https://pandas.pydata.org/docs/reference/api/pandas.read_csv.html Statsmodels OLS and binomial GLM: https://www.statsmodels.org/stable/generated/statsmodels.regression.linear_model.OLS.html https://www.statsmodels.org/stable/generated/statsmodels.genmod.generalized_linear_model.GLM.html SciPy Ward hierarchy: https://docs.scipy.org/doc/scipy/reference/generated/scipy.cluster.hierarchy.linkage.html R agnes standardization and fpc cluster statistics: https://stat.ethz.ch/R-manual/R-devel/library/cluster/html/agnes.html https://stat.ethz.ch/CRAN/web/packages/fpc/fpc.pdf https://rdrr.io/cran/fpc/src/R/addclustermethods.R Scikit-learn Lasso, CV and tree pruning: https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.Lasso.html https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.TimeSeriesSplit.html https://scikit-learn.org/stable/modules/tree.html#minimal-cost-complexity-pruning