<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Engin SAN on Medium]]></title>
        <description><![CDATA[Stories by Engin SAN on Medium]]></description>
        <link>https://medium.com/@mavericfb?source=rss-329bd4d718e9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*81QGIZ1onsKDl-sM</url>
            <title>Stories by Engin SAN on Medium</title>
            <link>https://medium.com/@mavericfb?source=rss-329bd4d718e9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 18:22:49 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mavericfb/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[From Databricks to Shiny: Building an End-to-End Spark Machine Learning Pipeline with R Integration]]></title>
            <link>https://medium.com/@mavericfb/from-databricks-to-shiny-building-an-end-to-end-spark-machine-learning-pipeline-with-r-integration-ccd20af03a65?source=rss-329bd4d718e9------2</link>
            <guid isPermaLink="false">https://medium.com/p/ccd20af03a65</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[bigquery]]></category>
            <category><![CDATA[databricks]]></category>
            <category><![CDATA[r]]></category>
            <dc:creator><![CDATA[Engin SAN]]></dc:creator>
            <pubDate>Fri, 09 May 2025 12:58:28 GMT</pubDate>
            <atom:updated>2025-05-09T13:18:35.236Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong><em>Introduction</em></strong></h4><p><em>In this article, I walk through an end-to-end machine learning project using Apache Spark on Databricks, combining the power of big data processing, SQL transformations, pipeline modeling, and interactive visualization in R Shiny.</em></p><p><em>We’ll explore how to:</em></p><ul><li><em>Load and process CMS synthetic patient data in Spark.</em></li><li><em>Use SQL and PySpark to prepare and model data with regression, classification and clustering.</em></li><li><em>Export results for visualization and exploration in a R Shiny dashboard.</em></li></ul><p><em>This project bridges the gap between scalable machine learning in Spark and interactive visualization in R — a valuable workflow for data scientists working across platforms.</em></p><h4><strong>Step 1: Loading BigQuery Data into Databricks</strong></h4><p><em>Using Databricks’ native BigQuery connector, I pulled synthetic patient-level data from the CMS OMOP dataset in the Google Cloud into a Spark DataFrame. This data includes demographic, drug, and visit-related information, ideal for regression and classification tasks.</em></p><pre># I will use patient data, retrieve a sample with 100000 rows, from bigquery! to do all analyses and ML implementations in my project..<br><br># Initialize the client<br>client = bigquery.Client()<br><br># SQL Query<br>query = &quot;&quot;&quot;<br>WITH person_data AS (<br>  SELECT <br>    person_id, <br>    gender_concept_id, <br>    year_of_birth, <br>    race_concept_id, <br>    ethnicity_concept_id<br>  FROM `bigquery-public-data.cms_synthetic_patient_data_omop.person`),<br>condition_counts AS (<br>  SELECT <br>    person_id, <br>    COUNT(*) AS condition_count<br>  FROM `bigquery-public-data.cms_synthetic_patient_data_omop.condition_occurrence`<br>  GROUP BY person_id),<br>drug_counts AS (<br>  SELECT <br>    person_id, <br>    COUNT(DISTINCT drug_concept_id) AS drug_variety<br>  FROM `bigquery-public-data.cms_synthetic_patient_data_omop.drug_exposure`<br>  GROUP BY person_id),<br>visit_counts AS (<br>  SELECT <br>    person_id, <br>    COUNT(*) AS visit_count<br>  FROM `bigquery-public-data.cms_synthetic_patient_data_omop.procedure_occurrence`<br>  GROUP BY person_id)<br> SELECT <br>    p.*,<br>  COALESCE(c.condition_count, 0) AS condition_count,<br>  COALESCE(d.drug_variety, 0) AS drug_variety,<br>  COALESCE(v.visit_count, 0) AS visit_count,<br>FROM person_data p<br>LEFT JOIN condition_counts c ON p.person_id = c.person_id<br>LEFT JOIN drug_counts d ON p.person_id = d.person_id<br>LEFT JOIN visit_counts v ON p.person_id = v.person_id<br>LIMIT 100000<br>&quot;&quot;&quot;<br><br># Run the query and convert to pandas DataFrame to display results<br>df = client.query(query).to_dataframe()</pre><p><em>After loading, I used Spark SQL for initial explorations and data analysis; some examples :</em></p><pre>#after displaying data, convert from pandas to spark dataframe because the remaining part will be on spark :<br>df_spark_loaded = spark.createDataFrame(df)<br>df_spark_loaded.show(5)<br><br>+---------+-----------------+-------------+---------------+--------------------+---------------+------------+-----------+<br>|person_id|gender_concept_id|year_of_birth|race_concept_id|ethnicity_concept_id|condition_count|drug_variety|visit_count|<br>+---------+-----------------+-------------+---------------+--------------------+---------------+------------+-----------+<br>|   477637|             8507|         1909|           8527|            38003564|            343|          19|        333|<br>|  1542531|             8507|         1909|           8527|            38003564|             70|           1|         61|<br>|  1766631|             8507|         1913|           8527|            38003564|              0|           0|          0|<br>|  1942300|             8507|         1913|           8527|            38003564|              0|           0|          0|<br>|  1802000|             8507|         1917|           8527|            38003564|              3|          69|          3|<br>+---------+-----------------+-------------+---------------+--------------------+---------------+------------+-----------+<br>only showing top 5 rows</pre><pre>#check data types:<br>df_spark_loaded.dtypes<br><br>Out[8]: [(&#39;person_id&#39;, &#39;bigint&#39;),<br> (&#39;gender_concept_id&#39;, &#39;bigint&#39;),<br> (&#39;year_of_birth&#39;, &#39;bigint&#39;),<br> (&#39;race_concept_id&#39;, &#39;bigint&#39;),<br> (&#39;ethnicity_concept_id&#39;, &#39;bigint&#39;),<br> (&#39;condition_count&#39;, &#39;bigint&#39;),<br> (&#39;drug_variety&#39;, &#39;bigint&#39;),<br> (&#39;visit_count&#39;, &#39;bigint&#39;)]</pre><pre># check if null values exist:<br>from pyspark.sql.functions import expr<br><br>null_exprs = [<br>    expr(f&quot;sum(case when {c} is null then 1 else 0 end)&quot;).alias(c)<br>    for c in df.columns<br>]<br><br>df_spark_loaded.select(*null_exprs).show()<br><br>+---------+-----------------+-------------+---------------+--------------------+---------------+------------+-----------+<br>|person_id|gender_concept_id|year_of_birth|race_concept_id|ethnicity_concept_id|condition_count|drug_variety|visit_count|<br>+---------+-----------------+-------------+---------------+--------------------+---------------+------------+-----------+<br>|        0|                0|            0|              0|                   0|              0|           0|          0|<br>+---------+-----------------+-------------+---------------+--------------------+---------------+------------+-----------+</pre><pre># Get summary statistics and convert to pandas to display<br>summary_pd = df_spark_loaded.describe().toPandas()<br><br># Format only &#39;mean&#39; and &#39;stddev&#39; rows<br>for col in summary_pd.columns[1:]:<br>    summary_pd.loc[summary_pd[&#39;summary&#39;].isin([&#39;mean&#39;, &#39;stddev&#39;]), col] = (<br>        ps.to_numeric(summary_pd.loc[summary_pd[&#39;summary&#39;].isin([&#39;mean&#39;, &#39;stddev&#39;]), col], errors=&#39;coerce&#39;)<br>        .round(2)<br>        .astype(str)<br>    )<br><br># Display<br>print(summary_pd)<br><br>  summary   person_id gender_concept_id year_of_birth race_concept_id  \<br>0   count      100000            100000        100000          100000   <br>1    mean  1167091.17           8518.86        1935.4          8168.8   <br>2  stddev   673617.99             12.48         12.98         1708.72   <br>3     min           2              8507          1909               0   <br>4     max     2326850              8532          1983            8527   <br><br>  ethnicity_concept_id condition_count drug_variety visit_count  <br>0               100000          100000       100000      100000  <br>1          38003563.98          126.41        46.89      121.81  <br>2                 0.12          123.69        49.03      114.11  <br>3             38003563               0            0           0  <br>4             38003564             937          235         816  </pre><pre>#filtering patients whose birth later than 1980<br>df_spark_loaded.filter(df_spark_loaded[&#39;year_of_birth&#39;] &gt; 1980).show()<br>+---------+-----------------+-------------+---------------+--------------------+---------------+------------+-----------+<br>|person_id|gender_concept_id|year_of_birth|race_concept_id|ethnicity_concept_id|condition_count|drug_variety|visit_count|<br>+---------+-----------------+-------------+---------------+--------------------+---------------+------------+-----------+<br>|  1414881|             8507|         1982|           8527|            38003564|             73|          29|         66|<br>|    45947|             8507|         1981|           8527|            38003564|             89|         105|         87|<br>|  2088662|             8507|         1982|           8527|            38003564|              0|           0|          0|<br>|     8584|             8507|         1983|           8527|            38003564|             36|           5|         29|<br>|  1698668|             8507|         1983|           8527|            38003564|            306|         185|        276|<br>|  2110287|             8507|         1981|           8527|            38003564|            100|          75|         90|<br>|  1226485|             8507|         1981|           8527|            38003564|             18|          36|         16|<br>|  1927822|             8507|         1982|           8527|            38003564|             20|          58|         28|<br>|  1557401|             8507|         1982|           8527|            38003564|            143|           8|        116|<br>|  2273714|             8507|         1983|           8527|            38003564|            137|         149|        178|<br>|   571673|             8507|         1982|           8527|            38003564|             97|          45|        110|<br>|   319932|             8507|         1981|           8527|            38003564|            111|           6|        131|<br>|  1075982|             8507|         1981|           8527|            38003564|            198|           5|        207|<br>|  1163177|             8507|         1982|           8527|            38003564|              0|           0|          0|<br>|  2251881|             8507|         1982|           8527|            38003564|            373|          66|        358|<br>|  1893687|             8507|         1982|           8527|            38003564|            227|         125|        171|<br>|  1859144|             8507|         1982|           8527|            38003564|            208|          95|        204|<br>|    80928|             8507|         1982|           8527|            38003564|            156|          99|        167|<br>|   976749|             8507|         1983|           8527|            38003564|             50|           9|         25|<br>|   562471|             8507|         1982|           8527|            38003564|            162|           8|        153|<br>+---------+-----------------+-------------+---------------+--------------------+---------------+------------+-----------+<br>only showing top 20 rows</pre><pre>#filter and group by birth year<br>from pyspark.sql.functions import avg, max, min<br>condition_bybirth_df = df_spark_loaded.groupBy(&quot;year_of_birth&quot;).agg(<br>    avg(&quot;condition_count&quot;).alias(&quot;average&quot;),<br>    max(&quot;condition_count&quot;).alias(&quot;maximum&quot;),<br>    min(&quot;condition_count&quot;).alias(&quot;minimum&quot;)<br>)<br>condition_bybirth_df.show()<br>+-------------+------------------+-------+-------+<br>|year_of_birth|           average|maximum|minimum|<br>+-------------+------------------+-------+-------+<br>|         1919|154.03875188726724|    650|      0|<br>|         1936|120.55811889973381|    839|      0|<br>|         1958| 122.0817843866171|    838|      0|<br>|         1921| 151.1281914893617|    777|      0|<br>|         1983|             112.5|    433|      0|<br>|         1972|121.18045112781955|    785|      0|<br>|         1979|116.52941176470588|    715|      0|<br>|         1969|            123.36|    660|      0|<br>|         1930| 137.0058417419012|    822|      0|<br>|         1964|120.76618705035972|    569|      0|<br>|         1967|119.78965517241379|    725|      0|<br>|         1911|149.28308207705192|    603|      0|<br>|         1937| 122.8896776101745|    793|      0|<br>|         1924| 142.2275673831457|    793|      0|<br>|         1940| 100.9444184960299|    739|      0|<br>|         1918|148.27573529411765|    842|      0|<br>|         1975|111.53378378378379|    603|      0|<br>|         1935|118.29837037037036|    726|      0|<br>|         1960|119.79958246346555|    673|      0|<br>|         1934|120.08370436331255|    779|      0|<br>+-------------+------------------+-------+-------+<br>only showing top 20 rows</pre><pre>#display maximum visit counts by year of birth <br>maxvisit_bybirth = df_spark_loaded.groupBy(&quot;year_of_birth&quot;).max(&quot;visit_count&quot;).sort(&quot;year_of_birth&quot;).show()<br>+-------------+----------------+<br>|year_of_birth|max(visit_count)|<br>+-------------+----------------+<br>|         1909|             653|<br>|         1910|             590|<br>|         1911|             576|<br>|         1912|             652|<br>|         1913|             623|<br>|         1914|             684|<br>|         1915|             584|<br>|         1916|             665|<br>|         1917|             614|<br>|         1918|             765|<br>|         1919|             648|<br>|         1920|             637|<br>|         1921|             743|<br>|         1922|             655|<br>|         1923|             670|<br>|         1924|             713|<br>|         1925|             709|<br>|         1926|             717|<br>|         1927|             793|<br>|         1928|             669|<br>+-------------+----------------+<br>only showing top 20 rows</pre><h4>Step 2: Data Cleaning &amp; Feature Engineering with Spark SQL</h4><p><em>Before modeling, I:</em></p><ul><li><em>Checked nulls and dropped unnecessary data in key columns.</em></li><li><em>Separated feature and target columns</em></li><li><em>Indexed categorical columns like gender_concept_id, race_concept_id, etc.</em></li><li><em>Used VectorAssembler to create a single feature vector.</em></li><li><em>Scaled features with StandardScaler for normalization.</em></li><li><em>Split data as train (80%) and test (20%)</em></li></ul><pre>from pyspark.sql.functions import col<br>from pyspark.ml.feature import StringIndexer, VectorAssembler, StandardScaler<br>from pyspark.ml import Pipeline<br><br><br># Drop rows with nulls in important columns<br>df_clean = df_spark_loaded.dropna(subset=[&quot;gender_concept_id&quot;, &quot;race_concept_id&quot;, &quot;ethnicity_concept_id&quot;, &quot;year_of_birth&quot;, &quot;condition_count&quot;, &quot;drug_variety&quot;, &quot;visit_count&quot;])<br><br># Convert categorical columns to numeric indexes<br>indexers = [<br>    StringIndexer(inputCol=col, outputCol=col+&quot;_index&quot;, handleInvalid=&quot;keep&quot;)<br>    for col in [&quot;gender_concept_id&quot;, &quot;race_concept_id&quot;, &quot;ethnicity_concept_id&quot;]<br>]<br><br># Vector assembler: It combines the indexed categorical columns and other feature columns into a single feature vector using VectorAssembler. This is stored in a new column named features<br>assembler = VectorAssembler(<br>    inputCols=[&quot;gender_concept_id_index&quot;, &quot;race_concept_id_index&quot;, &quot;ethnicity_concept_id_index&quot;, &quot;year_of_birth&quot;, &quot;condition_count&quot;, &quot;drug_variety&quot;],<br>    outputCol=&quot;features&quot;<br>)<br># StandardScaler: The StandardScaler is used to standardize features by removing the mean and scaling to unit variance. This is a common preprocessing step for machine learning algorithms that are sensitive to the scale of input features (e.g., linear regression, logistic regression, clustering).<br>scaler = StandardScaler(inputCol=&quot;features&quot;, outputCol=&quot;scaledFeatures&quot;, withMean=True, withStd=True)<br><br># Create a pipeline: A Pipeline is created to chain the transformations (indexing and vector assembly) into a single workflow. This pipeline is then fitted to the cleaned DataFrame (df_clean) and applied to transform it into the final prepared DataFrame (df_prepared)<br>pipeline = Pipeline(stages=indexers + [assembler, scaler])<br>df_prepared = pipeline.fit(df_clean).transform(df_clean)<br><br># Show final prepared data<br>df_prepared.select(&quot;features&quot;, &quot;scaledFeatures&quot;, &quot;visit_count&quot;).show(5, truncate=False)</pre><pre># The last step before modeling:<br># Train/test split: This splits the df_with_array DataFrame into two subsets: train_data (80% of the data) and test_data (20% of the data). This is a common practice in machine learning to separate data for training and testing models.<br>train_data, test_data = df_with_array.randomSplit([0.8, 0.2], seed=42)</pre><h4>Step 3: Regression with Spark ML</h4><p><em>To predict the number of visits (visit_count), I trained a linear regression model using Spark ML:</em></p><pre>from pyspark.ml.regression import LinearRegression<br>from pyspark.ml.evaluation import RegressionEvaluator<br><br># Define regression model<br>lr = LinearRegression(featuresCol=&quot;scaledFeatures&quot;, labelCol=&quot;visit_count&quot;)<br><br># Fit model<br>lr_model = lr.fit(train_data)<br><br># Predict<br>lr_predictions = lr_model.transform(test_data)<br><br># Evaluate using RMSE § R²<br>evaluator_rmse = RegressionEvaluator(metricName=&quot;rmse&quot;, labelCol=&quot;visit_count&quot;, predictionCol=&quot;prediction&quot;)<br>evaluator_r2 = RegressionEvaluator(metricName=&quot;r2&quot;, labelCol=&quot;visit_count&quot;, predictionCol=&quot;prediction&quot;)<br><br>print(&quot;Regression RMSE:&quot;, evaluator_rmse.evaluate(lr_predictions))<br>print(&quot;Regression R²:&quot;, evaluator_r2.evaluate(lr_predictions))</pre><h4>Step 4: Classification for Visit Intensity</h4><p><em>Next, I converted the regression task into a binary classification problem:</em></p><ul><li><em>Label: 1 if visit_count ≥ mean, else 0.</em></li><li><em>Model: LogisticRegression in Spark.</em></li><li><strong>Metrics:</strong></li><li><em>AUC</em></li><li><em>Accuracy</em></li><li><em>F1 Score</em></li></ul><p><em>This provided insight into how well the model distinguishes between high and low visit intensity.</em></p><pre>clf = LogisticRegression(featuresCol=&quot;scaledFeatures&quot;, labelCol=&quot;label&quot;)<br>clf_model = clf.fit(train_data)<br>clf_predictions = clf_model.transform(test_data)</pre><h4>Step 5: Clustering (Grouping similar patients)</h4><p><em>In this step I carried out K means method to cluster data as follows:</em></p><pre>from pyspark.ml.clustering import KMeans<br>from pyspark.ml.evaluation import ClusteringEvaluator<br><br># ✅ Step 1: Train KMeans on `train_data`<br>kmeans = KMeans(featuresCol=&quot;scaledFeatures&quot;, k=3, seed=1)<br>kmeans_model = kmeans.fit(train_data)<br><br># ✅ Step 2: Predict clusters<br>kmeans_result = kmeans_model.transform(test_data)</pre><ul><li><strong>Metrics:</strong></li><li><em>Silhouette Score</em></li></ul><p><em>The Silhouette Score is a metric used to evaluate the quality of clustering. It measures how similar a data point is to its own cluster (cohesion) compared to other clusters (separation). The score ranges from -1 to 1:</em></p><p><em>1: Perfect clustering (data points are well-matched to their own cluster and far from others).</em></p><p><em>0: Overlapping clusters (data points are on or near the decision boundary between clusters).</em></p><p><em>-1: Incorrect clustering (data points are closer to other clusters than their own).</em></p><h4>Step 6: Export data and ML predictions as parquet files to R and Build a Dashboard</h4><p>It should be noted that parquet file format is really good in size and performance!!!</p><pre># Final datasets to save, now using df_with_array-based results<br>datasets = [<br>    (df_spark_loaded, &quot;tmp_patient&quot;, &quot;patient_data_final.parquet&quot;),<br>    <br>    (lr_predictions.select(&quot;prediction&quot;, &quot;visit_count&quot;, *feature_names),<br>     &quot;tmp_regression&quot;, &quot;regression_predictions_final.parquet&quot;),<br>    <br>    (clf_predictions_split.select(&quot;prob_0&quot;, &quot;prob_1&quot;, &quot;prediction&quot;, &quot;label&quot;, *feature_names),<br>     &quot;tmp_classification&quot;, &quot;classification_predictions_final.parquet&quot;),<br>    <br>    (kmeans_result.select(&quot;prediction&quot;, &quot;visit_count&quot;, *feature_names),<br>     &quot;tmp_clustering&quot;, &quot;clustering_results_final.parquet&quot;)<br>]<br><br># Loop and save datasets<br>for df, tmp_name, final_name in datasets:<br>    tmp_path = f&quot;dbfs:/FileStore/tmp/{tmp_name}&quot;<br>    final_path = f&quot;dbfs:/FileStore/tmp/{final_name}&quot;<br>    <br>    print(f&quot;📦 Writing to temp: {tmp_path}&quot;)<br>    df.coalesce(1).write.mode(&quot;overwrite&quot;).parquet(tmp_path)<br>    <br>    # Get actual .parquet file inside the temp folder<br>    files = dbutils.fs.ls(tmp_path)<br>    real_parquet_file = [f for f in files if f.name.endswith(&quot;.parquet&quot;)][0].path<br><br>    # Move to clean final path<br>    dbutils.fs.cp(real_parquet_file, final_path, True)<br>    print(f&quot;✅ Written to final: {final_path}&quot;)</pre><p><em>Check if saved parquet files by reading into spark:</em></p><pre>df_test2 = spark.read.parquet(&quot;dbfs:/FileStore/tmp/tmp_regression&quot;)<br>df_test2.show(5)</pre><p><em>Loading data into the app in R:</em></p><pre>library(arrow)<br>library(dplyr)<br>library(purrr)<br># Set the download and target directories<br>downloads_path &lt;- &quot;~/Downloads&quot;<br>target_dir &lt;- &quot;~/R_Projects/spark_google_project/spark-databricks-bigquery/data&quot;<br><br># Create the target directory if it doesn&#39;t exist<br>if (!dir.exists(target_dir)) {<br>  dir.create(target_dir, recursive = TRUE)<br>}<br><br># Expected output filenames in order of download<br>output_names &lt;- c(<br>  &quot;patient_data.parquet&quot;,<br>  &quot;regression_predictions.parquet&quot;,<br>  &quot;classification_predictions.parquet&quot;,<br>  &quot;clustering_results.parquet&quot;<br>)<br><br># Get all .parquet files that start with &#39;part-0000&#39; in Downloads<br>files &lt;- list.files(downloads_path, pattern = &quot;^part-0000.*\\.parquet$&quot;, full.names = TRUE)<br><br># Sort files by last modified time (oldest first = first downloaded)<br>files_sorted &lt;- files[order(file.info(files)$mtime)]<br><br># Copy and rename<br>for (i in seq_along(files_sorted)) {<br>  new_path &lt;- file.path(target_dir, output_names[i])<br>  file.copy(files_sorted[i], new_path, overwrite = TRUE)<br>  message(sprintf(&quot;✅ %s → %s&quot;, basename(files_sorted[i]), output_names[i]))<br>}<br><br><br># Define file paths<br>patient_data &lt;- read_parquet(file.path(target_dir, &quot;patient_data.parquet&quot;))<br>regression_predictions &lt;- read_parquet(file.path(target_dir, &quot;regression_predictions.parquet&quot;))<br>classification_predictions &lt;- read_parquet(file.path(target_dir, &quot;classification_predictions.parquet&quot;))<br>clustering_results &lt;- read_parquet(file.path(target_dir, &quot;clustering_results.parquet&quot;))</pre><p><em>Following transferring files to R, next step is to build the dash. Here are some sample codes of the dashboard app I created:</em></p><pre>library(shiny)<br>library(bslib)<br>library(highcharter)<br>library(DT)<br>library(dplyr)<br>library(arrow)<br>library(shinycssloaders)<br>library(caret)<br>library(pROC)<br>library(htmltools)<br>library(fontawesome)<br>library(scales)<br>library(ggplot2)<br>library(stringi)<br><br>patient_data &lt;- read_parquet(&quot;data/patient_data.parquet&quot;)<br>regression_results &lt;- read_parquet(&quot;data/regression_predictions.parquet&quot;)<br>classification_results &lt;- read_parquet(&quot;data/classification_predictions.parquet&quot;)<br>clustering_results &lt;- read_parquet(&quot;data/clustering_results.parquet&quot;)<br><br>patient_data_summary&lt;-patient_data%&gt;%<br>  mutate(age = 2025 - year_of_birth)%&gt;%<br>  select(year_of_birth, condition_count, drug_variety, visit_count)<br># Create cluster labels<br>cluster_labels &lt;- clustering_results %&gt;%<br>  group_by(prediction) %&gt;%<br>  summarise(avg_visits = mean(visit_count, na.rm = TRUE)) %&gt;%<br>  arrange(avg_visits) %&gt;%<br>  mutate(cluster_label = c(&quot;Low-User&quot;, &quot;Mid-User&quot;, &quot;High-User&quot;))<br><br>clustering_labeled &lt;- clustering_results %&gt;%<br>  mutate(age = 2025 - year_of_birth)%&gt;%<br>  left_join(cluster_labels, by = &quot;prediction&quot;)<br># Custom theme with brand colors<br>my_theme &lt;- bs_theme(<br>  bootswatch = &quot;flatly&quot;,<br>  primary = &quot;#3498db&quot;,<br>  secondary = &quot;#2c3e50&quot;,<br>  success = &quot;#2ecc71&quot;, <br>  info = &quot;#3498db&quot;,<br>  warning = &quot;#f39c12&quot;,<br>  danger = &quot;#e74c3c&quot;,<br>  bg = &quot;#f8f9fa&quot;,<br>  fg = &quot;#2c3e50&quot;,<br>  base_font = font_google(&quot;Inconsolata&quot;)  # Correct way<br>)<br>........<br>ui &lt;- page_fillable(<br>  title = &quot;CMS Patient ML Dashboard&quot;,<br>  theme = my_theme,<br>  <br>  # Custom CSS and max-width wrapper<br>  tags$head(<br>    tags$style(HTML(&quot;<br>    /* Global font size shrink */<br>    body {<br>      font-size: 14px !important;<br>    }<br>    .nav-title {<br>      font-size: 1.6rem;<br>    }<br>    .nav-subtitle {<br>      font-size: 0.85rem;<br>    }<br>........<br>   # Metric boxes<br>      div(class = &quot;metrics-container&quot;,<br>          metric_box(&quot;Total Patients&quot;, format(nrow(patient_data), big.mark = &quot;,&quot;), <br>                     &quot;users&quot;, &quot;#3498db&quot;),<br>          metric_box(&quot;Avg. Visit Count&quot;, round(mean(patient_data$visit_count, na.rm = TRUE), 1), <br>                     &quot;hospital&quot;, &quot;#2ecc71&quot;),<br>          metric_box(&quot;Classification Accuracy&quot;, <br>                     paste0(round(mean(classification_results$prediction == classification_results$label) * 100, 1), &quot;%&quot;), <br>                     &quot;chart-line&quot;, &quot;#e74c3c&quot;),<br>          metric_box(&quot;Clusters Identified&quot;, &quot;3&quot;, &quot;sitemap&quot;, &quot;#f39c12&quot;)<br>      ),<br>      <br>      # Main content<br>      uiOutput(&quot;dynamic_ui&quot;) %&gt;% <br>        withSpinner(type = 1, color = &quot;#3498db&quot;, <br>                    color.background = &quot;#f8f9fa&quot;, <br>                    proxy.height = &quot;400px&quot;),<br>      <br>      # Modal<br>      modalDialog(<br>        title = &quot;About This Dashboard&quot;,<br>        HTML(&#39;<br>&lt;p&gt;This dashboard presents machine learning analyses of synthetic CMS patient data:&lt;/p&gt;<br>&lt;ul&gt;<br>  &lt;li&gt;&lt;strong&gt;Raw Data:&lt;/strong&gt; View the source data used for the analyses&lt;/li&gt;<br>  &lt;li&gt;&lt;strong&gt;Regression:&lt;/strong&gt; Regression models to predict continuous outcomes&lt;/li&gt;<br>  &lt;li&gt;&lt;strong&gt;Classification:&lt;/strong&gt; Predicting binary outcomes with performance metrics&lt;/li&gt;<br>  &lt;li&gt;&lt;strong&gt;Clustering:&lt;/strong&gt; Patient segmentation based on usage patterns&lt;/li&gt;<br>&lt;/ul&gt;<br>&lt;p&gt;&lt;small&gt;Built with Shiny, bslib, highcharter and caret&lt;/small&gt;&lt;/p&gt;<br>&#39;),<br>        easyClose = TRUE,<br>        footer = modalButton(&quot;Close&quot;),<br>        size = &quot;m&quot;,<br>        id = &quot;about_modal&quot;<br>      )<br>  )<br>)<br>.......<br>server &lt;- function(input, output, session) {<br>  <br>  # About modal trigger<br> # observeEvent(input$about_btn, {<br>  #  showModal(id = &quot;about_modal&quot;)<br>  #})<br>  <br>  # Server logic to show modal<br>  observeEvent(input$about_btn, {<br>    showModal(modalDialog(<br>      title = &quot;About This Dashboard&quot;,<br>      &quot;This dashboard presents machine learning analysis using CMS synthetic patient data.&quot;,<br>      easyClose = TRUE,<br>      footer = modalButton(&quot;Close&quot;)<br>    ))<br>  })<br>  <br>  # Calculate regression metrics once<br>  reg_metrics &lt;- reactive({<br>    lm_model &lt;- lm(prediction ~ visit_count, data = regression_results)<br>    rmse &lt;- sqrt(mean(lm_model$residuals^2))<br>    r_squared &lt;- summary(lm_model)$r.squared<br>    correlation &lt;- cor(regression_results$visit_count, regression_results$prediction)<br>    <br>    list(<br>      rmse = rmse,<br>      r_squared = r_squared,<br>      correlation = correlation,<br>      model = lm_model<br>    )<br>  })<br>.....<br><br> output$data_summary &lt;- renderDT({<br>    summary_df &lt;- data.frame(<br>      Variable = names(patient_data_summary),<br>      Type = sapply(patient_data_summary, class),<br>      Missing_Values = sapply(patient_data_summary, function(x) sum(is.na(x))),<br>      Mean = sapply(patient_data_summary, function(x) if(is.numeric(x)) round(mean(x, na.rm = TRUE), 2) else NA),<br>      Median = sapply(patient_data_summary, function(x) if(is.numeric(x)) round(median(x, na.rm = TRUE), 2) else NA),<br>      Min = sapply(patient_data_summary, function(x) if(is.numeric(x)) round(min(x, na.rm = TRUE), 2) else NA),<br>      Max = sapply(patient_data_summary, function(x) if(is.numeric(x)) round(max(x, na.rm = TRUE), 2) else NA)<br>    )<br>    <br>    datatable(<br>      summary_df,<br>      options = list(<br>        pageLength = 5,<br>        scrollX = TRUE,<br>        dom = &quot;t&quot;,<br>        style = &quot;bootstrap4&quot;,<br>        autoWidth = TRUE,<br>        ordering = FALSE,  # disables sorting<br>        columnDefs = list(list(width = &#39;auto&#39;, targets = &quot;_all&quot;))<br>      ),<br>      rownames = FALSE,<br>      class = &quot;compact nowrap&quot;,<br>      caption = htmltools::tags$caption(<br>        style = &quot;caption-side: top; text-align: center; backgroundColor = &#39;#2c3e50&#39;; font-weight: bold; color = &#39;white&#39;; font-size: 1.1em;&quot;,<br>        &quot;Data Summary Statistics&quot;<br>      )<br>    )<br>  })<br>.....<br></pre><p>Some screenshots of the app:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cAWkOU8iBKepJy7MYl0gaA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MO73NYYoQYtnVK_R6ja7nQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qWRLVVzp1iskgsXHbpax-w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QOojxYWodXgJS1N2hsHzRA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0QptC3SRzLYaxNK68AYLGg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ieqEI9436vqCwpzE3r-Z6Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ATnfXoy_1YnIkuESwKsF8w.png" /></figure><p><em>The following is the link of dashboard that you can review:</em></p><p><a href="https://engin-san.shinyapps.io/spark-databricks-bigquery/">CMS Patient ML Dashboard</a></p><p><em>R project files and R codes (pushed to Github via git from R Studio) with Databricks cloud notebook (some sample codes showed here) link can be reached from my private Github repo (please contact me to add your Github account to the project if you are really interested):</em></p><p><a href="https://github.com/enginsan75/datascience_project">https://github.com/enginsan75/datascience_project</a></p><h4>Conclusion</h4><p><em>This project shows how Spark’s power can be combined with R’s visualization flexibility:</em></p><ul><li><em>SQL and ML pipelines in Databricks simplify big data modeling.</em></li><li><em>Exporting results to R bridges analytics and communication.</em></li><li><em>Shiny adds an interactive layer for stakeholders and end-users.</em></li></ul><p><em>By integrating the best of Spark and Shiny, you can scale from raw data to insights — and deliver them beautifully.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ccd20af03a65" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>