<?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 Mike Curry on Medium]]></title>
        <description><![CDATA[Stories by Mike Curry on Medium]]></description>
        <link>https://medium.com/@mdcurry1138?source=rss-d20ee40a1cdd------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*M-hnqKnxHLChRPkL.jpg</url>
            <title>Stories by Mike Curry on Medium</title>
            <link>https://medium.com/@mdcurry1138?source=rss-d20ee40a1cdd------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 13:27:44 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mdcurry1138/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[Ohio Career Tech Education (CTE) & Graduation Outcomes. Analysis Notes.]]></title>
            <link>https://medium.com/@mdcurry1138/ohio-career-tech-education-cte-graduation-outcomes-analysis-notes-1a2044e278b8?source=rss-d20ee40a1cdd------2</link>
            <guid isPermaLink="false">https://medium.com/p/1a2044e278b8</guid>
            <dc:creator><![CDATA[Mike Curry]]></dc:creator>
            <pubDate>Tue, 08 Apr 2025 16:20:51 GMT</pubDate>
            <atom:updated>2025-04-08T16:28:32.644Z</atom:updated>
            <content:encoded><![CDATA[<p><em>The following set of static data-visualizations and accompanying commentary is intended as supplementary to the provided PowerBI CTE Dashboard Report. Three widely observable categories for CTE engagement are identified and examined against three widely observable Post-Graduate Outcomes, as well as Four-Year Graduation Rates and Graduation Rate Changes.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/710/0*XNnzaUBPpuX8MyXT" /></figure><p><strong>An Overview of CTE Engagement. </strong>Three categories of CTE engagement are found to have sufficiently wide-spread engagement for further analysis: ‘Students who Completed a Pathway and are Prepared for College or Career Success’; ‘Students who Earned 12 or more Dual Enrollment Credits’; ‘Students who Earned at Least 12 Credential Points in a Single Career Field or a State Recognized License’. Above, Disaggregating CTE engagement by Graduation Rating, higher rates of Career Pathway Completion and 12+ Dual Enrollment, correlate with higher graduation rates. Generally, the rate of CTE engagement in the category of Credential Points / State Recognized Licenses is the same regardless of Graduation Rating.</p><p><strong>Examined below, categories of CTE with lower engagement rates.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/708/0*VgRQUklsRm6yGtbD" /></figure><p><strong>Graduation Seals &amp; Apprenticeships. </strong>Focusing in on CTE categories with lower overall engagement rates, Pre-Apprenticeship Completion is highest near median Graduation rates/ratings. Graduation Seals Completion may be higher in schools with higher graduation rates. However, owing to the high variability and sparsity of the available data, conclusions can only be drawn tentatively.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/0*HlQYVawsWh3I9YXO" /></figure><p><strong>Note on Gradation Rates Vs. Ratings. </strong>It is worth taking a moment to note that Graduation Ratings are weighted, taking into account factors other than Graduation Rates. While Star Rating is a convenient category for comparison, in this report it is often useful to split the Graduation Rate distribution into five equally sized bins (Q-Cuts) rather than use the somewhat more nebulous ‘Graduation Rating’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/717/0*ST6xm7qe6XKm59u3" /></figure><p><strong>Graduation Rate Q-Cuts Vs. CTE engagement. </strong>When re-examining CTE categories with lower engagement as above compared instead with q-cut bins, a somewhat stronger correlation can be seen between higher graduation rates and Seal Completion. Given a range of near to 1–2% of students completing Graduation Seal Requirement plus 250 Service hours, it is difficult to make conclusions about the significance of this category’s impact on Graduation Rates.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/490/0*TNE_6GOqWAh9ZLi2" /></figure><p><strong>Four-Year Graduation Rates FY19–23. </strong>Looking at the last five years of graduation rates by HS Building, graduation is generally on the rise — by a little over 1%. There is a spike in graduation rates during FY21. This may be due to the unusual circumstance in education during the pandemic, including remote learning and the temporary suspension of state testing requirements.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gyggF7bjcgwFq5U2" /></figure><p><strong>Graduate Outcomes Overview. </strong>Throughout Ohio, about 55% of graduates enrolled in college after completing high school. Another 39% joined the job market as “Gainfully Employed”. The other major Outcomes category of interest in “Unknown”. It is recommended that the reader refer to the PowerBI Dashboard report, with particular emphasis on the above three categories as they relate to other factors of district profiles. For example, it may be observed that Rural Districts tend to have the highest rates of graduates becoming “Gainfully Employed”, while Urban Districts with high poverty rates have the highest percent of students whose Outcomes are “Unknown”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/0*IbKXVrpCL9-NY7hy" /></figure><p><strong>Outcomes &amp; Graduate Ratings. </strong>Schools with higher graduation ratings have a higher percentage of students that enroll in four-year colleges. Remarkably, rates of “Gainfully Employed” and two-year college enrollment has little or no correlation with a school’s Graduation Ratings; an exception being a slightly lower “Gainfully Employed” rate for districts with a graduation rating of One Star.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/632/0*lDrn9252PoZ8M1nK" /></figure><p><strong>Outcomes &amp; Graduate Ratings. </strong>Due to the relatively lower percentages, these categories of Post-Graduation Outcomes are graphed separately. Again, as above, it is remarkable that <em>none </em>of the examined categories show significant correlation to graduation ratings.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/588/0*NVNbVWJVKEhQenbc" /></figure><p><strong>Pathway Completion Rate Quartiles &amp; Graduation Improvement. </strong>Here, the Pathway Completion Rate has been split into Quartiles, and further split into whether the graduation rates have gone up or down in the last five reporting years. Schools with higher Career Pathways engagement are more likely to show an improvement in graduation, and conversely less likely to have had a decrease in graduation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/0*2cVPrn-Hli8UwyEV" /></figure><p><strong>Heatmap of Q-Cut bins for Gradation Rate Changes &amp; Pathway Completion Rates. </strong>Here, a crosstab is formed between equally sized bins color-saturation corresponds to the number of schools falling within a block. On the left, extremes in both positive and negative graduation rate changes correspond to low participation rates for Career Pathways programs. Conversely, on the right moderate changes in graduation rates correspond to high levels of Career Pathways engage. These correspondences may be related to greater shifts in gradation rates among lower performing schools, and likewise smaller shifts in graduation rates among higher performing schools.</p><p><strong>Top Three CTE Engagement Indicators Versus Top Three Graduate Outcome Indicators. Linear Regressions On Scatterplots with Kernel Density Estimation (KDE) Heatmap Plots.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9dsWJ7lq3zJJ8WFR" /></figure><p>Three categories of CTE engagement (“Career Pathway Completion”, “Industry Recognized Credentials”, “12+ Dual Enrollment Credits”) are compared to three categories of Graduate Outcomes (“Gainful Employment”, “Two-Year College Enrollment”, “Four-Year College Enrollment”). Each point represents a particular Ohio Public High School. Generally, there is a lot of error when imposing best-fit lines on statewide trends for CTE engagement versus outcomes. Nonetheless, a few remarkable patterns may be noted about the plots above. On the top right plot, Career Pathway completion rates trend positively with graduates who enroll in four-year colleges. On the middle left, schools with higher rates of students earning industry recognized credentials generally have a higher percentage of graduates who go directly into the workforce. On the bottom right, schools with a higher percentage of students earning dual enrollment credits are also somewhat more likely to have a higher percentage of students enrolling in four-year colleges. For Community College enrollment, at least of a building-level analysis, very little co-trending can be observed in relation to rates of Career Pathway completion or Industry Credentials Earned.</p><p><strong>CTE Engagement &amp; Graduate Outcomes, Disaggregated by District Poverty Status:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hq0mC5q_rOZueSm5" /></figure><p>For CTE Engagement in the top bar plot above, higher rates of Career Pathways completion trends directly with lower poverty status; for both Industry Credentials and Dual Enrollment rates, highest completion centers towards Average poverty status. For Outcomes in the lower bar plot above, four-year college enrollment rates trend directly with lower poverty status; higher “Gainfully Employment” rates centers towards average poverty status; two-year college enrollment remains relatively flat across poverty status levels, dipping slightly at “Very Low” poverty.</p><p><strong>CTE Engagement &amp; Graduate Outcomes, Disaggregated by District Population Size:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cBSNQABqNVqK0lkd" /></figure><p>With the exception of Dual Enrollment, “Large” Population values are outliers to otherwise mostly consistent trends. For CTE Engagement in the top bar plot above, Pathway completion, Industry Credentials and Dual Enrollment, all decrease directly with population size. For Outcomes in the lower bar plot above, as with CTE engagement, Employment and four-year college enrollment mostly decrease with population size. Once again, Community College enrollment remains mostly flat across population size with slightly higher rates in “Very Large” districts.</p><p><strong>CTE Engagement &amp; Graduate Outcomes, Disaggregated by Geographic Grouping:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*59UNnJZZeCgPHD-6" /></figure><p>Unlike the two previous disaggregations, Geographic Grouping categories do not fall as neatly along a spectrum. For CTE Engagement in the top bar plot above, Small Town and Rural schools show nearly the same engagement rates; the highest Pathway Completion rates can be observed in Suburb schools; while Urban schools have the lowest Pathway completion and Dual Enrollment rates, they show relatively stronger Industry Credential engagement. For Outcomes in the lower bar plot above: again, Small Town and Rural schools show similar results with Small Towns having lower Employment rates; the highest four-year college rates are among Suburb schools, while the lowest are found in Urban areas.</p><p><strong>Scatterplots overlayed with KDE of Disagregations. </strong>In the following graphs, the three most prominent CTE Engagement indicators against each of the three most prominent Graduate Outcomes. Each point is a particular High School. The color-coded squiggles are single-cut KDE plots — showing where each subgroup is in highest concentration. The results act essentially like venn-diagrams on disagregated groupings for each pair of Engage Vs. Outcome for CTE.</p><p><strong>Geographic Grouping: Rural, Small Town, Suburb, Urban</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eWfTYKxJJXm_d7bC46o1lQ.png" /></figure><p><strong>District Poverty Status: high to low</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GJfj3IvGU4MyT9DpYOJNHQ.png" /></figure><p><strong>Population Size: small to large</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PEI0uRWgnaD_liJzyyjdQA.png" /></figure><p><strong>A Unique Supervised Machine Learning Approach.</strong> First, all available categories of Graduation Outcome for all Ohio public High Schools were examined at once to determine the most distinct groupings of outcomes, using standard k-means clustering techniques. Next, predictive categorical models were applied (Random Forest and XGBoost), using all CTE engagement values and disaggregations categories, in order to most accurately predict which previously found cluster each school belongs to. Once the accuracy of a trained model was sufficiently optimized, the model’s predictive power was then re-examined using Permutation Importance and Shapley Values. The result is a set of ranked lists, clearly showing which factors of CTE Engagement and Disagregate grouping are most valuable in predicting existing Graduation Outcome clusters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*eScWFtRqhlBfjD0TjtAHjA.png" /></figure><p>Optimizing the number of clusters for Post-Graduate Outcomes. The Elbow Plot above is smoother than to be desired, and indicates a lack of strong natural clustering. In other words, outcomes are a blob — values in one factor have little correspondence to other factors. Similar results are found with CTE Engagement and also combined Engagement &amp; Outcomes.</p><p><strong>Visualizing the Resulting Clusters.</strong> Here, data is cataloged into k=5 Outcome clusters. Prominent CTE Engagement vs Prominent Outcomes are graphed with KDE line plots revealing said clusters. Most distinctive stratification occurs with Four-Year College Enrollment. Two-Year Enrollment remains unstratified. Employment vs. CTE Engagement has some interesting overlap in clusters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RIDmDWBCkdLWDHqcEbkUPQ.png" /></figure><p>Available data was combined into a predictive model that aims to accurately categorize each school within the five clusters above. While the the validation accuracy for any given model was unfortantly not able to be brought above 65%, with five categories of outcomes clusters, the predicted assignment is still significantly better than random.</p><p>An examination of the Feature Importance for our most accurate model yeilds the following bar chart of predictive factors for Graduation Outcomes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1015/1*jwEayCcHgMvmCda2ttYbVw.png" /></figure><p>Although many of the most predictive factors for grouping Outcomes are known ones like Percent in Poverty or Minority enrollment, it is iteresting to note that Readiness Seals and Pathway Completion are among the most predictive factors. This suggests that even as Readiness Seal engagement is very low overall, whether a school has higher engagement makes a large impact on Post Graduate Outcome groupings. It is therefore strongly recommended that schools with strong engagement in these programs be more thoroughly examined and their successes immulated elsewhere.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1a2044e278b8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Uneven Pandemic Impact and Recovery in Ohio Schools Attendance]]></title>
            <link>https://medium.com/@mdcurry1138/attendance-in-ohio-public-schools-three-years-of-pandemic-impact-a6addfb40326?source=rss-d20ee40a1cdd------2</link>
            <guid isPermaLink="false">https://medium.com/p/a6addfb40326</guid>
            <dc:creator><![CDATA[Mike Curry]]></dc:creator>
            <pubDate>Mon, 07 Apr 2025 16:11:48 GMT</pubDate>
            <atom:updated>2025-04-08T14:05:25.603Z</atom:updated>
            <content:encoded><![CDATA[<p><em>On the heels of state-mandated quarantine and hastily deployed virtual education, schools throughout the State of Ohio observed a dramatic drop in school attendance rates. Recovery to pre-pandemic attendance rates has been a slow processthat remains incomplete. Misleadingly, records indicate an increase in attendance rates during 2019–20; these numbers must be considered unreliable as they reflect the lenient and half-hazard standards of ‘virtual attendance’. This article leaves off an investigation into the complex topic of contributing causes, and focuses instead on visualizing the impact on attendance in the years following the pandemic.</em></p><p><strong>Recovery Status:</strong> In the three years following the pandemic, 88% (2729 out 3110) of Ohio schools experienced a statistically significant drop in attendance rates*. Two thirds of impacted schools are either in the process of recovery or have fully recovered, while roughly a third continued to show no improvement. About 12% of Ohio schools had no statistically significant change in attendance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/660/0*_bkBQVE-8XCQ7jhU" /></figure><p><em>Note: changes in attendance rates are considered significant whose absolute-value is greater than two standard deviations of the four year average prior to the pandemic, taken per school.</em></p><p><strong>Timing of Max-Impact on Attendance from Pandemic:</strong> In the three years following the pandemic, nearly all Ohio schools experienced a drop in attendance rates. The majority have begun to recover. For attendance, the ‘max impact’ is the lowest attendance value observed since the onset of the pandemic. Schools counted as hitting max impact in FY23 have yet to show improvement.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/0*tIfCSzX1uiiCAplv" /></figure><p><strong>Overview of attendance distribution changes:</strong> pre-pandemic in Green shows 2930 (94.2%) Ohio schools at|above 90% attendance, with a median attendance at 94.8%. Prior to the pandemic, attendance below 90% was nearly a 2-Sigma event in Ohio. Previously, over half of Ohio schools had above 95% attendance; now only 11% of schools stand in the same range.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*-m2TZDhyKjITlkAT" /></figure><p><strong>Recovery in the Lower Quartiles of Attendance:</strong> looking at the four year average prior to the pandemic, only 9 (0<strong>.</strong>2%) schools fell below 80% attendance. At max impact, 283 schools fell below 80% (9.1% of schools). Presently, 84 schools stand in the same range (2.7%) — a recovery of more than two-thirds within this range.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/530/0*H_WdEJXk9G70sEtV" /></figure><p><strong>Max Impact on Attendance Rates: </strong>Ohio schools observed an average decrease in attendance of 3%. Nearly all schools were impacted.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/490/0*RUV-HJMEqJNBS3FQ" /></figure><p><strong>Current Net Change in Attendance: </strong>Adding the amount of improvement to the amount of impact by school results in the current state of recovery. For a number of schools the net result is a higher attendance rate than before the pandemic shown in blue, while the peak of the distribution still remains in the negative shown in orange.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/563/0*u0q1UtAsBM2NVFoo" /></figure><p><strong>Improvement By Attendance Q-cut Interval: </strong>Splitting pre-pandemic average attendance rates into equal-sized bins, schools in the lower bins observe a higher portion of schools in the process of attendance recovery. Arguably, schools with attendance in the lower quartiles have a greater room for improvement, and it is reassuring to see that they are now headed in the right direction. However, it is remarkable that schools in the higher quartiles have been slower to show improvement. While the impact on higher performing schools is shown below to be less severe, less of these schools are returning to their respective pre-pandemic norms.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/563/0*yHEWjCp3QUjk_xSV" /></figure><p><strong>Recovery Q-Cuts Compared to Attendance Q-Cuts:</strong> Two remarkable, though perhaps not surprising trends may be observed here. First, the leftmost column represents schools with the smallest percent of recovery; many of these schools at 0% recovery ; note the concentration of low recovery rates in schools that had better attendance to begin with. Second, the largest recovery rates are concentrated among schools that were struggling with attendance before being impacted. This begs a comparison between PrePandemic attendance and respective sizes of impact.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/610/0*XLF2uPRYJCYiSlW3" /></figure><p><strong>Absence Rate Impact Compared to Attendance Rate Q-Cuts:</strong> Subtracting Attendance Rate from 100 yields the ‘Absence Rate’. Here, orange represents an increase in absences, and blue the subsequent decrease in absences since Max Impact. It should not be surprising that schools with higher absence rates have shown larger impact sizes. This graph serves as a useful reference point for the graph that follows it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/0*OHn7ipCgiedMbOCX" /></figure><p><strong>Normalized Absence Rate Impact Vs. PrePandemic Attendance Q-Cuts: </strong>Normalizing Absence Rate changes provides a way to compare relative impact and improvement. (For example, comparing two schools with absences rates of 5% and 20%, a 50% increase in absences would yield impacts of 2.5% and 10% respectively. The school with a higher initial absence rate is impacted more in terms of the number of students missing school, but the normalized impact is viewed as equal the example case.) With the exception of the upper-most interval, the higher the initial absence rate, the more severe the impact even as we compare normalized rates. Among the schools with the lowest initial Attendance interval, the increase in absences at max impact were on average more than double their prior rates. In short, schools that were struggling before the pandemic were impacted more severely.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/575/0*pKDAnsWE3FDDUsXW" /></figure><p><strong>Baseline Z-Score Migration Averages by Attendance Q-Cuts:</strong> on average, schools in the higher PrePandemic attendance Quartiles have the largest negative migration, and schools with lower attendance rates have more positive z-score migration. Generally, schools with higher attendance rates to begin with have less room to improve, whereas the opposite is generally the case among schools with lower attendance rates to begin with. It is noteworthy that all three of the left-most q-cuts all demonstrate positive average migrations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/575/0*s8axj-oWgFvKnmku" /></figure><p><strong>Large Z-Migration Values:</strong> Examining Z-Score migration values greater than half a standard deviation of change, and graphing both positive and negative migration per q-cut, reveals that schools with lower attendance rates prior to the pandemic experienced larger changes in attendance rates — both positive and negative. These changes are examined relative to the overall distribution shift of Ohio schools pre versus post pandemic. This demonstrates that there is significantly more variation in the lower quartiles of attendance rates, and suggests the impact and recovery have been significantly more varied among the lower quartiles of attendance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/571/0*P0BwbGNIQzu9UHtZ" /></figure><h3>Overview of Disaggregated Impact Distributions:</h3><p><strong>With Vs. Without Disabilities, Size of Attendance Rate Impact:</strong> there is less than one quartile overlap between the two groups; more than three quarters of students with disabilities experienced a greater attendance rate impact than three quarters of students without disabilities, demonstrating a very significant difference (effect size) in the two groups.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/660/0*gultYJFlNJdcdh7g" /></figure><p><strong>Racial/Ethnic Disaggregation, Size of Attendance Rate Impact:</strong> mostly moderate differences in impact can be observed in this disaggregation. Most significantly, the ‘Asian &amp; Pacific Islander’ subgroup showed the least amount of impact, having just over a quarter of the distribution overlapping with other subgroups. ‘Black’, ‘Hispanic’, and ‘Multiracial’ subgroups experienced minute differences in impact. The ‘White’ subgroup shows moderately less impact than all but the ‘Asian &amp; Pacific Islander’ subgroup. The wider range of variability in ‘American Indian or Alaskan Native’ can partially be attributed to the very small population size — less than one half of a percent of the overall enrollment in Ohio.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/765/0*jfxSCfmEqGYI9P5M" /></figure><p><strong>Economic Advantage Vs. Disadvantage, Size of Attendance Rate Impact:</strong> by far the most significant difference in attendance rate impact can be observed in economic disaggregation; all of the economically advantaged group can be seen to have less impact than more than three quarters of students with Economic Disadvantage, while a quarter of economically advantaged students showed less impact than any of those disadvantaged.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/716/0*m4MImV6ZvEL-jOmn" /></figure><p><strong>Correlations: </strong>Applying Pearson’s r to subgroup enrollment versus indicators of impact on Absence Rates, yields a few low to moderate correlations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/771/1*dz3CfG7iJxRTG8T6lACTHw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/466/0*Hu5ktjN9kaUY5q1q" /></figure><p><strong>(i.) Disadvantage: </strong>there is a moderately positive correlation (r = 0.5) between the percent of disadvantaged students enrolled and the raw increase in absences recorded. Normalizing Absence Rate changes (changes taken as a percent-increase relative to the pre-existent Absence Rate for the given school) yields a lower correlation (r = 0.4), while there is a greater correlation between percent of disadvantaged enrollment vs percent of advantaged enrollment (r = 0.3 vs r = -0.2). While the impact is greater in the disadvantaged group, this group is correlated to greater normalized improvement, whereas the advantaged group shows a slight negative correlation to improvement.</p><p><strong>(ii.) Disability: </strong>For the percent of enrollment of students with Disabilities, no correlations can be found in the examined indicators.</p><p><strong>(iii.) Race/Ethnicity:</strong> most correlations between percent of subgroup enrollments for this disaggregation are negligible. Two low to moderate correlations can be found in the subgroups ‘Black’ and ‘White’. Low positive correlations exist between the percent of enrollment of black students and: one, absence rates at max impact (r = 0.5); two, the absence rates post-pandemic (r = 0.4); three, the raw impact size (r = 0.4). However, when absence rate changes are normalized, no correlation can be observed between black enrollment percentages and impact indicators. For the subgroup ‘White’, low to moderate negative correlations may be observed between percent of enrollment and raw indicators of absence rate impact (r = -0.5). Normalized indicators yield one low negative correlation between percent of white student enrollment and the size of impact (r = -0.4). As this is the only correlation to normalized impact among race/ethnicity disaggregate subgroups and the r value is relatively small, race/ethnicity is either not an substantial correlation to impact, or more likely, it is itself correlated with a more significant factor, e.g. relative economic advantage.</p><p><strong>Summary Remarks: </strong><em>While the pandemic impacted attendance rates in nearly all schools throughout the State of Ohio, both the size of impact and the degree of recovery is not distributed equally. Overall, schools with lower prior attendance records have either bounced back more rapidly than other groups or taken a steep turn for the worse. However, these same schools together as an average have recovered more fully than schools among those with higher prior attendance rates. The distribution curve for attendance has remained shifted to the left since the pandemic, with very few schools returning to above 95% where almost half of Ohio schools used to be. Prior higher attendance schools, while having lost less ground, have been slowest in recovering the percentage points lost. Among the correlations to disaggregate groups, Economic Disadvantage was most deeply impacted and most fully to recover.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a6addfb40326" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Planet Finding App]]></title>
            <link>https://medium.com/@mdcurry1138/planet-finding-app-6413c077c9c4?source=rss-d20ee40a1cdd------2</link>
            <guid isPermaLink="false">https://medium.com/p/6413c077c9c4</guid>
            <dc:creator><![CDATA[Mike Curry]]></dc:creator>
            <pubDate>Mon, 25 May 2020 14:48:17 GMT</pubDate>
            <atom:updated>2020-05-25T14:48:17.555Z</atom:updated>
            <content:encoded><![CDATA[<p>Supervised Machine Learning models are trained on a combined data-set from CalTech and STScI to identify probable planet baring stars in NASA’s TESS satellite light-curve data.</p><p>NASA’s TESS satellite is a started taking light readings of 200,000 of the brightest, closest stars in 2018. They expect to find about 300 earth-sized exoplanets within the next year. Data from this on-going project is being made available to the public. For my very first co-op project, another Data Science student and I paired up to see if we could find anything interesting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/985/1*8IJEBZpRjnWPD3EYBc9Sqg.jpeg" /></figure><p>To be clear, neither of us are astrophysicists. Nonetheless, after brainstorming together, we came up with a way for a way that machine learning might contribute to NASA’s project without any reference to physics. To train a classification model, all we needed was a set of data to train on with and without exoplanets —think hotdog / not a hotdog from the show Silicone Valley. We had access to the the raw data without any classification. If we could get a list of stars in the data that had already been established as likely to have planets, then we were in business.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*wql03HsvySJpfHsx-rchuQ.gif" /></figure><p>As it turned out, CalTech had already begun composing a list of most likely stars in the TESS data to have planets. They wanted to get this information out there to direct the attention of the physics community towards the stars that were most likely to yield interesting results, and to get people to start pointing equipment in the right directions. As it so happened, this is exactly the information we also needed to build a classification model.</p><p>We combined the CalTech data with data from STScI in Baltimore, MD, together the data formed X and y vectors of our models. We also found a number of helpful Jupyter Notebooks on the community resources section of NASA’s website to create nice light-curve visuals like the one below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9cCZWaY_vp1L6eMiOsy_ag.png" /></figure><p>Essentially, our model took in the whole swath of these scattered data-points for each planet and was charged to produce a single probability for whether each star had at least one planet. Unlike the graph above, we were not finding a fit curve, or doing any real mathematical analysis. The power of this approach, though it could never stand alone, is that it allows us to look for patterns that were not necessarily looking for explicitly. While initially physics might find probable planets in the data using rigid and well defined rules, our secondary / piggy-back approach allowed us to look for general patterns. Most notably, we are not really able to say exactly what the patterns are that our model is picking up on, only that it must be catching on to something if it is predicting accurately.</p><p>PART 1: GETTING DATA AND VISUALIZING IT</p><p>Getting data from CalTech:</p><pre><strong>import</strong> <strong>pandas</strong> <strong>as</strong> <strong>pd</strong><br><br><em># Getting labelled TESS Objects of Interest df from Caltech:</em><br>toi = pd.read_csv(&#39;https://exofop.ipac.caltech.edu/tess/&#39; + <br>                  &#39;download_toi.php?sort=toi&amp;output=csv&#39;)<br><br><em># Isolating columns of interest:</em><br>toi = toi[[&#39;TIC ID&#39;,<br>           &#39;TOI&#39;,<br>           &#39;Epoch (BJD)&#39;,<br>           &#39;Period (days)&#39;,<br>           &#39;Duration (hours)&#39;,<br>           &#39;Depth (mmag)&#39;,<br>           &#39;Planet Radius (R_Earth)&#39;,<br>           &#39;Planet Insolation (Earth Flux)&#39;,<br>           &#39;Planet Equil Temp (K)&#39;,<br>           &#39;Planet SNR&#39;,<br>           &#39;Stellar Distance (pc)&#39;,<br>           &#39;Stellar log(g) (cm/s^2)&#39;,<br>           &#39;Stellar Radius (R_Sun)&#39;,<br>           &#39;TFOPWG Disposition&#39;,<br>          ]]</pre><pre>#some cleaning<br>toi.columns = toi.columns.str.replace(&#39; &#39;, &#39;_&#39;)</pre><p>Getting data from STScI</p><pre><strong>from</strong> <strong>astroquery.mast</strong> <strong>import</strong> Catalogs<br><strong>from</strong> <strong>astropy.table</strong> <strong>import</strong> Table<br><strong>from</strong> <strong>tqdm</strong> <strong>import</strong> tqdm<br><br><em># Getting additional data on TESS Objects of Interest from STScI:</em><br>tic_catalog = pd.DataFrame()<br><strong>for</strong> tic_id <strong>in</strong> tqdm(toi[&#39;TIC_ID&#39;].unique()):<br>    row_data = Catalogs.query_criteria(catalog=&quot;Tic&quot;, ID=tic_id)<br>    row_data = row_data.to_pandas()<br>    tic_catalog = tic_catalog.append(row_data)<br>tic_catalog = tic_catalog.reset_index(drop=<strong>True</strong>)<br><br><em># Renaming ID column to make this consistent with Caltech TOI dataframe:</em><br>tic_catalog = tic_catalog.rename(columns={&#39;ID&#39;: &#39;TIC_ID&#39;})<br><br><em># Isolating columns of interest:</em><br>tic_catalog = tic_catalog[[&#39;TIC_ID&#39;,<br>                           &#39;ra&#39;,<br>                           &#39;dec&#39;,<br>                           &#39;pmRA&#39;,<br>                           &#39;pmDEC&#39;,<br>                           &#39;plx&#39;,<br>                           &#39;gallong&#39;,<br>                           &#39;gallat&#39;,<br>                           &#39;eclong&#39;,<br>                           &#39;eclat&#39;,<br>                           &#39;Tmag&#39;,<br>                           &#39;Teff&#39;,<br>                           &#39;logg&#39;,<br>                           &#39;MH&#39;,<br>                           &#39;rad&#39;,<br>                           &#39;mass&#39;,<br>                           &#39;rho&#39;,<br>                           &#39;lum&#39;,<br>                           &#39;d&#39;,<br>                           &#39;ebv&#39;,<br>                           &#39;numcont&#39;,<br>                           &#39;contratio&#39;,<br>                           &#39;priority&#39;]]<br><br>tic_catalog.columns = tic_catalog.columns.str.replace(&#39; &#39;, &#39;_&#39;)</pre><p>Getting dataproduct URLs for stars in the dataframes above cataloged by TIC id from STScI:</p><pre><strong>from</strong> <strong>astroquery.mast</strong> <strong>import</strong> Observations<br><br><em># Getting all dataproducts for TESS Objects of Interest from STScI:</em><br>dataproducts = pd.DataFrame()<br><strong>for</strong> tic_id <strong>in</strong> tqdm(toi[&#39;TIC_ID&#39;].unique()):<br>    row_data = Observations.query_criteria(obs_collection=&quot;TESS&quot;,<br>                                           target_name=tic_id)<br>    row_data = row_data.to_pandas()<br>    dataproducts = dataproducts.append(row_data)<br>dataproducts = dataproducts.reset_index(drop=<strong>True</strong>)<br><br><em># Renaming ID column to make this consistent with Caltech TOI dataframe:</em><br>dataproducts = dataproducts.rename(columns={&#39;target_name&#39;: &#39;TIC_ID&#39;})<br><br><em># Isolating TIC IDs (target_name) and dataURL values to get associated files:</em><br>dataproducts = dataproducts[[&#39;TIC_ID&#39;, &#39;dataURL&#39;]]<br><br>dataproducts.columns = dataproducts.columns.str.replace(&#39; &#39;, &#39;_&#39;)</pre><p>To inspect the uniqueness of dataproducts available for each star (TIC id):</p><pre><em># Getting list of unique TIC IDs in each of the three dataframes:</em><br>toi_unique_ids = toi[&#39;TIC_ID&#39;].unique().tolist()<br>tic_catalog_unique_ids = tic_catalog[&#39;TIC_ID&#39;].unique().tolist()<br>dataproducts_unique_ids = dataproducts[&#39;TIC_ID&#39;].unique().tolist()<br>dataproducts_unique_ids = [int(tic_id) <strong>for</strong> tic_id <strong>in</strong> dataproducts_unique_ids]</pre><p>After exploring the above resulting lists, it was time to try to extract some information. Relying heavily on tutorials found through the NASA community pages (<em>See </em><a href="https://github.com/spacetelescope/notebooks/blob/master/notebooks/"><em>https://github.com/spacetelescope/notebooks/blob/master/notebooks/</em></a><em>) </em>, the following yield all light-curves from an example star:</p><pre><strong>from</strong> <strong>astropy.io</strong> <strong>import</strong> fits<br><strong>import</strong> <strong>matplotlib.pyplot</strong> <strong>as</strong> <strong>plt</strong><br><br><em># Getting urls for all dataproducts associated with TIC ID 29781292:</em><br>urls_for_29781292 = dataproducts[dataproducts[&#39;TIC_ID&#39;] == &#39;29781292&#39;][<br>    &#39;dataURL&#39;].tolist()<br><br><em># Getting urls for all lc.fits files associated with TIC ID 29781292:</em><br>lcs_for_29781292 = [url <strong>for</strong> url <strong>in</strong> urls_for_29781292 <strong>if</strong> <br>                    url.endswith(&#39;lc.fits&#39;)]<br><br><em># Describing and plotting all lc.fits files associated with TIC ID 29781292:</em><br><em># See https://github.com/spacetelescope/notebooks/blob/master/notebooks/</em><br><em># MAST/TESS/beginner_how_to_use_lc/beginner_how_to_use_lc.ipynb</em><br><strong>for</strong> url <strong>in</strong> lcs_for_29781292:<br>    <br>    fits_file = (&#39;https://mast.stsci.edu/api/v0.1/Download/file?uri=&#39; + url)<br>    <br>    # print(fits.info(fits_file), &quot;<strong>\n</strong>&quot;)<br>    <br>    # print(fits.getdata(fits_file, ext=1).columns)<br>    <br>    <strong>with</strong> fits.open(fits_file, mode=&quot;readonly&quot;) <strong>as</strong> hdulist:<br>        tess_bjds = hdulist[1].data[&#39;TIME&#39;]<br>        sap_fluxes = hdulist[1].data[&#39;SAP_FLUX&#39;]<br>        pdcsap_fluxes = hdulist[1].data[&#39;PDCSAP_FLUX&#39;]<br>    <br>    fig, ax = plt.subplots()<br><br>    ax.plot(tess_bjds, pdcsap_fluxes, &#39;ko&#39;)<br><br>    ax.set_ylabel(&quot;PDCSAP Flux (e-/s)&quot;)<br>    ax.set_xlabel(&quot;Time (TBJD)&quot;)<br><br>    plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/428/1*YGyFIWdBNeHTEATT-a8zBA.jpeg" /><figcaption>An Example of a light curve plot: <em>TIC ID 29781292</em></figcaption></figure><p>For the sample star chosen for this example there were another 12 plots like the one above plotted from the code block above. Some stars had several of dataproducts, while others had none.</p><p>For most stars, the data plots below were also available. Again, information for how to do this was found from at <a href="https://github.com/spacetelescope/notebooks/blob/master/notebooks/MAST/"><em>https://github.com/spacetelescope/notebooks/blob/master/notebooks/MAST/</em></a></p><pre><strong>import</strong> <strong>numpy</strong> <strong>as</strong> <strong>np</strong><br><br><em># Getting urls for all dvt.fits files associated with TIC ID 29781292:</em><br>dvts_for_29781292 = [url <strong>for</strong> url <strong>in</strong> urls_for_29781292 <strong>if</strong> <br>                    url.endswith(&#39;dvt.fits&#39;)]<br><br><em># Describing and plotting all lc.fits files associated with TIC ID 29781292:</em><br><em># See https://github.com/spacetelescope/notebooks/blob/master/notebooks/MAST/</em><br><em># TESS/beginner_how_to_use_dvt/beginner_how_to_use_dvt.ipynb</em><br><strong>for</strong> url <strong>in</strong> dvts_for_29781292:<br>    <br>    fits_file = (&#39;https://mast.stsci.edu/api/v0.1/Download/file?uri=&#39; + url)<br>    <br>    print(fits.info(fits_file), &quot;<strong>\n</strong>&quot;)<br>    <br>    print(fits.getdata(fits_file, ext=1).columns)<br>    <br>    <strong>with</strong> fits.open(fits_file, mode=&quot;readonly&quot;) <strong>as</strong> hdulist:<br><br>        star_teff = hdulist[0].header[&#39;TEFF&#39;]<br>        star_logg = hdulist[0].header[&#39;LOGG&#39;]<br>        star_tmag = hdulist[0].header[&#39;TESSMAG&#39;]<br><br>        period = hdulist[1].header[&#39;TPERIOD&#39;]<br>        duration = hdulist[1].header[&#39;TDUR&#39;]<br>        epoch = hdulist[1].header[&#39;TEPOCH&#39;]<br>        depth = hdulist[1].header[&#39;TDEPTH&#39;]<br><br>        times = hdulist[1].data[&#39;TIME&#39;]<br>        phases = hdulist[1].data[&#39;PHASE&#39;]<br>        fluxes_init = hdulist[1].data[&#39;LC_INIT&#39;]<br>        model_fluxes_init = hdulist[1].data[&#39;MODEL_INIT&#39;]<br>    <br>    sort_indexes = np.argsort(phases)<br><br>    fig, ax = plt.subplots(figsize=(12,4))<br><br>    ax.plot(phases[sort_indexes], fluxes_init[sort_indexes], &#39;ko&#39;,<br>           markersize=2)<br><br>    ax.plot(phases[sort_indexes], model_fluxes_init[sort_indexes], &#39;-r&#39;)<br><br>    ax.set_ylabel(&quot;Flux (relative)&quot;)<br>    ax.set_xlabel(&quot;Orbital Phase&quot;)<br><br>    plt.show()</pre><p>This produces all of the dvt light-curve plots available for a star in the TESS data. An example dvt plot:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/777/1*rnhE-1h90HSOyURiujHK9g.jpeg" /></figure><p>Finally, we could save our wrangled data in new csv files:</p><pre>toi.to_csv(&#39;toi_example.csv&#39;)<br>tic_catalog.to_csv(&#39;tic_catalog_example.csv&#39;)<br>dataproducts.to_csv(&#39;dataproducts_example.csv&#39;)</pre><p>PART 2: BUILDING A PREDICTIVE MODEL</p><p>Since we were going to need to get our data into SQL database, we started by pulling our csv data saved above into a pandas df, transferred it into a sqlite db, then back into a pandas df, merged on the unique star number (TIC id).</p><pre><strong>from</strong> <strong>sqlalchemy</strong> <strong>import</strong> create_engine<br><strong>from</strong> <strong>astropy.io</strong> <strong>import</strong> fits<br><br><em># Importing example data:</em><br>toi = pd.read_csv(&#39;toi_example.csv&#39;)<br>tic_catalog = pd.read_csv(&#39;tic_catalog_example.csv&#39;)<br><br><em># Getting it into an sqlite database:</em><br>engine = create_engine(&#39;sqlite://&#39;, echo=<strong>False</strong>)<br><br>toi.to_sql(&#39;toi&#39;, con=engine, index=<strong>False</strong>)<br>tic_catalog.to_sql(&#39;tic_catalog&#39;, con=engine, index=<strong>False</strong>)</pre><pre><em># Pulling data from sql database:</em><br>toi = pd.read_sql_table(&#39;toi&#39;, engine).drop(columns=&#39;Unnamed: 0&#39;)<br>tic_catalog = pd.read_sql_table(<br>    &#39;tic_catalog&#39;, engine).drop(columns=&#39;Unnamed: 0&#39;)<br><br><em># Assembling data needed for model:</em><br>df = toi.merge(tic_catalog, on=&#39;TIC_ID&#39;)</pre><p>Next came a Test/Train split. In this case, because the size of the training set was relatively small, we decided against a validation split.</p><pre><strong>from</strong> <strong>sklearn.model_selection</strong> <strong>import</strong> train_test_split<br><br><em># Separating confirmed planets from false positives:</em><br>df[&#39;TFOPWG_Disposition&#39;] = df[<br>    &#39;TFOPWG_Disposition&#39;].replace({&#39;KP&#39;: 1, &#39;CP&#39;: 1, &#39;FP&#39;: 0})<br><br><em># Creating confirmed planets dataframe:</em><br>cp_df = df[df[&#39;TFOPWG_Disposition&#39;] == 1]<br><br><em># Creating false positives dataframe:</em><br>fp_df = df[df[&#39;TFOPWG_Disposition&#39;] == 0]<br><br><em># Train/test split on both dataframes:</em><br>cp_train, cp_test = train_test_split(cp_df, random_state=42)<br>fp_train, fp_test = train_test_split(fp_df, random_state=42)<br><br><em># Combining training dataframes:</em><br>train = cp_train.append(fp_train)<br>train = train.sample(frac=1, random_state=42).reset_index(drop=<strong>True</strong>)<br><br><em># Combining test dataframes:</em><br>test = cp_test.append(fp_test)<br>test = test.sample(frac=1, random_state=42).reset_index(drop=<strong>True</strong>)<br><br><em># Dropping columns from training dataframe that aren&#39;t used in model:</em><br>X_train = train.drop(columns=[&#39;TIC_ID&#39;, &#39;TOI&#39;, &#39;TFOPWG_Disposition&#39;])<br><em># Getting labels for training data:</em><br>y_train = train[&#39;TFOPWG_Disposition&#39;].astype(int)<br><br><em># Dropping columns from test dataframe that aren&#39;t used in model:</em><br>X_test = test.drop(columns=[&#39;TIC_ID&#39;, &#39;TOI&#39;, &#39;TFOPWG_Disposition&#39;])<br><em># Getting labels for test data:</em><br>y_test = test[&#39;TFOPWG_Disposition&#39;].astype(int)</pre><p>Finally it was time to build a Keras Neural Network model:</p><pre><strong>from</strong> <strong>tensorflow</strong> <strong>import</strong> keras<br><strong>from</strong> <strong>tensorflow.keras.models</strong> <strong>import</strong> Sequential<br><strong>from</strong> <strong>tensorflow.keras.layers</strong> <strong>import</strong> Dense<br><strong>from</strong> <strong>tensorflow.keras</strong> <strong>import</strong> optimizers<br><strong>from</strong> <strong>tensorflow.keras.wrappers.scikit_learn</strong> <strong>import</strong> KerasClassifier<br><strong>from</strong> <strong>sklearn.preprocessing</strong> <strong>import</strong> RobustScaler<br><strong>from</strong> <strong>sklearn.impute</strong> <strong>import</strong> SimpleImputer<br><strong>from</strong> <strong>sklearn.pipeline</strong> <strong>import</strong> make_pipeline<br><br><em># Setting up model architecture for neural net:</em><br><strong>def</strong> create_model():<br>    <em># Instantiate model:</em><br>    model = Sequential()<br>    <em># Add input layer:</em><br>    model.add(Dense(20, input_dim=33, activation=&#39;relu&#39;))<br>    <em># Add hidden layer:</em><br>    model.add(Dense(20, activation=&#39;relu&#39;))<br>    <em># Add output layer:</em><br>    model.add(Dense(1, activation=&#39;sigmoid&#39;))<br>    <em># Compile model:</em><br>    model.compile(loss=&#39;binary_crossentropy&#39;, optimizer=&#39;adam&#39;,<br>              metrics=[&#39;accuracy&#39;])<br>    <strong>return</strong> model<br><br><em># Putting neural net in a pipeline:</em><br>pipeline = make_pipeline(<br>    SimpleImputer(strategy=&#39;mean&#39;),<br>    RobustScaler(),<br>    KerasClassifier(build_fn=create_model, verbose=2)<br>)<br><br><em># Fitting the neural net:</em><br>pipeline.fit(X_train,<br>             y_train,<br>             kerasclassifier__batch_size=5,<br>             kerasclassifier__epochs=50,<br>             kerasclassifier__validation_split=.2,<br>             kerasclassifier__verbose=2)<br><br><em># Printing train and test accuracy:</em><br>print(&#39;<strong>\n\n</strong>&#39;)<br>print(f&#39;Train Accuracy Score:&#39;, pipeline.score(X_train, y_train), &#39;<strong>\n</strong>&#39;)<br>print(f&#39;Test Accuracy Score:&#39;, pipeline.score(X_test, y_test))</pre><p>After running 50 epochs, accuracy honed in on about 80% with a loss around 1.1:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/571/1*kDcB5iZqxiPAGv1YXqyuPA.jpeg" /></figure><p>In a addition to building the model itself, my DS partner and I set out to create a simple interactive app with our findings. As a minimal product, we hoped for a user to be able to select a star from the data and see a light-curve graph with our model’s predictions.</p><p>In a addition to building the model itself, my DS partner and I set out to create a simple interactive app with our findings. As a minimal product, we hoped for a user to be able to select a star from the data and see a light-curve graph with our model’s predictions.</p><p>To tackle this, I built a Python Flask App. In retrospect, we really didn’t need to reproduce all of our work in the app, but we did. I created a number of python classes in Object Oriented Programming style to most easily transfer our local work on a sqlite database to a populating our production PostgreSQL DB and used SQLAlchemy. The idea was to build something that we could come back to and build out more features.</p><pre>from flask_sqlalchemy import SQLAlchemy</pre><pre>#Instantiate<br>DB = SQLAlchemy()</pre><pre># create visualization info class<br>class Visual_Table(DB.Model):<br>  id = DB.Column(DB.Integer, primary_key=True)<br>  TIC_ID = DB.Column(DB.BigInteger, nullable=False)<br>  dataURL = DB.Column(DB.String(100))<br>  def __repr__(self):<br>  return &#39;&lt;Visual_Table {}&gt;&#39;.format(self.TIC_ID)</pre><pre>class TOI_Table(DB.Model):<br>  id = DB.Column(DB.Integer, primary_key=True)<br>  TIC_ID = DB.Column(DB.BigInteger, nullable=False)<br>  TOI = DB.Column(DB.Float)<br>  Epoch = DB.Column(DB.Float)<br>  Period = DB.Column(DB.Float)<br>  Duration = DB.Column(DB.Float)<br>  Depth = DB.Column(DB.Float)<br>  Planet_Radius = DB.Column(DB.Float)<br>  Planet_Insolation = DB.Column(DB.Float)<br>  Planet_Equil_Temp = DB.Column(DB.Float)<br>  Planet_SNR = DB.Column(DB.Float)<br>  Stellar_Distance = DB.Column(DB.Float)<br>  Stellar_log_g = DB.Column(DB.Float)<br>  Stellar_Radius = DB.Column(DB.Float)<br>  TFOPWG_Disposition = DB.Column(DB.String)<br>  def __repr__(self):<br>  return &#39;&lt;TOI_Table {}&gt;&#39;.format(self.TIC_ID)</pre><pre>class TIC_Cat_Table(DB.Model):<br>  id = DB.Column(DB.Integer, primary_key=True)<br>  TIC_ID = DB.Column(DB.BigInteger, nullable=False)<br>  ra = DB.Column(DB.Float)<br>  dec = DB.Column(DB.Float)<br>  pmRA = DB.Column(DB.Float)<br>  pmDEC = DB.Column(DB.Float)<br>  plx = DB.Column(DB.Float)<br>  gallong = DB.Column(DB.Float)<br>  gallat = DB.Column(DB.Float)<br>  eclong = DB.Column(DB.Float)<br>  eclat = DB.Column(DB.Float)<br>  Tmag = DB.Column(DB.Float)<br>  Teff = DB.Column(DB.Float)<br>  logg = DB.Column(DB.Float)<br>  MH = DB.Column(DB.Float)<br>  rad = DB.Column(DB.Float)<br>  mass = DB.Column(DB.Float)<br>  rho = DB.Column(DB.Float)<br>  lum = DB.Column(DB.Float)<br>  d = DB.Column(DB.Float)<br>  ebv = DB.Column(DB.Float)<br>  numcont = DB.Column(DB.Float)<br>  contratio = DB.Column(DB.Float)<br>  priority = DB.Column(DB.Float)<br>  def __repr__(self):<br>    return &#39;&lt;TIC_Cat_Table {}&gt;&#39;.format(self.TIC_ID)</pre><p>To populate this database, I created three functions to live in a .py file to fetch data for our three tables above. The nearly 200 lines of code of these functions can be found: <a href="https://github.com/mikedcurry/TESS_Flask_App/blob/master/App_TESS/Data_in.py">https://github.com/mikedcurry/TESS_Flask_App/blob/master/App_TESS/Data_in.py</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6413c077c9c4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Live in the Best Place App]]></title>
            <link>https://medium.com/@mdcurry1138/live-in-the-best-place-app-ec0039d5a2c1?source=rss-d20ee40a1cdd------2</link>
            <guid isPermaLink="false">https://medium.com/p/ec0039d5a2c1</guid>
            <category><![CDATA[data-visualization]]></category>
            <dc:creator><![CDATA[Mike Curry]]></dc:creator>
            <pubDate>Sun, 05 Apr 2020 18:27:48 GMT</pubDate>
            <atom:updated>2020-04-05T18:27:48.884Z</atom:updated>
            <content:encoded><![CDATA[<p><em>An App to Rank Cities based upon user selected factors</em></p><p><strong>Project Roles &amp; Objectives:</strong></p><p>This project was put together over the course of eight weeks by a team of 14 students with four disciplines — UX, iOS, Full Stack Web, and Data Science. We were given two weeks to plan, five weeks to build, and one week to clean and present our documentation. Much of the user research and data collection had been done by a previous team. There were two DS students on this team. Between the two of us, my role was to clean data, build a model for sorting cities by multiple factors, and to create data visualizations. My DS partner worked primarily on building our API to connect our model to both the iOS and web teams. I spent most of the five weeks of build-time alternating between Jupyter Notebooks and pair programming with my DS partner to integrate my work into our API.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/986/1*pk_0K-S_ujnC6cN4RrLTIg.jpeg" /></figure><p>After a day of initial data wrangling, I cleaned and reduced our data to the largest 256 US cities with populations of about one hundred thousand or larger. Our API would give our web developers access to 189 city features ranging from: crime safety ratings, economic growth factors, school ratings, diversity, air quality, etc.</p><h4>FIRST STEPS: RANKING CITIES BY MULTIPLE FACTORS</h4><p>The overall goal was for the first release cycle was for our model to return a list of top recommendations based upon which factors a user selected as important to them. The hope was to eventually add sliders to each selected feature, to be able to weigh relative importance of each factor. Even with this relatively tiny data set and without adding weighted relative importance, the number of possible ranked lists based exceeds 3*10³⁴⁹; my team needed a live model.</p><p>First I created a simple function using pandas manipulations.</p><pre># returns df filtered by quantile of factors</pre><pre>def rankify(df, factors, top=10, quant=.75):<br>  df_copy = df.copy()<br>  for i in factors:<br>     df_copy = df_copy[df[i] &gt; df_copy[i].quantile(quant)]<br>     df_copy[&#39;score&#39;] = df_copy[factors].mean(axis=1)<br>     df_copy = df_copy.sort_values(&#39;score&#39;, ascending=False)<br>  return df_copy[&#39;name&#39;].head(top).tolist()</pre><p>For a given input dataframe and list of factors, the above function takes only the cities that appear in the intersection of the top 25% for each of the factors listed. In other words, a city with a low score in any of the categories listed is axed from the list. From there, a mean is taken across each row to provide a relative score for comparing to other cities, and cities are sorted by the resulting values.</p><p>Although the results from this initial function had some pretty glaring issues, by handing over this minimally viable product to my team, they were able to start working on integrating it into our app, while I improved my model and further cleaned my data.</p><h4>ISSUES TO RESOLVE</h4><ol><li>Different factors were on vastly difference scales. For example, population might vary on the scale of millions, while economic growth usually varies on partial percentages. Whichever factor had the biggest numbers had the biggest influence on the overall rank. To begin to fix this, I used a min-max scaler, shrinking the range of values for all factors to be from zero to one.</li><li>While I pushed these slight improvements, another issue occurred to me — distribution. Since distributions were not all skewed in the same direction, comparing the upper quartile of each factor once again resulted in a varied range. This time, the model favored factors with a right skew in distribution. I then turned to a robust scaler, that redistributed each quartile, but the results still somewhat biased towards certain initial distributions.</li></ol><pre>import numpy as np<br>from sklearn.preprocessing import MinMaxScaler<br># from sklearn.preprocessing import StandardScaler<br>from sklearn.preprocessing import RobustScaler<br>from sklearn.impute import SimpleImputer</pre><pre># Instantiate<br># scaler = StandardScaler()<br>mms = MinMaxScaler()<br>rscaler = RobustScaler()</pre><pre>#Isolate numeric columns<br>numeric = robust_df.select_dtypes(&#39;number&#39;)<br>x = numeric.values</pre><pre># Impute NaNs with means<br>imp_mean = SimpleImputer(missing_values=np.nan, strategy=&#39;mean&#39;)<br>imp_mean.fit(x)<br>SimpleImputer(add_indicator=False, copy=True, fill_value=None,<br>missing_values=np.nan, strategy=&#39;mean&#39;, verbose=0)<br>x = imp_mean.transform(x)</pre><pre># Scale / Normalize / Standardize<br># x_scaled = scaler.fit_transform(x)<br>x_scaled = rscaler.fit_transform(x)<br>x_scaled = mms.fit_transform(x)<br>df_temp = pd.DataFrame(x_scaled, columns=numeric.columns, index = robust_df.index)<br>robust_df[numeric.columns] = df_temp</pre><p>Even while the scale was made the same between factors, the skew of distribution was widely different from one factor to another. If a factor had a strong right-skew (left leaning) distribution, then the resulting upper quartile was had a bigger range than if it were left-skewed. This gave more influence to factors with right-leaning distributions. I had to find a way to create perfectly uniform distributions for each factor.</p><h4>A SIMPLE SOLUTION TO PRODUCE A FLAT DISTRIBUTION</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/399/1*fCeIxJN5zBBsKaROMKRDnw.png" /></figure><p>Finally, it occurred to me that what I was looking for was a flat distribution which could be accomplished much more easily by ranking each factor using pandas own built-in .rank() function. In this way, each factor had scale between 0 and 1 with each city equally distributed in percentile rank. When plotted, the distribution became square.</p><p>By the time I had resolved these issues with data distribution, my Data Science partner had developed a rudamentary flask API, deployed it Heroku, and was serving results from my initial function to the Front End of our Web Dev team. Even while the initial results were nonsensical the team was able to build around the model until it was improved. Updated the data base to improve the results was a seemless push, with complete seperation of our respective concerns. Then when the average was taken across multiple factors no bias was given.</p><h3>RELEASE CYCLE 2: DATA VISUALIZATION</h3><p>After experimenting with color pallets and other package versions of a vertically stacked bar graph, I decided that to do something a little more unique with my data visualization. I really like the way violin plots make it easy to compare distributions of a handful of factors all at once.</p><p>First I started by graphing one Violin Plot using the seaborn library.</p><pre>import seaborn as sns</pre><pre>sns.set(style=&quot;whitegrid&quot;)</pre><pre>ax = sns.violinplot(x=redu_df[&#39;avg_commute_time&#39;])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/357/1*KA0mydI7adli8QyV6Ysftg.jpeg" /></figure><p>Although the above seaborn violin plot is essentially the same as a Kernel Density Estimate plot, the mirrored effect in combination with an overlay of a box plot gives a user a lot of information in one spot. Here we see that the medium of average commute times is just over 25 minutes, while the vast majority of average commute times for our 256 cities is below 35 minutes. We can see that there are few outliers to the extreme right where some cities’ commuters spend about 45 minutes on average.</p><p>Comparing multiple factors first required standardizing the data. Otherwise, the distributions would not be on the same scale. For example, income tax data rate would be mostly in the hundredth’s place while commute time would be about three orders of magnitude bigger — not the most visually accessible graph.</p><pre>x = [&#39;cost_of_living&#39;, &#39;score_outdoors&#39;, &#39;score_education&#39;, &#39;score_commute&#39;]</pre><pre>sns.set(style=&quot;whitegrid&quot;)</pre><pre>g = sns.catplot(data=norm_df[x], kind=&quot;violin&quot;, split=True, height=4, aspect=1.5, orient=&quot;h&quot;);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/444/1*OdUnEqFHQoE6ddVkRprOfw.jpeg" /></figure><p>A user can take the top handful of factors and compare the distribution of those factors between all cities under consideration. For example, cost of living appears to be a fairly bell-shaped distribution, while education is bipolar.</p><p>Next I played with the same information in a slightly different format, known as a swarm plot.</p><pre>import matplotlib.pyplot as plt</pre><pre>ax = sns.catplot(data=norm_df[x], kind=&quot;swarm&quot;, split=True, height=5, aspect=1.5, orient=&quot;h&quot;);</pre><pre>plt.axvline(x=.7)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/546/1*3b1u1k_CyFtp0-mmATDTxA.jpeg" /></figure><p>Although, again this information is essentially nothing more than a distribution plot, swarm plots are especially good at accessing a visual understanding of where clusters are at in the data. Looking again at the bipolar distribution of education ratings, for example, with this plot one can see that there is a rather large cluster to the left around 0.2 tapering out slowly toward the center. Whereas on the right side of the education distribution there appears to be a push to be in the top 25%. While the violin plot is more immediately accessible, it smooths our these nuances.</p><p>So, why not combine the two graphs? Do so is not more complicated than calling them both on the same axis and changing the colors of the overlaid plot.</p><pre>ax = sns.violinplot(data=norm_df[x], height=8, aspect=1.3, orient=&#39;h&#39;, inner=None)</pre><pre>ax = sns.swarmplot(data=norm_df[x], orient=&#39;h&#39;, color=&quot;white&quot;, edgecolor=&quot;black&quot;, size=2.5)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/474/1*xZb49aC0q7jUVTaGXb7blg.jpeg" /></figure><p>My UX designer decided that these plots were too difficult to interpret and asked me for something that was more simple and easy to understand. After some back and forth, I came up with the idea of a “slug plot” and went back to MatPlotLib to get extra control of fine details.</p><pre>import scipy.stats as stats<br>import numpy as np<br>import matplotlib.pyplot as plt</pre><pre>def displot(df, city, factor):<br>   fig, ax = plt.subplots(dpi=200)<br>   plt.style.use(&quot;seaborn&quot;)</pre><pre>   # Turn off tick labels<br>   ax.set_yticklabels([])<br>   ax.set_xticklabels([])</pre><pre>   # dist = redu_df[&#39;score_outdoors&#39;].copy()<br>   kde = stats.gaussian_kde(redu_df[factor])</pre><pre>   # plot complete kde curve as line<br>   pos = np.linspace(redu_df[factor].min(), redu_df[factor].max(), 101)<br>   plt.plot(pos, kde(pos))</pre><pre>   # find value x of factor in specified city<br>   x = redu_df.loc[redu_df[&#39;short_name&#39;] == city][factor].tolist()[0]</pre><pre>   # plot shaded kde only left of x<br>   shade = np.linspace(dist.min(), x, 101)<br>   plt.fill_between(shade,kde(shade), alpha=0.6)</pre><pre>   # plt.figure(figsize=(3,1))<br>   fig = plt.gcf()<br>   fig.set_size_inches(6, .8)</pre><pre>   plt.ylim(0,None)<br>   # plt.show()</pre><pre>   plt.axvline(x=x, color=&#39;black&#39;, lw=2)</pre><pre>   moo = int(round(ranked_df.loc[ranked_df[&#39;short_name&#39;] == city][factor].tolist()[0], 2)*100)<br>   text = &quot;{}&#39;s {} Percentile: {}%&quot;.format(city, factor, moo)        <br>   plt.xlabel(text)</pre><pre>   return plt.savefig(&#39;testplot.png&#39;)</pre><pre># example<br>plot(df=redu_df, city=&#39;Portland&#39;, factor=&#39;score_outdoors&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/969/1*S3SavKFeMGZXM3D4Sfw8Rg.png" /></figure><p>MatPlotLib is always a lot of code for a single graph, but it’s always my go-to when I need to do something truly custom. The idea of my “slug plot” distribution was that I could build it into a function and produce however many of the plots needs for a given city and a list of important factors. Being squished horizontally, my web folk could provide the user with a number of stacked distributions for easy comparison. Well, my web folk thought it was too boring, plus they didn’t want to have to deal with designing around multiple graphs being called to the front end.</p><p>It was back to the drawing board again. I was asked to make a visual that compared multiple factors for a given city with as much bang for my buck in a single API served data visual. So I made this.</p><pre>import numpy as np<br>import matplotlib.pyplot as plt<br></pre><pre>def radar_plt(df=ranked_df, city=city, factors=x):<br>   test = df.loc[df[&#39;short_name&#39;] == city][factors].T.reset_index()<br>   test.columns = [&#39;theta&#39;, &#39;r&#39;]<br>   test[&#39;r&#39;] = test[&#39;r&#39;]*100<br>   test[&#39;theta&#39;] = test[&#39;theta&#39;].replace(&#39;_&#39;, &#39; &#39;, regex=True<br>      ).replace(&#39;score &#39;, &#39;&#39;, regex=True<br>         ).replace(&#39;ranked &#39;, &#39;&#39;,<br>            regex=True<br>            ).str.title()</pre><pre>   test</pre><pre>   plt.style.use(&quot;bmh&quot;)</pre><pre>   fig = plt.figure(figsize=(10,10))<br>   ax = fig.add_subplot(111,polar=True)<br>   ax.spines[&#39;polar&#39;].set_visible(False)</pre><pre>   rank = test[&#39;r&#39;]<br>   # sample = np.random.uniform(low=0.5, high=13.3, size=(15,))<br>   N = test[&#39;r&#39;].shape[0]<br>   # colors= &#39;#f51646&#39;<br>   # colors = plt.cm.PuRd(test[&#39;r&#39;] / 10)<br>   # colors = plt.cm.viridis(test[&#39;r&#39;] / 100)<br>   colors = plt.cm.GnBu(test[&#39;r&#39;] / 150)</pre><pre>   width = np.pi / N*1.8<br>   theta = np.arange(0, 2*np.pi, 2*np.pi/N)<br>   bars = ax.bar(theta, rank, width=width, color=colors, alpha=0.9)</pre><pre>   ax.yaxis.grid(True)</pre><pre>   ax.set_xticks(theta)<br>   ax.set_xticklabels(test[&#39;theta&#39;], fontweight=&#39;bold&#39;, fontsize=12)# , fontname=&#39;FontAwesome&#39;)</pre><pre>   # puts % on y tick labels<br>   y_label_text = [&quot;{}%&quot;.format(int(loc)) for loc in plt.yticks()[0]]<br>   ax.set_yticklabels(y_label_text)</pre><pre>   # rrr = redu_df.loc[redu_df[&#39;short_name&#39;] == city][x].tolist()[0]<br>   # plt.axvline(x=rrr, color=&#39;black&#39;, lw=2)</pre><pre>   # print([&quot;{}%&quot;.format(int(loc)) for loc in plt.yticks()[0]])<br>   # return plt.show()<br>   return plt.savefig(&#39;radarplot.png&#39;, dpi=400)</pre><pre># Example:<br>city = &#39;Portland&#39;</pre><pre>x = [&quot;score_commute&quot;, &quot;score_cost_of_living&quot;, &quot;score_economy&quot;, &quot;score_education&quot;, &quot;score_environmental_quality&quot;, &quot;score_healthcare&quot;, &quot;score_housing&quot;, &quot;score_internet_access&quot;, &quot;score_leisure_&amp;_culture&quot;, &quot;score_outdoors&quot;, &quot;score_safety&quot;, &quot;score_startups&quot;, &quot;score_taxation&quot;, &quot;ranked_population&quot;]</pre><pre>radar_plt()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/689/1*gh39CPRPu9FLkq0TvAFNvg.png" /></figure><p>The radar bar plot above, for Portland Oregon, gives the percentile rank for a given input city for each specified factor. The color is set to be darker, thus more visible, for higher scores. This allows the user to immediately see which categories are a city’s strongest suites.</p><p>In the following three weeks, my web design partners once again redesigned the data visual for this project in our native Javascript back-end to increase the loading speed of our app. All that I had contributed to this aspect of the project lives on in branch history. Se la vie.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ec0039d5a2c1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Convolutional Neural Network to Identify Nearest City in a Photo]]></title>
            <link>https://medium.com/@mdcurry1138/a-convolutional-neural-network-to-identify-nearest-city-in-a-photo-aac5300d16be?source=rss-d20ee40a1cdd------2</link>
            <guid isPermaLink="false">https://medium.com/p/aac5300d16be</guid>
            <dc:creator><![CDATA[Mike Curry]]></dc:creator>
            <pubDate>Tue, 31 Mar 2020 17:50:24 GMT</pubDate>
            <atom:updated>2020-03-31T17:50:24.438Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v7bR2IBGjDozVquFrMlZPA.png" /></figure><p><em>A CNN for image recognition is trained on results from Google Images API for city names. The array of probabilities provided by a softmax output layer are examined to determine subtle similarities between cities. The plans for a “City Vibes” swiping app are here discussed.</em></p><p>This project originally started as a feature for iOS implementation of another app — Best Places to Live (link). In the third release cycle of our project, I teamed up with an iOS student to build out the feature described here. Fortunately for my partner, he was offered paid position midway through development. As a consequence, the front end of this feature has not yet been completed. Despite this setback, I have included my work on this feature as a stand-alone story in my project. I think the idea is fun, original, and would be fairly straight forward to develop. For the Machine Learning aspects of this project I have a proof of concept, and I have a skeleton outline of database architecture that would make this app function at a production level.</p><p>The overall idea of this project is to have a user swipe right or left on random images of cities. If the user likes what they see in the photo, the app should find cities that have photos with similar content. Likewise, the app should shuffle cities with disliked features towards the bottom of the list.</p><p>The beauty of using a Neural Network to target cities by random photos is that the patterns it picks up on are subtle. Of the general subject matter in a photo, the NN picks up on lighting, texture, edges, color-scheme, and honestly who knows what else. The patterns are not predetermined, but opaquely found by whatever the NN can pick up on in the photos to optimize it’s target accuracy. Adding to this subtly is how top results are selected from Google Images. The subject of photos in google images for a given keyword are continuously sorted by popular user association. For example, ‘New York’ generally has grandiose skyline photos towards the top of the stack. ‘Denver’ tends to feature mountainous backgrounds with rocky crags. ‘Los Angeles’ has more street view photos.</p><p>The duel-layer of subtly, both from the NN and google images automatic sorting, give rise to the double potential to access user sub-conscious preference in ‘vibes’ from a given city photo.</p><p>The slightly more technical vision of this project is to: train a neural network for image recognition on random photos of cities; have the model output an array of probabilities representing each photo’s match to each city; have a user swipe left or right for each random city photo displayed; keep a running score of probable matches for each city per user; output a list of top matched cities for a user based upon images they have swiped.</p><p>Steps completed thus far:</p><ol><li>Use a script to pull random google images into a file system, using city names as keywords.</li><li>Design a CNN optimized for photo recognition, able to access file system, uses ‘city name’ as it’s target, and outputs an array of probabilities.</li><li>Design a database architecture that store hosted photo URLs with output probability arrays, user running totals data, and a simple model for keeping users’ city match scores.</li></ol><p>Starting with the end in mind, I first roughly sketched out a plan for a workable data architecture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*slXuGtBlDOVXTB9oLwuoFg.png" /><figcaption>Emphasis on ‘rough’ diagram</figcaption></figure><p>The core of the data for this app can be stored in two relatively simple tables. The first table should contain information about each photo: a url to the hosted image; a queue position key value; an array of probabilities for the percentage match to each city. The second table should contain basic user information: their position in the photo queue, and the running match-score for each city. The second table could either live in the Back End or on the user’s device.</p><p>To complete the core of the app, a very simple model should update user match-score data. This model should take the current user score values and either add or subtract the current user input image array based on included Boolean values. Because of the simplicity of this model, it should live natively in the BE of the app and does not justify a separate DS API. Of course, this model could be greatly improved upon with only slightly more complex arithmetic to calculate the running total, but the general idea is there with just addition and subtraction.</p><p>The general flow through this diagram is:</p><p>The user initiated the app</p><ol><li>A request is sent to the User Swipe Data table for the queue position</li><li>This key is used to access the next photo in the Photo Info table</li><li>A fresh photo URL is served</li><li>User input, left/right swipe plus PhotoID, is sent to BE model</li><li>Model gets current swipe data and does arithmetic to update running total, updates user data table</li><li>This cycle loops</li></ol><p>A separate button for resulting recommendation</p><ol><li>Sends a request to User Swipe Data table</li><li>Model sorts running totals</li><li>Returns a list of top matched cities</li></ol><p>THE SCRIPT:</p><p>Getting a script to pull photos into a file system from Google Images API was made very easy since this is something that has been done before. After a short couple of hours of search, I had something that was immediately adaptable to my purpose. This allowed me to download multiple images from google for each city and put them in seperate file folders all at once: <a href="https://github.com/hardikvasa/google-images-download">https://github.com/hardikvasa/google-images-download</a></p><p>As a mock-up of what I expected to be able to do with my google images script, I started small with just nine photos between three cities. I manually downloaded these put the photos in folders in the same root directory as my project notebooks. Once I had my CNN working on this micro-set, I went to work on pulling photos from the google images API on a slightly larger scale. I was thrilled to have a directory of files with cities downloaded to my local machine.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/123/1*_Ig_lrtZIBql1X4qE5CHLQ.jpeg" /><figcaption>Files created by script with photos in each</figcaption></figure><p>With my newly adopted script, I could fill my city folders with as many random city photos as I specified. Again, I took the road of simplicity and only did four photos for each of the 256 cities. Good thing I went small, because it took me several hours to download these with sad home internet speeds.</p><p>THE CNN:</p><p>I decided to force all of my photos to be the same size. Maybe there is another way of doing this, but figured that the input vectors were all going need to be the same when they got plugged into the Neural Net. For this I used a prepossessing tool from Keras. Again I started small with a resolution of 224 by 224 by 3 (for colors). I’m not sure if there is any reason for this size exactly, but I found that a lot of instances of Keras use this exact size so I superstitiously followed the apparent convention.</p><pre>from tensorflow.keras.preprocessing import image</pre><pre>def process_img_path(img_path):<br>    return image.load_img(img_path, target_size=(224, 224))</pre><p>Loading one of my photos to take a look:</p><pre>image.load_img(&#39;./data/santa_fe/sfe1.jpg&#39;, target_size=(224,224))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/224/1*g4pxrddPRa-Va8BBhzwJjg.png" /><figcaption>Random Santa Fe image 224x224</figcaption></figure><p>Then I wrote a short function to apply this size requirement to each photo as it adds them as an array of values to a X vector.</p><pre>data = []</pre><pre>for i in [&#39;columbus&#39;, &#39;portland&#39;, &#39;santa_fe&#39;]:<br>    for file in os.listdir(&#39;./data/&#39;+i):<br>#         print(file) #to check if right files...<br>        if file[-3:] == &#39;jpg&#39;:<br>            path = os.path.join(f&#39;./data/{i}/&#39; + file)<br>            img = process_img_path(path)<br>            x = image.img_to_array(img)<br>            <br>            data.append(x)<br>#             print(x)</pre><p>For fun, we can take a peak at our vectorized photos:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/297/1*t6HPKBkQkpv0_VyXdzZyzw.png" /><figcaption>Vectorized Photo Array</figcaption></figure><p>Taking a quick look at the shape of this array, shows us that we have 9 photos, each being 224 by 224 pixles in 3 colors dimensions. Golden. Later the first number became 256 * n, the number of photos hosted per city.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/195/1*zRlCBepIWZEjkfoert68-w.png" /></figure><p>On my first attempt at creating a functional CNN, I created a simple target vector by manually creating an array. Each number represented a city.</p><pre>y = array([0, 0, 0, 1, 1, 1, 2, 2, 2])</pre><p>For a bigger set of photos, I had to get a little more python savvy:</p><pre># Create target vector</pre><pre>y = []<br>  for i in range(0, 256):<br>   j = [i]*4   # in this case 4 photos / city<br>   for p in j:<br>     y.append(p)</pre><pre>y = np.asarray(y)</pre><p>Every time I write something this simple that works, I feel like a mad-scientist!</p><p>y.shape yields:</p><pre>array([ 0, 0, 0, …, 255, 255, 255])</pre><p>Perfect, except that it needed to be made binary:</p><pre>from keras.utils import to_categorical<br>y_binary = to_categorical(y)</pre><p>This turned my 0–255 numbered target vector into zeros and ones like:</p><pre>array([[1., 0., 0., ..., 0., 0., 0.],<br>      [1., 0., 0., ..., 0., 0., 0.],        <br>      [1., 0., 0., ..., 0., 0., 0.],        <br>       ...,        <br>      [0., 0., 0., ..., 0., 0., 1.],        <br>      [0., 0., 0., ..., 0., 0., 1.],        <br>      [0., 0., 0., ..., 0., 0., 1.]], dtype=float32)</pre><p>Next, I split my data into train and test. If I had a much bigger set, I would probably use a train/validate/test split, but this project primarily a proof of concept. Plus, I can’t afford the computational power to run anything much bigger than four photos per city.</p><pre>from sklearn.model_selection import train_test_split</pre><pre>x_train, x_test, y_train, y_test = train_test_split(x, y_binary, test_size=0.25, stratify=y_binary)</pre><p>In my “bigger” set with four photos for each 256 cities, I used three pics to train and one to test. Admittedly, this is not even remotely close to producing something that could be proven accurate, but that’s not really the point of this project.</p><p>I had method for clearly defining my X and y vectors, now I needed to work out a model.</p><p>I wanted to create a neural network that could take in my array of photos, use each city as a target, and output an array of probabilities that told how likely each photo was each city.</p><p>After a lot of searching and digging, I found a number of very helpful articles on building NNs with Keras from Jason Browlee — my current hero. <a href="https://machinelearningmastery.com/category/deep-learning/">https://machinelearningmastery.com/category/deep-learning/</a> Seriously, how is this guy so awesome!?!</p><p>I also found some helpful information about how get an probabilities from a NN using a softmax output layer and a categorical crossentropy loss function from Haihan Lan — another current hero of mine. <a href="https://towardsdatascience.com/the-softmax-function-neural-net-outputs-as-probabilities-and-ensemble-classifiers-9bd94d75932">https://towardsdatascience.com/the-softmax-function-neural-net-outputs-as-probabilities-and-ensemble-classifiers-9bd94d75932</a></p><p>After learning from these masters in my field, building my CNN model with a softmax output layer looks deceptively simple:</p><pre>#imports<br>from tensorflow.keras.layers import Dense, Conv2D, MaxPooling2D, Flatten, GlobalAveragePooling2D<br>from tensorflow.keras.applications.resnet50 import ResNet50<br>from tensorflow.keras.models import Sequential, Model</pre><pre>#instantiate resnet50 &amp; sew own a head -- input layer shape <br>res = ResNet50(input_shape=(224, 224, 3), weights=&#39;imagenet&#39;, include_top=False)</pre><pre># sew my tail on this beast<br>x1 = res.output<br>x1 = GlobalAveragePooling2D()(x1)<br>predictions = Dense(y_train[0].shape[0], activation=&#39;softmax&#39;)(x1)</pre><pre>model = Model(res.input, predictions)</pre><p>Above, I’ve taken the beastly Resnet50 deep NN and simply Frankenstein on my own input and output layers. I’m not going to pretend that I understand how Resnet’s layer structure was dreamed up. However, I think it’s worth taking a moment to appreciate what’s under the hood on this model <strong>— prepare to scroll a ways.</strong> My model layers can be inspected using, model.summary:</p><pre>Model: &quot;model&quot; __________________________________________________________________________________________________ Layer (type)                    Output Shape         Param #     Connected to                      ================================================================================================== input_1 (InputLayer)            [(None, 224, 224, 3) 0                                             __________________________________________________________________________________________________ conv1_pad (ZeroPadding2D)       (None, 230, 230, 3)  0           input_1[0][0]                     __________________________________________________________________________________________________ conv1_conv (Conv2D)             (None, 112, 112, 64) 9472        conv1_pad[0][0]                   __________________________________________________________________________________________________ conv1_bn (BatchNormalization)   (None, 112, 112, 64) 256         conv1_conv[0][0]                  __________________________________________________________________________________________________ conv1_relu (Activation)         (None, 112, 112, 64) 0           conv1_bn[0][0]                    __________________________________________________________________________________________________ pool1_pad (ZeroPadding2D)       (None, 114, 114, 64) 0           conv1_relu[0][0]                  __________________________________________________________________________________________________ pool1_pool (MaxPooling2D)       (None, 56, 56, 64)   0           pool1_pad[0][0]                   __________________________________________________________________________________________________ conv2_block1_1_conv (Conv2D)    (None, 56, 56, 64)   4160        pool1_pool[0][0]                  __________________________________________________________________________________________________ conv2_block1_1_bn (BatchNormali (None, 56, 56, 64)   256         conv2_block1_1_conv[0][0]         __________________________________________________________________________________________________ conv2_block1_1_relu (Activation (None, 56, 56, 64)   0           conv2_block1_1_bn[0][0]           __________________________________________________________________________________________________ conv2_block1_2_conv (Conv2D)    (None, 56, 56, 64)   36928       conv2_block1_1_relu[0][0]         __________________________________________________________________________________________________ conv2_block1_2_bn (BatchNormali (None, 56, 56, 64)   256         conv2_block1_2_conv[0][0]         __________________________________________________________________________________________________ conv2_block1_2_relu (Activation (None, 56, 56, 64)   0           conv2_block1_2_bn[0][0]           __________________________________________________________________________________________________ conv2_block1_0_conv (Conv2D)    (None, 56, 56, 256)  16640       pool1_pool[0][0]                  __________________________________________________________________________________________________ conv2_block1_3_conv (Conv2D)    (None, 56, 56, 256)  16640       conv2_block1_2_relu[0][0]         __________________________________________________________________________________________________ conv2_block1_0_bn (BatchNormali (None, 56, 56, 256)  1024        conv2_block1_0_conv[0][0]         __________________________________________________________________________________________________ conv2_block1_3_bn (BatchNormali (None, 56, 56, 256)  1024        conv2_block1_3_conv[0][0]         __________________________________________________________________________________________________ conv2_block1_add (Add)          (None, 56, 56, 256)  0           conv2_block1_0_bn[0][0]                                                                            conv2_block1_3_bn[0][0]           __________________________________________________________________________________________________ conv2_block1_out (Activation)   (None, 56, 56, 256)  0           conv2_block1_add[0][0]            __________________________________________________________________________________________________ conv2_block2_1_conv (Conv2D)    (None, 56, 56, 64)   16448       conv2_block1_out[0][0]            __________________________________________________________________________________________________ conv2_block2_1_bn (BatchNormali (None, 56, 56, 64)   256         conv2_block2_1_conv[0][0]         __________________________________________________________________________________________________ conv2_block2_1_relu (Activation (None, 56, 56, 64)   0           conv2_block2_1_bn[0][0]           __________________________________________________________________________________________________ conv2_block2_2_conv (Conv2D)    (None, 56, 56, 64)   36928       conv2_block2_1_relu[0][0]         __________________________________________________________________________________________________ conv2_block2_2_bn (BatchNormali (None, 56, 56, 64)   256         conv2_block2_2_conv[0][0]         __________________________________________________________________________________________________ conv2_block2_2_relu (Activation (None, 56, 56, 64)   0           conv2_block2_2_bn[0][0]           __________________________________________________________________________________________________ conv2_block2_3_conv (Conv2D)    (None, 56, 56, 256)  16640       conv2_block2_2_relu[0][0]         __________________________________________________________________________________________________ conv2_block2_3_bn (BatchNormali (None, 56, 56, 256)  1024        conv2_block2_3_conv[0][0]         __________________________________________________________________________________________________ conv2_block2_add (Add)          (None, 56, 56, 256)  0           conv2_block1_out[0][0]                                                                             conv2_block2_3_bn[0][0]           __________________________________________________________________________________________________ conv2_block2_out (Activation)   (None, 56, 56, 256)  0           conv2_block2_add[0][0]            __________________________________________________________________________________________________ conv2_block3_1_conv (Conv2D)    (None, 56, 56, 64)   16448       conv2_block2_out[0][0]            __________________________________________________________________________________________________ conv2_block3_1_bn (BatchNormali (None, 56, 56, 64)   256         conv2_block3_1_conv[0][0]         __________________________________________________________________________________________________ conv2_block3_1_relu (Activation (None, 56, 56, 64)   0           conv2_block3_1_bn[0][0]           __________________________________________________________________________________________________ conv2_block3_2_conv (Conv2D)    (None, 56, 56, 64)   36928       conv2_block3_1_relu[0][0]         __________________________________________________________________________________________________ conv2_block3_2_bn (BatchNormali (None, 56, 56, 64)   256         conv2_block3_2_conv[0][0]         __________________________________________________________________________________________________ conv2_block3_2_relu (Activation (None, 56, 56, 64)   0           conv2_block3_2_bn[0][0]           __________________________________________________________________________________________________ conv2_block3_3_conv (Conv2D)    (None, 56, 56, 256)  16640       conv2_block3_2_relu[0][0]         __________________________________________________________________________________________________ conv2_block3_3_bn (BatchNormali (None, 56, 56, 256)  1024        conv2_block3_3_conv[0][0]         __________________________________________________________________________________________________ conv2_block3_add (Add)          (None, 56, 56, 256)  0           conv2_block2_out[0][0]                                                                             conv2_block3_3_bn[0][0]           __________________________________________________________________________________________________ conv2_block3_out (Activation)   (None, 56, 56, 256)  0           conv2_block3_add[0][0]            __________________________________________________________________________________________________ conv3_block1_1_conv (Conv2D)    (None, 28, 28, 128)  32896       conv2_block3_out[0][0]            __________________________________________________________________________________________________ conv3_block1_1_bn (BatchNormali (None, 28, 28, 128)  512         conv3_block1_1_conv[0][0]         __________________________________________________________________________________________________ conv3_block1_1_relu (Activation (None, 28, 28, 128)  0           conv3_block1_1_bn[0][0]           __________________________________________________________________________________________________ conv3_block1_2_conv (Conv2D)    (None, 28, 28, 128)  147584      conv3_block1_1_relu[0][0]         __________________________________________________________________________________________________ conv3_block1_2_bn (BatchNormali (None, 28, 28, 128)  512         conv3_block1_2_conv[0][0]         __________________________________________________________________________________________________ conv3_block1_2_relu (Activation (None, 28, 28, 128)  0           conv3_block1_2_bn[0][0]           __________________________________________________________________________________________________ conv3_block1_0_conv (Conv2D)    (None, 28, 28, 512)  131584      conv2_block3_out[0][0]            __________________________________________________________________________________________________ conv3_block1_3_conv (Conv2D)    (None, 28, 28, 512)  66048       conv3_block1_2_relu[0][0]         __________________________________________________________________________________________________ conv3_block1_0_bn (BatchNormali (None, 28, 28, 512)  2048        conv3_block1_0_conv[0][0]         __________________________________________________________________________________________________ conv3_block1_3_bn (BatchNormali (None, 28, 28, 512)  2048        conv3_block1_3_conv[0][0]         __________________________________________________________________________________________________ conv3_block1_add (Add)          (None, 28, 28, 512)  0           conv3_block1_0_bn[0][0]                                                                            conv3_block1_3_bn[0][0]           __________________________________________________________________________________________________ conv3_block1_out (Activation)   (None, 28, 28, 512)  0           conv3_block1_add[0][0]            __________________________________________________________________________________________________ conv3_block2_1_conv (Conv2D)    (None, 28, 28, 128)  65664       conv3_block1_out[0][0]            __________________________________________________________________________________________________ conv3_block2_1_bn (BatchNormali (None, 28, 28, 128)  512         conv3_block2_1_conv[0][0]         __________________________________________________________________________________________________ conv3_block2_1_relu (Activation (None, 28, 28, 128)  0           conv3_block2_1_bn[0][0]           __________________________________________________________________________________________________ conv3_block2_2_conv (Conv2D)    (None, 28, 28, 128)  147584      conv3_block2_1_relu[0][0]         __________________________________________________________________________________________________ conv3_block2_2_bn (BatchNormali (None, 28, 28, 128)  512         conv3_block2_2_conv[0][0]         __________________________________________________________________________________________________ conv3_block2_2_relu (Activation (None, 28, 28, 128)  0           conv3_block2_2_bn[0][0]           __________________________________________________________________________________________________ conv3_block2_3_conv (Conv2D)    (None, 28, 28, 512)  66048       conv3_block2_2_relu[0][0]         __________________________________________________________________________________________________ conv3_block2_3_bn (BatchNormali (None, 28, 28, 512)  2048        conv3_block2_3_conv[0][0]         __________________________________________________________________________________________________ conv3_block2_add (Add)          (None, 28, 28, 512)  0           conv3_block1_out[0][0]                                                                             conv3_block2_3_bn[0][0]           __________________________________________________________________________________________________ conv3_block2_out (Activation)   (None, 28, 28, 512)  0           conv3_block2_add[0][0]            __________________________________________________________________________________________________ conv3_block3_1_conv (Conv2D)    (None, 28, 28, 128)  65664       conv3_block2_out[0][0]            __________________________________________________________________________________________________ conv3_block3_1_bn (BatchNormali (None, 28, 28, 128)  512         conv3_block3_1_conv[0][0]         __________________________________________________________________________________________________ conv3_block3_1_relu (Activation (None, 28, 28, 128)  0           conv3_block3_1_bn[0][0]           __________________________________________________________________________________________________ conv3_block3_2_conv (Conv2D)    (None, 28, 28, 128)  147584      conv3_block3_1_relu[0][0]         __________________________________________________________________________________________________ conv3_block3_2_bn (BatchNormali (None, 28, 28, 128)  512         conv3_block3_2_conv[0][0]         __________________________________________________________________________________________________ conv3_block3_2_relu (Activation (None, 28, 28, 128)  0           conv3_block3_2_bn[0][0]           __________________________________________________________________________________________________ conv3_block3_3_conv (Conv2D)    (None, 28, 28, 512)  66048       conv3_block3_2_relu[0][0]         __________________________________________________________________________________________________ conv3_block3_3_bn (BatchNormali (None, 28, 28, 512)  2048        conv3_block3_3_conv[0][0]         __________________________________________________________________________________________________ conv3_block3_add (Add)          (None, 28, 28, 512)  0           conv3_block2_out[0][0]                                                                             conv3_block3_3_bn[0][0]           __________________________________________________________________________________________________ conv3_block3_out (Activation)   (None, 28, 28, 512)  0           conv3_block3_add[0][0]            __________________________________________________________________________________________________ conv3_block4_1_conv (Conv2D)    (None, 28, 28, 128)  65664       conv3_block3_out[0][0]            __________________________________________________________________________________________________ conv3_block4_1_bn (BatchNormali (None, 28, 28, 128)  512         conv3_block4_1_conv[0][0]         __________________________________________________________________________________________________ conv3_block4_1_relu (Activation (None, 28, 28, 128)  0           conv3_block4_1_bn[0][0]           __________________________________________________________________________________________________ conv3_block4_2_conv (Conv2D)    (None, 28, 28, 128)  147584      conv3_block4_1_relu[0][0]         __________________________________________________________________________________________________ conv3_block4_2_bn (BatchNormali (None, 28, 28, 128)  512         conv3_block4_2_conv[0][0]         __________________________________________________________________________________________________ conv3_block4_2_relu (Activation (None, 28, 28, 128)  0           conv3_block4_2_bn[0][0]           __________________________________________________________________________________________________ conv3_block4_3_conv (Conv2D)    (None, 28, 28, 512)  66048       conv3_block4_2_relu[0][0]         __________________________________________________________________________________________________ conv3_block4_3_bn (BatchNormali (None, 28, 28, 512)  2048        conv3_block4_3_conv[0][0]         __________________________________________________________________________________________________ conv3_block4_add (Add)          (None, 28, 28, 512)  0           conv3_block3_out[0][0]                                                                             conv3_block4_3_bn[0][0]           __________________________________________________________________________________________________ conv3_block4_out (Activation)   (None, 28, 28, 512)  0           conv3_block4_add[0][0]            __________________________________________________________________________________________________ conv4_block1_1_conv (Conv2D)    (None, 14, 14, 256)  131328      conv3_block4_out[0][0]            __________________________________________________________________________________________________ conv4_block1_1_bn (BatchNormali (None, 14, 14, 256)  1024        conv4_block1_1_conv[0][0]         __________________________________________________________________________________________________ conv4_block1_1_relu (Activation (None, 14, 14, 256)  0           conv4_block1_1_bn[0][0]           __________________________________________________________________________________________________ conv4_block1_2_conv (Conv2D)    (None, 14, 14, 256)  590080      conv4_block1_1_relu[0][0]         __________________________________________________________________________________________________ conv4_block1_2_bn (BatchNormali (None, 14, 14, 256)  1024        conv4_block1_2_conv[0][0]         __________________________________________________________________________________________________ conv4_block1_2_relu (Activation (None, 14, 14, 256)  0           conv4_block1_2_bn[0][0]           __________________________________________________________________________________________________ conv4_block1_0_conv (Conv2D)    (None, 14, 14, 1024) 525312      conv3_block4_out[0][0]            __________________________________________________________________________________________________ conv4_block1_3_conv (Conv2D)    (None, 14, 14, 1024) 263168      conv4_block1_2_relu[0][0]         __________________________________________________________________________________________________ conv4_block1_0_bn (BatchNormali (None, 14, 14, 1024) 4096        conv4_block1_0_conv[0][0]         __________________________________________________________________________________________________ conv4_block1_3_bn (BatchNormali (None, 14, 14, 1024) 4096        conv4_block1_3_conv[0][0]         __________________________________________________________________________________________________ conv4_block1_add (Add)          (None, 14, 14, 1024) 0           conv4_block1_0_bn[0][0]                                                                            conv4_block1_3_bn[0][0]           __________________________________________________________________________________________________ conv4_block1_out (Activation)   (None, 14, 14, 1024) 0           conv4_block1_add[0][0]            __________________________________________________________________________________________________ conv4_block2_1_conv (Conv2D)    (None, 14, 14, 256)  262400      conv4_block1_out[0][0]            __________________________________________________________________________________________________ conv4_block2_1_bn (BatchNormali (None, 14, 14, 256)  1024        conv4_block2_1_conv[0][0]         __________________________________________________________________________________________________ conv4_block2_1_relu (Activation (None, 14, 14, 256)  0           conv4_block2_1_bn[0][0]           __________________________________________________________________________________________________ conv4_block2_2_conv (Conv2D)    (None, 14, 14, 256)  590080      conv4_block2_1_relu[0][0]         __________________________________________________________________________________________________ conv4_block2_2_bn (BatchNormali (None, 14, 14, 256)  1024        conv4_block2_2_conv[0][0]         __________________________________________________________________________________________________ conv4_block2_2_relu (Activation (None, 14, 14, 256)  0           conv4_block2_2_bn[0][0]           __________________________________________________________________________________________________ conv4_block2_3_conv (Conv2D)    (None, 14, 14, 1024) 263168      conv4_block2_2_relu[0][0]         __________________________________________________________________________________________________ conv4_block2_3_bn (BatchNormali (None, 14, 14, 1024) 4096        conv4_block2_3_conv[0][0]         __________________________________________________________________________________________________ conv4_block2_add (Add)          (None, 14, 14, 1024) 0           conv4_block1_out[0][0]                                                                             conv4_block2_3_bn[0][0]           __________________________________________________________________________________________________ conv4_block2_out (Activation)   (None, 14, 14, 1024) 0           conv4_block2_add[0][0]            __________________________________________________________________________________________________ conv4_block3_1_conv (Conv2D)    (None, 14, 14, 256)  262400      conv4_block2_out[0][0]            __________________________________________________________________________________________________ conv4_block3_1_bn (BatchNormali (None, 14, 14, 256)  1024        conv4_block3_1_conv[0][0]         __________________________________________________________________________________________________ conv4_block3_1_relu (Activation (None, 14, 14, 256)  0           conv4_block3_1_bn[0][0]           __________________________________________________________________________________________________ conv4_block3_2_conv (Conv2D)    (None, 14, 14, 256)  590080      conv4_block3_1_relu[0][0]         __________________________________________________________________________________________________ conv4_block3_2_bn (BatchNormali (None, 14, 14, 256)  1024        conv4_block3_2_conv[0][0]         __________________________________________________________________________________________________ conv4_block3_2_relu (Activation (None, 14, 14, 256)  0           conv4_block3_2_bn[0][0]           __________________________________________________________________________________________________ conv4_block3_3_conv (Conv2D)    (None, 14, 14, 1024) 263168      conv4_block3_2_relu[0][0]         __________________________________________________________________________________________________ conv4_block3_3_bn (BatchNormali (None, 14, 14, 1024) 4096        conv4_block3_3_conv[0][0]         __________________________________________________________________________________________________ conv4_block3_add (Add)          (None, 14, 14, 1024) 0           conv4_block2_out[0][0]                                                                             conv4_block3_3_bn[0][0]           __________________________________________________________________________________________________ conv4_block3_out (Activation)   (None, 14, 14, 1024) 0           conv4_block3_add[0][0]            __________________________________________________________________________________________________ conv4_block4_1_conv (Conv2D)    (None, 14, 14, 256)  262400      conv4_block3_out[0][0]            __________________________________________________________________________________________________ conv4_block4_1_bn (BatchNormali (None, 14, 14, 256)  1024        conv4_block4_1_conv[0][0]         __________________________________________________________________________________________________ conv4_block4_1_relu (Activation (None, 14, 14, 256)  0           conv4_block4_1_bn[0][0]           __________________________________________________________________________________________________ conv4_block4_2_conv (Conv2D)    (None, 14, 14, 256)  590080      conv4_block4_1_relu[0][0]         __________________________________________________________________________________________________ conv4_block4_2_bn (BatchNormali (None, 14, 14, 256)  1024        conv4_block4_2_conv[0][0]         __________________________________________________________________________________________________ conv4_block4_2_relu (Activation (None, 14, 14, 256)  0           conv4_block4_2_bn[0][0]           __________________________________________________________________________________________________ conv4_block4_3_conv (Conv2D)    (None, 14, 14, 1024) 263168      conv4_block4_2_relu[0][0]         __________________________________________________________________________________________________ conv4_block4_3_bn (BatchNormali (None, 14, 14, 1024) 4096        conv4_block4_3_conv[0][0]         __________________________________________________________________________________________________ conv4_block4_add (Add)          (None, 14, 14, 1024) 0           conv4_block3_out[0][0]                                                                             conv4_block4_3_bn[0][0]           __________________________________________________________________________________________________ conv4_block4_out (Activation)   (None, 14, 14, 1024) 0           conv4_block4_add[0][0]            __________________________________________________________________________________________________ conv4_block5_1_conv (Conv2D)    (None, 14, 14, 256)  262400      conv4_block4_out[0][0]            __________________________________________________________________________________________________ conv4_block5_1_bn (BatchNormali (None, 14, 14, 256)  1024        conv4_block5_1_conv[0][0]         __________________________________________________________________________________________________ conv4_block5_1_relu (Activation (None, 14, 14, 256)  0           conv4_block5_1_bn[0][0]           __________________________________________________________________________________________________ conv4_block5_2_conv (Conv2D)    (None, 14, 14, 256)  590080      conv4_block5_1_relu[0][0]         __________________________________________________________________________________________________ conv4_block5_2_bn (BatchNormali (None, 14, 14, 256)  1024        conv4_block5_2_conv[0][0]         __________________________________________________________________________________________________ conv4_block5_2_relu (Activation (None, 14, 14, 256)  0           conv4_block5_2_bn[0][0]           __________________________________________________________________________________________________ conv4_block5_3_conv (Conv2D)    (None, 14, 14, 1024) 263168      conv4_block5_2_relu[0][0]         __________________________________________________________________________________________________ conv4_block5_3_bn (BatchNormali (None, 14, 14, 1024) 4096        conv4_block5_3_conv[0][0]         __________________________________________________________________________________________________ conv4_block5_add (Add)          (None, 14, 14, 1024) 0           conv4_block4_out[0][0]                                                                             conv4_block5_3_bn[0][0]           __________________________________________________________________________________________________ conv4_block5_out (Activation)   (None, 14, 14, 1024) 0           conv4_block5_add[0][0]            __________________________________________________________________________________________________ conv4_block6_1_conv (Conv2D)    (None, 14, 14, 256)  262400      conv4_block5_out[0][0]            __________________________________________________________________________________________________ conv4_block6_1_bn (BatchNormali (None, 14, 14, 256)  1024        conv4_block6_1_conv[0][0]         __________________________________________________________________________________________________ conv4_block6_1_relu (Activation (None, 14, 14, 256)  0           conv4_block6_1_bn[0][0]           __________________________________________________________________________________________________ conv4_block6_2_conv (Conv2D)    (None, 14, 14, 256)  590080      conv4_block6_1_relu[0][0]         __________________________________________________________________________________________________ conv4_block6_2_bn (BatchNormali (None, 14, 14, 256)  1024        conv4_block6_2_conv[0][0]         __________________________________________________________________________________________________ conv4_block6_2_relu (Activation (None, 14, 14, 256)  0           conv4_block6_2_bn[0][0]           __________________________________________________________________________________________________ conv4_block6_3_conv (Conv2D)    (None, 14, 14, 1024) 263168      conv4_block6_2_relu[0][0]         __________________________________________________________________________________________________ conv4_block6_3_bn (BatchNormali (None, 14, 14, 1024) 4096        conv4_block6_3_conv[0][0]         __________________________________________________________________________________________________ conv4_block6_add (Add)          (None, 14, 14, 1024) 0           conv4_block5_out[0][0]                                                                             conv4_block6_3_bn[0][0]           __________________________________________________________________________________________________ conv4_block6_out (Activation)   (None, 14, 14, 1024) 0           conv4_block6_add[0][0]            __________________________________________________________________________________________________ conv5_block1_1_conv (Conv2D)    (None, 7, 7, 512)    524800      conv4_block6_out[0][0]            __________________________________________________________________________________________________ conv5_block1_1_bn (BatchNormali (None, 7, 7, 512)    2048        conv5_block1_1_conv[0][0]         __________________________________________________________________________________________________ conv5_block1_1_relu (Activation (None, 7, 7, 512)    0           conv5_block1_1_bn[0][0]           __________________________________________________________________________________________________ conv5_block1_2_conv (Conv2D)    (None, 7, 7, 512)    2359808     conv5_block1_1_relu[0][0]         __________________________________________________________________________________________________ conv5_block1_2_bn (BatchNormali (None, 7, 7, 512)    2048        conv5_block1_2_conv[0][0]         __________________________________________________________________________________________________ conv5_block1_2_relu (Activation (None, 7, 7, 512)    0           conv5_block1_2_bn[0][0]           __________________________________________________________________________________________________ conv5_block1_0_conv (Conv2D)    (None, 7, 7, 2048)   2099200     conv4_block6_out[0][0]            __________________________________________________________________________________________________ conv5_block1_3_conv (Conv2D)    (None, 7, 7, 2048)   1050624     conv5_block1_2_relu[0][0]         __________________________________________________________________________________________________ conv5_block1_0_bn (BatchNormali (None, 7, 7, 2048)   8192        conv5_block1_0_conv[0][0]         __________________________________________________________________________________________________ conv5_block1_3_bn (BatchNormali (None, 7, 7, 2048)   8192        conv5_block1_3_conv[0][0]         __________________________________________________________________________________________________ conv5_block1_add (Add)          (None, 7, 7, 2048)   0           conv5_block1_0_bn[0][0]                                                                            conv5_block1_3_bn[0][0]           __________________________________________________________________________________________________ conv5_block1_out (Activation)   (None, 7, 7, 2048)   0           conv5_block1_add[0][0]            __________________________________________________________________________________________________ conv5_block2_1_conv (Conv2D)    (None, 7, 7, 512)    1049088     conv5_block1_out[0][0]            __________________________________________________________________________________________________ conv5_block2_1_bn (BatchNormali (None, 7, 7, 512)    2048        conv5_block2_1_conv[0][0]         __________________________________________________________________________________________________ conv5_block2_1_relu (Activation (None, 7, 7, 512)    0           conv5_block2_1_bn[0][0]           __________________________________________________________________________________________________ conv5_block2_2_conv (Conv2D)    (None, 7, 7, 512)    2359808     conv5_block2_1_relu[0][0]         __________________________________________________________________________________________________ conv5_block2_2_bn (BatchNormali (None, 7, 7, 512)    2048        conv5_block2_2_conv[0][0]         __________________________________________________________________________________________________ conv5_block2_2_relu (Activation (None, 7, 7, 512)    0           conv5_block2_2_bn[0][0]           __________________________________________________________________________________________________ conv5_block2_3_conv (Conv2D)    (None, 7, 7, 2048)   1050624     conv5_block2_2_relu[0][0]         __________________________________________________________________________________________________ conv5_block2_3_bn (BatchNormali (None, 7, 7, 2048)   8192        conv5_block2_3_conv[0][0]         __________________________________________________________________________________________________ conv5_block2_add (Add)          (None, 7, 7, 2048)   0           conv5_block1_out[0][0]                                                                             conv5_block2_3_bn[0][0]           __________________________________________________________________________________________________ conv5_block2_out (Activation)   (None, 7, 7, 2048)   0           conv5_block2_add[0][0]            __________________________________________________________________________________________________ conv5_block3_1_conv (Conv2D)    (None, 7, 7, 512)    1049088     conv5_block2_out[0][0]            __________________________________________________________________________________________________ conv5_block3_1_bn (BatchNormali (None, 7, 7, 512)    2048        conv5_block3_1_conv[0][0]         __________________________________________________________________________________________________ conv5_block3_1_relu (Activation (None, 7, 7, 512)    0           conv5_block3_1_bn[0][0]           __________________________________________________________________________________________________ conv5_block3_2_conv (Conv2D)    (None, 7, 7, 512)    2359808     conv5_block3_1_relu[0][0]         __________________________________________________________________________________________________ conv5_block3_2_bn (BatchNormali (None, 7, 7, 512)    2048        conv5_block3_2_conv[0][0]         __________________________________________________________________________________________________ conv5_block3_2_relu (Activation (None, 7, 7, 512)    0           conv5_block3_2_bn[0][0]           __________________________________________________________________________________________________ conv5_block3_3_conv (Conv2D)    (None, 7, 7, 2048)   1050624     conv5_block3_2_relu[0][0]         __________________________________________________________________________________________________ conv5_block3_3_bn (BatchNormali (None, 7, 7, 2048)   8192        conv5_block3_3_conv[0][0]         __________________________________________________________________________________________________ conv5_block3_add (Add)          (None, 7, 7, 2048)   0           conv5_block2_out[0][0]                                                                             conv5_block3_3_bn[0][0]           __________________________________________________________________________________________________ conv5_block3_out (Activation)   (None, 7, 7, 2048)   0           conv5_block3_add[0][0]            __________________________________________________________________________________________________ global_average_pooling2d (Globa (None, 2048)         0           conv5_block3_out[0][0]            __________________________________________________________________________________________________ dense (Dense)                   (None, 256)          524544      global_average_pooling2d[0][0]    ================================================================================================== Total params: 24,112,256 Trainable params: 524,544 Non-trainable params: 23,587,712 __________________________________________________________________________________________________</pre><p>Like I said, it’s a beast. Notice the last couple lines: over 24 million parameters, over a half millions of which are trainable! Mind boggling.</p><p>It feels a bit like cheating to add just a half-dozen lines of code to re-purpose it. The fifty layers are ResNet50 have been trained on millions of photos to identify all kinds of particular objects. Perhaps targeting cities captured in pictures is a wildly different affair, but it seems like a good place to start for picking up on subtle content of photos.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aac5300d16be" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Purchasing Power & Carbon Efficiency]]></title>
            <link>https://medium.com/@mdcurry1138/purchasing-power-carbon-efficiency-f6116ec2a680?source=rss-d20ee40a1cdd------2</link>
            <guid isPermaLink="false">https://medium.com/p/f6116ec2a680</guid>
            <category><![CDATA[climate-change]]></category>
            <dc:creator><![CDATA[Mike Curry]]></dc:creator>
            <pubDate>Sat, 03 Aug 2019 04:14:09 GMT</pubDate>
            <atom:updated>2019-08-04T20:26:49.708Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/469/1*ulw9_kIRWSZaE_IMQ2SNyg.png" /><figcaption><a href="https://cdiac.ess-dive.lbl.gov/ftp/ndp030/global.1751_2013.ems">Carbon Emissions (millions of metric-tons of carbon)</a></figcaption></figure><p>The graph above probably looks familiar. It represents global carbon emission dating back to 1750. Two other graphs that look quite similar are Gross World Product and Human Population. All three variables are on intertwined trajectories, and if you have ever left the shelter of your favorite rock, it would be difficult to avoid stumbling over any number of such graphs — depicting the explosion of our species and it’s creations.</p><p>Your gut-reaction to this iconic curve is likely to fall into one of two camps: (1) immediate dread, thinking about the impact that all this carbon dioxide is having on our global environment, or (2) awe at the amazing prowess of human progress. Maybe it’s both. In whichever camp you pitch your tent, you may find it difficult to wrap your head around the relationship between carbon emissions and increased standards of living, and/or you may find it hard to reason clearly through the compounding effect of population.</p><p>Using opensource data from the <a href="https://data.worldbank.org/">World Bank</a>, and inspired by <a href="https://www.gapminder.org/">Hans Rosling</a>, I set out to visualize the relationship of wealth, carbon emissions, and human population in one mesmerizing visual. The goal was to make a single graphic that helps to shed light on the dynamic between wealth creation and carbon emissions, without the compounding effects of population.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1005/1*hvpPAMKg4vZvCp7dEPHAKg.gif" /><figcaption>All Countries (Population by Bubble Size)</figcaption></figure><p>Each colorful bubble represents a different country, with size proportionate to population. On the horizontal axis, Carbon Emissions are measured in Metric Tons of CO2 per person per year. The vertical axis represents wealth through Purchase Power Parity (<a href="https://en.wikipedia.org/wiki/Purchasing_power_parity">PPP</a>) per person per year.</p><p>Movement up, represents an increase in average buying power. Movement right represents increased carbon emissions. A bubble moving along a positively-sloped straight line would represent increased wealth, but at the constantly <em>proportionate </em>cost in carbon emissions — unchanging carbon efficiency. An economy gaining in carbon efficiency should curve upwards — moving towards more purchasing power per carbon. Ideally a country should float closer towards the left while rising; decreasing carbon emissions per person while simultaneously increasing purchasing power.</p><p>Above, notice how the bubbles appear to be moving in a sweeping motion along a straight line, as if pivoting from the origin. Without applying any math, this sweeping motion is reminiscent of an exponential curve — countries appear to be increasing in carbon-efficiency as they produce more wealth.</p><p><strong>*Below*<em> </em></strong><em>blue: United States — red: EU — orange: Middle East &amp; North Africa — dark purple: China — green: India — light purple: UN classified Least Developed Countries.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CojAQCk7q_rWMZ7xVEYAbw.gif" /><figcaption>Select Countries and Regions for Discussion</figcaption></figure><p>While each bubble is changing in proportion to its respective population, notice how the bottom left countries can be more readily seen to grow. Watch India in green, and the UN classified ‘Least Developed Countries’ lumped together as light purple.</p><p>Above, the light blue dot to the right represents the United States. As the visual cycles from 1990 to 2014, it is possible to see the average annual income of someone living in the US rising from $24k to $55k . <a href="http://www.in2013dollars.com/1990-dollars-in-2018?amount=24000">Adjusted for inflation</a> relative to 2018, this works out to be a rise from about $46k to $58k.</p><p>In 1990, each American could claim an average responsibility of about 19 Metric Tons of carbon dioxide, lowering substantially to around 16 Metric Tons in 2014. This happened while at the same time Purchasing power increased, thus representing an increase in carbon efficiency. <em>Maybe.</em></p><p>The big purple bubble above representing China shows the average income of someone in China rising from just under $1k per year to over $13k — about $2k to $14k adjusted for inflation. At the same time period China moves swiftly to the right. The average Chinese citizen moved from a responsibility of 2.2 Metric Tons of carbon dioxide per year to 7.5 between 1990 and 2014. China increased it’s purchasing power 620% per person while increasing carbon emissions by 240%. Impressive! Meanwhile, the US increased purchasing power by 26% on average while <em>decreasing</em> carbon emissions by 16%.</p><p><strong>*Below* </strong><em>red: United States — blue: China</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/984/1*nj0XxXrTvjCXon_Fxk6T1Q.gif" /></figure><p>While Americans may be tempted to pat ourselves on the back over our average increase in purchasing power and simultaneous decrease in carbon emissions, there is an important compounding effect to note. China’s blitz towards the right, and the US’s slide to the left, is probably in large-part due to the US outsourcing carbon-intensive industry towards China. One is tempted to perform a vector addition between the two bubbles to see where they are headed together.</p><p>In any case, both countries can be seen to rise in purchasing power over time. While China first appears to be on a flatter slope towards a more carbon-intensive creation of wealth, the time-frame makes it too short to tell. With a few more years of data, it is reasonable to expect that China, among other countries, should begin to float more directly upward towards less carbon-intensive, more efficient wealth creation.</p><p><em>The World, Unified as One Blue Bubble</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g-UL-qFjnIJq1Y-pJbJhYg.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f6116ec2a680" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>