<?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 Dallin Stewart on Medium]]></title>
        <description><![CDATA[Stories by Dallin Stewart on Medium]]></description>
        <link>https://medium.com/@dallinpstewart?source=rss-596349f77bb5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*x1SvFsRVWIgl17JfdlIk4g.jpeg</url>
            <title>Stories by Dallin Stewart on Medium</title>
            <link>https://medium.com/@dallinpstewart?source=rss-596349f77bb5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 23:25:38 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dallinpstewart/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[NYC Taxi Trip Duration Predictor]]></title>
            <link>https://medium.com/@dallinpstewart/nyc-taxi-trip-duration-predictor-a66c0f884766?source=rss-596349f77bb5------2</link>
            <guid isPermaLink="false">https://medium.com/p/a66c0f884766</guid>
            <category><![CDATA[linear-regression]]></category>
            <category><![CDATA[lightgbm]]></category>
            <category><![CDATA[random-forest-classifiers]]></category>
            <category><![CDATA[pca-analysis]]></category>
            <category><![CDATA[xgboost]]></category>
            <dc:creator><![CDATA[Dallin Stewart]]></dc:creator>
            <pubDate>Tue, 28 May 2024 17:16:20 GMT</pubDate>
            <atom:updated>2024-05-28T17:16:20.732Z</atom:updated>
            <content:encoded><![CDATA[<p>By Dallin Stewart, Jeff Hansen, Dylan Skinner, Jason Vasquez</p><h3>Introduction</h3><p>We tackle the challenge of predicting taxi ride durations in New York City based on starting and stopping coordinates. A ‘taxi ride duration’ refers to how long, in seconds, a taxi ride takes. This research question is relevant for urban commuters and transportation systems, and it incorporates the myriad of factors influencing taxi ride times. These factors include traffic patterns, congestion, time of day, and external variables such as local events or weather conditions. The strengths of machine learning methods align well with the intricacies of this problem, and allow us to uncover more nuanced relationships within the data. Beyond the potential convenience for individual riders, the ability to predict taxi ride times carries practical implications for optimizing taxi fleet management, city resource allocation, and enhancing overall traffic flow in New York.</p><p>In preparation for our analysis, we conducted initial research about travel time prediction. We quickly learned about the importance of removing outlying data and unnecessary attributes [RR22] (see section 8. Data Cleaning). Additionally, we learned which models typically perform best with travel time prediction [BLM18] and concluded that tree based ensembles are typically best for this type of task [HPMP20].</p><p>Kaggle published the dataset we are exploring for a coding competition, so over one thousand other groups have investigated this research question. Successful teams performed feature engineering to create fields such as month, day, hour, day of the week, and used models such as Random Forest Regression, Extra Trees Regression, PCA, XGBoost, linear regression, and Light GBM [RIS17].</p><p>The original dataset came fully complete, does not contain missing data, and includes fields such as: taxi driver, the number of passengers, and whether the trip time was recorded in real time. We added a second dataset that contains weather information with timestamps, temperature, precipitation, cloud cover, and wind information at every hour [AAD22]. The NYC taxi cab dataset was published by NYC Taxi and Limousine Commission (TLC) in Big Query on Google Cloud Platform and is well documented and densely populated with over one million data points [TLC23]. The weather dataset is much more sparse and has a much larger time range than needed to match the NYC Taxi data. These datasets provide a good source for addressing our research questions because they extensively cover NYC taxi travel for a significant time period. In short, the data allows us to effectively identify significant features impacting taxi trip duration and develop a robust predictive model for accurate estimations.</p><p>While we focus our primary investigation on determining taxi cab trip duration, we are also interested in several other questions. What days of the week and times of day are most busy? Where are the most popular destinations? Furthermore, the multifaceted exploration of temporal, spatial, and environmental influences on travel durations in NYC presents a well-rounded analysis to reveal comprehensive insights into travel behaviors. This poses questions such as how do environmental factors such as rain impact taxi popularity? Our data is well suited for our research question in exploring and predicting taxi trip duration, and has a single, clear answer. A process of machine learning model development will help us go one step further and develop a robust predictive model to estimate and understand trip durations accurately. Our approach, seen below, is comprehensive and unique in several ways, for example we use K-Means clustering to group the pickup and drop-off locations together, and use a grid search to find optimal hyperparameters of each model.</p><h3>Feature Engineering</h3><p>In pursuit of a model with higher predictive power, we included several additional features in our dataset that fall in one of three distinct feature groups: datetime, distance, and weather.</p><h3>Data Cleaning</h3><p>The taxi cab duration dataset from Kaggle contained several outliers that required removal. For example, some trips lasted 1 second, and others lasted over 980 days. To prevent erroneous data, we removed all rows where trip_duration was in the .005 quantile, or less than 60 seconds. The dataset also contained outliers in the pickup and dropoff locations that fell far outside New York City. We fixed these rows by removing any point outside of city limits. For the full plot visualization code, see section 8. Data Cleaning in the Appendix.</p><h3>Datetime</h3><p>One of the most important features in our dataset is passenger pickup time, originally represented as a string in the format YYYY-MM-DD HH:MM:SS. We created multiple time features from this column including pickup_month, one-hot encoded pickup_day columns, pickup_hour, and pickup_minute. We also added other versions of these data points including one-hot encoded pickup_period, pickup_hour_sin, pickup_hour_cos, and pickup_datetime_norm. See section 8. Data Cleaning.clean_data in the Appendix for more details.</p><h4>Pickup Period</h4><p>The feature pickup_period captures the time of day when passengers were picked up in one of four periods: morning (6:00 AM to 12:00 PM), afternoon (12:00 PM to 6:00 PM), evening (6:00 PM to 12:00 AM), and night (12:00 AM to 6:00 AM). These divisions align intuitively with significant periods of the day for taxi services, such as morning rush hours and evening nightlife. See section 8. Data Cleaning.clean_data in the Appendix for more details.</p><h4>Pickup Period Sine/Cosine</h4><p>We applied a circular encoding to time to account for the cyclical nature of the hours of the day. We created pickup_hour_sin and pickup_hour_cos features using sine and cosine transformations to avoid discontinuities such as the start and end of a day. See section 8. Data Cleaning.clean_data in the Appendix for more details.</p><h4>Pickup Datetime Norm</h4><p>The final feature we created in the datetime feature grouping was pickup_datetime_norm to represent the normalized pickup datetime. This feature converts the pickup datetime from nanoseconds to seconds, then scales the value by the maximum to place all the values between 0 and 1. See section 8. Data Cleaning.clean_data in the Appendix for more details.</p><h3>Distance</h3><p>We created two features that estimate distance between pickup and dropoff locations: the Manhattan distance and the average distances between local coordinate clusters.</p><h4>Manhattan Distance</h4><p>We include the Manhattan Distance feature because of its grid based metric. Many of the streets of New York are laid out in a grid-like fashion, so this metric can better approximate road distances than the Euclidean distance. The Manhattan distance is also more simple and interpretable, since it computes the sum of the absolute values of the differences between the 𝑥 and 𝑦 coordinates of the two points. We calculated the Manhattan distance by first converting the pickup and dropoff coordinate points into radians with 𝑅=6371 km, the radius of the Earth in kilometers. See section 9. Feature Engineering.distance in the Appendix for the full implementation.</p><h4>Computing Distance with Dijkstra’s Algorithm</h4><p>With over 1.4 million data points over a relatively small geography, the pick up and dropoff locations provide an effective proxy for the actual road map of New York. We can use this information to estimate the distance between the two points using a modified version of Dijkstra’s algorithm. We chose to use Dijkstra’s algorithm because it is a well known and well documented algorithm for finding the shortest path between two points in a graph. We modified the algorithm to find the shortest path between two points in a graph, where the edges of the graph are the roads in New York City with weights equal to their geographic length, and the nodes are the pick up and drop-off locations.</p><p>We can reduce the size of the graph by removing nodes that are too close together, removing the few hundred nodes that lie well outside the metropolitan area, and cropping the graph for each distance calculation to only include nodes that lie roughly between the pick up and dropoff locations. This reduces the size of the graph from over 1.4 million nodes to a few thousand nodes. We can then use Dijkstra’s algorithm to find the shortest path between the pick up and dropoff locations. The resulting cost of the shortest path is an estimate of the actual driving distance required to travel between the two points, which is one of the strongest predictors of taxi ride duration.</p><h3>Weather</h3><p>When considering potential features to add to our dataset, accounting for the effect of local weather on taxi ride time was one of the most obvious additions to include. For example, if it is raining or snowing, we may assume there will be more traffic on the roads, and more people who would normally walk would prefer a taxi. A dataset created by Kaggle user [AAD22] contains a myriad of weather data for New York City between 2016 and 2022 on an hourly basis. This dataset includes features such as temperature (in Celcius), precipition (in mm), cloud cover (low, mid, high, and total), wind speed (in km/h), and wind direction. We decided to use temperature, precipitation, and total cloud cover as features in our dataset with a simple join on the pickup datetime rounded to the nearest whole hour. See sections 8. Data Cleaning.get_clean_weather and 9. Feature Engineering.add_weather_feature in the Appendix for more information.</p><h3>Feature Selection</h3><p>As seen in section 2. Feature Enginnering, we created several new features in addition to those already in the dataset. We also consider which features are unnecessary or unhelpful.</p><h3>𝐿1 Regularization</h3><p>To determine the most important features, we utilized 𝐿1 regularization since it functions by setting unneeded feature coefficents to 0 and typically out-performs step-wise feature removal. We did not use 𝐿2 regularization because the large number of features allows 𝐿1 regularization to perform better.</p><h3>Data Exploration and Visualization</h3><h3>Data Exploration</h3><p>Before visualizing the data, we will first perform basic data exploration to show the effects of adding the features mentioned above.</p><p>We built a function get_X_y() that performs basic feature engineering and returns two Pandas dataframes: 𝑋 and 𝑦. We also built the function generate_features() that performs more advanced feature engineering and returns one Pandas dataframe: 𝑋. See section 8. Data Cleaning in the Appendix for the full function. The table below shows a single example of the data and features from the final feature_X dataframe.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BbtSnmaioH9NCN3x6Y1ecQ.png" /></figure><h3>Data Visualization</h3><p>In the following figure, the top two graphs visualize the pickup and dropoff locations overlaid over a map of NYC. The bottom two graphs display the pickup and dropoff locations clustered into groups using KMeans clustering. These charts reveal that pickup locations are more heavily clustered around downtown (Manhattan), while the dropoff locations are more evenly distributed throughout the city. This distribution indicates that Manhattan, where more people go to work, is the most popular place to hail a taxi. The most popular destination is still in Manhattan, but the destinations are much more distributed across New York. While it is difficult to definitively conclude the cause for this difference, one possible explanation is that people get rides home more frequently. For the full plot implementation, see section 7. Visualization in the Appendix.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ldh64r58AszBFV2N.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TGd17xVEO_xzXU5L.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ztayU4mKMv-uUuuN.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6vg6JnBsq12y5bAj.png" /></figure><p>We can also learn about the factors that influence a New Yorker’s decision to take a taxi from the data. For example, in the figure below, the graph on the left displays the most popular times of day to hail a taxi, which peeks around 6:00 PM and drops the lowest around 4:00 PM. We also see that poor weather encourages more people to take a taxi during the day when people are more likely to be returning from their daily activities, but less likely to choose to go out at night in the first place. The graph on the right shows the most popular days of the week for taxis, which peeks on Friday and Saturday and during the evenings of the weekdays. In the graph on the right, brighter colors indicate more taxi rides, and darker colors indicate fewer taxi rides. For the full plot implementation, see section 7. Visualization in the Appendix.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tgUL5duqU0b5_xD5.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lX0Otvaj8xkN7Lcx.png" /></figure><h3>Modeling and Results</h3><p>Our primary research question is to predict the duration of a taxi ride in New York City. To achieve this goal, we implemented a variety of machine learning models including Lasso regression, Random Forest regression, XGBoost, and LightGBM. We explain our implementation, training, optimization, and results for each model below.</p><p>After performing feature engineering, we performed hyperparameter grid searches for the each of these models. The table below shows the training time for each model in the first row, and the optimal hyperparameter choices and the best Root Mean Squared Error (RMSE) for each model:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GCznKY0BwVDnziM6jbVnBw.png" /></figure><p>See sections 1. Lasso Feature Selection, 2. LightGBM Hyperparameter Selection, XGBoost Hyperparameter Selection, 4. XGBoost Model, 5. Random Foreset Hyperparameter Selection in the Appendix for the code implementations.</p><h3>Interpretation</h3><p>The residual plots below demonstrate how far away our models’ predictions deviate from the actual value, and they provide insights into how each model makes predictions See section 7. Visualizations.plot_residual in the Appendix for the plotting code. As seen across all of the residual plots, all of the models generally tend to predict the mean of the actual data. This behavior indicates our model is underfit.</p><p>The Random Forest residual plot reveals a multimodal-like distribution with three main hills. This layout implies that the Random Forest model identified several clusters with different means from the taxi data. Additionally, the LightGBM residuals appear bi-modal, suggesting that the model found an additional clustering. The bin-like prediction values for the LightGBM model is likely a result of LightGBM’s use of histogram binning to speed up the training process.</p><p>The Lasso model’s slightly right-skewed normal distribution likely stems from its underfitting linear model. Despite its limitation, the Lasso model’s residual plot aligns remarkably well with the actual trip duration distribution depicted in the histograms below. Furthermore, the XGBoost model appears very similar to the Lasso model, but with more skew to the right. This difference likely arrises because the dataset has many more shorter trips than longer ones, and the model is more likely to predict the mode over the mean.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/596/0*SLjZt8WsNJcPpQBS.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/596/0*PvDdoZ6aRuptnijk.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/596/0*eUklXWrdWeLh1tvg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/596/0*BEqOCFYJhziYeR3i.png" /></figure><p>The figures below depict the actual distribution of taxi trip durations along with our model’s predicted distributions See section 7. Visualizations.plot_actual_vs_predicted_distributions in the Appendix for the plotting code. The plot on the left depicts the distribution of outputs from a LightGBM model with optimal parameters (100 estimators, 30 leaves, and a max_depth of 50). This model is not very strong, as it predicts the mean of the actual distribution almost exclusively. This poor performance implies that the feature space is not large enough for the model to create a more accurate approximation of the distribution.</p><p>We generated the plot on the right with a different LightGBM model using much larger parameters (100,000 estimators, 500 leaves and a max_depth of 50). This model took a full hour to train and around 15 minutes to make predictions. As the prediction distribution demonstrates, this model makes predictions farther from the mean, indicating that the model fits the data better as we raise its complexity and compute capabilities. With enough compute resources and time, we could increase the model parameters to higher values and create more features for the data. This upgrade would allow the model to better approximate the data instead of simply predicting the mean.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*Nx_nqcXr6VjoiGPy.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/597/0*79egsECqUUSjG3HR.png" /></figure><p>The map in Figure 1 at the end of this paper plots cluster pairs which have the highest travel time to distance traveled ratio on average. See section 7. Visualizations.duration_per_distance in the Appendix for the code. Interestingly, some of the cluster paths cross major roadways, implying that there should be more support roads that cross under or over the major highways. Furthermore, a majority of the largest duration trips per distance occur in Manhattan. This demonstrates that the public transit system could be improved to optimize taxi traffic use.</p><h3>Ethical Implications</h3><p>Our research involves analyzing a large dataset created by tracking some of the life-style patterns of real people living in New York during 2016, raising concerns about privacy and responsible data usage for individual behaviors, locations, and travel patterns. Our dataset and model protect this data by excluding all personally identifiable information to ensure that only aggregate information can be meaningful, and the patterns of individuals remain indiscernible.</p><p>The risk of misinterpretation or misuse of our predictive models is very real — especially considering its weak predictive power. Users could misunderstand predictions, leading to inappropriate decision-making. Our predictive model may contain and inadvertently perpetuate biases that we are unaware of, such as inappropriate associations with certain neighborhoods and taxis. Furthermore, users might misunderstand the predictive and uncertain nature of the model and treat its estimates as certainties. For instance, if taxi companies or transportation authorities were to make decisions solely based on the model’s predictions without considering broader traffic management strategies, it could inadvertently lead to concentrated traffic, worsening congestion in certain areas. If our model were deployed in conjunction with algorithms influencing taxi availability, the system might inadvertently create self-fulfilling feedback loops, disproportionately affecting certain areas or demographics that cannot afford taxi’s and therefore will not be seen in the data.</p><p>To address these issues, clear communication about the model’s limitations, potential biases, and intended use is crucial. Providing educational resources, user-friendly interfaces, adequate documentation, and implementing fairness-aware algorithms can contribute to responsible and ethical deployment. Regular assessments, periodic audits, and interventions are necessary to avoid reinforcing existing biases. We have also considered ethical responsibilities such as the responsible disclosure of findings, ensuring the public benefits from the research, and avoiding any unintentional harm. Active engagement with potential stakeholders and the community can further help address concerns and foster ethical practices.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LBPfhbcd_wT2bwuz.png" /><figcaption>Figure 1: Cluster pairs with highest travel time to distance</figcaption></figure><h3>References</h3><p>[RR22] — Roy, B., Rout, D. (2022). Predicting Taxi Travel Time Using Machine Learning Techniques Considering Weekend and Holidays. In: Abraham, A., et al. Proceedings of the 13th International Conference on Soft Computing and Pattern Recognition (SoCPaR 2021). SoCPaR 2021. Lecture Notes in Networks and Systems, vol 417. Springer, Cham. <a href="https://doi.org/10.1007/978-3-030-96302-6_24">https://doi.org/10.1007/978-3-030-96302-6_24</a></p><p>[HPMP20] — Huang, H., Pouls, M., Meyer, A., Pauly, M. (2020). Travel Time Prediction Using Tree-Based Ensembles. In: Lalla-Ruiz, E., Mes, M., Voß, S. (eds) Computational Logistics. ICCL 2020. Lecture Notes in Computer Science(), vol 12433. Springer, Cham. <a href="https://doi.org/10.1007/978-3-030-59747-4_27">https://doi.org/10.1007/978-3-030-59747-4_27</a></p><p>[BLM18] — Bai, M., Lin, Y., Ma, M., Wang, P. (2018). Travel-Time Prediction Methods: A Review. In: Qiu, M. (eds) Smart Computing and Communication. SmartCom 2018. Lecture Notes in Computer Science(), vol 11344. Springer, Cham. <a href="https://doi.org/10.1007/978-3-030-05755-8_7">https://doi.org/10.1007/978-3-030-05755-8_7</a></p><p>[RIS17] — Meg Risdal. (2017). New York City Taxi Trip Duration. Kaggle. <a href="https://kaggle.com/competitions/nyc-taxi-trip-duration">https://kaggle.com/competitions/nyc-taxi-trip-duration</a></p><p>[TLC23] — TLC Trip Record Data. (2023). NYC Taxi and Limousine Commission. <a href="https://www.nyc.gov/site/tlc/about/tlc-trip-record-data.page">https://www.nyc.gov/site/tlc/about/tlc-trip-record-data.page</a></p><p>[AAD22] — Aadam. (2022). NYC Weather — 2016 to 2022. <a href="https://www.kaggle.com/datasets/aadimator/nyc-weather-2016-to-2022">https://www.kaggle.com/datasets/aadimator/nyc-weather-2016-to-2022</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a66c0f884766" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Causal Inference with Graph Neural Networks]]></title>
            <link>https://medium.com/@dallinpstewart/causal-inference-with-graph-neural-networks-92a9b83c382c?source=rss-596349f77bb5------2</link>
            <guid isPermaLink="false">https://medium.com/p/92a9b83c382c</guid>
            <category><![CDATA[graph-neural-networks]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[causal-inference]]></category>
            <category><![CDATA[bayesian-networks]]></category>
            <dc:creator><![CDATA[Dallin Stewart]]></dc:creator>
            <pubDate>Tue, 21 May 2024 17:02:15 GMT</pubDate>
            <atom:updated>2024-05-21T17:02:15.048Z</atom:updated>
            <content:encoded><![CDATA[<p>By Dallin Stewart, Dylan Skinner, Gwen Johnson, Jason Vasquez</p><h3>Abstract</h3><p>Neural networks have revolutionized computer science by modeling complex data relationships, yet the need to elucidate their predictions and understand underlying causality grows increasingly crucial. This paper explores the integration of causal inference, traditionally rooted in statistics and philosophy, into neural networks, particularly focusing on Graph Neural Networks (GNNs) for causal modeling. Leveraging GNNs’ capabilities in learning graph-structured data representations, we conduct supervised classification tasks on the LUCAS0 dataset to assess GNNs’ ability to capture causal relationships and enhance interpretability and robustness. Results reveal varying accuracies across GNN architectures, with Transformer convolutional layers showing the highest performance. Comparisons against Bayesian networks, which exploit causal relationships, demonstrate superior accuracy with less training time. Moreover, employing do-calculus exposes GNNs’ limitations in discerning precise causal relationships, underscoring the importance of causal inference for improving neural networks’ predictive power. This study advocates for deeper integration of causal inference into neural network research to foster more interpretable and reliable AI systems, suggesting future exploration of diverse datasets and model architectures to validate and extend these findings.</p><h3>Introduction</h3><p>Neural networks are at the center of computer science research and have revolutionized our ability to model complex relationships with data.<br>As these networks continue to proliferate in decision-making processes, output explanation and gaining a deeper understanding of the causality behind their predictions become increasingly essential. The distinction between correlation and causation is not merely philosophical; it creates the foundation for building robust, interpretable, and ethically sound AI systems.</p><p>Causal inference is a field deeply rooted in statistics and philosophy that offers a framework to disentangle cause-and-effect relationships from observed data. Traditionally, researchers have applied causal inference in fields including epidemiology, economics, and social sciences. However, integrating these ideas into the domain of neural networks presents a promising frontier with implications ranging from improving model interpretability to enhancing the fairness and accountability of AI systems.</p><p>In this paper, we explore the intersection of causal inference and neural networks by focusing on the application of Graph Neural Networks (GNNs) to causal modeling. We leverage these unique capabilities of GNNs to learn representations of graph-structured data and perform a supervised classification task on the LUCAS0 dataset. Our goal is to determine if GNNs can capture causal relationships within a graph and provide insights into the interpretability and robustness of these models. We also use a Bayesian network as a baseline machine learning model that leverages causal relationships to compare against the neural network.</p><h3>Related Work</h3><p>Integrating causal inference with neural networks has garnered significant interest in recent years. Other studies have proposed several approaches to combine the strengths from these two fields and leverage the expressive power of neural networks to model causal relationships. Koch et al. discusses ongoing work to extend causal inference to settings where confounding is non-linear, time-varying, or encoded in text, networks, and images (Koch 2023). Furthermore, Yuan et al. compared the performance of CNN’s on causal data to previous methods.</p><h3>Graph Neural Networks</h3><p>The Graph Neural Networks that Mori et al. originally proposed in 2005 are a class of neural networks that operate on graph-structured data. They have gained significant attention in recent years due to their versatility in handling various types of graph data, including social networks, citation networks, biological networks, and more.</p><p>Unlike traditional neural networks, which operate on grid-like structures such as images or sequences, GNNs’ architectures allow them to capture and leverage the structural information present in graphs. One remarkable feature allows them to learn meaningful representations of nodes in a graph for various downstream tasks such as node classification, link prediction, and graph classification. Their ability to capture and model complex relationships in graph data makes them invaluable tools for exploring and understanding real world phenomena represented in graph form.</p><p>In this study, we apply GNNs to a supervised classification task by training it on a labeled, tabular dataset, where we associate each graph instance (or node) with a target label.</p><h3>The do Operator</h3><p>The do operator is a way to represent interventions in a causal model, i.e. the effect of an intervention on a variable. For example, consider the following model involving smoking. If a person’s fingernails (<em>N</em>) have turned yellow, this implies a higher probability that they are a heavy smoker (<em>S</em>) and hence have a higher probability of developing lung cancer (<em>C</em>). However, simply dyeing someone’s fingernails yellow does not impact their probability of developing lung cancer. So, in terms of do calculus, we can denote the process of setting a variable <em>N</em> to have a value yellow by do(<em>N</em> = yellow). We note that P (<em>C</em> | <em>N</em> = yellow) != P (<em>C</em> | do(<em>N</em> = yellow)). With this in mind, we now define the do operator.</p><p><strong>Theorem 4.1 </strong>In a causal diagram Γ with nodes X1, . . . , Xn and joint<br>distribution P (X1, . . . , Xn), the result of doing Xi = xi on the joint distribution is<br>P (X1, . . . , Xn | do(Xi = xi)) = P (x1, . . . , xn) / P (xi | par(xi)) = ∏(for all j!=i)<br>P (xj | par(xj )).</p><p>In this equation, par(xi) represents values of the parent nodes of PAR(Xi) of<br>Xi in Γ. We call the probabilities on the right hand side of the above equation preintervention. Preintervention means that we use the probabilities from the original model before “doing” Xi = xi. The equation above describes how we calculate the probability of several events happening given one event has happened. What if we want to find the<br>probability of a single event happening, given we do a single event? This scenario leads to the following corollary.<br><strong>Corollary 4.1.1</strong> If X and Y are random variables in a causal diagram Γ and<br>PAR(X) are the parents of X, then</p><p>P (y | do(x)) = ∑ (for all par) P (x, y, par) / P (x | par)</p><p>where the sum runs over all values par that the variables PAR(X) can take.<br>If X has no parents, then</p><p>P (y | do(x)) = P (x, y) / P (x) = P (y | x).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nHFYs_FGPZD-I_IVM5nZlw.png" /><figcaption>Figure 1: Basic causal diagram. Note it is in the form of a directed acyclic graph (DAG).</figcaption></figure><p>Let us now consider a basic example to see how this works. Consider the following causal diagram in Figure 1. In this diagram, nodes A and C are both parents of B. So, for any values of x and b, Corollary 4.1.1 tells us that</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A3xh2vrh1WUMmmC0Wq8-uw.png" /></figure><p>which, written out, is</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Eu2f9ZQro1B7JmN37eItVw.png" /></figure><p>Since each node only depends conditionally on their parents, we can rewrite the expression as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rc2tZLdIY2RGgMLz7NIurQ.png" /></figure><p>which simplifies to</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*98l_0XkZbAeXImbQ-g8kTw.png" /></figure><p>Since there is only one instance where we are considering the probability with respect to c, we can further reduce this to</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3GYYjuW5WH9SZqhbFZIy0g.png" /></figure><p>which is our final answer. While this introduction to the do operator might feel a bit abstract, it is the foundation of all current research in causal inference.</p><h3>Data</h3><p>For our project, we used the LUCAS0 dataset [7], which is a synthetic toy data set with causal Bayesian networks and binary variables. The LUCAS0 dataset is a DAG with 11 nodes and 2000 training samples (see Figure 2).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qRLAf5b_xiOQp3f7bqhEeA.png" /><figcaption>Figure 2: Basic causal diagram. Note it is in the form of a directed acyclic graph (DAG). Our target variable is shaded in pink, and the nodes in teal constitute the Markov blanket of the target variable.</figcaption></figure><p>We associate each node of the graph with a specific conditional probability that the creators of the dataset used to generate the data (see Table 5 in Appendix A).</p><h3>Experiments and Testing</h3><p>Graph Neural Networks and Bayesian Networks perform well when handling complex structured data that consists of underlying causal relationships and do calculus operations. By examining these models more closely, we can assess their predictive power in capturing these underlying do-calculus operations. In order to do so, we train these models to predict lung cancer based on the components of the graph provided in Figure 2 and evaluate their accuracy.</p><h3>Graph Convolutional Layers</h3><p>We begin by training several graph neural networks with five different types of convolutional layers and performing a grid search of learning rates (0.001, 0.005, 0.01, 0.05). Each model includes a unique convolutional layer variant as at least one of seven convolutional layers. Each layer is followed by a ReLU activation function and dropout regularization, except the final layer. We describe each of these convolutional layers below.</p><p>The first type of layer we experiment with is a standard graph convolution layer acting as a control for comparison against the other layers. The other four layer types we test are Chebyshev convolution model, SAGE convolution model, GAT convolution model and a Transformer convolution model.</p><p>Defferrard describes a method of using Chebyshev polynomials for rapid filtering in graph neural networks. While previous methods of filtering signals in graphs require expensive computations, Defferrard implements Chebyshev polynomials in order to approximate kernels. These functions are easy to work with and recursively compute an orthogonal basis efficiently. The resulting combination of these Chebyshev terms can effectively represent the new filter function.</p><p>Researchers created SAGE convolutional layers to generate embeddings using node features such as various attributes, profile information and graph structure. The algorithm achieves this embedding scheme with a forward propagation algorithm that uses <em>K</em> parameters of the model to search through the nodes. It then creates the node’s embedding by sampling and aggregating the graph information. This approach provides better generalization to unseen nodes and facilitates node feature learning in a network. This algorithm is popular because of its robustness to complex node features and information.</p><p>GATConv uses attention mechanisms in order to perform node classification. One author created this type of specialized attention layer for graph neural networks, and explained that “One of the benefits of attention mechanisms is that they allow for dealing with variable sized inputs, focusing on the most relevant parts of the input to make decisions”.</p><p>Researchers first adopted Graph Transformer convolution layers in an attempt to combine feature propagation and label propagation as discussed in <em>Masked Label Prediction</em> (2021). The Transformer Convolution layer relies on a general vanilla structure of a transformer while also accounting for edge features. This layer is similar to the GATConv layer since they both use multi-headed attention.</p><h3>Bayesian Network</h3><p>To further investigate the ability of neural networks to learn causal relationships, we compared the results of the neural network with a Bayesian network. A Bayesian network can include causal relationships implicitly in its initialization before it fits the data. If the Bayesian network performed better than the neural networks, then we can infer that the neural networks are not able to fully grasp causal relationships. We can also infer that learning causal relationships are essential for higher accuracy when such a dependency exists in the data.</p><p>Bayesian networks, also known as belief networks or directed acyclic graphical models, are probabilistic graphical models that represent a set of variables and their conditional dependencies via a directed acyclic graph (DAG). Each node in the graph represents a random variable, and the edges between nodes represent probabilistic dependencies, indicating direct influences or causal relationships between variables.</p><p>One of the key features of Bayesian networks is their ability to model uncertainty and reason under ambiguity using Bayesian inference. By leveraging Bayes’ theorem, Bayesian networks can update beliefs about variables based on observed evidence and allow for efficient probabilistic reasoning.</p><p>When comparing Bayesian networks with neural networks in learning causal relationships, Bayesian networks offer a structured framework for explicitly modeling causal dependencies between variables. We can encode prior knowledge or assumptions about causal relationships into the network structure to facilitate causal inference and reasoning. Furthermore, Bayesian networks can provide insights into causal mechanisms that may not be fully captured by neural networks alone. This source of insights is particularly salient in tasks where understanding causal relationships is crucial, such as predictive modeling in domains like healthcare or finance.</p><p>For a comprehensive understanding of Bayesian networks and their applications, a seminal reference is “Probabilistic Graphical Models: Principles and Techniques” by Daphne Koller and Nir Friedman. This book covers foundational concepts, algorithms, and applications of probabilistic graphical models, including Bayesian networks, making it an invaluable resource for researchers and practitioners in the field.</p><h3>Results</h3><h3>Convolutional Layers and Learning Rates</h3><p>While the initial accuracies provided in Table 1 appear relatively high, the performance of these models have several faults. The total percentage of lung cancer patients in this dataset is 0.7215, so models with this level of accuracy are likely predicting “True” each time rather than learning from the data. This behavior will cause the model to generalize poorly on other unseen data. With this in mind, both the standard and Chebyshev convolution yield insignificant results. The Transformer convolution provides the most accurate results at the expense of longer training time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*obkYzqai220Jqa8m3gxwOw.png" /><figcaption>Table 1: Models by Convolutional Layers and Learning Rates</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sz5LhUufHd_aEyXacUBtkQ.png" /><figcaption>Table 2: Models by Convolutional Layers and Average Training Times</figcaption></figure><h3>Bayesian Networks</h3><p>For the Bayesian network, we initialized the model with the causal relationships on the dataset defined above, split the data randomly into 80% training data and 20% test data, then fit the model on the training data, which took 0.09 seconds. The model was able to predict cancer with 86.25% accuracy on the test set, beating every GNN we tested except for the Transformer models.</p><h3>Evaluating Models with do Calculus</h3><p>Let’s consider the following conditional probabilities with <strong>do</strong> operators applied:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ARZK5mwY0jdpYeaVQCy8kQ.png" /></figure><p>where LC is lung cancer, YF is yellow fingers, PP is peer pressure, A is anxiety, AD is attention disorder, and CA is car accident. We note that we chose this probability because it does not involve any variables that are in the Markov blanket of our target variable. Thus, we should expect that there is very little predictive power in this probability.</p><p>Following the do calculus algorithm, we write P(LC = T | do(YF = T)) (using corollary 4.1.1) as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RQLMyzjfAMGvptBwX_mJQw.png" /></figure><p>where S is smoking. Since the Lung Cancer node has Smoking and Genetics as parents, and Smoking has parent Anxiety and Peer Pressure (see Figure 2), we can write Equation 2 to</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eIDyK8RTtF9jwiSffxCfug.png" /></figure><p>where each S, A, G, PP is in terms of {T, F}.</p><p>Since not every term is in terms of every variable, we can rewrite the Equation 3 as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_vpe9nqBl6A6FCMdcN02bA.png" /></figure><p>Using the probabilities from Table 5 on Equation 4 we get</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UMiKn3A-MS4Gb9X0BQXEFQ.png" /><figcaption>Table 3: The resulting probabilities of the do statements found in Equation 1.</figcaption></figure><p>Table 3 shows similar calculations on the other probabilities in Equation 1. These probabilities are what we expect based on the causal diagram. For example, the probability of cancer given do(YF = T) is hardly higher than the probability of lung cancer on its own. This helps us understand that while cancer patients are more likely to have yellow fingers, yellow fingers themselves do not cause cancer. However the probability of cancer given do(S = T) is much higher, implying that smoking does cause cancer.</p><p>We compare these probabilities to the probability output by our GNN in Table 4. To calculate these probabilities, we took a data point with False for every feature except for one feature artificially set to True, and then passed this data point through our model. The discrepancy in the probabilities seems to imply that our neural network was unable to pickup on causality, as it assumed that everyone with yellow fingers has cancer (even absent smoking).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y0Fpz9uY-atHAYA2fjbeJA.png" /><figcaption>Table 4: The resulting probabilities of the do statements running the data points through the Transformer model with a learning rate of .01 as seen in 1.</figcaption></figure><h3>Conclusion</h3><p>This project seeks to examine how neural networks can be used to perform do-calculus and causal inference. Graph neural networks have gained significant popularity in their ability to handle complex relationships and capture meaningful node representations. These networks achieve successful results in both computational efficiency and accuracy, with a Transformer convolutional layer model leading in performance. Bayesian networks also prove that a model that understands the causal relationships between the data can outperform most neural networks in much less time. Furthermore, using do-calculus we conclude that neural networks are unable to pickup on the exact nature of causal relationships. These results indicate that the field of causal inference is very important in neural networks and the better that neural networks can understand causal relationships, the higher the predictive power.</p><p>We recognize that there is significant room for improvement especially with a topic as complicated as causal inference in deep learning. For future work, we hope to experiment with a wider variety of datasets to explore how other graphical relationships perform with our models. Given that our testing is confined to this dataset and lacks sufficient validation across other graphs and model performances, we suggest that future work couple these results with other reliable studies in making important claims such as lung cancer detection.</p><h3>References</h3><p>[1] Micha¨el Defferrard, Xavier Bresson, and Pierre Vandergheynst. Convolutional neural networks on graphs with fast localized spectral filtering. 2017.</p><p>[2] Marco Gori, Gabriele Monfardini, and Franco Scarselli. A new model for learning in graph domains. In Proceedings of the International Joint Conference on Neural Networks, volume 2, pages 729–734 vol. 2, 01 2005.</p><p>[3] William L. Hamilton, Rex Ying, and Jure Leskovec. Inductive representation learning on large graphs. 2018.</p><p>[4] Bernard Koch, Tim Sainburg, Pablo Geraldo, Song Jiang, Yizhou Sun, and Jacob Gates Foster. Deep learning of potential outcomes. CoRR, abs/2110.04442, 2021.</p><p>[5] Daphne Koller and Nir Friedman. Probabilistic Graphical Models: Principles and Techniques. MIT Press, 2009.</p><p>[6] Judea Pearl. Causal inference in statistics: An overview. Statistics Surveys, 3:96–146, 2009.</p><p>[7] Research Group for Lung Cancer Analysis. Lucas (lung cancer simple set) dataset. ETH Zurich Causality and Machine Learning Group, 2020. The LUCAS dataset contains CT scan images and annotations for lung cancer detection.</p><p>[8] Yunsheng Shi, Zhengjie Huang, Shikun Feng, Hui Zhong, Wenjing Wang, and Yu Sun. Masked label prediction: Unified message passing model for semi-supervised classification. 2021.</p><p>[9] Petar Velickovi´c, Guillem Cucurull, Arantxa Casanova, Adriana Romero, Pietro Lio, and Yoshua Bengio. Graph attention networks. 2018.</p><p>[10] Ye Yuan, Xueying Ding, and Ziv Bar-Joseph. Causal inference using deep neural networks. CoRR, abs/2011.12508, 2020.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=92a9b83c382c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Lunar Ascent: From Earth to Moon’s Orbit]]></title>
            <link>https://medium.com/@dallinpstewart/lunar-ascent-from-earth-to-moons-orbit-83cdf65b2350?source=rss-596349f77bb5------2</link>
            <guid isPermaLink="false">https://medium.com/p/83cdf65b2350</guid>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[hamilton]]></category>
            <category><![CDATA[optimal-control]]></category>
            <category><![CDATA[rockets]]></category>
            <category><![CDATA[control-theory]]></category>
            <dc:creator><![CDATA[Dallin Stewart]]></dc:creator>
            <pubDate>Tue, 14 May 2024 17:27:29 GMT</pubDate>
            <atom:updated>2024-09-21T00:27:18.772Z</atom:updated>
            <content:encoded><![CDATA[<h3>Optimal Trajectory From Earth to Moon’s Orbit</h3><p>Dallin Stewart, Jason Vasquez, Dylan Skinner</p><h3>Abstract</h3><p>We present a simulation of a rocket’s path from Earth’s surface to the orbit of the Moon. We model the complex dynamics involved in rocket propulsion, gravitational interactions, and orbital mechanics by leveraging differential equations and numerical methods. Our simulation captures the stages of ascent, including liftoff, trajectory optimization, and orbital insertion. Through detailed analysis and visualization, we explore the critical factors influencing orbital maneuvers required for this trajectory. The results offer insights into the challenges and considerations of space exploration, paving the way for future missions to celestial bodies beyond Earth’s orbit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YAdSHnwsNTY8035LIKiujA.png" /></figure><h3>Background</h3><p>Space travel presents a highly relevant and classic optimal control problem, influenced by numerous factors such as drag, fuel consumption, gravitational forces from multiple celestial bodies, and varying mass considerations. Navigating a rocket from Earth’s surface to the Moon’s orbit requires modeling complex dynamics that encompass rocket propulsion, gravitational interactions, and orbital mechanics. We rely on a set of differential equations and numerical methods to simulate and analyze these dynamics in order to accurately optimize trajectory and orbital insertion.</p><p>Understanding and optimizing orbital maneuvers for interplanetary travel has been a longstanding challenge in aerospace engineering and space exploration. Previous research has explored various aspects of trajectory optimization, spacecraft propulsion, and orbital transfers to achieve efficient and successful missions beyond Earth’s immediate vicinity. One such investigation is “<a href="https://www.sciencedirect.com/science/article/pii/S0094576509003956">Minimum-time Earth–Moon and Moon–Earth orbital maneuvers using time-domain finite element method</a>” by S.A. Fazelzadeh and G.A. Varzandian that employed a method similar to ours. Another instance of prior research that our project built upon was a Volume 4 example project from 2020 ‘Rocket Launch Trajectory’ by Ahn et. al. This project attempted to reach Earth’s orbit, and we wanted to build on this by leaving Earth’s orbit and reaching the moon’s. Notably, the formulation and solution of optimal control problems have been instrumental in advancing our understanding of spaceflight dynamics and guiding mission planning efforts in order to achieve recent feats such as landing on the moon and Mars.</p><p>This study builds upon existing research by focusing on the specific trajectory from Earth’s surface to the moon’s orbit. By conducting detailed analysis and visualizing critical factors affecting orbital maneuvers, our simulation provides valuable insights into the challenges and considerations of space exploration beyond Earth’s orbit. The results obtained pave the way for enhanced mission planning and spacecraft design, contributing to the realization of future missions to celestial bodies throughout the solar system and beyond.</p><h3>Mathematical Representation</h3><p>To solve this problem, we defined a cost functional, a state-space evolution equation, and initial and endpoint conditions. We then utilized Pontraygin’s maximum principle (PMP) to formulate the co-state evolution equations and solve for the optimal control in terms of the co-state. This theorem allows us to set up a boundary-value problem and solve for the state, costate and optimal control. We define the code and steps for this process below. We also made several simplifying assumptions in this project as follows.</p><p>Assumptions</p><ol><li>Rocket, earth, and moon have point mass for the sake of calculating gravity</li><li>Rocket, earth, and moon are the only objects for the sake of calculating gravity (no influence of the sun, stars, etc)</li><li>Rocket, earth, and moon lie on a 2D plane</li><li>Moon’s orbit is perfectly circular</li><li>Rocket’s mass does not change</li><li>Rocket is single stage</li><li>The earth’s position remains at the origin of the 2D plane</li><li>The moon’s position at time zero is on the 𝑥-axis</li></ol><p>Unless otherwise specified, we define the units for this project as follows:</p><ul><li>Mass: kilograms (kg)</li><li>Distance: meters (m)</li><li>Force: newtons (N)</li><li>Angle: degrees (°)</li><li>Speed: meters per second (m/s)</li><li>Time: seconds (s)</li></ul><h3>Cost Functional</h3><p>We seek to find the optimal thrust for a rocket to leave Earth and begin orbiting the moon. To do so, we set up our cost functional as</p><p>𝐽[𝑢]=∫(𝑐/2)*|𝑢(𝑡)|**2𝑑𝑡 from 0 to final time tf</p><p>where we can interpret</p><p>𝑢=[𝑢𝑥, 𝑢𝑦]</p><p>as the thrust in the 𝑥- and 𝑦-directions, respectively. We also define our initial conditions as</p><p>𝑥(0)=𝑅𝑒,</p><p>𝑥(𝑡𝑓)=𝐿𝑚cos⁡(𝜃)+(𝑅𝑚+ℎ𝑓)cos⁡(90+𝜃)</p><p>𝑦(0)=0,</p><p>𝑦(𝑡𝑓)=𝐿𝑚sin⁡(𝜃)+(𝑅𝑚+ℎ𝑓)sin⁡(90+𝜃)</p><p>𝑥′(0)=0,</p><p>𝑥′(𝑡𝑓)=𝑣𝑓cos⁡(𝜃)</p><p>𝑦′(0)=𝜔𝑒,</p><p>𝑦′(𝑡𝑓)=𝑣𝑓sin⁡(𝜃)</p><p>where</p><ul><li>𝑐 is the scaling constant for the cost of thrust</li><li>𝑅𝑒 is the radius of the Earth,</li><li>𝐿𝑚 is the distance from the Earth to the moon,</li><li>𝑅𝑚 is the radius of the moon,</li><li>ℎ𝑓 is the desired height above the moon to enter orbit,</li><li>𝑣𝑓 is the final velocity of the rocket to enter orbit,</li><li>𝜔𝑒 is the angular velocity of the Earth at the equator,</li><li>𝜃 is the angle between the 𝑥-axis and the line between the Earth and the moon, assuming the Earth is at the origin.</li></ul><h3>State Space</h3><p>We define our state space equation as</p><p>x=[𝑥, 𝑦, 𝑥′, 𝑦′],</p><p>and our state space evolution equation as</p><p>x′=[𝑥′, 𝑦′, 𝑥″, 𝑦″]</p><p>where 𝑥″ and 𝑦″ are the acceleration in the 𝑥 and 𝑦 directions, respectively. Using Newton’s second law, this gives:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OvZzvN1pmXxgqw4XgAUtdQ.png" /></figure><p>where</p><ul><li>𝐺 is the universal gravitational constant</li><li>𝑀𝑒 is the mass of the Earth</li><li>𝑀𝑚 is the mass of the moon</li><li>𝑚𝑟 is the mass of the rocket</li><li>𝑢𝑥 is the rocket’s thrust in the 𝑥 direction</li><li>𝑢𝑦 is the rocket’s thrust in the 𝑦 direction</li><li>𝐿𝑥 is the 𝑥 position of the moon</li><li>𝐿𝑦 is the 𝑦 position of the moon</li><li>𝑐 is the drag constant 14</li><li>𝐴 is the surface area of the top of the rocket</li><li>𝜌(𝑥,𝑦) is the air density at position (𝑥,𝑦)</li></ul><h3>Hamiltonian</h3><p>We now derive the Hamiltonian equation. We have</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/906/1*8giMuaaPahk3I_5SueY9Zg.png" /></figure><p>Plugging in 𝑥″ and 𝑦″ into the Hamiltonian equation, we get</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UTd0ttmJUwle4fxs3emMOw.png" /></figure><p>Co-State Evolution</p><p>We now derive the necessary equations for the PMP. We first derive the necessary equations for the adjoint equations (co-state evolution). We have</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xMwi_7emdrwO6jgyA_CdvQ.png" /></figure><p>Optimal Control</p><p>Using 𝜕𝐻𝜕𝑢=0, we get our optimal control 𝑢~ defined as</p><p>𝑢~ = (1/c)[𝑝3, 𝑝4].</p><h3>Initial Solutions</h3><p>Our initial attempt at this problem included a stationary moon. This assumption reduced the complexity of our evolution equations and still lead to acceptable results. We included the static location of the moon in the numerical solver by providing the angle (𝜃) between the 𝑥-axis and the line between the Earth and the moon. When the moon was at the origin, (𝜃=0), we achieved the following result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lugwDT_Xg_R0Nono.png" /></figure><p>We see that when the moon is stationary and on the 𝑥-axis, the rocket takes a straight path to the moon, ending slightly above it in order to enter its orbit. In this visualization, the size of the Earth and moon are not to scale. We increased the size of the Earth and the moon to illustrate the rocket’s path.</p><p>We also tested our system when the moon was not on the 𝑥-axis. When the angle between the 𝑥-axis and the line between the Earth and the moon is set to 𝜃=41.212 degrees, we achieved the following result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*imo4nnnOYvL65JQN.png" /></figure><p>Similar to when the moon was on the 𝑥-axis, we see that the rocket takes a straight path to the moon, ending far enough from the moon to enter orbit safely. In this image, the size of the Earth and moon <em>are</em> to scale.</p><p>Once we were able to achieve satisfactory results with a stationary moon, we removed this simplifying assumption and allowed the moon to move.</p><h3>Future Work</h3><p>Throughout this project we made several simplifying assumptions. From these assumptions, we achieved satisfactory results and learned more about the complicated dynamics of space travel as we can see in the images above. Despite these results, we feel that the project is not yet at its full potential and could be improved in several ways.</p><p>One of the first improvements is implementing variable fuel consumption, thus adding variable weight to the rocket. This improvement would change the rocket’s optimal solution and make the problem more realistic.</p><p>A second improvement is making the rocket’s limitations more realistic. In typical rocket launches, the rocket has at least two phases: a phase inside the Earth’s atmosphere and a phase outside the Earth’s atmosphere. This design involves a drastic change in the rocket’s weight and maximum thrust, which would be a significant change to our model that would allow for a more accurate reflection of the dynamics of a real rocket launch.</p><p>The final improvement we would make is optimizing our system over final time. Including final time in the cost function would allow us to achieve a solution that is not only optimal over thrust, but also over time. Finding the optimal time to reach the moon would make the results of the system much more interesting and would potentially lead to new insights into the dynamics of space travel.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=83cdf65b2350" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Passive Vehicle Sensor Analysis]]></title>
            <link>https://medium.com/@dallinpstewart/passive-vehicle-sensor-analysis-bef910dd67a2?source=rss-596349f77bb5------2</link>
            <guid isPermaLink="false">https://medium.com/p/bef910dd67a2</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[hmm]]></category>
            <category><![CDATA[kalman-filter]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[clustering]]></category>
            <dc:creator><![CDATA[Dallin Stewart]]></dc:creator>
            <pubDate>Tue, 07 May 2024 17:02:15 GMT</pubDate>
            <atom:updated>2024-09-21T00:32:51.401Z</atom:updated>
            <content:encoded><![CDATA[<h3>Automatic Passive Road Quality Detector</h3><p>By Dallin Stewart, Gwen Martin, and Eliza Powell</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0Oo9WTQLcetTufr1" /><figcaption>Photo by <a href="https://unsplash.com/@gibblesmash139?utm_source=medium&amp;utm_medium=referral">gibblesmash asdf</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Abstract</h3><p>We investigate the application of passive vehicle sensor data for estimating real-time road surface conditions and the vehicle’s state vector. While noise from physical imperfections, the motion of the engine, and sensor reading errors is inevitable, these factors significantly affect the accuracy of the data collected. Implementing a Kalman filter enables more accurate vehicle position, velocity, and acceleration estimation. While spectral clustering is unable to reliably determine road conditions, hidden Markov models prove effective in accurately predicting road quality through passive sensor data.</p><h3>Problem Statement and Motivation</h3><p>Autonomous vehicle systems rely on a variety of data inputs to ensure safe navigation. Sensors including GPS trackers, accelerometers, and gyroscopes, among many others, provide crucial information about the surrounding environment to assess and navigate current road conditions. This information helps autonomous systems make informed decisions in real-time, enhancing safety and efficiency on the road. Therefore, integrating sensor data is vital for advancing autonomous and safe transportation systems.</p><p>Autonomous systems become increasingly powerful as their data increases in accuracy and reliability. Filtering and improving vehicle sensor data is an active area of research with a variety of effective published techniques. One such example is a deep neural network architecture known as CarSpeedNet that predicts car speed using accelerometer data from smartphones. Tesla’s Autopilot leads the cutting edge in applying artificial intelligence to create safe driving environments and provide the autopilot feature with accurate information about the vehicle’s physical behavior. A group of researchers experiments with various CNN and LSTM architectures on our same dataset to distinguish between road types. Others apply Kalman filtering to odometry and sonar signals to ensure accurate positioning and navigation for autonomous robots and vehicles. See the References section for more details.</p><p>We seek to answer the following questions: how can we improve the accuracy of vehicle sensors and how can we determine road conditions as a vehicle drives. Our paper contributes to the advancement of vehicle behavior measurement and road condition prediction which are crucial components for enhancing driving safety and autonomous vehicle capabilities.</p><h3>Data</h3><p>The Passive Vehicular Sensors Dataset (PVS) was compiled by researchers at the Universidade Federal de Santa Catarina. This dataset is available on Kaggle and contains data from three sets of accelerometers, gyroscopes, magnetometers, thermometers, and GPS trackers. The data comes from three different drivers each driving vehicles on three different routes mapped in the figure below, for a total of nine unique scenarios.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nMp3fdS6pjI9139W.png" /><figcaption><em>Latitude and longitude data from one driver on the three different courses.</em></figcaption></figure><p>The dataset includes a variety of general information such as latitude, longitude, altitude, and speed. It also includes inertial, gyroscopic, and temperature data from five sensors around the suspension and dashboard. The dataset also provides nominal data that describes the road type (paved, unpaved, dirt, cobblestone, asphalt), road quality (good, regular, bad), and whether speed bumps are present.</p><p>We exclude columns containing irrelevant metadata and missing data from the analysis to focus on informative features for vehicle state and road condition estimation. Our final dataset contains just over one million rows with samples taken every millisecond for a total of three hours of driving data. We allocate six datasets from the first two driving locations for training, two datasets from the remaining location for testing, and the last dataset for validation.</p><p>While the dataset is well constructed and compiled by a reliable source, the methods we explore seek to reduce the inaccuracies inherent in this type of noisy vehicle sensor data.</p><h3>Methods</h3><h3>Feature Engineering</h3><p>Since the dataset comes cleaned and well prepared in advance, we only create two additional types of features. The first is a smoothed version of the original accelerometer data. We smooth the noisy data by computing the moving average of the acceleration using a 200 millisecond window size. Smoothing helps reduce noise and fluctuations in the sensor readings to create cleaner and more interpretable data for analysis.</p><p>Another critical feature we engineer is the distance from the starting location in meters. We construct this column by converting latitude and longitude coordinates to meters using Vincenty’s formula for the geodesic distance between two points. This approximation accounts for the curvature of the Earth’s surface and converts the units for position from coordinates to meters and standardizes the units for location with the rest of the features.</p><h3>Kalman Filter</h3><p>Another critical feature we engineer is the distance from the starting location in meters. We construct this column by converting latitude and longitude coordinates to meters using Vincenty’s formula for the geodesic distance between two points. This approximation accounts for the curvature of the Earth’s surface and converts the units for position from coordinates to meters and standardizes the units for location with the rest of the features.</p><h4>State Equations</h4><p>𝑥𝑘+1=𝐹𝑘*𝑥𝑘+𝑤𝑘</p><p>𝑧𝑘=𝐻𝑘*𝑥𝑘+𝑣𝑘</p><h4>Hidden and Observed States</h4><p>𝑥𝑇=[𝑥(𝑡), 𝑦(𝑡), 𝑧(𝑡), 𝑥˙(𝑡), 𝑦˙(𝑡), 𝑧˙(𝑡), 𝑥¨(𝑡), 𝑦¨(𝑡), 𝑧¨(𝑡)]</p><p>𝑧𝑇=[𝑥(𝑡), 𝑦(𝑡), 𝑧(𝑡), 𝑥¨(𝑡), 𝑦¨(𝑡), 𝑧¨(𝑡)]</p><h4>Transition Matrices</h4><pre>F = [[1, 0, 0, 0, 0, 0, 0, 0, 0],<br>     [0, 1, 0, 0, 0, 0, 0, 0, 0],<br>     [0, 0, 1, 0, 0, 0, 0, 0, 0],<br>     [0, 0, 0, 1, 0, 0, 0, 0, 0],<br>     [0, 0, 0, 0, 1, 0, 0, 0, 0],<br>     [0, 0, 0, 0, 0, 1, 0, 0, 0],<br>     [0, 0, 0, 0, 0, 0, 1, 0, 0],<br>     [0, 0, 0, 0, 0, 0, 0, 1, 0],<br>     [0, 0, 0, 0, 0, 0, 0, 0, 1]]<br><br>+0.1*[[0, 0, 0, 1, 0, 0, 0, 0, 0],<br>      [0, 0, 0,0, 1, 0, 0, 0, 0],<br>      [0, 0, 0,0, 0, 1, 0, 0, 0],<br>      [0, 0, 0,0, 0, 0, 1, 0, 0],<br>      [0, 0, 0,0, 0, 0, 0, 1, 0],<br>      [0, 0, 0,0, 0, 0, 0, 0, 1],<br>      [0, 0, 0,0, 0, 0, 0, 0, 0],<br>      [0, 0, 0,0, 0, 0, 0, 0, 0],<br>      [0, 0, 0,0, 0, 0, 0, 0, 0]]<br><br>𝐻= [[1, 0, 0, 0, 0, 0, 0, 0, 0],<br>    [0, 1, 0, 0, 0, 0, 0, 0, 0],<br>    [0, 0, 1, 0, 0, 0, 0, 0, 0].<br>    [0, 0, 0, 0, 0, 0, 1, 0, 0],<br>    [0, 0, 0, 0, 0, 0, 0, 1, 0],<br>    [0, 0, 0, 0, 0, 0, 0, 0, 1]]</pre><p>We construct the 𝐹 matrix by observing that acceleration is the derivative of velocity with respect to time, and velocity is the derivative of position. In order to estimate the derivatives for position, we add the current position and the product of time step and velocity, where the time step is 0.1. We perform a similar operation for velocity and acceleration.</p><p>We do not include a control variable 𝑢 since we do not have data for the throttle position or brake position. Finally, we let the vectors 𝑤 and 𝑣 represent noise in the hidden state and observation state, respectively.</p><p>Before applying the Kalman filter, we downsample the original location data by 90 to allow the filter to more easily identify the true state as shown in the figure below. Downsampling leaves enough information to sufficiently convey the data the GPS records without forcing the Kalman filter to overfit with erratic jumps in estimated position.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ugaEL9TNfoTk0yqs.png" /><figcaption><em>Comparing the x position results from the Kalman Filter trained on the original data and the downsized data.</em></figcaption></figure><h3>Clustering</h3><p>K-means is a clustering algorithm that works by assigning data points to the nearest cluster center (centroid), then iteratively updating to minimize the total distance between each point and its assigned center. On the other hand, spectral clustering analyzes the connections and similarities between data points. The model transforms this map of connections into a new space that distinguishes the clusters even more. This approach is robust to noise and can handle high dimensional data well.</p><p>We compare the performance of these two unsupervised clustering techniques in predicting the type of road. We train this model on gyroscope and accelerometer information in the x, y, and z directions. We also create additional features for each sample by computing the mean, variance, minimum, and maximum of the twenty data points closest in time to each sample to capture the broader context of each data point. We balance the training data by randomly sampling equal numbers of points per label (paved and unpaved).</p><h3>Hidden Markov Models</h3><p>Hidden Markov Models (HMMs) model systems with hidden states that generate observable outputs (emissions). Each state emits specific outputs and transitions probabilistically. HMMs can estimate the most likely hidden state explaining an observation sequence, making them valuable for tasks like speech recognition. We apply this model to predict the quality of road (hidden) based on the vertical acceleration data (observations). In this model, the hidden states are latent variables that do not directly represent information we are interested in but still encode relevant information useful for making predictions.</p><p>To train and test the model, we concatenate the data, then separate “bad” from “good/regular” indices to create a different dataframe for each class. We then train one GMMHMM on the “good/regular” data and another on the “bad’’ data. The model makes a prediction for each time window by setting the two HMMs in competition against each other. The model predicts “good/regular” if the scaled log probability from the corresponding HMM is higher, and ``bad” otherwise. This rescaling factor essentially shifts the decision boundary between the good and bad classifications. We can find the optimal rescaling factor using a grid search over scales between 0.5 and 2.0. This optimization achieves the most favorable balance between true positives and false positives, similar to optimizing with a ROC curve. We also perform a grid search over the number of components and test hyperparameters between two and eight (inclusive). See the table at the end of the next section for more details.</p><h3>Results and Analysis</h3><h3>Determining True Position and Acceleration</h3><p>The Kalman filter’s core functionality lies in refining noisy sensor observations to estimate the true state of a system, including both position and acceleration. In the figure below, we see that the model filters the noise in acceleration data so that the result is less volatile while also accurately predicting position. The second figure shows the same data on a smaller time interval to better visualize how the model performs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Gx_Dz-99sO8-mnPo.png" /><figcaption><em>Kalman filter results compared to the original observed data.</em></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Ju4fTNENJShIlnCA.png" /><figcaption><em>Kalman filter results zoomed in to highlight model trends.</em></figcaption></figure><h3>Predicting Road Quality</h3><p>Our clustering models are unable to discern the differences between asphalt, dirt, and cobblestone road types reliably. When clustering into three groups, the K-means model only achieves 30 accuracy, while the spectral model achieves 45 accuracy. This poor accuracy indicates that the clustering models are unable to identify the correlation between the type of road and the data.</p><p>Since the three-class models are unsuccessful, we attempt to train two-class models to discover if they more accurately predict paved and unpaved roads. The K-means model achieves 50 accuracy, while the spectral model achieves 80 accuracy. However, the full confusion matrix indicates that the spectral model’s high performance is primarily due to the disproportionate ratio of paved road over unpaved road labels in the data (see the following figure). We address this issue by sampling an equal number of paved and unpaved data points. However, this approach also produces poor results, suggesting that clustering algorithms may not be well-suited to capture the subtle differences between road types based solely on gyroscope and vertical accelerometer data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Asaq46KHixzdXGXe.png" /><figcaption><em>Confusion matrices for a K-means model and a spectral clustering model. Neither model accurately discerned between “paved” and “unpaved” road types.</em></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ADFWxIDXfsaBcLio.png" /><figcaption><em>HMM prediction results. The sections in blue are time steps where the model predicted the road quality correctly, while orange indicates incorrect predictions. The vertical dotted black lines mark the splits between the three different drive data sources.</em></figcaption></figure><p>The previous figure visualizes the road quality predictions from the second approach for predicting road type. This method relies on an HMM to learn from the raw acceleration data in the vertical direction recorded with the accelerometer on the dashboard. After performing a grid search over all possible combinations of n_components and rescaling factors, the model performed best with five components and rescaling the prediction confidence by 0.98. This model classifies “good/regular” roads with 85.7 accuracy and “bad” roads with 100 accuracy. Since 80 of the labels are “good” and 20 are labeled “bad”, the model’s overall accuracy is 88.6. For testing purposes, the model only makes predictions on thirty second intervals because the road quality does not change very frequently. Consequently, some of the prediction error might arise from intervals that contain both “good/regular” roads and “bad” roads.</p><p>Components:</p><ul><li>2: Good Road: 0.904, Bad Road: 0.167</li><li>3: Good Road: 0.476, Bad Road: 1.000</li><li>4: Good Road: 0.333, Bad Road: 1.000</li><li>5: Good Road: 0.619, Bad Road: 1.000</li><li>6: Good Road: 0.286, Bad Road: 1.000</li><li>7: Good Road: 0.571, Bad Road: 0.833</li><li>8: Good Road: 0.238, Bad Road: 1.000</li></ul><p><em>Accuracy Results of a grid search over the number of parameters in each HMM before optimizing the rescaling factor.</em></p><p>These results demonstrate the HMM’s effectiveness in capturing the underlying dynamics of road quality based on acceleration data. This suggests a strong correlation between vertical acceleration and the hidden emission states associated with good and bad road conditions. This predictive power paves the way for deploying such models for real-time road assessment tasks.</p><h3>Ethical Considerations</h3><p>While there are several ethical issues that arise from this project, we consider several factors that may affect the results and consequences of our findings. The technology to passively and autonomously collect road quality data may impact certain communities if this data is interpreted or applied inappropriately. Poor quality roads may be associated with lower economic areas, so it is important that these routes remain anonymous. In this study, all participant information remains confidential.</p><p>However, if the algorithms are used to allocate road maintenance resources, a model biased towards well-maintained roads might continuously prioritize repairs in wealthier areas. This could create a negative feedback loop where poorer areas with lower quality roads receive even fewer resources, worsening their condition over time. Decision makers must combine algorithmic data analysis with human expertise to ensure informed choices when allocating resources.</p><p>We also acknowledge the inherent challenge in assessing the reliability of this data and validating the accuracy of the measurements. While our models reduce some of this variability, we recognize that error may still permeate our results. As a consequence, these findings should be weighed carefully with other factors while making impactful decisions.</p><h3>Conclusion</h3><p>In this investigation, we seek to accurately clean noise from position and acceleration using a Kalman filter. We also leverage hidden Markov models and clustering techniques to passively predict road quality.</p><p>Kalman filtering proves highly effective in eliminating noise from acceleration data and providing accurate predictions of the vehicle’s position. Further research could investigate adaptive Kalman filters that adjust their internal parameters in real-time based on changing environmental conditions. A future investigation could also include extra parameters in the state space to incorporate additional complexity and handle features such as “jerk” or “bumps”. These changes may lead to improved noise reduction and prediction accuracy across diverse driving scenarios.</p><p>Our exploration of road quality prediction reveals that hidden Markov models significantly outperform clustering techniques. Neither spectral clustering nor K-means clustering accurately identify road quality trends using only accelerometer and gyroscope data. In contrast, after optimizing hyperparameters, our HMM achieves high accuracy in predicting both “good” and “bad” road quality.</p><p>Regardless of the model’s success, future work might also explore various data preprocessing techniques. Including more customized smoothed data could potentially enhance the performance of the HMM and other models. While clustering methods prove inadequate, future research should explore more promising models for this type of problem such as neural networks in order to achieve further improvements.</p><h3>References</h3><h4><a href="https://arxiv.org/html/2401.07468v1">CarSpeedNet: A Deep Neural Network-based Car Speed Estimation from Smartphone Accelerometer (Or, 2024)</a></h4><ul><li>Author: Barack Or</li><li>Year: 2024</li><li>URL: <a href="https://arxiv.org/html/2401.07468v1">arXiv</a></li></ul><h4><a href="https://www.tesla.com/en_IE/autopilot">Autopilot (Tesla, 2024)</a></h4><ul><li>Year: 2024</li><li>URL: <a href="https://www.tesla.com/en_IE/autopilot">Tesla</a></li></ul><h4><a href="https://link.springer.com/article/10.1007/s00607-021-00914-0">Road surface type classification based on inertial sensors and machine learning (Menegazzo &amp; von Wangenheim, 2021)</a></h4><ul><li>Authors: Jeferson Menegazzo, Aldo von Wangenheim</li><li>Year: 2021</li><li>URL: <a href="https://link.springer.com/article/10.1007/s00607-021-00914-0">Springer</a></li></ul><h4><a href="https://doi.org/10.1109/IFIC.2000.859866">Sensor data fusion using Kalman filter (Sasiadek &amp; Hartana, 2000)</a></h4><ul><li>Authors: J.Z. Sasiadek, P. Hartana</li><li>Year: 2000</li><li>DOI: <a href="https://doi.org/10.1109/IFIC.2000.859866">10.1109/IFIC.2000.859866</a></li></ul><h4><a href="https://doi.org/10.1109/SBESC51047.2020.9277846">Multi-Contextual and Multi-Aspect Analysis for Road Surface Type Classification Through Inertial Sensors and Deep Learning (Menegazzo &amp; von Wangenheim, 2020)</a></h4><ul><li>Authors: J. Menegazzo, A. von Wangenheim</li><li>Year: 2020</li><li>DOI: <a href="https://doi.org/10.1109/SBESC51047.2020.9277846">10.1109/SBESC51047.2020.9277846</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bef910dd67a2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Keeping Up with the Jones’: Electric Vehicle Adoption in the U.S.]]></title>
            <link>https://medium.com/@dallinpstewart/keeping-up-with-the-jones-electric-vehicle-adoption-in-the-u-s-09a645b7830b?source=rss-596349f77bb5------2</link>
            <guid isPermaLink="false">https://medium.com/p/09a645b7830b</guid>
            <category><![CDATA[predictive-analytics]]></category>
            <category><![CDATA[modeling]]></category>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[electric-vehicles]]></category>
            <dc:creator><![CDATA[Dallin Stewart]]></dc:creator>
            <pubDate>Tue, 30 Apr 2024 23:04:23 GMT</pubDate>
            <atom:updated>2024-09-21T00:27:56.238Z</atom:updated>
            <content:encoded><![CDATA[<h3>Predicting Electric Vehicle Adoption in the U.S.</h3><p>By Dallin Stewart, Jeff Hansen, Eliza Powell, Gwen Martin</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zkRBw--aUZMGafGT" /><figcaption>Photo by <a href="https://unsplash.com/@charliedeets?utm_source=medium&amp;utm_medium=referral">Charlie Deets</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Abstract</h3><p>In this study, we endeavor to model the production and adoption of combustion, hybrid, and electric vehicles in the United States from 2010 into the near future. We explore the dynamics influenced by societal behaviors, cultural dynamics, and social interactions due to government regulations, economic disasters, and the growth of charging infrastructure. Our analyses reveal a shifting trend towards electric vehicles, emphasizing the need for proactive infrastructure development. This study lays the groundwork for assessing the myriad of influences on the adoption of alternative vehicles, and contributes to a more informed and realistic understanding of future automotive landscapes.</p><h3>Background and Motivation</h3><p>We seek to model the production of combustion, hybrid, and electric vehicles (EVs) in the United States from 2010 into the near future. Electric vehicles are crucial in mitigating climate change by reducing greenhouse gas emissions and dependence on fossil fuels. Modeling their adoption over time aids in understanding societal transitions to cleaner and sustainable transportation, guiding policy decisions and infrastructure development toward a more sustainable future.</p><p>Automotive companies first began producing hybrid vehicles in 1999, but the first fully electric vehicles were not commercially available until 2010. Since then, demand for these types of vehicles has increased significantly. We model the adoption of hybrid and electric vehicles over time since 2010 with a modified SIR model. While there are many factors that influence which types of vehicles companies produce and sell in the United States, we rely primarily on the effect that the relative population of each type of car has on the other populations. While cars do not directly influence each other in this way, this dynamic emerges from of people’s decisions, which do affect each other. For example, local cultural values transmit as people exchange ideas and share their priorities. In addition, people with more friends and associates who own hybrid or electric vehicles are more likely to make a similar purchase. By incorporating the effect of social influence and cultural dynamics within our modified SIR model, we strive to better understand the intricate interactions shaping the adoption of hybrid and electric vehicles. This assumption acknowledges the significance of societal behaviors in steering the future landscape of sustainable transportation.</p><p>This model is helpful for navigating the dynamics of vehicle production, adoption, and sustainability. By examining the patterns of hybrid and electric vehicle adoption, our research offers practical insights for policymakers. These insights can inform decisions on infrastructure development, economic policies, and environmental impact goals. Understanding the factors that determine the adoption of sustainable transportation fosters a more informed and effective approach in shaping the future of the automotive industry and society as a whole.</p><p>Prior research on modeling EV adoption commonly relies on statistical, econometric, and machine learning models rather than ordinary differential equations (Afandizadeh 2023). For example, Javid and Nejat sought to measure EV adoption and its effect on greenhouse gas emissions (Nejat 2017). Their approach relies on techniques such as mixed logit, generalized extreme value, and probit statistical models. After reviewing current research and studies on this topic, we observe that previous models primarily employed data-driven approaches like these to understand the determinants of consumer EV purchasing behavior rather than predictive dynamical models like the one we present here.</p><h3>Modeling</h3><p>We model electric vehicle adoption with a modified SIR model with three states: combustion (c), hybrid (H), and electric (E). While we constrain the total population to a constant, and model each population as a ratio of the entire population. These constraints ensure the ratios will always sum to one. The initial conditions in each version of the model presented are the ratios of car purchases in 2010, since this was the first year that EVs were commercially available (Doe 2022).</p><p>For more clear control over the model, the parameters that dictate the interaction and transition between states are determined by the states in question. For example, 𝑐ℎ indicates the rate of transition from combustion to hybrid vehicles, while ℎ𝑐 indicates hybrid to combustion transitions. See Table 1 for more details. The model computes the difference before creating the differential equation. We explore multiple scenarios in the Results section, and each will vary from the model presented below by including additional terms or modifying these parameters</p><p><em>Differential Equations</em></p><p>𝐶˙=(ℎ𝑐−𝑐ℎ)⋅𝐶(𝑡)⋅𝐻(𝑡)+(𝑒𝑐−𝑐𝑒)⋅𝐶(𝑡)⋅𝐸(𝑡)</p><p>𝐻˙=(𝑐ℎ−ℎ𝑐)⋅𝐶(𝑡)⋅𝐻(𝑡)+(𝑒ℎ−ℎ𝑒)⋅𝐻(𝑡)⋅𝐸(𝑡)</p><p>𝐸˙=(𝑐𝑒−𝑒𝑐)⋅𝐶(𝑡)⋅𝐸(𝑡)+(ℎ𝑒−𝑒ℎ)⋅𝐻(𝑡)⋅𝐸(𝑡)</p><p><em>Parameters</em></p><p>hcHybrid to Combustion</p><p>chCombustion to Hybrid</p><p>ceCombustion to Electric</p><p>ecElectric to Combustion</p><p>heHybrid to Electric</p><p>ehElectric to Hybrid</p><h3>Results</h3><p>We begin our investigation with a conservative model of electric vehicle adoption, assuming current conditions and perceptions do not change significantly. Since transportation industries do not directly measure or record the rate of transition between vehicles types in the United States, we must instead rely on total sales data in order to determine these coefficients. Based on vehicle proportion data (Doe 2022), we fine-tuned the parameters to most closely align historical proportion patterns while also yielding a conservative approach to electric adoption. Under these conditions, ℎ𝑐−𝑐ℎ=−0.05, 𝑒𝑐−𝑐𝑒=−0.09, and 𝑒ℎ−ℎ𝑒=−0.19. This model indicates that people who already own a hybrid vehicle (green) transition most to a new electric vehicle, but more people transition from combustion to hybrid or electric than the opposite direction. See the Conservative Model in the figure below.</p><p>However, a model that more closely matches the historical data implies a much more drastic shift in electric vehicle adoption. We tune the parameters of our conservative model to ℎ𝑐−𝑐ℎ=−0.09, 𝑒𝑐−𝑐𝑒=−0.09, and 𝑒ℎ−ℎ𝑒=−0.02. We also incorporate an additional term to the rate of change in the population of electric vehicles, 𝑒=0.0007. This addition changes the model from a pure SIR model to 𝐸˙=(𝑐𝑒−𝑒𝑐)⋅𝐶(𝑡)⋅𝐸(𝑡)+(ℎ𝑒−𝑒ℎ)⋅𝐻(𝑡)⋅𝐸(𝑡)+𝑒.</p><p>In this projection, the total population of vehicles increases because of the rise in electric vehicles, but the transition between hybrid and electric vehicles and vice versa is much more equal. See the Progressive Model in the following figure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1vwDa-3rqztDJWLSMreWNw.png" /><figcaption><em>Model predictions, without explicitly accounting for outside influences. Scattered data represents real ratios of combustion, hybrid, and electric car sales. (Source: U.S. Department of Energy).</em></figcaption></figure><p>Armed with these models in isolation, we now consider how additional factors might influence the future adoption of these alternative vehicles.</p><h3>Phasing Out Combustion Vehicles: California Regulation</h3><p>In August 2022, California approved new legislation requiring all new cars sold after 2035 to be zero emission vehicles. According to the New York Times, California’s vehicle conversion “is widely expected to accelerate the global transition toward electric vehicles” (Davenport 2022). In an effort to analyze the production of vehicles in California, we examine in isolation the population of electric and combustion vehicles in the near future. This model reflects trends in California and predictions by Symon et. al. based on the current conversion around electric sales in California. Because this data only measures electric vehicle production, we determine the proportion of combustion vehicles by calculating the remaining percentage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*TI4dO4CheYkenUiMq110vg.png" /><figcaption><em>The following data was obtained by `California Globe’ (Symon 2023) and describes past proportions of vehicles in California as well as planned sales proportions for the future.</em></figcaption></figure><p>In this scenario, we do not differentiate hybrid from electric, as the regulations only prohibits combustion car sales. Instead, we assume that the electric category includes any form of a zero emission vehicle, including battery electric vehicles, plug-in hybrid electric vehicles as well as fuel cell electric vehicles. Furthermore, we restrict this model to only account for the population of cars sold within the state of California. We thus arrive at the following dynamical model for California regulation of electric vehicles:</p><p>𝐶˙=(−0.4)⋅𝐶(𝑡)⋅𝐸(𝑡)+(−0.023)⋅𝐶(𝑡)</p><p>𝐸˙=(0.3)⋅𝐶(𝑡)⋅𝐸(𝑡)+(0.1)⋅𝐸(𝑡)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/0*VVobe-37c9IVZoKI.png" /><figcaption><em>Modeled Proportion of Electric and Combustion Vehicles in California</em></figcaption></figure><p>This model is unable to perfectly match reality, as the predicted proportions range between 0.05 and 0.17 while the true data reflects significant growth from 0.10 to 0.30. However, this model resembles the general shape and structure of the true data. By 2035, we see that the proportion of combustion sales falls near zero, while electric vehicles is approximately 1.</p><h3>Disaster Effect</h3><p>Incorporating the effects of economic disasters into our model is crucial for gaining a better understanding of how adverse conditions impact consumer behavior and the dynamics of vehicle sales. During recessions, consumers tend to prioritize essential expenses and delay discretionary spending such as vehicle purchases. In order to understand the effect that a recession has on car sales, we first examine historical car sales in relation to economic recessions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7bx1FVZMiGNlW3wM.png" /><figcaption><em>Source: U.S. Bureau of Economic Analysis</em></figcaption></figure><p>From this data, we see that as an economic disaster occurs, the total number of vehicle sales immediately decreases. After the recession has ended, the total number of car sales steadily increases back to its original equilibrium. We can predict the trajectory of car sales when an economic disaster occurs based on factors such as predicted length (𝐷) and rate of intensity of the disaster (𝑟). In addition, our model includes an upper limit (𝑈), a lower limit (𝐿), and reflects the total number of car sales (𝑆).</p><p>𝑆˙=𝑟⋅𝑆⋅(1−𝑆−𝐿𝑈−𝐿)⋅(𝑡−𝐷)</p><p>We compare our disaster model to actual car sale data from the 2008 Housing Market crash and the Covid-19 Pandemic:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SxJVr0cI7BD1s9sF.png" /><figcaption><em>Source: U.S. Bureau of Economic Analysis</em></figcaption></figure><p>We now transition from modeling the effects of a disaster on total car sales to the effects of the disaster on combustion, hybrid, and electric vehicle sales individually. We adjust the original model in the first figure to account for the effects of an economic disaster on each car type:</p><p>𝐶˙=(ℎ𝑐−𝑐ℎ)⋅𝐶(𝑡)⋅𝐻(𝑡)+(𝑒𝑐−𝑐𝑒)⋅𝐶(𝑡)⋅𝐸(𝑡)+𝑐+𝑅1(𝑡)</p><p>𝐻˙=(𝑐ℎ−ℎ𝑐)⋅𝐶(𝑡)⋅𝐻(𝑡)+(𝑒ℎ−ℎ𝑒)⋅𝐻(𝑡)⋅𝐸(𝑡)+ℎ+𝑅2(𝑡)</p><p>𝐸˙=(𝑐𝑒−𝑒𝑐)⋅𝐶(𝑡)⋅𝐸(𝑡)+(ℎ𝑒−𝑒ℎ)⋅𝐻(𝑡)⋅𝐸(𝑡)+𝑒+𝑅3(𝑡)</p><p>In this system of equations, each 𝑅𝑖=𝑟𝑆(1+𝑆−𝐿𝑖𝐿𝑖)(𝑡−𝐷) reflects the effect of the disaster corresponding to each vehicle type for the duration of the disaster. 𝐿𝑖 reflects the lower limit of each vehicle type. This value is proportional to each vehicle’s initial condition, measured when the disaster strikes. We leave the upper limit as the default upper limit from the base model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kxqUexeAlM3Owcqd.png" /><figcaption><em>Modeling the effects of a potential economic disaster in the year of 2040. Graph has been adjusted to reflect quantities of sales instead of proportion of sales.</em></figcaption></figure><p>We can observe the adverse impact of the disaster on vehicle sales in the model, along with the subsequent rebound in sales for each vehicle type. This model aptly mirrors the overall shape and severity of genuine economic disasters, providing a solid foundation for sales predictions. However, over-idealism still limits the predictive power of the model. While the predicted rate of returning to normalcy precisely matches the rate of the initial decline, the true recovery pace is typically more gradual than the initial downturn. Simply put, the recovery period following a disaster tends to be lengthier than the time it takes to reach the peak of the crisis. This discrepancy becomes evident when examining car sales during the 2008 Housing Market crash (refer to the previous figure). Our model proves conservative during the crash and overly optimistic during the recovery phase. Delving deeper into these limitations promises a more nuanced understanding and, consequently, more accurate modeling results.</p><h3>Reliance on Charging Stations</h3><p>When deciding to switch to an electric vehicle, consumers often consider the range that an EV can travel on a single charge. As companies provide more charging stations, EVs can travel farther, and this factor may appear more enticing to consumers. This relationship implies that the expansion of electric vehicle adoption is intimately linked to the availability of charging stations. To account for this relationship in our model, we include a fourth term 𝑆˙(𝑡) to represent the number of charging stations in the US, and we update the 𝐸˙(𝑡) term by adding 𝛼𝑆(𝑡). This term represents the number of additional EVs that people purchase because of the construction of charging stations. We also add an additional (1−𝐸(𝑡)) factor and multiply this by the right-hand side of the 𝐸˙(𝑡) equation to ensure that electric vehicles do not surpass 100% of total sales.</p><p>𝐸˙(𝑡)=[(𝑐𝑒−𝑒𝑐)⋅𝐶(𝑡)⋅𝐸(𝑡)+(ℎ𝑒−𝑒ℎ)⋅𝐻(𝑡)⋅𝐸(𝑡)+𝑒+𝛼⋅𝑆(𝑡)]⋅(1−𝐸(𝑡))</p><p>In order to create the 𝑆˙(𝑡) portion of the model, we found data regarding the number of charging stations in the US at the end of each year. As demonstrated in the following figure, the number of charging stations over time patterns exponential growth. A simple way to model this growth is 𝑆˙(𝑡)=𝛽𝑆(𝑡), but this causes the number of charging stations to grow to infinity. To combat this we add a discount factor (1−𝑆(𝑡)𝐶𝑠). We claim that the number of charging stations will never surpass the number of current gas stations, which is roughly 168,000. So we set 𝐶𝑠=168,000 when running the model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/559/0*BMBvcMgVhffx5dlu.png" /><figcaption><em>The rate of charging stations is exponential overtime (Source: U.S. Department of Energy).</em></figcaption></figure><p>Putting all of these additions together yields the system of equations:</p><p>𝐶˙(𝑡)=(ℎ𝑐−𝑐ℎ)⋅𝐶(𝑡)⋅𝐻(𝑡)+(𝑒𝑐−𝑐𝑒)⋅𝐶(𝑡)⋅𝐸(𝑡)</p><p>𝐻˙(𝑡)=(𝑐ℎ−ℎ𝑐)⋅𝐶(𝑡)⋅𝐻(𝑡)+(𝑒ℎ−ℎ𝑒)⋅𝐻(𝑡)⋅𝐸(𝑡)</p><p>𝐸˙(𝑡)=[(𝑐𝑒−𝑒𝑐)⋅𝐶(𝑡)⋅𝐸(𝑡)+(ℎ𝑒−𝑒ℎ)⋅𝐻(𝑡)⋅𝐸(𝑡)+𝛼⋅𝑆(𝑡)]⋅(1−𝐸(𝑡))</p><p>𝑆˙(𝑡)=𝛽𝑆(𝑡)⋅(1−𝑆(𝑡)𝐶𝑠)</p><p>After iterative adjustments to the parameters in the above equations, we were able to fit the model’s growth to the actual data between 2011 and 2022 (see the previous figure). We then extended the model to 2022–2050 while maintaining the same initial conditions and parameters to estimate the future growth of each type of vehicle and charging station. As seen in the previous figure, we project that EVs will surpass combustion vehicles in the year 2035. Examining at the red line representing the charging stations, we can see that the growth is exponential between 2011 to around 2035, but diminishes as the population approaches the critical capacity. Finally, we note that the overall system reaches a steady equilibrium where EVs represent the majority of the total purchases, hybrid vehicles represent a portion of the sales, no more charging stations are constructed, and combustion vehicle purchases tend to 0.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1010/0*fcm_F-CvW12YmvYe.png" /></figure><p><em>Our model’s parameters are adjusted to match empirical data from 2011–2022</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/0*GmUq1GmWTbtaS5GF.png" /><figcaption><em>After fitting the model to 2011–2022 data, it makes predictions from 2022–2050</em></figcaption></figure><h3>Analysis and Conclusion</h3><p>Across all analyzed factors, we observe a consistent upward trend in the adoption of hybrid and electric vehicles, coupled with a decline in combustion vehicles. This trend underscores the imperative for proactive measures as the production of electric vehicles expands. Policymakers should consider strategic initiatives, such as incentivizing the widespread development of charging infrastructure to support the increasing demand for electric vehicles. Additionally, these insights highlight the importance of formulating policies that encourage sustainable transportation practices, fostering a transition toward cleaner and more environmentally friendly vehicle options. This proactive approach not only aligns with environmental goals but also supports the evolving preferences of consumers, ultimately shaping a more sustainable future for the automotive industry.</p><p>We began the process of modeling electric vehicle adoption by starting with a very simple framework based on an SIR model. We then explored various potential situations that we hypothesized would have a significant effect on people’s car purchasing designs in the United States. While each of these variations reflect the changes to the model accurately, they all suffer from the same fundamental simplification. We assume that the size of each population is the primary influence on the rate of adoption, similar to the transmission of disease. However, this idea of cultural influence and local proliferation on vehicle purchases is certainly not the only factor affecting the type of car people choose to purchase.</p><p>A more appropriate model would allow the transition rate parameters to change with respect to time to incorporate more factors like changing views on electric cars, variations in relative prices, and developments in government incentive programs in a more complex and realistic manner. Furthermore, we could explore a broader range of scenarios. For instance, an examination of the production proportions of electric, hybrid, and combustion vehicles within individual car manufacturing companies may provide insights into economic trends and other behavioral patterns. Rather than addressing these factors individually, our eventual goal is to integrate them into a comprehensive model that can collectively consider multiple variables. By consolidating factors like government incentives, charging resource limitations, and the impact of natural disasters, this unified model would offer a more cohesive framework. This integrated approach not only helps in eliminating unrealistic assumptions but also ensures that the model encompasses all discussed situations, creating a more comprehensive and robust analytical tool.</p><h3>References</h3><h4>Symon, E. (2023). 25.4% Of All New Cars Sold In California Now Electric</h4><ul><li>Source: <a href="https://californiaglobe.com/fr/25-4-of-all-new-cars-sold-in-california-now-electric/#:~:text=According%20to%20a%20new%20California,electric%20car%20sales%20by%202035.">California Globe</a></li></ul><h4>Davenport, Coral, Friedman, Lisa, &amp; Plumer, Brad (2022). California to Ban the Sale of New Gasoline Cars</h4><ul><li>Source: <a href="https://www.nytimes.com/2022/08/24/climate/california-gas-cars-emissions.html">The New York Times</a></li></ul><h4>U.S. Bureau of Economic Analysis (2023). Total Vehicle Sales</h4><ul><li>Source: <a href="https://fred.stlouisfed.org/series/TOTALSA">Federal Reserve Bank of St. Louis</a></li></ul><h4>U.S. Department of Energy (2023). Alternative Fueling Station Counts by State</h4><ul><li>Source: <a href="https://afdc.energy.gov/stations/states">AFDC — Alternative Fuels Data Center</a></li></ul><h4>U.S. Department of Energy, Energy Vehicle Technologies Office, Oak Ridge National Laboratory (2022). Transportation Energy Data Book, Edition 40, Table 6.2</h4><ul><li>Source: <a href="https://tedb.ornl.gov/data/">Available at TEDB</a>, as of Jun. 21</li></ul><h4>Nejat, Jarvid (2017). A Comprehensive Model of Regional Electric Vehicle Adoption and Penetration</h4><h4>Afandizadeh, S., Sharifi, D., Kalantari, N., et al. (2023). Using machine learning methods to predict electric vehicles penetration in the automotive market</h4><ul><li>Source: <a href="https://doi.org/10.1038/s41598-023-35366-3">Scientific Reports</a></li></ul><h4>Jia, Jianmin, Shi, Baiying, Che, Fa, &amp; Zhang, Hui (2020). Predicting the Regional Adoption of Electric Vehicle (EV) With Comprehensive Models</h4><ul><li>Source: <a href="https://doi.org/10.1109/ACCESS.2020.3014851">IEEE Access</a></li></ul><h4>Salari, Nasir (2022). Electric vehicles adoption behaviour: Synthesising the technology readiness index with environmentalism values and instrumental attributes</h4><ul><li>Source: <a href="https://doi.org/10.1016/j.tra.2022.07.009">Transportation Research Part A: Policy and Practice</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=09a645b7830b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Power of the Fast Fourier Transform for Data Quality]]></title>
            <link>https://medium.com/@dallinpstewart/the-power-of-the-fast-fourier-transform-for-data-quality-1a5143077795?source=rss-596349f77bb5------2</link>
            <guid isPermaLink="false">https://medium.com/p/1a5143077795</guid>
            <category><![CDATA[convolution]]></category>
            <category><![CDATA[data-cleaning]]></category>
            <category><![CDATA[filtering]]></category>
            <category><![CDATA[fourier-transform]]></category>
            <dc:creator><![CDATA[Dallin Stewart]]></dc:creator>
            <pubDate>Wed, 09 Aug 2023 02:33:21 GMT</pubDate>
            <atom:updated>2023-08-09T02:33:21.084Z</atom:updated>
            <content:encoded><![CDATA[<p>A variety of signal processing techniques to augment noisy audio files and images | <a href="https://github.com/binDebug3/Cool_Math/blob/main/Analyze_Sound/fourier_transform.ipynb">View Code</a></p><blockquote><em>“Anytime a signal is processed, there’s a good chance that a Fast Fourier Transform is involved… And if [scientists] had discovered it sooner, it may have put a stop to the nuclear arms race.”</em></blockquote><p>- Derek Muller (Veritasium)</p><h3>The Fast Fourier Transform</h3><p>The Discrete Fourier Transform (DFT) is a fascinating mathematical tool that breaks down complex signals, like audio data, into their fundamental frequency components. It’s like discovering the hidden musical notes within a seemingly chaotic symphony. By representing a signal in terms of its constituent frequencies, the Fourier transform enables us to analyze, modify, and process the data with great precision.</p><p>One of its crucial applications lies in audio denoising, where unwanted noise can be isolated and removed by filtering out specific frequency components, leaving behind the clearer, more intelligible sound. Thanks to the Fourier transform’s ability to unveil the underlying structure of signals, it has become an indispensable tool in modern audio processing, enhancing the quality of our listening experiences by eliminating distractions and revealing the true essence of human speech and music.</p><figure><img alt="Racecar driving fast" src="https://cdn-images-1.medium.com/max/1000/1*EInbxrE90AvYRT9VtHBDFA.jpeg" /><figcaption>No, even faster than that</figcaption></figure><p>The Fast Fourier Transform (FFT) is like a turbocharged version of the regular Fourier Transform. While both reveal frequency components in a signal, the FFT is faster because it cleverly reduces redundant calculations and takes advantage of patterns in the data. It’s like finding a shortcut through a maze instead of wandering around aimlessly. By being more efficient, the FFT can process large amounts of data much quicker, making it the foundational technique in various fields like audio processing. It can swiftly identify and remove unwanted noise from audio, providing us with clearer, more enjoyable sound experiences quickly.</p><h3>Convolution</h3><figure><img alt="Convolution depiction" src="https://cdn-images-1.medium.com/max/1024/1*F8pG0BKZqwtxnkF3i-CHIg.png" /><figcaption><a href="https://arxiv.org/pdf/1603.07285.pdf">Source</a></figcaption></figure><p>Convolution is another mathematical operation used in signal processing to mix two audio signals together. It combines the elements of two periodic sound samples to create a new sound vector. The process involves multiplying corresponding elements of the two samples and then summing them up to produce the resulting vector. However, when dealing with large audio files, this calculation can be computationally expensive. Thankfully, the DFT allows us to efficiently compute convolutions by using component-wise multiplication in the frequency domain, which significantly speeds up the process. This FFT approach reduces the computation time from O(n²) to O(n log n), making smooth audio processing a possibility today.</p><h3>Filtering</h3><p>Imagine you have an audio file with some annoying background or white noise that’s distracting you from the music you love or a video with a treasured memory. By taking advantage of the processing power of the FFT, we can identify, isolate, and remove unwanted noise from any audio.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J0Txl2f4yX4Y4umb7Lsqlg.png" /></figure><p>First, we identify the frequencies we want to get rid of in the audio signal by applying the FFT to the original audio file. This operation returns a list of frequencies and the strength of their contribution to the audio. Second, we can then choose any range of frequencies to reduce or remove completely by setting them to zero. Finally, we take the inverse FFT (IFFT) of the resulting array to obtain a cleaned audio file without the unwanted noise.</p><figure><img alt="DFT Frequencies" src="https://cdn-images-1.medium.com/max/1024/1*BX8jGmc-wy3MdjotbbPs1Q.png" /></figure><p>This technique, known as spectral gating, is a common approach for cleaning audio files. By selectively removing specific frequency components corresponding to unwanted noise, spectral gating acts as a virtual “noise gate” for audio signals. It’s like having a smart bouncer at a club who lets in only the good vibes and keeps the unwanted trouble out. Whether it’s eliminating background hum, static, or any other annoying interference, spectral gating allows us to isolate and suppress those unwanted frequencies, leaving behind a pristine and enjoyable audio experience. Interestingly enough, the 2-dimensional version works for images as well.</p><h3>Cleaning Images</h3><figure><img alt="Blurry grayscale license plate" src="https://cdn-images-1.medium.com/max/1024/1*d9rRc30S535j3aU147MftA.png" /></figure><p>To clean images using the FFT, we can follow a similarly powerful process. First, we take the two-dimensional DFT of the image matrix, which transforms the image from the spatial domain to the frequency domain. This allows us to analyze the frequency components present in the image. Next, we identify spikes in the DFT, which are abnormally high frequency values. These spikes could be caused by noise or unwanted artifacts in the image. To do this, we plot the log of the magnitudes of the Fourier coefficients, making it easier to spot significant frequency spikes.</p><figure><img alt="DFT applied to an image" src="https://cdn-images-1.medium.com/max/1024/1*CGp0pZUPwOZpBVCRDYxuHg.png" /></figure><p>Once we’ve pinpointed these unwanted frequencies, we modify the corresponding entries in the DFT matrix to reduce or remove their influence. This is like selectively muting specific noise frequencies while keeping the essential image details intact. Finally, we perform the Inverse DFT (IDFT) on the modified DFT matrix, which brings the cleaned image back to the spatial domain. The result is a cleaner version of the original image, with the periodic noise and unwanted frequencies effectively reduced or eliminated.</p><pre>def clean(self, low_freq, high_freq): <br>    &quot;&quot;&quot; Remove a range of frequencies from thesamples usingthe DFT.<br>    <br>    Parameters:<br>        low_freq (float): Lower bound of the frequency range to zero out.<br>    &quot;&quot;&quot;<br><br>    # set local variables<br>    f = self.samples<br>    n = len(self.samples)<br>    r = self.rate<br>    c = fftpack.fft(f)<br><br>    # find klow and khigh<br>    klow = int(low_freq * n / r)<br>    khigh = int(high_freq * n / r)<br>    <br>    # set the given range to zero<br>    c[klow:khigh+1] = np.zeros(khigh-klow+1)<br>    c[n-khigh:n-klow+1] = np.zeros(khigh-klow+1)<br>    # update self.samples<br>    self.samples = fftpack.ifft(c)</pre><figure><img alt="Clear grayscale license plate" src="https://cdn-images-1.medium.com/max/1024/1*me2zyD993a-FfwzNRAcL6A.png" /><figcaption>Now that we’ve cleaned the image, you can read the month!</figcaption></figure><p>This technique can be particularly useful for images that contain periodic noise or are captured from screens or digital displays. By leveraging the DFT’s ability to analyze and manipulate frequency components, we can enhance the quality and visual clarity of digital images, improving the overall viewing experience.</p><h3>Source Code</h3><p>While there is a lot of research on alternate techniques for signal processing and cleaning, the Fourier Transform is one of the most important and fundamental. The modern age of technology would not be the same without it. In the wake of the Oppenheimer movie release, world politics might look very different if it had been published sooner. If you would like to review my code for this project, it is available on my <a href="https://github.com/binDebug3/Cool_Math/blob/main/Analyze_Sound/fourier_transform.ipynb">GitHub</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1a5143077795" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Your Computer Is Lying to You]]></title>
            <link>https://medium.com/@dallinpstewart/your-computer-is-lying-to-you-c07a5e502a7d?source=rss-596349f77bb5------2</link>
            <guid isPermaLink="false">https://medium.com/p/c07a5e502a7d</guid>
            <category><![CDATA[floating-points]]></category>
            <category><![CDATA[computers]]></category>
            <category><![CDATA[stability]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[conditioning]]></category>
            <dc:creator><![CDATA[Dallin Stewart]]></dc:creator>
            <pubDate>Tue, 18 Jul 2023 23:55:29 GMT</pubDate>
            <atom:updated>2024-09-21T00:33:14.776Z</atom:updated>
            <content:encoded><![CDATA[<p>A brief demonstration of the hardware limitations that force your computer to misrepresent information | <a href="https://github.com/binDebug3/Cool_Math/blob/main/Computers_Lie/conditioning_stability.py">View Code</a>.</p><blockquote><em>“People don’t understand computers. Computers are magical boxes that do things. People believe what computers tell them”</em></blockquote><p>- Bruce Scheneier</p><h3>Why Your Computer Lies</h3><p>Your computer lies to you all the time. It lies about the numbers it calculates, the images it displays, and even the programs it runs. But why does it do this? And how can you know when you can trust it? We’ll explore a few of the reasons why computers have to misrepresent information, and how you can avoid situations where these changes cause problems. We’ll also discuss concepts like function conditioning and algorithm stability, which are important for understanding how computers work.</p><p>Whenever your computer does anything, it has to do math. However, the physical limitations of computer hardware and the design of these computations (such as floating point arithmetic) introduce errors due to their inherent finite precision of numerical representation. Computers use a fixed number of bits (binary digits) to store real numbers, limiting the range and accuracy of values they can represent. As a result, when dealing with numbers that have a vast range or require high precision, the numbers may be rounded or truncated during storage, leading toa loss of information.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aJxlDCpKAkwSY4SV1zCYLQ.jpeg" /></figure><p>Furthermore, floating-point arithmetic follows specific rules to perform operations like addition, subtraction, multiplication, and division on these approximate representations. These operations can introduce rounding errors, especially when combining numbers with vastly different magnitudes. Think adding 0.000001 to 10,000,000. This phenomenon is known as numerical instability or ill-conditioning. Over multiple computations, these small errors can accumulate and propagate, resulting in significant inaccuracies in the final results.</p><p>The challenge then lies in designing algorithms that minimize the amplification of errors, and selecting appropriate data types and precision levels to strike a balance between computational efficiency and numerical accuracy, especially in scientific and engineering applications where precision and reliability are crucial.</p><h3>Underflow and Overflow</h3><p>Underflow and overflow are two important concepts when discussing the representation of numerical values in computers. These phenomena occur when numbers exceed the limits of the finite range that can be stored using a specific data type, or when the magnitude of the number becomes too small to be accurately represented.</p><p>Underflow happens when a computed result becomes too close to zero to be represented accurately. When numbers with very small magnitudes are involved in calculations, they might be rounded down to zero due to the limited precision of floating-point representations. This loss of significant digits can lead to significant loss of information and result in inaccurate or meaningless calculations. Underflow can especially affect iterative algorithms where small values are repeatedly multiplied or divided.</p><p>Overflow occurs when a computed result exceeds the maximum value that can be represented by the chosen data type. When numbers with very large magnitudes are involved in calculations, they may exceed the range that the data type can handle. As a consequence, the representation “wraps around” to the minimum value, resulting in erroneous results. Overflow can be particularly problematic in algorithms that involve exponentiation, summation, or multiplication of large values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rpUUBoeZYABcDaxDPN3JJQ.jpeg" /><figcaption>No, not that kind of overflow</figcaption></figure><p>Underflow and overflow can force your computer to lie to you because they lead to inaccurate numerical results. These issues can misrepresent the accuracy and precision of computations, giving a false sense of reliability and potentially leading to erroneous conclusions or decisions. To ensure trustworthy results, it is essential to handle underflow and overflow carefully and be aware of their impact on numerical computations.</p><h3>Conditioning</h3><p>One way to handle the impact of these inaccuracies is by considering the condition number of a function. This mathematical concept quantifies the sensitivity of the function’s output with respect to changes in its input. In simpler terms, it measures how much the output of the function is likely to change when there are small variations in the input.</p><p>Mathematically, the condition number is defined as the ratio of the relative change in the output to the relative change in the input. A high condition number indicates that the function is <em>ill-conditioned</em> and highly sensitive to input changes, while a low condition number suggests that the function is more stable and less sensitive to perturbations in the input.</p><figure><img alt="Wilkinson Polynomial" src="https://cdn-images-1.medium.com/max/1024/1*PLpyENsjSyVtc23xKRYvTg.png" /><figcaption>Wilkinson Polynomial</figcaption></figure><p>Functions with large condition numbers can contribute to significant errors and instability in numerical computations, especially when dealing with ill-conditioned problems. Hence, it is important to consider the condition number of a function to ensure accurate and reliable results in various computational tasks.</p><figure><img alt="Graph of the Wilkinson Polynomial" src="https://cdn-images-1.medium.com/max/800/1*gKg51ihFvqs6iBQDE1QWeA.png" /><figcaption><a href="https://kitchingroup.cheme.cmu.edu/blog/2014/02/21/Wilkinson-s-polynomial/">The Kitchin Research Group</a></figcaption></figure><p>For example, for an ill-conditioned function like the Wilkinson Polynomial, even minor changes to the inputs and coefficients can cause large errors in the output, making these computations less reliable. This plot serves as a visual representation of the challenges and impact of dealing with ill-conditioned functions.</p><figure><img alt="Roots of perturbed and original wilkinson polynomials" src="https://cdn-images-1.medium.com/max/640/1*XiETKeO1bcAk4ycuY75ugQ.png" /></figure><p>Here, the unperturbed Wilkinson polynomial’s roots are shown as large points in the complex plane, while the perturbed roots resulting from 100 different variations of the function are depicted as smaller points. The scattering of the small points around the larger ones highlights how small variations in the polynomial’s coefficients can lead to significant deviations in the computed roots.</p><h3>Stability</h3><p>While conditioning refers to the sensitivity of a mathematical problem to changes in its input, stability relates to how accurately an algorithm computes the value of a function from exact input, by accounting for the amplification of errors during the computation. In other words, it measures how well the algorithm maintains its accuracy despite small errors in the input.</p><p>A stable algorithm is one that produces results that are close to the true solution for a given problem by minimizing the amplification of errors during execution, even when subjected to slight changes in the input. As an example, consider the plot below, which demonstrates the effect of ill-conditioned functions on the accuracy and stability of polynomial fitting to data.</p><figure><img alt="Scatter plot with polynomial approximations" src="https://cdn-images-1.medium.com/max/640/1*L038Z3rdDr6JksG_7RQvhg.png" /></figure><p>The data points, represented by dots on the plot, are approximated by two different polynomials using the ordinary least squares technique. The red curve represents the unstable approach for this computation, while the green curve corresponds to the stable approach.</p><p>The effect of the instability increases as the degree of the approximating polynomial increases, which we can see with this degree fourteen example. In contrast, the stable approach provides a smoother fit that closely matches the data points with significantly smaller errors. By employing numerical stable QR factorization and triangular solve algorithms, the stable approach reduces error amplification. As a result, it provides more robust and accurate polynomial fits, especially for higher degrees of the polynomial.</p><h3>Can I Ever Trust My Computer?</h3><p>You can rest assured, for most day to day situations and applications, computers have enough precision and memory to perform reliably. Furthermore, computer scientists design the software you enjoy in clever ways that mitigate the limitations of your hardware on the performance of your machine. However, these limitations are very real and they can cause legitimate problems, especially in industries that require precise calculations such as stock trading, cryptocurrency, and finance. If you’d like to see how I made the plots and calculations I showed in this article, you can view the source code on my <a href="https://github.com/binDebug3/Cool_Math/blob/main/Computers_Lie/conditioning_stability.py">GitHub</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c07a5e502a7d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Create Iron Man’s Jarvis with Python]]></title>
            <link>https://medium.com/@dallinpstewart/how-to-create-iron-mans-jarvis-with-python-db3a70b3a791?source=rss-596349f77bb5------2</link>
            <guid isPermaLink="false">https://medium.com/p/db3a70b3a791</guid>
            <category><![CDATA[speech-recognition]]></category>
            <category><![CDATA[jarvis]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[virtual-assistant]]></category>
            <category><![CDATA[chatbots]]></category>
            <dc:creator><![CDATA[Dallin Stewart]]></dc:creator>
            <pubDate>Tue, 11 Jul 2023 16:26:43 GMT</pubDate>
            <atom:updated>2023-07-11T16:26:43.785Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><em>“People worry that computers will get too smart and take over the world, but the real problem is that they’re too stupid and they’ve already taken over the world.”</em></blockquote><p>- Pedro Domingos</p><h3>DIY Jarvis</h3><p>In today’s technology-driven world, the idea of having a personal virtual assistant, like Jarvis from the Iron Man movies, has become increasingly captivating. Inspired by the seamless interactions between Tony Stark and his AI companion, I have always wanted to have my own intelligent assistant to simplify daily life. This fascination inspired me to learn more about STEM and eventually led me on a journey to create my own customized virtual assistant using Python.</p><figure><img alt="A blue and pink image of a robot wearing headphones" src="https://cdn-images-1.medium.com/max/300/1*VFm5JUDsPzfXo5ERqYoViQ.png" /><figcaption>Lila, your customized virtual assistant</figcaption></figure><p>Imagine having an assistant that understands your voice commands, seamlessly performs tasks, and retrieves relevant information for you. By leveraging speech recognition and natural language processing, a personal assistant can interpret your requests and respond intuitively. From managing your schedule and sending emails to providing personalized recommendations, this digital companion can automate routine tasks and enhance your productivity.</p><p>As I explore my development process, I’ll cover various capabilities and features of my virtual assistant, which I named Lila. By integrating with external services and APIs, it can fetch real-time updates, retrieve data, and even extend its functionalities to suit specific needs. Regardless of your programming background, this guide will provide you with the necessary tools and knowledge to bring your digital companion to life. To give you an idea, here are a few of the features I have already implemented for my personal use:</p><ul><li>Launch an application on your computer</li><li>Retrieve weather information</li><li>Conduct a Google search</li><li>Check for recent unread emails</li><li>Access your Google Calendar</li></ul><h3>Voice Interface</h3><p>To create an interactive voice interface, we can leverage the power of Python packages such as speech_recognition and pyttsx3. These packages enable us to seamlessly integrate speech recognition and synthesis capabilities into our virtual assistant.</p><p>With speech recognition, the assistant listens through the microphone, quietly analyzing the background for any spoken commands. It utilizes various open source transcription models to accurately transcribe what you say, allowing it to understand spoken words. Once the speech recognition model detects an activation word or phrase, the magic happens! The assistant intelligently parses the command, looking for specific keywords that help it understand your needs and intentions</p><figure><img alt="A close up of an audio control system" src="https://cdn-images-1.medium.com/max/1000/1*B7b8vCvhGPkdgb1jmm0-Xg.jpeg" /></figure><p>To get started, let’s take a look at a code snippet that demonstrates how to record human speech and convert text into spoken words using the speech_recognition and pyttsx3 packages:</p><pre>def mic_input():<br>    &quot;&quot;&quot;<br>    Takes input from the microphone and returns it as a string<br>    :return: (string) input from the microphone, (boolean) False if failure<br>    &quot;&quot;&quot;<br>    try:<br>        r = sr.Recognizer()<br>        with sr.Microphone() as source:<br>            print(&quot;Listening...&quot;)<br>            r.energy_threshold = 4000<br>            audio = r.listen(source, timeout=30, phrase_time_limit=20)<br><br>        try:<br>            print(&quot;Recognizing...&quot;)<br>            command = r.recognize_google(audio, language=&#39;en-in&#39;).lower()<br>            print(f&quot;User said: {command}\n&quot;)<br>        except Exception:<br>            print(&quot;Say that again please...&quot;)<br>            command = mic_input()<br>        return command<br>    except Exception as ex:<br>        print(ex)<br>        return False<br><br>def tts(text):<br>    &quot;&quot;&quot;<br>    Text to speech function<br>    :param text: (string) text to be spoken<br>    :return: (boolean) True if successful, False if failure<br>    &quot;&quot;&quot;<br>    try:<br>        engine.say(text)<br>        engine.runAndWait()<br>        engine.setProperty(&#39;rate&#39;, 175)<br>        return True<br>    except Exception as ex:<br>        print(ex)<br>        return False</pre><p>The mic_input() function is used to capture audio input from the microphone. It utilizes the SpeechRecognition library (sr) to listen to the microphone input for a specified duration and convert it to text while filtering out background noise. The function returns the recognized command as a string, and if there is a recognition failure, it prompts the user to repeat their command.</p><p>The tts function is responsible for converting text to speech using a text-to-speech engine in the say() method to speak aloud. The speech is then played using the runAndWait() method. If any error occurs during the text-to-speech conversion, the function returns False. With the basic code for interaction covered, let’s go over some of the specific features Lila has.</p><h3>Gmail</h3><p>In order to fulfill the user’s request to send an email, the virtual assistant leverages the Gmail API. This API allows seamless integration with the user’s Gmail account, enabling actions such as checking for unread emails and sending new ones. By utilizing a get_credentials() function, the virtual assistant ensures secure access to the user’s Gmail account, obtaining and saving the necessary credentials for future use.</p><pre>def check_unread():<br>    &quot;&quot;&quot;Shows basic usage of the Gmail API.<br>    Lists the user&#39;s Gmail labels.<br>    &quot;&quot;&quot;<br>    creds = get_credentials()<br><br>    try:<br>        # Call the Gmail API<br>        service = build(&#39;gmail&#39;, &#39;v1&#39;, credentials=creds, cache_discovery=False)<br><br>        # Define the search parameters for the email query<br>        today = datetime.today() + timedelta(days=1)<br>        one_day_ago = today - timedelta(days=3)<br>        query = &quot;is:unread after:{} before:{}&quot;.format(one_day_ago.strftime(&#39;%Y/%m/%d&#39;), today.strftime(&#39;%Y/%m/%d&#39;))<br><br>        # Execute the email query<br>        result = service.users().messages().list(userId=&#39;me&#39;, q=query).execute()<br><br>        return process_query(result, service)<br><br>    except HttpError as error:<br>        print(f&#39;An error occurred: {error}&#39;)</pre><p>To handle the task of checking for unread emails, the check_unread() function queries the user’s inbox to find unread messages within a specified time range, typically the last 24 hours. Once the query is executed, the results are processed by the process_query() function.</p><figure><img alt="A laptop with a tab for gmail open" src="https://cdn-images-1.medium.com/max/1000/1*ayyOp6oCq1VSMeM2lCtalg.jpeg" /></figure><p>This function extracts relevant information from the retrieved email messages, such as the sender, subject, and received time. It decodes the message content and prepares a summary of the unread emails. This summary can include the sender’s name, subject, and other details, depending on the level of detail requested.</p><p>By combining these functions, the virtual assistant can accurately report the number of unread emails in the last day and provide a summary of their key details. This functionality showcases the assistant’s ability to interact with external services and handle email-related tasks, enhancing productivity and keeping the user informed about their inbox status.</p><h3>Push Code to GitHub Automatically</h3><p>Imagine you’re working on a coding project and you want to easily push your code to a version control system like Git. That’s where the virtual assistant comes in to help! With just a simple request, the assistant can help you push your code effortlessly.</p><pre>def push_code(name, message=None, master=True):<br>    try:<br>        push_path = os.path.abspath(config.dir_dict[name])<br>    except KeyError as ex:<br>        print(ex)<br>        return False<br><br>    if not os.path.exists(push_path):<br>        return False<br><br>    if master:<br>        master = &quot;master&quot;<br>    else:<br>        master = &quot;main&quot;<br><br>    command = f&quot;cd {push_path} &amp;&amp; git pull origin {master} &amp;&amp; git add .&quot;<br><br>    if message is None:<br>        # add commit pull push with a default commit message<br>        command += &quot; &amp;&amp; git commit -m &#39;pushing&#39;&quot;<br>    else:<br>        # add commit pull push with the passed-in commit message<br>        command += f&quot; &amp;&amp; git commit -m &#39;{message}&#39;&quot;<br><br>    command += f&quot; &amp;&amp; git push origin {master}&quot;<br><br>    print(&quot;\n&quot;.join(command.split(&quot; &amp;&amp; &quot;)))<br>    subprocess.run(command, shell=True)<br><br>    return True</pre><p>When you ask the virtual assistant to push your code, the push_code function takes a few parameters, such as the name of the project and an optional commit message to perform your request. Depending on the value of the master parameter, the function sets the default branch to either “master” or “main”. It then forms a command that navigates to the project directory, pulls the latest changes from the remote repository, stages all the modified files, and commits them with a commit message. If you didn’t provide a commit message, the function adds a default message like “pushing” to keep things simple. However, if you did provide a message, it incorporates that into the commit. Finally, the function completes the process by pushing the committed changes to the remote repository.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*Ewmvoy6OfUCPkP7XHqht5w.jpeg" /></figure><p>The virtual assistant displays the commands it’s executing, so you can stay informed about the actions being performed behind the scenes and add a layer of transparency. By utilizing this function, our virtual assistant makes it effortless for you to push your code and keep your project up to date with the latest changes. You can simply focus on your coding journey without worrying about the details of version control.</p><h3>Check the Weather</h3><p>Now let’s assume you’re getting ready for the day, and you want to know what the weather has in store for you. With a simple request, the virtual assistant can fetch the current weather for any city you’d like.</p><pre>def fetch_weather(city):<br>    &quot;&quot;&quot;<br>    Get the weather in the city<br>    :param city: (string) city<br>    :return: (string) weather<br>    &quot;&quot;&quot;<br>    api_key = config.weather_api_key<br>    units_format = &quot;&amp;units=imperial&quot;<br><br>    weather_data = get_data(city, api_key, units_format)<br><br>    if weather_data[&quot;cod&quot;] == &quot;404&quot;:<br>        city = config.local_city<br>        weather_data = get_data(city, api_key, units_format)<br><br>    if weather_data[&quot;cod&quot;] != &quot;404&quot;:<br>        main_data = weather_data[&quot;main&quot;]<br>        weather_description_data = weather_data[&quot;weather&quot;][0]<br>        weather_description = weather_description_data[&quot;description&quot;]<br>        current_temperature = main_data[&quot;temp&quot;]<br>        current_pressure = main_data[&quot;pressure&quot;]<br>        current_humidity = main_data[&quot;humidity&quot;]<br>        wind_data = weather_data[&quot;wind&quot;]<br>        wind_speed = wind_data[&quot;speed&quot;]<br><br>        final_response = f&quot;&quot;&quot;<br>                The weather in {city} is currently {weather_description} <br>                with a temperature of {current_temperature} degrees fahrenheit<br>        &quot;&quot;&quot;<br>        if not config.skip:<br>            final_response += f&quot;&quot;&quot;<br>                atmospheric pressure of {current_pressure} a m use, <br>                humidity of {current_humidity} percent <br>                and wind speed reaching {wind_speed} miles per hour&quot;&quot;&quot;<br><br>        return final_response<br><br>    return &quot;Sorry Sir, I couldn&#39;t find the city in my database. Please try again&quot;<br><br><br>def get_data(city, api_key, units_format):<br>    base_url = &quot;http://api.openweathermap.org/data/2.5/weather?q=&quot;<br>    complete_url = base_url + city + &quot;&amp;appid=&quot; + api_key + units_format<br><br>    response = requests.get(complete_url)<br>    weather_data = response.json()<br><br>    return weather_data</pre><p>When you ask the virtual assistant to check the weather, it taps into the fetch_weather function, which retrieves the weather information using an API and the name of the city as a parameter. Using the get_data function, the assistant sends a request to the OpenWeatherMap API, which responds with weather data as a JSON object.</p><figure><img alt="A man with a black umbrella walking through a rainy downtown district" src="https://cdn-images-1.medium.com/max/1000/1*QXOUxRTFx1WNBjW1b-wnPA.jpeg" /></figure><p>Once the weather data is obtained, the function extracts the relevant information such as the weather description, current temperature, atmospheric pressure, humidity, and wind speed. These details are formatted into a final response string, providing you with a snapshot of the current weather conditions.</p><h3>Full Feature List</h3><p>That was just a few of the many helpful features a virtual assistant is capable of! In the future, I’d like to develop a natural language understanding deep learning model that will allow the user to speak more freely as they interact with the virtual assistant instead of relying on keywords. If you’d like to view the code for more of the functionality, you can browse the full list of commands and functionalities below or view the project on <a href="https://github.com/binDebug3/VirtualAssistant">GitHub</a>.</p><ul><li>Launch: Open an application on your computer</li><li>Run: Execute another Python program</li><li>Push: Upload code to version control software</li><li>Switch window: Change the active window on your computer</li><li>Lock computer: Lock the computer screen</li><li>Screenshot: Capture a screenshot of the screen</li><li>System info: Retrieve system information</li><li>IP address: Display the IP address of the computer</li><li>Close notes: Close an open note-taking application</li><li>Note: Create a new note</li><li>Image: Open the most recent screenshot taken</li><li>Merge PDF: Combine two input PDF files</li><li>Jupiter: Convert an IPYNB file to PDF</li><li>Extract text: Extract all text from a PDF document</li><li>Joke: Tell a joke</li><li>XKCD: Open the most recent XKCD comic</li><li>Piano: Play background music by The Piano Guys</li><li>Date: Display the current date</li><li>Time: Provide the current time</li><li>Weather: Retrieve the weather information</li><li>News: Search for news articles</li><li>Go to: Open a specific URL in a web browser</li><li>Tell me about: Perform a Wikipedia search</li><li>Google: Conduct a Google search</li><li>YouTube: Perform a YouTube search</li><li>Calculate: Perform a Wolfram Alpha search</li><li>Where is: Conduct a Google Maps search</li><li>What is: Perform a Wolfram Alpha search</li><li>What can you do: Provide a list of capabilities</li><li>Development: Share upcoming capabilities</li><li>Keyword: Display a list of keywords</li><li>Silent mode: Switch to silent mode</li><li>Voice mode: Switch to voice mode</li><li>Earbud mode: Switch to earbud mode</li><li>Press mode: Switch to press mode</li><li>Terminal mode: Switch to terminal mode</li><li>Power down: Turn off the virtual assistant</li><li>Check email: Check for recent unread emails</li><li>Send email: Send an email</li><li>Check calendar: Access your Google Calendar</li><li>Add event: Add an event to your Google Calendar</li><li>To-do: Display your to-do list</li><li>Start my day: Provide the weather and to-do list to start your day</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=db3a70b3a791" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Database Automation with Fuzzy Entity Matching]]></title>
            <link>https://medium.com/@dallinpstewart/automating-human-tasks-with-fuzzy-entity-matching-23c8fff73e48?source=rss-596349f77bb5------2</link>
            <guid isPermaLink="false">https://medium.com/p/23c8fff73e48</guid>
            <category><![CDATA[internships]]></category>
            <category><![CDATA[fuzzy-matching]]></category>
            <category><![CDATA[levenshtein-distance]]></category>
            <category><![CDATA[cosine-similarity]]></category>
            <category><![CDATA[climate-action]]></category>
            <dc:creator><![CDATA[Dallin Stewart]]></dc:creator>
            <pubDate>Tue, 04 Jul 2023 16:06:00 GMT</pubDate>
            <atom:updated>2024-09-21T00:28:54.531Z</atom:updated>
            <content:encoded><![CDATA[<p>An application of entity matching I implemented while interning at Wells Fargo.</p><blockquote><em>“An algorithm must be seen to be believed.”</em></blockquote><p>- Donald Knuth</p><h3>Wells Fargo Climate Initiative</h3><p>In the summer of 2022 I worked for the Climate Initiative Analytics team at Wells Fargo. The team had been recently founded in order to help the company reach its <a href="https://www.wellsfargo.com/about/corporate-responsibility/environment/">goal</a> to help accelerate the transition to a low-carbon economy and reduce the impacts of climate change. Wells Fargo has committed to achieving net-zero greenhouse gas emissions by 2050, including financed emissions, and has set a goal of deploying $500 billion in sustainable finance between 2021 and 2030. Financed emissions refer to the greenhouse gas emissions that result from the projects and activities that a financial institution invests in or finances rather than direct emissions from a company building, for example.</p><p>To achieve these goals, Wells Fargo is working with clients to help finance their emissions reduction efforts, driving innovation and accelerating market-based solutions to the climate crisis, and enhancing energy and resource efficiency in its own physical assets. They have already achieved carbon neutrality for Scope 1 and Scope 2 emissions.</p><p>Before Wells Fargo could begin working with their clients, they needed to develop a method of reporting on their financed emissions. While they had all of their investment records stored internally, and every company’s emissions records were publicly available, not every company had an available ID, so the only way to match some of our internal data with the external data was with the name of the company. However, company names were not always consistent between databases. For example, our data might call one company “Pacific Gas and Electric” why the other dataset simply refers to the same company as “PG&amp;E.”</p><h3>Fuzzy String Matching</h3><p>The time I spent developing a fuzzy string matching algorithm played a vital role in tackling this challenge to match internal data with external records based on company names. Fuzzy string matching is a technique used to compare two strings of text and determine how similar they are to each other, even if they are not an exact match.</p><p>Unlike exact string matching, fuzzy string matching takes into account variations in spelling, punctuation, and other factors that can make two strings appear different but still convey the same or a similar meaning. This comparison is possible because of algorithms such as Levenshtein distance, cosine-similarity, and Soundex. They assign scores to the degree of similarity between two strings based on specific criteria, allowing for efficient and accurate matching of text data.</p><p>The challenge then becomes deciding which algorithm works best for a given dataset, and what types of data cleaning lead to the most accurate results. Taking steps like removing extra whitespace, standardizing capitalization, removing certain punctuation marks, and modifying abbreviations can all have a significant impact on accuracy and reliability, but not always a positive one. In the next few sections, I will discuss the various algorithms I tested and the method I developed to compare them and identify the best algorithm for our requirements.</p><h3>Cosine Similarity</h3><p>The cosine similarity algorithm is a measure of similarity between two non-zero vectors of an inner product space that measures the cosine of the angle between them. That’s a lot of math words. Heuristically, this method relies on representing objects, such as the name of a company, as vectors, and then finding the closest two vectors. In our case, we can compare the similarity between two strings by representing them as vectors of their character frequencies.</p><p>The first step is to represent each string as a vector of character frequencies, where the values in each vector correspond to the frequency of each character in the string. The cosine similarity between two vectors can then be calculated using the following formula:</p><figure><img alt="Cosine similarity formula" src="https://cdn-images-1.medium.com/max/548/1*cE2UtIH81Wp059mEVTCjOg.png" /></figure><p>where A and B are the vectors of character frequencies for the two strings being compared, and “dot” represents the <a href="https://en.wikipedia.org/wiki/Dot_product">dot product</a> of the two vectors. The ‖A‖ and ‖B‖ represent the magnitudes of the two vectors.</p><p>For example, let’s consider the two strings “apple” and “banana”. We can represent these strings as vectors of character frequencies, as follows:</p><p>“apple” = [a:1, p:2, l:1, e:1]<br>“banana” = [b:1, a:3, n:2]</p><p>We can then calculate the cosine similarity between these two vectors using the formula above:</p><figure><img alt="Cosine similarity calculation" src="https://cdn-images-1.medium.com/max/953/1*2wM2Calawbzla-pNK12dWA.png" /></figure><p>This indicates that the strings “apple” and “banana” have a relatively low similarity score based on their character frequencies.</p><h3>Levenshtein Distance Algorithm</h3><p>The <a href="https://en.wikipedia.org/wiki/Levenshtein_distance">Levenshtein distance algorithm</a> is a technique used to measure the difference between two strings of text by counting the minimum number of operations (insertions, deletions, or substitutions) needed to transform one string into the other. The algorithm works by constructing a matrix where each cell represents the distance between two substrings of the input strings.</p><p>Starting from the top left corner of the matrix, the algorithm compares each pair of corresponding characters in the input strings and calculates the distance between them. It then populates the matrix by taking the minimum value of the three possible operations (insertion, deletion, or substitution) needed to transform one substring into the other, and repeats this process for every cell in the matrix until the bottom right corner is reached. The final value in the bottom right corner of the matrix represents the Levenshtein distance between the two input strings.</p><p>For example, let’s consider the strings “kitten” and “sitting”. The matrix for these strings would look like this:</p><figure><img alt="Levenshtein distance table" src="https://cdn-images-1.medium.com/max/329/1*D37Ake7WR_A9NjLAF7kwxA.png" /></figure><p>The top row and left column of the matrix represent the empty string and the characters of the two input strings. The value in each cell represents the Levenshtein distance between the substrings formed by the row and column indices. For example, the value in cell (3,4) represents the distance between the substrings “kit” and “sitt”. The final value in the bottom right corner of the matrix is 3, which means that the Levenshtein distance between “kitten” and “sitting” is 3, indicating that three operations (substitute “k” with “s”, insert “i”, and insert “g”) are needed to transform one string into the other.</p><h3>Scoring</h3><p>When it comes to fuzzy string matching, it is important to understand that the scores obtained are not measures of correctness, but rather indicators of confidence. Although these scores may resemble percentages, they do not represent an absolute degree of similarity between two strings. Instead, they serve as relative measures, comparing the similarity of one string to another within a given context.</p><p>To determine the most effective method for fuzzy string matching, these algorithms are compared using benchmark datasets or test cases with known correct matches. The performance of each algorithm is evaluated based on factors such as accuracy, efficiency, and robustness. This comparison helps in selecting the most suitable algorithm for a specific use case, taking into account the specific requirements and constraints of the matching task.</p><p>In summary, fuzzy string matching scores should not be interpreted as absolute measures of correctness, but rather as relative indicators of confidence. By leveraging various algorithms and comparing their performance, it becomes possible to achieve efficient and accurate matching of text data despite variations in spelling, punctuation, and other factors that can affect string similarity.</p><h3>Conclusion</h3><p>My internship with Wells Fargo implementing fuzzy string matching algorithms was a great experience. Working with such a reputable and sustainability-focused company was very inspiring for me, and I loved the invaluable opportunity to apply data science techniques in real world problems. Fuzzy string matching proved to be a powerful solution to identify matching records across different data sources accurately. I am grateful to have worked with such an amazing team, and for the chance to contribute to the company’s efforts towards a sustainable future. The experience has reinforced my passion for data science and the positive impact it can have on society.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=23c8fff73e48" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Crafting Handwritten Digit Recognition Models without Neural Networks]]></title>
            <link>https://medium.com/@dallinpstewart/crafting-handwritten-digit-recognition-models-without-neural-networks-9fd5c50bda51?source=rss-596349f77bb5------2</link>
            <guid isPermaLink="false">https://medium.com/p/9fd5c50bda51</guid>
            <category><![CDATA[nearest-neighbors]]></category>
            <category><![CDATA[kd-tree]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[classification-algorithms]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Dallin Stewart]]></dc:creator>
            <pubDate>Tue, 27 Jun 2023 16:42:10 GMT</pubDate>
            <atom:updated>2024-09-21T00:26:35.939Z</atom:updated>
            <content:encoded><![CDATA[<h3>Handwritten Digit Recognition with K-Nearest Neighbors</h3><p>A K-Nearest Neighbor machine learning approach to the classic handwritten digit classification problem | <a href="https://github.com/binDebug3/Cool_Math/blob/main/Handwritten_Digits/nearest_neighbor.py">View Code</a>.</p><blockquote><em>“You’re the average of the five people you spend the most time with.”</em></blockquote><p>- Jim Rohn</p><h3>Recognizing Handwritten Digits</h3><p>Writing a program to classify hand-written digits is one of the classic introductory challenges for students new to artificial intelligence and neural networks. The problem requires the program to look at a small (28x28) grayscale image of a single digit and output the correct number, which is challenging because a computer doesn’t process data and images the same way we do.</p><figure><img alt="A 28x28 image of a handwritten digit" src="https://cdn-images-1.medium.com/max/800/1*3RkHb81kU7pREDGuMst_ZQ.png" /><figcaption>A 28x28 image of a handwritten digit</figcaption></figure><p>Machine learning is a branch of artificial intelligence that refers to any algorithm that modifies itself to optimize a certain task or goal. Today, the most popular AI implementations rely on algorithms like neural networks (AlphaGo) and transformers (ChatGPT), but there are a lot of other methods like the one we’ll explore today. We can actually solve this particular class of problem without any fancy neural networks by cleverly restructuring the problem and applying a much (mathematically) simpler algorithm called K-Nearest Neighbors instead. With an accuracy of about 90%, it is not the most powerful technique, but performs surprisingly well for such a fundamentally simple idea.</p><p>Heuristically, the algorithm stores representations of the images and their solution digits from the training data in memory. When a new image is input, the algorithm finds the most similar images in its training data, tells them to “vote” on which digit the image represents, and outputs the winning digit as the answer.</p><h3>Computing Distance</h3><p>The first thing we have to do before we can start classifying images is define distance, also known as choosing a “metric”. This may feel a little silly and completely irrelevant — distance after all is just the amount of space between two objects! However, a lot of the power and utility of mathematics comes from rigorously defining even the most complex ideas by stripping away all of the semantic ambiguity. This approach allows us to consistently and reliably create and apply theorems that lead to amazing results like this classification solution.</p><p>The simple definition of distance above might work in the three dimensional space we are accustomed to, but what about four dimensional space? What happens when we have to deal with a hundred dimensions, or even a million? We can compute the length of a straight line from point “x” to point “z” with the <em>Euclidean metric</em>:</p><figure><img alt="The euclidean metric" src="https://cdn-images-1.medium.com/max/694/1*RQ2_lkCE6J6JvJhAo3nsvg.png" /></figure><p>Part of the nearest neighbor problem requires finding the closest data point or object to a given reference point among a set of scattered points or objects. The goal is to determine the most similar or proximate entity based on the metric we just defined. For example, we might be looking for the friend closest to us in a crowded market, deciding which fruits in a basket have the most similar color, or identifying the closest two vectors in an abstract vector space.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*JOGi_IwuOkTnAq9rbtBw-A.jpeg" /></figure><h3>K-D Trees</h3><p>One approach to finding the closest friend is to check every single point, or friend, compute the distance, and return the closest one. This exhaustive search approach takes so long that it only works on relatively small datasets. Fortunately, we have an alternative in K-D trees.</p><figure><img alt="A big tree" src="https://cdn-images-1.medium.com/max/1000/1*_dgtQrzxgvE43S2mJKe6DQ.jpeg" /><figcaption>No, not that kind of tree</figcaption></figure><p>A K-D tree (short for K-Dimensional tree or a tree in the Kth dimension) is a data structure that organizes points in a multi-dimensional space. It enables efficient searching and retrieval of points based on their proximity to a query point. The process of construction and application of a K-D tree can be understood as follows:</p><ol><li>Construction: Initially, the algorithm selects a pivot point from the given dataset. The pivot divides the space into two regions along a chosen dimension. Points to the left of the pivot are assigned to the left subtree, while those to the right are assigned to the right subtree.</li><li>Recursive Partitioning: The process continues recursively on each subtree, selecting a new pivot and dividing the space further along a different dimension. This alternation of dimensions ensures balanced and efficient partitioning.</li><li>Tree Structure: The resulting K-D tree forms a hierarchical structure, where each node represents a pivot point and has two child nodes corresponding to the left and right subtrees.</li><li>Efficient Search: To find the nearest neighbor or points within a specific range, a search query follows a path down the tree based on comparisons between the query point and the pivot points. It selectively explores regions of the tree, pruning branches that are unlikely to contain the desired points. By comparing distances and intelligently traversing the tree, the search algorithm efficiently narrows down the potential candidates.</li><li>Balancing: To maintain efficiency, balancing techniques such as median or mean splitting can be applied during construction. These ensure that the tree remains balanced, preventing degeneration into a long linear structure and optimizing search performance.</li></ol><figure><img alt="A graphical representation of a mathematical K-D Tree" src="https://cdn-images-1.medium.com/max/1000/1*4NQg8YjRf5ZmuiSgIiBu8Q.png" /><figcaption>(<a href="https://opendsa-server.cs.vt.edu/ODSA/Books/Everything/html/KDtree.html">OpenDSA</a>)</figcaption></figure><p>In short, K-D trees organize points in a hierarchical structure, recursively dividing space along different dimensions. This structure facilitates efficient searching by selectively exploring relevant regions. By harnessing the structure of K-D trees, we can quickly find and select the K nearest neighbors to any image of a digit, which will be relevant once we begin exploring how the actual algorithm works. To be clear, the “k” in K-D tree refers to the dimension of the data (728 in our case), while the “k” in k-nearest neighbors refers to the number of neighbors we will compare (we’ll use 4 for our demonstration).</p><h3>The Nearest Neighbor Algorithm</h3><p>We’ve finally gotten to the purpose of all that math we’ve been reviewing. The k-nearest neighbor algorithm is a simple yet powerful technique used for classification problems like our own. It operates based on the principle that objects or data points with similar characteristics tend to exist close to each other in the feature space. Here’s a concise explanation of how the K-NN algorithm works:</p><ol><li>Data Preparation: First, the algorithm requires a labeled dataset, where each data point is associated with a class or a value. It also requires a query point for which we want to determine the class or value. We will use the MNIST dataset of 3000 28x28 grayscale labeled images of handwritten digits.</li><li>Constructing the K-D Tree: To efficiently find the nearest neighbors of a new handwritten digit, we construct a K-D tree from the labeled dataset. This step will enable efficient searching by eliminating large portions of the feature space that do not contain relevant neighbors.</li><li>Querying the K-D Tree: When a query image is provided, the algorithm traverses the K-D tree to search for the k nearest neighbors. Starting from the root node, it compares the query image’s features with the features stored in each node and selects the branch that is closer to the query image using the distance metric we defined earlier. By iteratively moving down the tree, it eventually reaches leaf nodes that contain potential nearest neighbors.</li><li>Neighbor Selection: The k-NN algorithm selects the “k” nearest neighbors to the query point based on the calculated distances. These neighbors are the data points with the smallest distances to the query point.</li><li>Voting or Averaging: For classification tasks, the algorithm determines the class of the query point by majority voting among the k nearest neighbors. Each neighbor’s class has a vote according to its label, and the class with the most votes becomes the predicted class for the query point.</li><li>Output: The algorithm outputs the predicted class or value for the query point based on the results of the voting step.</li></ol><p>The k-NN algorithm is flexible and can be adapted to handle different scenarios. The choice of the value for k, the number of neighbors to consider, is crucial and depends on the dataset and problem at hand. A smaller k value leads to more local and potentially noisy decisions, while a larger k value captures more global information but may overlook local patterns.</p><p>I’ve included the most complicated part of the program below. I’ll explain how the code gets to this method for a little bit of context. When we want to classify a new image, we pass it to the “predict” method of the KNeighborsClassifier class. This class already has the constructed K-D tree as an attribute. The predict method returns the best result by calling the tree’s query method, which is described in detail below.</p><pre> def query(self, z):<br>        &quot;&quot;&quot;Find the value in the tree that is nearest to z.<br>        Parameters:<br>            z ((k,) ndarray): a k-dimensional target point.<br>        Returns:<br>            ((k,) ndarray) the value in the tree that is nearest to z.<br>            (float) The Euclidean distance from the nearest neighbor to z.<br>        &quot;&quot;&quot;<br><br>        def KDSearch(current, nearest, dStar):<br>            # base case<br>            if current is None:<br>                return nearest, dStar<br>            <br>            # initialize search values<br>            x = current.value<br>            i = current.pivot<br>            <br>            # if the norm of x-z is less than d* update nearest and d*<br>            if la.norm(x - z) &lt; dStar:<br>                nearest = current<br>                dStar = la.norm(x - z)<br>            <br>            # update nearest and d* recursively with the appropriate child<br>            if z[i] &lt; x[i]:<br>                nearest, dStar = KDSearch(current.left, nearest, dStar)<br>                if z[i] + dStar &gt;= x[i]:<br>                    nearest, dStar = KDSearch(current.right, nearest, dStar)<br>            <br>            else:<br>                nearest, dStar = KDSearch(current.right, nearest, dStar)<br>                if z[i] - dStar &lt;= x[i]:<br>                    nearest, dStar = KDSearch(current.left, nearest, dStar)<br>           <br>            return nearest, dStar<br>        <br>        # return the results of the KD search starting from the root<br>        node, dStar = KDSearch(self.root, self.root, la.norm(self.root.value - z))<br>        return node.value, dStar</pre><figure><img alt="7" src="https://cdn-images-1.medium.com/max/800/1*3RkHb81kU7pREDGuMst_ZQ.png" /><figcaption>7!</figcaption></figure><p>In my exploration of handwritten digit classification using the k-nearest neighbors algorithm, I’ve been captivated by the remarkable ways in which mathematics can uncover meaningful patterns in images and data. It’s truly amazing to witness how mathematical concepts can be applied to accurately recognize and differentiate handwritten digits. This experience demonstrates the potential of mathematics in unraveling new insights and making advancements in data analysis. I am excited to see how mathematics will continue to play a vital role in applications like this, expanding our understanding and shaping the world around us in remarkable ways. Please visit my <a href="https://github.com/binDebug3/Cool_Math/blob/main/Handwritten_Digits/nearest_neighbor.py">GitHub</a> repository if you’d like to view the full program.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9fd5c50bda51" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>