<?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 Giovanny Espitia on Medium]]></title>
        <description><![CDATA[Stories by Giovanny Espitia on Medium]]></description>
        <link>https://medium.com/@giovannyespitiag117?source=rss-2fc54db6b4c2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*egKyvj-wp4MNYgbW3CopPA.jpeg</url>
            <title>Stories by Giovanny Espitia on Medium</title>
            <link>https://medium.com/@giovannyespitiag117?source=rss-2fc54db6b4c2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 17:13:53 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@giovannyespitiag117/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[Approximating Sine Functions with Neural Networks: A Deep Learning Tutorial]]></title>
            <link>https://medium.com/@giovannyespitiag117/approximating-sine-functions-with-neural-networks-a-deep-learning-tutorial-167d8492be84?source=rss-2fc54db6b4c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/167d8492be84</guid>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[regression]]></category>
            <dc:creator><![CDATA[Giovanny Espitia]]></dc:creator>
            <pubDate>Tue, 04 Jun 2024 04:23:34 GMT</pubDate>
            <atom:updated>2024-06-04T04:23:34.647Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*sWVbNqbzEudoj4kB4NxctQ.png" /></figure><h4>Introduction</h4><p>In this article, we implement a simple feed forward neural network in PyTorch to learn a sinusoidal function. Specifically, we create a synthetic dataset of 10000 samples according to the following expression:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/160/0*wFE7lBXEr3yw2XDp.png" /><figcaption>Equation 1.</figcaption></figure><p>Where <em>A </em>corresponds to some arbitrary coefficient and ε corresponds to some parameters that is sampled from a uniform distribution with zero mean and unity standard deviation. We introduce the noise in order to make a more general model.</p><h4>Python Implementation</h4><p><strong><em>Generating and visualizing the dataset</em></strong></p><pre>#dependencies <br>import numpy as np<br>import matplotlib.pyplot as plt<br>import torch <br>import torch.nn as nn<br>import torch.optim as optim<br><br>#generating and visualizing dataset<br>x = np.linspace(-4 * np.pi, 4 * np.pi, 10000)<br>y = np.sin(x) + 0.5 * np.random.randn(len(x))<br><br>plt.figure(figsize=(10, 6))<br>plt.scatter(x, y)<br>plt.title(&quot;Sine Function with Random Noise&quot;)<br>plt.xlabel(&quot;x&quot;)<br>plt.ylabel(&quot;y&quot;)<br>plt.grid(True)<br>plt.show()</pre><p>This code results in Figure 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/844/1*DHS_cMQVqwC_6serecg7dw.png" /><figcaption>Figure 1. A sinusoidal function with Gaussian noise.</figcaption></figure><p><strong><em>Implementing the model</em></strong></p><p>In order to implement the model, we first transform our inputs and targets into PyTorch tensors, which are the data structures used for representing inputs and outputs in PyTorch models. For this project, we use a simple feed-forward neural network architecture, which is a straightforward multi-layer perceptron (MLP) with fully connected layers. It is left as an exercise for the reader to increase the complexity of the architecture, such as by adding more layers, using different activation functions, or incorporating techniques like dropout or batch normalization, which may help decrease the loss and improve the model’s performance after training. The chosen loss function for this model is the mean squared error (MSE) loss, also known as the L2 loss function, which is a common choice for regression problems. The selected optimizer is the Adam optimizer, a popular adaptive learning rate optimization algorithm, with a learning rate of 0.001, which is a typical starting value for many problems. The network is trained for 10,000 epochs, where one epoch represents one complete pass through the entire training dataset. This number of epochs may need to be adjusted based on the complexity of the problem, the size of the dataset, and the observed convergence of the loss during training. Please note that while this architecture and setup can serve as a baseline, further tuning and experimentation with different architectures, hyperparameters, and techniques may be necessary to achieve optimal performance on a specific problem or dataset.</p><pre>#transforming the input and output arrays to tensors<br>x_tensor = torch.from_numpy(x).float().view(-1, 1)<br>y_tensor = torch.from_numpy(y).float().view(-1, 1)<br><br>#implementing the model<br>class Net(nn.Module):<br>  def __init__(self):<br>    super(Net, self).__init__()<br>    self.hidden = nn.Linear(1, 128)<br>    self.hidden2 = nn.Linear(128, 256)<br>    self.hidden3 = nn.Linear(256, 128)<br>    self.output = nn.Linear(128, 1)<br>  <br>  def forward(self, x):<br>    x = torch.relu(self.hidden(x))<br>    x = torch.relu(self.hidden2(x))<br>    x = torch.relu(self.hidden3(x))<br>    x = self.output(x)<br>    return x<br><br>#instantiating the model, criterion (loss function), and optimizer<br>model = Net()<br>criterion = nn.MSELoss()<br>optimizer = optim.Adam(model.parameters(), lr = 0.001)<br><br>#training loop<br>num_epochs = 10000<br>for epoch in range(num_epochs):<br>  #forward pass<br>  outputs = model(x_tensor)<br>  loss = criterion(outputs, y_tensor)<br>  optimizer.zero_grad()<br>  loss.backward()<br>  optimizer.step()<br><br>  if (epoch + 1) % 100 == 0:<br>    print(f&quot;Epoch [{epoch+1}/{num_epochs}], Loss: {loss.item():.4f}&quot;)<br><br>#inference and visualization<br><br># Test the trained model<br>with torch.no_grad():<br>    predicted = model(x_tensor)<br><br># Plot the original function and the learned function<br>plt.figure(figsize=(10, 6))<br>plt.scatter(x, y, color=&#39;blue&#39;, label=&#39;Original Function&#39;)<br>plt.plot(x, predicted.numpy(), color=&#39;red&#39;, label=&#39;Learned Function&#39;)<br>plt.title(&quot;Original Function vs. Learned Function&quot;)<br>plt.xlabel(&quot;x&quot;)<br>plt.ylabel(&quot;y&quot;)<br>plt.legend()<br>plt.grid(True)<br>plt.show()</pre><p>This code achieves a minimum loss of 0.2425. Figure 2 shows the predicted outputs superimposed on the training data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/844/1*H_UxXM1qHp457lC1maBHtQ.png" /><figcaption>Figure 2. The outputs of the neural network follow a sine wave like trendline.</figcaption></figure><p>As we can observe, however, the performance of the neural network is not optimal due to the lack of smoothness in the produced curve. This simple exercise serves as an indicator that while deep learning is generally a good approach to solve a problem, legacy machine learning techniques such as polynomial regression or Gaussian processes (a Bayesian method) might provide a better alternative in terms of accuracy and efficiency for this specific task.</p><h4>Conclusion</h4><p>In conclusion, in this article, we implemented a simple neural network to approximate a sine function. A synthetic dataset was generated according to the Equation 1. As shown in Figure 2, the model is able to capture the general trend of the training data; however, the lack of smoothness in the predicted curve indicates suboptimal learning. This exercise emphasizes the importance of carefully selecting the appropriate machine learning approach for a particular problem. While deep learning is a powerful and versatile technique, it may not always be the most suitable choice, especially for tasks involving modeling smooth functions or when computational efficiency is a critical factor In a future article, we will revisit the same problem using a Gaussian process regression approach, which is a Bayesian non-parametric method often well-suited for modeling continuous functions and providing uncertainty estimates.</p><p><strong><em>Code Availability</em></strong></p><p><a href="https://github.com/espitia01/MediumPosts/blob/main/ffnn_sinefunction.ipynb">MediumPosts/ffnn_sinefunction.ipynb at main · espitia01/MediumPosts</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=167d8492be84" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Accelerating Materials Discovery with Deep Learning using PyTorch: Band — gap Prediction]]></title>
            <link>https://blog.stackademic.com/accelerating-materials-discovery-with-deep-learning-using-pytorch-band-gap-prediction-d84f7c158be1?source=rss-2fc54db6b4c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/d84f7c158be1</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[computational-physics]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[material-science]]></category>
            <category><![CDATA[pytorch]]></category>
            <dc:creator><![CDATA[Giovanny Espitia]]></dc:creator>
            <pubDate>Tue, 21 May 2024 20:15:22 GMT</pubDate>
            <atom:updated>2024-05-22T00:54:04.213Z</atom:updated>
            <content:encoded><![CDATA[<h3>Accelerating Materials Discovery with Deep Learning Using PyTorch: Band — gap Prediction</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*0ix7BsHQ9BSLzY9_KzEzUw.png" /></figure><h4>Introduction</h4><p>The use of deep learning in science began gaining momentum at the end of the last decade due to advances in the field, such as the transformer architecture [3] and convolutional neural networks [5]. These advancements enabled breakthroughs such as predicting the manner in which proteins will fold using AlphaFold [4], cancer detection using computer vision [7], and prediction of chaotic systems such as the weather using models like FourCastNet [1]. Recently, researchers have begun employing deep learning for materials discovery [2], high-throughput screening, and as a complement to ab initio methods such as density functional theory (DFT) [6]. In this article, we scratch the surface of this by implementing a feedforward neural network to predict the band gap of materials. To train the network, we make use of the Materials Project database. We focus on the band gap, as it is an important property that determines macroscopic features such as the type of material (conductor, insulator, semiconductor) and thus its potential for various applications in industry. In future articles, we will present more complex projects, such as mapping spectral data to material properties and compositions or using deep learning as a function approximator for the exchange and correlation potential in DFT.</p><h4>Material Band — gap Theory</h4><p>The band — gap of a material is the range of energy values where no electronic states exist. Often, the band — gap also refers to the energy difference between the top of the valence band and the bottom of the conduction band. This phenomenon is also interpreted as the amount of energy required to promote an electron from the valence to the conduction band. In metals, these two bands often are indistinguishable ( &lt; 0.1 eV), thus resulting in a “sea of electrons”. In semiconductors however, the range of values is typically from 0.5 eV to 3 eV. Insulators on the other hand, have a bandgap of more than 4 eV. It is important to note that the bandgap of a semiconductor is dependent on temperature. In general, an increase in temperature results in a smaller band — gap. This is due to an increase in interatomic spacing as a result of more energetic atomic vibrations in the lattice. In 1967, Y.P. Varshni proposed an empirical relationship that gave the relationship of the semiconductor band — gap energy as a function of temperature.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/202/0*EWVgb4535CtmXg2U.png" /><figcaption>Equation 1.</figcaption></figure><p>In Equation 1, alpha, beta, and the energy at absolute zero are external input parameters. The following table shows band — gap energies of common materials:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/615/1*5ob3A9BEPrqXayC2eIx2aQ.png" /><figcaption>Table 1. The wavelength shown corresponds to the wavelength of the emitted photon after a transition from excited to ground state.</figcaption></figure><p>The following plot depicts the band — gap energy of other semiconducting materials.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/776/1*iYEYAEflMoE_AE-QNeLmzw.png" /><figcaption>Figure 1. The band — gap energy of semiconducting materials decreases as a the temperature increases.</figcaption></figure><h4><em>Materials Project Database</em></h4><p>The Materials Project database is maintained by a multi-institutional effort with the goal of computing the properties of all inorganic materials using ab initio methods such as DFT. Projects such as these are important as they allow researchers to focus on materials that show desired properties and thus accelerate the pace of materials discovery. By allowing researchers to focus, we are referring to further computational analysis to compute properties that are not well approximated with DFT, such as the potential for superconductivity, as well as the physical synthesis of the material.</p><h3>Implementing a Neural Net for Material Band — gap Prediction</h3><p>In this section, we implement the material band gap predictor. First, we prepare a dataset using the Materials Project API. The dataset will consist of a series of features such as the mean atomic number, the lattice parameters, the lattice angles, and the average distance between atoms in their corresponding crystal structures. Second, we implement a simple feedforward neural network (FFNN) with a single hidden layers and train it using the Adam optimizer with a mean squared error (L2) loss function. Finally, we perform inference on unseen materials and visualize the results.</p><h4>Preparing the Descriptors and Dataset</h4><p>The performance of a model is only as good as the data used to train it. In this project, our goal is to build a band gap predictor, as this quantity requires extensive computational resources when using ab initio methods. For this reason, the selected features are easily measurable in the laboratory.</p><p><em>Importing dependencies</em></p><pre>import numpy as np<br>import matplotlib.pyplot as plt<br>import pandas as pd<br>from sklearn.preprocessing import StandardScalar <br>from sklearn.model_selection import train_test_split<br>from pymatgen.io.cif import CifParser<br>from urllib.request import urlopen<br>from pymatgen.ext.matproj import MPRester<br>from pymatgen.ext.matproj import MPRestError<br>from sklearn.metrics import mean_squared_error, r2_score</pre><p>Next, we must create an MPRester object. In order to do so, one must create an account with the materials project and obtain the API key. In this article.</p><pre>m = MPRester(&quot;YOUR API KEY GOES HERE&quot;)</pre><p>To create our dataset, we must query the dataset. In this article, we will focus on materials with a composition of materials that correspond to a formula of the type “ABC3”. Some materials with this stoichiometry include perovskites and anti-perovskites.</p><pre>results = m.materials.summary.search(<br>    formula=&quot;ABC3&quot;,<br>    fields=[&quot;structure&quot;, &quot;band_gap&quot;]<br>)</pre><p>As we can see, the .search method has two parameters. Namely, the formula as well as the material fields. In this tutorial, we are interested in the structure of the material as well as the band — gap. In the following code snippet, we iterate through the results object, store the different features of the structure on lists, and create a pandas data frame using the latter.</p><pre>mean_atomic_numbers = []<br>max_atomic_numbers = []<br>min_atomic_numbers = []<br>std_atomic_numbers = []<br>a_parameters = []<br>b_parameters = []<br>c_parameters = []<br>alpha_parameters = []<br>beta_parameters = []<br>gamma_parameters = []<br>mean_distance_matrix = []<br>max_distance_matrix = []<br>min_distance_matrix = []<br>std_distance_matrix = []<br>band_gaps = []<br><br>for r in results:<br>    bg = r.band_gap<br>    if bg &gt; 1 and bg &lt; 6:<br>      structure = r.structure<br><br>      mean_atomic_numbers += [np.mean(structure.atomic_numbers)]<br>      max_atomic_numbers += [np.max(structure.atomic_numbers)]<br>      min_atomic_numbers += [np.min(structure.atomic_numbers)]<br>      std_atomic_numbers += [np.std(structure.atomic_numbers)]<br><br>      # Lattice parameters:<br>      a_parameters += [structure.lattice.abc[0]]<br>      b_parameters += [structure.lattice.abc[1]]<br>      c_parameters += [structure.lattice.abc[2]]<br>      alpha_parameters += [structure.lattice.angles[0]]<br>      beta_parameters += [structure.lattice.angles[1]]<br>      gamma_parameters += [structure.lattice.angles[2]]<br><br>      mean_distance_matrix += [np.mean(structure.distance_matrix)]<br>      max_distance_matrix += [np.max(structure.distance_matrix)]<br>      min_distance_matrix += [np.min(structure.distance_matrix)]<br>      std_distance_matrix += [np.std(structure.distance_matrix)]<br><br>      band_gaps += [bg]<br><br>dataset_df = pd.DataFrame({&quot;mean_atomic_numbers&quot;: mean_atomic_numbers,<br>                           &quot;max_atomic_numbers&quot;: max_atomic_numbers,<br>                           &quot;min_atomic_numbers&quot;: min_atomic_numbers,<br>                           &quot;std_atomic_numbers&quot;: std_atomic_numbers,<br>                           &quot;a_parameters&quot;: a_parameters,<br>                           &quot;b_parameters&quot;: b_parameters,<br>                           &quot;c_parameters&quot;: c_parameters,<br>                           &quot;alpha_parameters&quot;: alpha_parameters,<br>                           &quot;beta_parameters&quot;: beta_parameters,<br>                           &quot;gamma_parameters&quot;: gamma_parameters,<br>                           &quot;mean_distance_matrix&quot;: mean_distance_matrix,<br>                           &quot;max_distance_matrix&quot;: max_distance_matrix,<br>                           &quot;min_distance_matrix&quot;: min_distance_matrix,<br>                           &quot;std_distance_matrix&quot;: std_distance_matrix<br>                           })</pre><p><em>Visualizing the data</em></p><p>To gain a better understanding of the data, we plot it. Specifically, we are interested in the distribution of the selected features as well as the target quantity (the band — gap).</p><pre>sns.set(style=&quot;whitegrid&quot;)<br>sns.set_palette(&quot;viridis&quot;)<br><br>fig, axs = plt.subplots(2, 2, figsize=(16, 10))<br><br>sns.histplot(data=dataset_df, x=&quot;mean_atomic_numbers&quot;, kde=True, ax=axs[0, 0])<br>axs[0, 0].set_title(&quot;Distribution of Mean Atomic Numbers&quot;)<br><br>sns.histplot(data=dataset_df, x=&quot;max_atomic_numbers&quot;, kde=True, ax=axs[0, 1])<br>axs[0, 1].set_title(&quot;Distribution of Max Atomic Numbers&quot;)<br><br>sns.histplot(data=dataset_df, x=&quot;std_atomic_numbers&quot;, kde=True, ax=axs[1, 0])<br>axs[1, 0].set_title(&quot;Distribution of Std Atomic Numbers&quot;)<br><br>sns.histplot(data=dataset_df, x=&quot;band_gaps&quot;, kde=True, ax=axs[1, 1])<br>axs[1, 1].set_title(&quot;Distribution of Band Gaps&quot;)<br><br>plt.tight_layout()<br><br>plt.show()</pre><p>This results in the following figure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CYe4_mh8VyKhBma4hjMV7Q.png" /><figcaption>Figure 2. Distribution of features. As we can see, most materials in our dataset are semiconductors with a few observations of insulators.</figcaption></figure><h4>Neural Network Architecture</h4><p>In this project, we use a simple FFNN in order to ensure that the reader can run the model without the need for external compute. It is left as an exercise to the reader to improve upon the results of the presented architecture. The neural network consists of a single hidden layer with a hidden size of 64. The input layer has a size equal to the number of input features (14). The outputs of the hidden neurons are passed through the ReLU nonlinear activation function.</p><h4>Implementation</h4><p>Before implementing the neural network, we must first normalize our input features, create the train — test split, and convert the latter two into tensors. For this project, the tensor deep learning framework of choice is PyTorch.</p><pre>scaler = StandardScaler().fit(dataset_df)<br>scaled_dataset_df = scaler.transform(dataset_df)<br><br>X_train_scaled, X_test_scaled, y_train, y_test = train_test_split(<br>    scaled_dataset_df, band_gaps, test_size=.25, random_state=None)</pre><p><em>Importing the PyTorch dependencies</em></p><pre>import torch<br>import torch.nn as nn<br>import torch.optim as optim<br><br>X_train_scaled = torch.tensor(X_train_scaled, dtype=torch.float32)<br>X_test_scaled = torch.tensor(X_test_scaled, dtype=torch.float32)<br>y_train = torch.tensor(y_train, dtype=torch.float32).view(-1, 1)<br>y_test = torch.tensor(y_test, dtype=torch.float32).view(-1, 1)</pre><p><em>Implementing the model</em></p><pre>class Net(nn.Module):<br>    def __init__(self, input_size, hidden_size):<br>        super(Net, self).__init__()<br>        self.hidden = nn.Linear(input_size, hidden_size)<br>        self.output = nn.Linear(hidden_size, 1)<br><br>    def forward(self, x):<br>        x = torch.relu(self.hidden(x))<br>        x = self.output(x)<br>        return x</pre><p><em>Defining the hyper — parameters, loss function, optimizer, and training loop</em></p><pre>class Net(nn.Module):<br>    def __init__(self, input_size, hidden_size):<br>        super(Net, self).__init__()<br>        self.hidden = nn.Linear(input_size, hidden_size)<br>        self.output = nn.Linear(hidden_size, 1)<br><br>    def forward(self, x):<br>        x = torch.relu(self.hidden(x))<br>        x = self.output(x)<br>        return x<br><br>input_size = X_train_scaled.shape[1]<br>hidden_size = 64<br>learning_rate = 0.001<br>num_epochs = 200<br><br>net = Net(input_size, hidden_size)<br><br>criterion = nn.MSELoss()<br>optimizer = optim.Adam(net.parameters(), lr=learning_rate)<br><br>train_losses = []<br>for epoch in range(num_epochs):<br>    # Forward pass<br>    outputs = net(X_train_scaled)<br>    loss = criterion(outputs, y_train)<br>    <br>    # Backward pass and optimization<br>    optimizer.zero_grad()<br>    loss.backward()<br>    optimizer.step()<br>    <br>    train_losses.append(loss.item())<br>    <br>    if (epoch + 1) % 10 == 0:<br>        print(f&quot;Epoch [{epoch+1}/{num_epochs}], Loss: {loss.item():.4f}&quot;)</pre><p>As stated in the code, the model is trained using the Adam optimizer with L2 as the loss criterion. Moreover, the model is trained for 200 epochs using a learning rate of 0.1 (this learning rate was found to have the best results.). After training the model, we compute the loss in the test set and also visualize the loss as a function of epoch. A negative exponential curve is indicative of learning.</p><pre>with torch.no_grad():<br>    outputs = net(X_test_scaled)<br>    test_loss = criterion(outputs, y_test)<br>    print(f&quot;Test Loss: {test_loss.item():.4f}&quot;)<br><br>plt.figure(figsize=(8, 6))<br>plt.plot(range(1, num_epochs+1), train_losses)<br>plt.xlabel(&quot;Epoch&quot;)<br>plt.ylabel(&quot;Training Loss&quot;)<br>plt.title(&quot;Training Loss vs. Epoch&quot;)<br>plt.grid(True)<br>plt.show()</pre><p>This results in a test loss of 0.0019 and the following learning curve:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/686/1*aCnoorTZGr0OqNqQb0ATUA.png" /><figcaption>Figure 3. Training loss</figcaption></figure><p><em>Conducting inference and evaluating the model</em></p><p>To asses the performance of the model on the test data, we will make use of sklearn. Moreover, we will visualize the scatter plot of the predicted vs actual band — gap, plot the residuals vs actual band — gap, as well as calculate the accuracy of the model within an acceptable error threshold of 0.10 eV.</p><pre>with torch.no_grad():<br>    y_pred = net(X_test_scaled)<br><br>y_pred_np = y_pred.numpy().flatten()<br>y_test_np = y_test.numpy().flatten()<br><br>mse = np.mean((y_pred_np - y_test_np) ** 2)<br>print(f&quot;Mean Squared Error (MSE): {mse:.4f}&quot;)<br><br>mae = np.mean(np.abs(y_pred_np - y_test_np))<br>print(f&quot;Mean Absolute Error (MAE): {mae:.4f}&quot;)<br><br>ss_res = np.sum((y_test_np - y_pred_np) ** 2)<br>ss_tot = np.sum((y_test_np - np.mean(y_test_np)) ** 2)<br>r2 = 1 - (ss_res / ss_tot)<br>print(f&quot;R-squared (R2) Score: {r2:.4f}&quot;)<br><br>actual_avg = np.mean(y_test_np)<br>actual_std = np.std(y_test_np)<br>print(f&quot;Actual Average: {actual_avg:.4f}&quot;)<br>print(f&quot;Actual Standard Deviation: {actual_std:.4f}&quot;)<br><br>plt.figure(figsize=(8, 6))<br>plt.scatter(y_test_np, y_pred_np, color=&#39;blue&#39;, alpha=0.5)<br>plt.plot([y_test_np.min(), y_test_np.max()], [y_test_np.min(), y_test_np.max()], color=&#39;red&#39;, linestyle=&#39;--&#39;, linewidth=2)<br>plt.xlabel(&#39;Actual Band Gap&#39;)<br>plt.ylabel(&#39;Predicted Band Gap&#39;)<br>plt.title(&#39;Predicted vs. Actual Band Gap&#39;)<br>plt.grid(True)<br>plt.show()<br><br>residuals = y_pred_np - y_test_np<br>plt.figure(figsize=(8, 6))<br>plt.scatter(y_test_np, residuals, color=&#39;blue&#39;, alpha=0.5)<br>plt.axhline(y=0, color=&#39;red&#39;, linestyle=&#39;--&#39;, linewidth=2)<br>plt.xlabel(&#39;Actual Band Gap&#39;)<br>plt.ylabel(&#39;Residuals&#39;)<br>plt.title(&#39;Residuals vs. Actual Band Gap&#39;)<br>plt.grid(True)<br>plt.show()<br></pre><p>This resulted in a mean squared error (MSE) of 0.0019 and mean absolute error (MAE) of 0.0285 indicating that, on average, the model’s predictions deviate from the actual band gap values by a small margin. The R-squared (R2) score of 0.9987 suggests that the model explains 99.87% of the variance in the band gap values, indicating a strong predictive relationship between the features and the target variable. Moreover, the plot in Figure 5. suggests that the model appears to have a good fit and consistent performance across the range of band gap values. This is due to the residuals being mostly centered around zero, and the lack of significant patterns or biases in the plot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/686/1*6La7G3Bc50nFlGA2tK1OKw.png" /><figcaption>Figure 4. The linear relationship between actual and predicted values suggest good model performance on the test set.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/713/1*HA3O3r3hZu1_lVZ0JvWeIQ.png" /><figcaption>Figure 5. The random scatter of residuals around the zero line, along with the high R-squared value and low mean absolute error, indicates a well-fitting model with consistent performance across the range of band gap values.</figcaption></figure><p>Last, we obtained an accuracy of 97.5% assuming an acceptable error of 0.10 eV between the predicted and actual values. To supplement this project, the reader is encouraged to compute the accuracy utilizing a bigger dataset or use techniques should as k — cross validation to minimize model overfitting. Overall, the performance of the model was very good considering how simple the model architecture is.</p><h4>Conclusion</h4><p>In this article, we make use of deep learning to build a simple feedforward neural network (FFNN) to serve as a material band gap predictor using material structure predictors such as the mean atomic number and mean distance between the material’s constituents within the lattice. Moreover, the theory and importance of band gap are provided, as well as a detailed implementation for the dataset creation and exploration, model architecture, training, inference, and evaluation. We encourage the reader to explore other articles where we show how to use deep learning for other tasks in the field, such as enhancing ab initio methods or serving as a screening tool using combinatorial methods to improve the efficiency of material discovery. It is also left up to the reader as an exercise to improve upon the results shown in this article by trying a more sophisticated architecture, creating a more comprehensive dataset, and considering more material compositions beyond the one considered here.</p><p><strong><em>Code Availability</em></strong></p><p>To try the model yourself, please checkout the notebook hosted in the following link:</p><p><a href="https://github.com/espitia01/MediumPosts/blob/main/bandgap_neuralnet.ipynb">MediumPosts/bandgap_neuralnet.ipynb at main · espitia01/MediumPosts</a></p><p><strong><em>References</em></strong></p><ol><li>Bi, K., Xie, L., Zhang, H., Chen, X., Gu, X., &amp; Tian, Q. (2023). Accurate medium-range global weather forecasting with 3D neural networks. <em>Nature</em>, <em>619</em>(7970), 533–538. <a href="https://doi.org/10.1038/s41586-023-06185-3">https://doi.org/10.1038/s41586-023-06185-3</a></li><li>2. Goodall, R. E. A., &amp; Lee, A. A. (2020). Predicting materials properties without crystal structure: deep representation learning from stoichiometry. <em>Nature Communications</em>, <em>11</em>(1). <a href="https://doi.org/10.1038/s41467-020-19964-7">https://doi.org/10.1038/s41467-020-19964-7</a></li><li>3. Hu, R., &amp; Singh, A. (2021). Transformer is All You Need: Multimodal Multitask Learning with a Unified Transformer. <em>arXiv (Cornell University)</em>. <a href="https://arxiv.org/abs/2102.10772v1">https://arxiv.org/abs/2102.10772v1</a></li><li>Jumper, J., Evans, R., Pritzel, A., Green, T., Figurnov, M., Ronneberger, O., Tunyasuvunakool, K., Bates, R., Žídek, A., Potapenko, A., Bridgland, A., Meyer, C., Kohl, S. a. A., Ballard, A. J., Cowie, A., Romera-Paredes, B., Nikolov, S., Jain, R., Adler, J., . . . Hassabis, D. (2021). Highly accurate protein structure prediction with AlphaFold. <em>Nature</em>, <em>596</em>(7873), 583–589. <a href="https://doi.org/10.1038/s41586-021-03819-2">https://doi.org/10.1038/s41586-021-03819-2</a></li><li>Krizhevsky, A., Sutskever, I., &amp; Hinton, G. E. (2012). ImageNet Classification with Deep Convolutional Neural Networks. <em>Neural Information Processing Systems</em>, <em>25</em>, 1097–1105. <a href="http://books.nips.cc/papers/files/nips25/NIPS2012_0534.pdf">http://books.nips.cc/papers/files/nips25/NIPS2012_0534.pdf</a></li><li>Li, H., Wang, Z., Zou, N., Ye, M., Xu, R., Gong, X., Duan, W., &amp; Xu, Y. (2022). Deep-learning density functional theory Hamiltonian for efficient ab initio electronic-structure calculation. <em>Nature Computational Science</em>, <em>2</em>(6), 367–377. <a href="https://doi.org/10.1038/s43588-022-00265-6">https://doi.org/10.1038/s43588-022-00265-6</a></li><li>Sathykumar, K., Munoz, M., Singh, J., Hussain, N., &amp; Babu, B. A. (2020). Automated lung cancer detection Using Artificial intelligence (AI) Deep Convolutional Neural Networks: A Narrative Literature review. <em>Curēus</em>. <a href="https://doi.org/10.7759/cureus.10017">https://doi.org/10.7759/cureus.10017</a></li></ol><h3>Stackademic 🎓</h3><p>Thank you for reading until the end. Before you go:</p><ul><li>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq"><strong>X</strong></a><strong> | </strong><a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a><strong> | </strong><a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a><strong> | </strong><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a></li><li>Visit our other platforms: <a href="https://plainenglish.io/"><strong>In Plain English</strong></a><strong> | </strong><a href="https://cofeed.app/"><strong>CoFeed</strong></a><strong> | </strong><a href="https://venturemagazine.net/"><strong>Venture</strong></a><strong> | </strong><a href="https://blog.cubed.run/"><strong>Cubed</strong></a></li><li>Tired of blogging platforms that force you to deal with algorithmic content? Try <a href="https://differ.blog/"><strong>Differ</strong></a></li><li>More content at <a href="https://stackademic.com/"><strong>Stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d84f7c158be1" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/accelerating-materials-discovery-with-deep-learning-using-pytorch-band-gap-prediction-d84f7c158be1">Accelerating Materials Discovery with Deep Learning using PyTorch: Band — gap Prediction</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering RNNs for Stock Prediction: TensorFlow & Python Tutorial]]></title>
            <link>https://blog.stackademic.com/mastering-rnns-for-stock-prediction-tensorflow-python-tutorial-9cfaa6c0d328?source=rss-2fc54db6b4c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/9cfaa6c0d328</guid>
            <category><![CDATA[finance]]></category>
            <category><![CDATA[stocks]]></category>
            <category><![CDATA[recurrent-neural-network]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Giovanny Espitia]]></dc:creator>
            <pubDate>Tue, 09 Jan 2024 06:51:52 GMT</pubDate>
            <atom:updated>2024-01-11T00:56:08.512Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i52ii_KP9KXApPT80Zmetg.png" /></figure><h4>Introduction</h4><p>In this article, the focus is on Recurrent Neural Networks (RNNs), a type of neural network architecture utilized for datasets with time-dependent observations. The application of RNNs is notable in time series forecasting. The article starts with an explanation of the fundamental architecture of RNNs. Following this, there is a detailed walkthrough of an implementation of a basic RNN, trained using the SBUX historical data set. For a video guide on the implementation, refer to the provided URL.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FGpZww3R7j_8%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DGpZww3R7j_8&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FGpZww3R7j_8%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/04fcdc09a5480df6e8cfd45eb9231e83/href">https://medium.com/media/04fcdc09a5480df6e8cfd45eb9231e83/href</a></iframe><h4>Architecture Overview</h4><p>This overview is based on [1]. Traditional multilayer perceptron neural networks operate under the premise that inputs are independent. However, this premise does not hold for various types of sequence data. Instances such as words in a sentence, musical notes in a composition, stock prices over time, or molecules in a compound are sequence examples where elements are dependent on their predecessors. RNN cells address this dependency through a hidden state, effectively acting as memory, encapsulating the information observed up to that point. The hidden state’s value at any given time is determined by the previous time step’s hidden state and the current time step’s input. This can be described by:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/152/0*tL6Zlw6Fnfp66qHH.png" /></figure><p>Here, h(t)​ and h(t-1)​ represent the hidden state values at times <em>t</em> and <em>t</em>−1, respectively, while X(<em>t)</em>​ denotes the input value at time <em>t</em>. This equation is recursive. This recursive nature allows RNNs to encode information from sequences of arbitrary length.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/561/0*21HgBIml6MKvCGez.png" /></figure><p>Figure 1(a) graphically depicts the RNN cell. At time <em>t</em>, the cell receives input <em>x</em>(<em>t</em>) and generates output <em>y</em>(<em>t</em>). A portion of <em>y</em>(<em>t</em>), captured by the hidden state <em>h(t)</em>​, is recycled into the cell for subsequent use at time <em>t + 1. </em>In traditional neural networks, learned parameters are stored in weight matrices. Similarly, in RNNs, parameters are defined by three weight matrices: <em>U</em> for input weights, <em>V</em> for output weights, and <em>W</em> for hidden state weights. Figure 1(b) presents the RNN in an “unrolled view,” meaning the network is extended to show the entire sequence. This particular network, with three time steps, is tailored for processing sequences of three elements. It’s important to note that the weight matrices U, V, and W, mentioned earlier, are reused across each time step. This reuse, applying the same operation to varying inputs at each step, significantly reduces the number of parameters the RNN must learn The RNN’s operation can also be framed as a computation graph using equations. The internal state of the RNN at time <em>t</em> is captured by the hidden vector <em>h</em>(<em>t</em>), which is calculated as the sum of the weight matrix <em>W</em> and the previous time step’s hidden state <em>h(t</em>−1​_, along with the product of the weight matrix <em>U</em> and the input <em>x(t)</em>​ at time <em>t</em>, all passed through a tanh activation function. The preference for tanh over other functions like sigmoid is due to its greater efficiency in learning, which is beneficial in addressing the vanishing gradient problem, a topic explored later in the chapter. The output vector y(<em>t</em>​) at time <em>t</em> is computed as the product of the weight matrix <em>V</em> and the hidden state <em>h(t)</em>​. This product is then processed through a softmax activation function. The outcome of this operation is a vector representing a set of output probabilities.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/239/0*P1mXWeWk_v8h7COa.png" /></figure><h4>Back Propagation Through Time (BPTT)</h4><p>Similar to conventional neural networks, training RNNs also requires backpropagation of gradients. However, a distinctive aspect in RNNs is the shared weights across all time steps, meaning the gradient at each output is influenced not just by the current but also by previous time steps. This method is known as backpropagation through time (BPTT). Due to the shared nature of the weights <em>U</em>, <em>V</em>, and <em>W</em> in RNNs, it’s necessary to aggregate the gradients from different time steps during BPTT. This aggregation is a fundamental distinction between traditional backpropagation and BPTT. Take, for example, an RNN with five time steps as shown in Figure 2. In the forward pass, the network generates predictions <em>y(</em>​<em>t)</em>​ at each time <em>t</em>, which are then compared to the actual label <em>y(t)</em>​ to calculate a loss <em>L(t)</em>​. During backpropagation, indicated by dotted lines, the gradients of the loss with respect to the weights <em>U</em>, <em>V</em>, and <em>W</em> are computed at each time step. The parameters are then updated based on the sum of these gradients.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/765/0*Jv4YlRpkEiZRBW_j.png" /></figure><p>The equation displaying the gradient of the loss concerning the weight <em>W</em> is particularly important, as it highlights the root of what’s known as the vanishing and exploding gradient problem. This issue arises when the gradients of the loss tend towards zero or grow excessively large, posing challenges in training the network effectively. To comprehend the underlying cause, recall the equation of the SimpleRNN previously discussed; the hidden state <em>h(t)</em>​ relies on <em>h(t</em>−1)​, which is dependent on <em>h(t</em>−2​), and the pattern continues backwards.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/134/0*xWfpmd8oavAhwP4j.png" /></figure><p>Now, let’s examine the gradient at timestep <em>t</em>=3. According to the chain rule, the gradient of the loss with respect to <em>W</em> can be broken down into a product of three sub-gradients. The gradient of the hidden state <em>h(</em>2)​ with respect to <em>W</em> can be further divided into the sum of gradients of each hidden state relative to the one before it. Lastly, each gradient of a hidden state in relation to its predecessor can be further dissected into the product of gradients of the current hidden state against the previous hidden state.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/295/0*AvHY6GuUgERkdYQI.png" /></figure><p>Similar calculations are carried out to determine the gradient of the other losses, <em>L(</em>0)​ through <em>L(</em>4)​, with respect to <em>W</em>. These gradients are then aggregated to update <em>W</em>. In other articles, we will explore variants of the architecture explained here. Two useful ones being the Long Short Term Memory and Gated Recurrent Units variants that correct the issue of vanishing and exploding gradients.</p><h4>Implementing an RNN to predict the price of SBUX</h4><p>In this implementation, we will employ python and tensorflow. The latter being a tensor framework with a keras API for rapid implementation of neural networks. In this article, we will not delve into the mechanics of tensorflow. For an explanation please refer to the appropriate article in my profile or consult with the tensorflow documentation.</p><ol><li><strong><em>Import Dependencies</em></strong></li></ol><pre>import numpy as np<br>import pandas as pd<br>import matplotlib.pyplot as plt<br>from sklearn.preprocessing import MinMaxScaler<br>from keras.models import Sequential<br>from keras.layers import Dense<br>from keras.layers import SimpleRNN<br>from keras.layers import Dropout<br>import tensorflow as tf</pre><p>2. <strong><em>Reference and Clean the Data</em></strong></p><p>To download the dataset, visit the github repository referenced at the end of the article. Alternatively, visit Yahoo finance.</p><pre>data = pd.read_csv(&quot;/content/HistoricalData_1704511714407.csv&quot;)<br>data = data.iloc[::-1]<br>data = data.reset_index(drop=True)<br>length_data = len(data)<br>split_ratio = 0.7           # %70 train + %30 validation<br>length_train = round(length_data * split_ratio)<br>length_validation = length_data - length_train<br>print(&quot;Data length :&quot;, length_data)<br>print(&quot;Train data length :&quot;, length_train)<br>print(&quot;Validation data lenth :&quot;, length_validation)<br>train_data = data[:length_train].iloc[:,:2]<br>train_data[&#39;Date&#39;] = pd.to_datetime(train_data[&#39;Date&#39;])  # converting to date time object<br>validation_data = data[length_train:].iloc[:,:2]<br>validation_data[&#39;Date&#39;] = pd.to_datetime(validation_data[&#39;Date&#39;]) <br><br>dataset_train = train_data[&quot;Close/Last&quot;]<br>dataset_train = np.expand_dims(dataset_train, axis=1)<br><br>scaler = MinMaxScaler(feature_range = (0,1))<br>dataset_train_scaled = scaler.fit_transform(dataset_train)<br>dataset_train_scaled.shape<br><br>plt.subplots(figsize = (15,6))<br>plt.plot(dataset_train_scaled)<br>plt.xlabel(&quot;Days as 1st, 2nd, 3rd..&quot;)<br>plt.ylabel(&quot;Open Price&quot;)<br>plt.show()<br><br>X_train = []<br>y_train = []<br><br>time_step = 50<br><br>for i in range(time_step, length_train):<br>    X_train.append(dataset_train_scaled[i-time_step:i,0])<br>    y_train.append(dataset_train_scaled[i,0])<br><br>X_train, y_train = np.array(X_train), np.array(y_train)</pre><p>In this code block, we read the dataset using pandas. After that, we format it so that the last row become the first and vice-versa (we want our dataset to begin with the oldest observation). We then define our train/test percentages. Namely, 70% for training and the rest for testing. In this project, the only two features of our dataset that we are considering include the date as well the closing price. The following plot shows our training data:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2ZR60VP8R1eSskohy8IDag.png" /></figure><p>To improve the performance of our model, we also scale our data using a method from scikit learn. The method maps our targets into a range between 0 and 1.</p><p>3. <strong><em>Defining Model</em></strong></p><p>In this implementation we use the Sequential model from keras. The layers include RNN layers with varying number of neurons and hyperbolic tangent as the nonlinear activation function. After each layer, we add a Dropout as well to prevent overfitting. The last layer in our model is a fully connected layer.</p><pre># initializing the RNN<br>regressor = Sequential()<br><br># adding first RNN layer and dropout regulatization<br>regressor.add(<br>    SimpleRNN(units = 50,<br>              activation = &quot;tanh&quot;,<br>              return_sequences = True,<br>              input_shape = (X_train.shape[1],1))<br>             )<br><br>regressor.add(<br>    Dropout(0.2)<br>             )<br><br><br># adding second RNN layer and dropout regulatization<br><br>regressor.add(<br>    SimpleRNN(units = 50,<br>              activation = &quot;tanh&quot;,<br>              return_sequences = True)<br>             )<br><br>regressor.add(<br>    Dropout(0.2)<br>             )<br><br># adding third RNN layer and dropout regulatization<br><br>regressor.add(<br>    SimpleRNN(units = 50,<br>              activation = &quot;tanh&quot;,<br>              return_sequences = True)<br>             )<br><br>regressor.add(<br>    Dropout(0.2)<br>             )<br><br># adding fourth RNN layer and dropout regulatization<br><br>regressor.add(<br>    SimpleRNN(units = 50)<br>             )<br><br>regressor.add(<br>    Dropout(0.2)<br>             )<br><br># adding the output layer<br>regressor.add(Dense(units = 1))</pre><p>The following Figure depicts the architecture shown above:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/281/1*ziGQLeI68aY1OY1uubGOog.png" /></figure><p>4. <strong><em>Compiling and Fitting the Model</em></strong></p><p>To conduct the training, we select the Adam optimizer as our gradient descent method of choice. The associated loss function is chosen to be the L2 loss. To train our model, we conduct 50 epochs using a batch size of 32.</p><pre># compiling RNN<br>regressor.compile(<br>    optimizer = &quot;adam&quot;,<br>    loss = &quot;mean_squared_error&quot;,<br>    metrics = [&quot;accuracy&quot;])<br><br># fitting the RNN<br>history = regressor.fit(X_train, y_train, epochs = 50, batch_size = 32)</pre><p>After training, we have the following loss curve:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/855/1*ohiZgkGJQDu90nNtR40ROQ.png" /></figure><p>5. <strong><em>Testing our model using training data</em></strong></p><p>To evaluate the performance of our model, we examine the performance of the model using training data against the actual values.</p><pre>y_pred = regressor.predict(X_train)<br>y_pred = scaler.inverse_transform(y_pred)<br>y_train = scaler.inverse_transform(y_train)<br><br>plt.figure(figsize = (30,10))<br>plt.plot(y_pred, color = &quot;b&quot;, label = &quot;y_pred&quot; )<br>plt.plot(y_train, color = &quot;g&quot;, label = &quot;y_train&quot;)<br>plt.xlabel(&quot;Days&quot;)<br>plt.ylabel(&quot;Open price&quot;)<br>plt.title(&quot;Simple RNN model, Predictions with input X_train vs y_train&quot;)<br>plt.legend()<br>plt.show()</pre><p>This results in the following plot:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*beWrE4bw8sw3OVm7xCAD2Q.png" /></figure><p>6. <strong><em>Testing our model using unseen testing data</em></strong></p><pre>dataset_validation = validation_data[&quot;Close/Last&quot;].values # getting &quot;open&quot; column and converting to array<br>dataset_validation = np.reshape(dataset_validation, (-1,1))  # converting 1D to 2D array<br>scaled_dataset_validation =  scaler.fit_transform(dataset_validation)  # scaling open values to between 0 and 1<br>print(&quot;Shape of scaled validation dataset :&quot;,scaled_dataset_validation.shape)<br><br>X_test = []<br>y_test = []<br><br>for i in range(time_step, length_validation):<br>    X_test.append(scaled_dataset_validation[i-time_step:i,0])<br>    y_test.append(scaled_dataset_validation[i,0])<br><br>X_test, y_test = np.array(X_test), np.array(y_test)<br>X_test = np.reshape(X_test, (X_test.shape[0],X_test.shape[1],1))  # reshape to 3D array<br>y_test = np.reshape(y_test, (-1,1))<br><br>y_pred_of_test = regressor.predict(X_test)<br><br>y_pred_of_test = scaler.inverse_transform(y_pred_of_test)<br>print(&quot;Shape of y_pred_of_test :&quot;,y_pred_of_test.shape)<br><br># visualisation<br>plt.figure(figsize = (30,10))<br>plt.plot(y_pred_of_test, label = &quot;y_pred_of_test&quot;, c = &quot;orange&quot;)<br>plt.plot(scaler.inverse_transform(y_test), label = &quot;y_test&quot;, c = &quot;g&quot;)<br>plt.xlabel(&quot;Days&quot;)<br>plt.ylabel(&quot;Open price&quot;)<br>plt.title(&quot;Simple RNN model, Prediction with input X_test vs y_test&quot;)<br>plt.legend()<br>plt.show()</pre><p>This results in the following plot:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1jaHPQqSQONjoK9uufoqIA.png" /></figure><p>As we can see, the model is capable of following the general trend of the timeseries. However, it fails to capture the day to day stock price fluctuations. Perhaps this model would be useful for passive or growth investors but not for day traders. As a remark, we note that this model essentially takes in 50 observations to predict the next one. Joining the two figures results in:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gUjFTT9vIaAEVbveRgPYfQ.png" /></figure><p>7. <strong><em>Performance of our model</em></strong></p><p>Using scikit — learn, we compute the RMSE and accuracy of our model. The RMSE gives us an idea of how far the model predictions were in the same units as our data.</p><pre>from sklearn.metrics import mean_squared_error<br>rmse = mean_squared_error(scaler.inverse_transform(y_test), y_pred_of_test, squared=False)<br>def mean_absolute_percentage_error(actual, predicted):<br>    actual, predicted = np.array(actual), np.array(predicted)<br>    return np.mean(np.abs((actual - predicted) / actual)) * 100<br><br>mape = mean_absolute_percentage_error(scaler.inverse_transform(y_test), y_pred_of_test)</pre><p>Based on this, we determined that our model’s predictions are on average $2.65 dollars away from the actual values. Moreover, we estimated that our model has 97.90% ~ 98% accuracy.</p><h4>Summary</h4><p>This article provided an in-depth exploration of Recurrent Neural Networks (RNNs), emphasizing their application in processing time-dependent data, such as in time series forecasting. Key distinctions from traditional neural networks were highlighted, notably in handling sequential data and shared weights across time steps. Challenges like the vanishing and exploding gradient problem were addressed, underscoring the intricacies of training RNNs effectively. Practical implementation was illustrated through a case study using the SBUX historical dataset, employing Python and TensorFlow. This example not only showcased the theoretical aspects of RNNs but also demonstrated their practical applicability in predicting stock price trends, revealing both strengths and limitations. In summary, the article offered a comprehensive overview of RNNs, blending theory with practical application, and providing insights into their potential and challenges in real-world scenarios.</p><p><strong><em>Code Availability</em></strong></p><p><a href="https://github.com/espitia01/MediumPosts/blob/main/SBUX_predictor.ipynb">MediumPosts/SBUX_predictor.ipynb at main · espitia01/MediumPosts</a></p><p><strong><em>References</em></strong></p><ol><li>Atienza, R. (2020). <em>Advanced Deep Learning with TensorFlow 2 and Keras</em>. <a href="http://ofppt.scholarvox.com/catalog/book/88882283">http://ofppt.scholarvox.com/catalog/book/88882283</a></li></ol><h3>Stackademic</h3><p><em>Thank you for reading until the end. Before you go:</em></p><ul><li><em>Please consider </em><strong><em>clapping</em></strong><em> and </em><strong><em>following</em></strong><em> the writer! 👏</em></li><li><em>Follow us on </em><a href="https://twitter.com/stackademichq"><strong><em>Twitter(X)</em></strong></a><em>, </em><a href="https://www.linkedin.com/company/stackademic"><strong><em>LinkedIn</em></strong></a><em>, and </em><a href="https://www.youtube.com/c/stackademic"><strong><em>YouTube</em></strong></a><strong><em>.</em></strong></li><li><em>Visit </em><a href="http://stackademic.com/"><strong><em>Stackademic.com</em></strong></a><em> to find out more about how we are democratizing free programming education around the world.</em></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9cfaa6c0d328" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/mastering-rnns-for-stock-prediction-tensorflow-python-tutorial-9cfaa6c0d328">Mastering RNNs for Stock Prediction: TensorFlow &amp; Python Tutorial</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing Sentiment Analysis on X Data with DistilBERT and Huggingface: A Comprehensive Guide]]></title>
            <link>https://blog.stackademic.com/implementing-sentiment-analysis-on-x-data-with-distilbert-and-huggingface-a-comprehensive-guide-ea9c0679c92f?source=rss-2fc54db6b4c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/ea9c0679c92f</guid>
            <category><![CDATA[sentiment-analysis]]></category>
            <category><![CDATA[hugging-face-tutorials]]></category>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Giovanny Espitia]]></dc:creator>
            <pubDate>Wed, 03 Jan 2024 23:14:52 GMT</pubDate>
            <atom:updated>2024-01-12T01:57:24.073Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YYRW8N1JabIZeonS" /></figure><h3>Introduction</h3><p>In this article, we utilize the Transformers library from Huggingface to implement the DistilBERT model for sentiment analysis on X (Twitter) data. For detailed information on the transformer architecture and its implementation, refer to the related stories on my profile. The article starts with importing, exploring, and formatting the data for the model. It includes a section on tokenization. Finally, we fine-tune and test the model.</p><h4><strong>I. BERT and DistilBERT Model</strong></h4><p>Bidirectional Encoder Representations from Transformers (BERT) is a large language model (LLM) developed by Google in 2018 [2]. The standard BERT model has approximately 110 million weights. It is known for its effectiveness in natural language processing tasks and was trained on the Toronto Book Corpus and English Wikipedia. In this article, we will adapt this model for our specific requirements using DistilBERT, a lighter version with around 82 million parameters. Despite having fewer weights, DistilBERT maintains comparable effectiveness to BERT and allows for more efficient fine-tuning. Resource efficiency is crucial when working with large language models.</p><h4>II. Importing the Dataset</h4><p>The dataset for this project consists of X English messages. Unlike typical labeled datasets that categorize observations into positive or negative, this dataset includes six classes: anger, disgust, fear, joy, sadness, and surprise. The objective is to classify a given X post into the most appropriate emotion. Key libraries for this project are Huggingface transformers, datasets, and tokenizer. Confirm that these dependencies are installed on your system. We begin our implementation as follows:</p><pre>from datasets import load_dataset, Dataset<br><br>emotions = load_dataset(&#39;emotion&#39;)</pre><p>This snippet imports the dataset library as well as the <strong>load_dataset</strong> method. In our case, we note that the X messages dataset is named <em>emotion. </em>The <strong>load_dataset </strong>method returns an object whose datatype is dictionary. If we print the object, we obtain the following output:</p><pre>DatasetDict({<br>    train: Dataset({<br>        features: [&#39;text&#39;, &#39;label&#39;],<br>        num_rows: 16000<br>    })<br>    validation: Dataset({<br>        features: [&#39;text&#39;, &#39;label&#39;],<br>        num_rows: 2000<br>    })<br>    test: Dataset({<br>        features: [&#39;text&#39;, &#39;label&#39;],<br>        num_rows: 2000<br>    })<br>})</pre><p>As we can see, the <strong>DatasetDict</strong> dictionary has three elements. Namely, train, validation, and test. To isolate our training data, we can assign it to a new variable by referencing it through its key.</p><pre>training_ds = emotions[&#39;train&#39;]</pre><p>To obtain and print the first element in this subdataset, we do the following:</p><pre>training_ds[0]</pre><p><strong>Output:</strong></p><pre>{&#39;label&#39;: 0, &#39;text&#39;: &#39;i didnt feel humiliated&#39;}</pre><p>To access the features of our <strong>train_ds</strong> variable, we can do the following:</p><pre>print(training_ds.features)</pre><p><strong>Output:</strong></p><pre>{&#39;text&#39;: Value(dtype=&#39;string&#39;, id=None), &#39;label&#39;: ClassLabel(names=[&#39;sadness&#39;, &#39;joy&#39;, &#39;love&#39;, &#39;anger&#39;, &#39;fear&#39;, &#39;surprise&#39;], id=None)}</pre><h4>III. Converting the Dataset to a Dataframe (Pandas)</h4><p>To manipulate and visualize the training dataset, we convert the type from DatasetDict to pandas data frame. To do so, we do the following:</p><pre>import pandas as pd<br><br>emotions.set_format(type=&quot;pandas&quot;)<br>df = emotions[&quot;train&quot;][:]<br>df.head()</pre><p><strong>Output</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/735/1*cHD1wLoSSoAEpuLn34iBCQ.png" /></figure><p>To learn the emotion that corresponds to each label, we can add an additional column as follows:</p><pre>def label_int2str(row):<br>    return emotions[&quot;train&quot;].features[&quot;label&quot;].int2str(row)<br><br>df[&quot;label_name&quot;] = df[&quot;label&quot;].apply(label_int2str)<br>df.head()</pre><p><strong>Output</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/898/1*Yzu55G-KjCRoDeA4uTCLYQ.png" /></figure><h4>IV. Data Exploration</h4><p>In this section, we take a close look to the dataset as hand. Understanding the data is imperative since our model will only be as good as our data. Some interesting properties we can explore include the class distribution and the length of our observations (X posts).</p><p><strong><em>4.1 Distribution of classes in our data</em></strong></p><p>To visualize the distribution of classes in our dataset, we can make use of a histogram and plot it using matplotlib. We can do so as follows:</p><pre>import matplotlib.pyplot as plt<br><br>df[&quot;label_name&quot;].value_counts(ascending=True).plot.bar()<br>plt.title(&quot;Frequency of Classes&quot;)<br>plt.show()</pre><p><strong>Output</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/1*NTRMccZMPe-VGDshMRC_kA.png" /><figcaption>Figure 1</figcaption></figure><p>As we can learn from inspection, the class distribution is somewhat inbalanced. In an ideal scenario, we would have an equal number of instances per class. However, some ways to correct for inbalanced datasets include: 1) oversampling the minority class, 2) undersampling the majority class, and 3) simply obtaining more instances of our minority or underrepresented classes. In this project, we do not correct for class imbalace. If you are interested in learning more about how to correct for this issue, please refer to the appropriate article in my profile.</p><p><strong><em>4.2 Length of our Observations (X posts)</em></strong></p><p>With the advent of transformer architectures, we context window of models to learn increased relative to previous models used for NLP such as recurrent neural networks. This increase in the context window is attributed to the attention mechanism inherent in the architecture. However, its important to note that even transformer architectures still have a limit to the length of the input. This limit is known as the <strong><em>maximum context size </em></strong>and one of the current research efforts is to increase this limit. Late last year, OpenAI announced a significant increase in the maximum context size of its GPT — 4 model allowing input sequences that are sufficient for entire books. In our project, we note that the maximum context size of DistilBERT is only 512 tokens (for reference, the maximum context size of GPT — 3.5 is about 4096 tokens).</p><p><strong>Key Idea: Token</strong></p><p>A token simply refers to a ‘quanta’ or chunk of text from our input. In this project, we consider a token to be an individual token.</p><p>To get a better idea of the distribution of token we are dealing with, we can visualize the distribution of the words per X post. This can be done as follows:</p><pre>df[&quot;Words Per X Post&quot;] = df[&quot;text&quot;].str.split().apply(len)<br>df.boxplot(&quot;Words Per X Post&quot;, by=&quot;label_name&quot;, grid=False,<br>          showfliers=False, color=&quot;black&quot;)<br>plt.suptitle(&quot;&quot;)<br>plt.xlabel(&quot;&quot;)<br>plt.show()</pre><p><strong>Output</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/559/1*hf_5rYqfJzu03F0cI0lXhQ.png" /><figcaption>Figure 2</figcaption></figure><p>Figure 2 shows that the length of most X posts is shorter than the maximum context size. This indicates that our model is unlikely to face issues with inputs exceeding the maximum token length. If any post in our dataset exceeds this limit, truncation into two or more segments would be necessary, which could result in information or context loss.</p><h4>V. Tokenizing our Dataset</h4><p>In this project, we employ a technique known as subword tokenization to encode our input messages. In simple terms, subword tokenization allows one to encode our input chunks, in our case words, into units of disimilar size. Words that are appear with less frequency are encoded into shorter tokens, whereas words that appear more frequently are encoded into longer tokens. This ensures that the model allows for more attention in the smaller tokens. In our project, we will employ a tokenizer known as WordPiece. To call it, we do the following:</p><pre>from transformers import AutoTokenizer<br><br>model_ckpt = &quot;distilbert-base-uncased&quot;<br>tokenizer = AutoTokenizer.from_pretrained(model_ckpt)</pre><p>To examine how the tokenizer transforms the data, let’s explore the output after passing in some string variable:</p><pre>text = &quot;Follow Giovanny Espitia on Medium.&quot;<br>encoded_text = tokenizer(text)<br>print(encoded_text)</pre><p><strong>Output</strong></p><pre>{&#39;input_ids&#39;: [101, 3582, 21025, 7103, 10695, 2100, 9686, 23270, 2401, 2006, 5396, 1012, 102], &#39;attention_mask&#39;: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]}</pre><p>As we can see, the words in our text variable have been encoded into unique integers are shown in the values of the input_ids key. Using the input_ids, we can convert the elements of the key into tokens by using the tokenizer’s ‘convert_ids_to_tokens()’ method. This is done as follows:</p><pre>tokens = tokenizer.convert_ids_to_tokens(encoded_text.input_ids)<br>print(tokens)</pre><p><strong>Output</strong></p><pre>[&#39;[CLS]&#39;, &#39;token&#39;, &#39;##izing&#39;, &#39;text&#39;, &#39;is&#39;, &#39;a&#39;, &#39;core&#39;, &#39;task&#39;, &#39;of&#39;, &#39;nl&#39;,<br>&#39;##p&#39;, &#39;.&#39;, &#39;[SEP]&#39;]</pre><p>As we can see from the output, two new tokens have been added. In this case, the [CLS] and [SEP] tokens and the start and ending of the sequence. These ‘start’ and ‘stop’ tokens help our model identify the start and end of our input sequence (note: these tokens vary from model to model). To convert the tokenized text back into english, we can do so as follows:</p><pre>print(tokenizer.convert_tokens_to_string(tokens))</pre><pre>[CLS] follow giovanny espitia on medium. [SEP]</pre><p>To tokenize the entire dataset, we first need a processing function:</p><pre>def tokenize(batch):<br>    return tokenizer(batch[&quot;text&quot;], padding=True, truncation=True)</pre><p>This function applies the tokenizer to a batch of observations from our data. Moreover, since padding was set to true, it will add zeros to the inputs in order to match the size of the largest input in the batch. Using this function we can now tokenize the entire dataset:</p><pre>emotions_encoded = emotions.map(tokenize, batched=True, batch_size=None)</pre><h4>VI. Finetuning DistilBERT</h4><p>A pretrained DistilBERT model is used, similar to the one in the feature-based approach, but with a modification where AutoModelForSequenceClassification is chosen instead of AutoModel. This variant includes a classification head atop the pretrained model, facilitating easier training with the base model. It is necessary to specify the number of labels to predict, which in this case is six, as this determines the number of outputs for the classification head. To call the model, we write the following code:</p><pre>from transformers import AutoModelForSequenceClassification<br><br>num_labels = 6<br>model = (AutoModelForSequenceClassification<br>         .from_pretrained(model_ckpt, num_labels=num_labels)<br>         .to(device))</pre><p>For tracking metrics during training, a compute_metrics() function must be defined for the Trainer. This function takes an EvalPrediction object, which is a named tuple containing ‘predictions’ and ‘label_ids’, and should return a dictionary mapping each metric’s name to its value. In this specific application, the metrics computed will be the F1-score and the accuracy of the model.</p><pre>from sklearn.metrics import accuracy_score, f1_score<br><br>def compute_metrics(pred):<br>    labels = pred.label_ids<br>    preds = pred.predictions.argmax(-1)<br>    f1 = f1_score(labels, preds, average=&quot;weighted&quot;)<br>    acc = accuracy_score(labels, preds)<br>    return {&quot;accuracy&quot;: acc, &quot;f1&quot;: f1}</pre><p><em>Training the model</em></p><p>To train the model, we must first log into huggingface. This is done as follows:</p><pre>from huggingface_hub import notebook_login<br><br>notebook_login()</pre><p>After this, the TrainingArguments class is used to define training parameters, offering detailed control over the training and evaluation process. A key parameter to specify is the output_dir, which determines where all training artifacts are stored. The text also includes an example of how to use the TrainingArguments class.</p><pre>from transformers import Trainer, TrainingArguments<br>emotions_encoded = emotions.map(tokenize, batched=True, batch_size=None)<br><br><br>batch_size = 64<br>logging_steps = len(emotions_encoded[&quot;train&quot;]) // batch_size<br>model_name = f&quot;{model_ckpt}-finetuned-emotion&quot;<br>training_args = TrainingArguments(output_dir=model_name,<br>                                  num_train_epochs=2,<br>                                  learning_rate=2e-5,<br>                                  per_device_train_batch_size=batch_size,<br>                                  per_device_eval_batch_size=batch_size,<br>                                  weight_decay=0.01,<br>                                  evaluation_strategy=&quot;epoch&quot;,<br>                                  disable_tqdm=False,<br>                                  logging_steps=logging_steps,<br>                                  push_to_hub=True,<br>                                  log_level=&quot;error&quot;)</pre><p>Here we also set the batch size, learning rate, and number of epochs, and specify to load the best model at the end of the training run. With this final ingredient, we can instantiate and fine-tune our model with the Trainer:</p><pre>from transformers import Trainer<br><br>trainer = Trainer(model=model, args=training_args,<br>                  compute_metrics=compute_metrics,<br>                  train_dataset=emotions_encoded[&quot;train&quot;],<br>                  eval_dataset=emotions_encoded[&quot;validation&quot;],<br>                  tokenizer=tokenizer)<br>trainer.train();</pre><p><strong>Output</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ToRle_5blfmoI8KBl_Cxzw.png" /></figure><p>As we can see, the F1 score after two epochs us 92%. We can also compute the confusion matrix to evaluate the model.</p><pre>preds_output = trainer.predict(emotions_encoded[&quot;validation&quot;])<br>y_preds = np.argmax(preds_output.predictions, axis=1)<br>plot_confusion_matrix(y_preds, y_valid, labels)</pre><p>This code results in the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W_Mg078QIMRgnTuWm0muGw.png" /></figure><p>Ideally, a well perfoming model will have a diagonal. Since the model has an approximate diagonal, we can deduce that its ability to classify the emotion in an X post is accurate.</p><h4>VIII. Saving and Sharing the Model</h4><p>To push the model into your Huggingface account, you simply write the following:</p><pre>trainer.push_to_hub(commit_message=&quot;Training succesful.&quot;)</pre><p>Pushing the model onto Hugging face will allow us to use it in the future using the pipeline function.</p><h4>IX. Inference on the Huggingface Model Interface</h4><p>To conduct inference in our model, we can interact with it directly from the Huggingface UI. For reference, it appears as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*16WtnuA_uqDdIdEjQSZfmQ.png" /></figure><p>In the box, we simply input our X post. In our case, let’s try this recent post by notable investor Bill Ackman:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K03kcmK3PtDo0XP6LvryNw.png" /></figure><p>This is the output of the model:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jykSxPK6kxMS1aMhlvwdvg.png" /></figure><p>These labels correspond to 90% joy and 10% sadness. In my opinion, its somewhat accurate.</p><h4><em>X. Conclusion</em></h4><p>In this article, we explored the application of the DistilBERT model, using the Transformers library from Huggingface, for sentiment analysis on X data. We began by importing, exploring, and formatting the dataset, which comprised a variety of emotional labels beyond the conventional positive or negative categories. Utilizing the power of DistilBERT, a streamlined version of the original BERT model, we demonstrated how to efficiently fine-tune and test a large language model for a specific natural language processing task. The journey took us through various stages, including dataset preparation, understanding the nuances of tokenization, and the intricacies of subword tokenization using the WordPiece tokenizer. We highlighted the importance of addressing data imbalances and managing the constraints of maximum context size in transformer architectures. Our fine-tuning process involved the use of AutoModelForSequenceClassification for its built-in classification head, simplifying the training process. We defined custom metrics to track our model’s performance, focusing on accuracy and the F1-score, and discussed the significance of resource efficiency in handling large language models. In the end, we successfully trained and evaluated our model, achieving an impressive F1 score. We also examined the model’s performance through a confusion matrix, confirming its efficacy in accurately classifying emotions in X posts. The model was then shared on Huggingface, showcasing the ease with which machine learning models can be distributed and accessed in the modern era. We concluded with a demonstration of model inference using the Huggingface Model Interface, where we tested the model with real-world data, further validating its practical utility.</p><p><strong><em>Code Availability</em></strong></p><p><a href="https://github.com/espitia01/MediumPosts/blob/main/medium_article_post_3.ipynb">MediumPosts/medium_article_post_3.ipynb at main · espitia01/MediumPosts</a></p><p><strong><em>References</em></strong></p><ol><li>Stanford Online. (2023, May 19). <em>Stanford CS25: V2 I Introduction to Transformers w/ Andrej Karpathy</em> [Video]. YouTube. <a href="https://www.youtube.com/watch?v=XfpMkf4rD6E">https://www.youtube.com/watch?v=XfpMkf4rD6E</a></li><li>Wolf, T., Debut, L., Sanh, V., Chaumond, J., Delangue, C., Moi, A., Cistac, P., Rault, T., Louf, R., Morgan, F., &amp; Brew, J. (2020). Transformers: State-of-the-Art Natural Language Processing. <em>O’Reilly</em>. <a href="https://doi.org/10.18653/v1/2020.emnlp-demos.6">https://doi.org/10.18653/v1/2020.emnlp-demos.6</a></li></ol><h3>Stackademic</h3><p>Thank you for reading until the end. Before you go:</p><ul><li>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq">X</a> | <a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a><strong> |</strong> <a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a><strong> | </strong><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a></li><li>Visit our other platforms: <a href="https://plainenglish.io/"><strong>In Plain English</strong></a><strong> | </strong><a href="https://cofeed.app/"><strong>CoFeed</strong></a><strong> | </strong><a href="https://venturemagazine.net/"><strong>Venture</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ea9c0679c92f" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/implementing-sentiment-analysis-on-x-data-with-distilbert-and-huggingface-a-comprehensive-guide-ea9c0679c92f">Implementing Sentiment Analysis on X Data with DistilBERT and Huggingface: A Comprehensive Guide</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Decoding the Boundaries: Unraveling Science vs. Pseudo-Science Through Missed Research Insights]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@giovannyespitiag117/decoding-the-boundaries-unraveling-science-vs-pseudo-science-through-missed-research-insights-275ab6cf893e?source=rss-2fc54db6b4c2------2"><img src="https://cdn-images-1.medium.com/max/1024/1*V3-pQSI7bDkkMnYOrc6C1w.png" width="1024"></a></p><p class="medium-feed-snippet">Understanding the Distinction for Clearer Knowledge Advancement</p><p class="medium-feed-link"><a href="https://medium.com/@giovannyespitiag117/decoding-the-boundaries-unraveling-science-vs-pseudo-science-through-missed-research-insights-275ab6cf893e?source=rss-2fc54db6b4c2------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@giovannyespitiag117/decoding-the-boundaries-unraveling-science-vs-pseudo-science-through-missed-research-insights-275ab6cf893e?source=rss-2fc54db6b4c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/275ab6cf893e</guid>
            <category><![CDATA[physics]]></category>
            <category><![CDATA[philosophy-of-science]]></category>
            <category><![CDATA[science-communication]]></category>
            <category><![CDATA[philosophy]]></category>
            <category><![CDATA[science]]></category>
            <dc:creator><![CDATA[Giovanny Espitia]]></dc:creator>
            <pubDate>Wed, 15 Nov 2023 04:28:08 GMT</pubDate>
            <atom:updated>2023-11-15T04:28:08.588Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Python Guide: Building a Reservoir Computer from Scratch]]></title>
            <link>https://blog.stackademic.com/python-guide-building-a-reservoir-computer-from-scratch-c166d63038dc?source=rss-2fc54db6b4c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/c166d63038dc</guid>
            <category><![CDATA[physics]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[reservoir-computing]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Giovanny Espitia]]></dc:creator>
            <pubDate>Mon, 02 Oct 2023 22:29:13 GMT</pubDate>
            <atom:updated>2024-01-15T01:29:56.624Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wUXhX48jYRuAOtPJNFUJbA.png" /></figure><h4><strong>Introduction</strong></h4><p>A <strong>reservoir computer</strong> (RC), introduced by Jaeger and Haas [1] in 2004, belongs to the <strong>recurrent neural network </strong>(RNN) family. However, unlike traditional RNNs, an RC boasts characteristics that align it more closely with <strong>linear regression</strong>. In an RC, the reservoir, a collection of nodes, is initialized randomly and remains unaltered throughout training. This differs from standard RNNs, where complex internal dynamics undergo adjustments during the learning process. Consequently, with RCs, there’s no need for intensive optimization techniques like Back Propagation Through Time (BPTT). Training an RC primarily focuses on its <strong>output layer</strong>. The outputs from the reservoir nodes are linearly aggregated to yield the expected outcome, making the training process akin to that of a linear regression model. The readout (or output) layer weights are fine-tuned to minimize the discrepancy between the RC’s predictions and the actual outputs. The essence of an RC’s prowess in capturing nonlinear dynamics lies in the separation of its inherent network dynamics from its training method. Specifically, its high-dimensional reservoir produces a dynamic response to inputs, offering a big set of features adept at recognizing intricate temporal patterns, all while keeping the training linear. In the next section, we describe the mathematics behind the model.</p><h4><strong>Reservoir Computer</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qDFBA_GdGgr1oP8B7JUS4g.png" /><figcaption>Figure 1: a) A reservoir computer during the training phase. b) A reservoir computer during the prediction phase. This figure depicts the reservoir computer as a graph where each node represents a stage in the network process and each edge represents a stage or data flow between these stages. This architecture follows the implementation in [2]</figcaption></figure><p>Let <strong><em>u(t)</em> </strong>be an input vector that is fed into a reservoir <strong><em>R</em> </strong>through an input/reservoir coupler (<strong><em>I/R</em></strong>). The input to <strong><em>R</em> </strong>then becomes<strong>,</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/64/0*wMf6QaYCdvVEq27c.png" /></figure><p>Where</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/634/0*ghj-d1TgbeF_SFva.png" /></figure><p>In <strong><em>R </em></strong>the input is then combined with the current reservoir state, <strong><em>r(t)</em></strong> to produce its output (the next reservoir state) <strong><em>r(t + dt)</em></strong>. The reservoir is represented by an adjacency matrix <strong><em>A</em></strong> where,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/408/0*_mw8G09_32Tpsevc.png" /></figure><p>Following the implementation by [], <strong><em>r(t + dt)</em></strong> is therefore,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/286/0*ISiyGhOgDqG7QJq9.png" /><figcaption>Equation 1</figcaption></figure><p>Each reservoir node has a corresponding reservoir state.<strong><em> r(t + dt</em>) </strong>is then flowed to the reservoir/output coupler. Here, a mapping is done to obtain the same dimensionality as the input <strong><em>u(t)</em></strong><em>.</em> Through this mapping, we also obtain <strong><em>v(t)</em></strong>, which corresponds to the target output vector. The mapping is given by,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/585/0*wvRTHMGIiMzU8ma7.png" /><figcaption>Equation 2</figcaption></figure><p>In general, the goal of the system, depicted in Figure 1 (a), is for the output <strong><em>v(t)</em></strong> to approximate the actual desired output <strong><em>v’(t)</em></strong> corresponding <strong><em>u(t)</em></strong>. Thus, during the training process (<strong><em>-T ≤ t ≤ 0</em></strong>), an input <strong><em>u(t)</em></strong> is fed into the reservoir and the resulting reservoir state <strong><em>r(t) </em></strong>is then stored along with<strong><em> u(t)</em></strong> as training data. The parameters of <strong><em>W_{out}</em></strong> are then trained to minimize the mean squared difference between <strong><em>v(t)</em></strong> and <strong><em>v’(t)</em></strong>. Following the convention in the reservoir computing community, this is achieved through the regularized regression procedure given by,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/325/0*ZyMwsA8m5IMmqTBb.png" /></figure><p>Where <strong><em>β</em></strong> corresponds to the regularization constant and it prevents overfitting if <strong><em>β &gt; 0</em></strong>. This turns the problem of training into a linear regression problem. To transition from a training phase to the prediction phase, we let <strong><em>v(t + dt) = u(t + dt)</em></strong>. This corresponds to letting the output vector <strong><em>v(t + dt)</em></strong> serve as the input for the next timestep<strong><em> u(t + dt</em></strong>). Moreover, the network is allowed to run autonomously according to the following equation,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/348/0*GSmAZ7x_pNpMUTmB.png" /></figure><p>And thus, the output of “trained‘ reservoir computer gives the input (predicted) value for the next timestep <strong><em>u(t)</em></strong> for <strong><em>t &gt; 0</em></strong>. In Figure 1, a) corresponds to the training configuration and b) corresponds to the prediction configuration. In the next section, we implement the architecture described here and use it to learn the “climate” of a deterministic dynamical system.</p><h4>Implementation</h4><p>In this section, we implement the reservoir computing architecture put forth using python. Since we are interested in doing so from scratch, this will be done using only numpy and networkx. Numpy will help us take care of the matrix operations and networkx will help us define the reservoir network topology. For this implementation, the topology of choice is the Erdos Renyi network with an average degree of 6.</p><ol><li><strong><em>Import Dependencies</em></strong></li></ol><pre>import matplotlib.pyplot as plt<br>import numpy as np<br>import networkx as nx</pre><p><strong><em>2. Define the Reservoir Computer Class</em></strong></p><pre>class ReservoirComputer:<br>    def __init__(self, dim_system, dim_reservoir, rho, sigma, density):<br>        self.dim_system = dim_system<br>        self.dim_reservoir = dim_reservoir<br>        self.r_state = np.zeros(dim_reservoir)<br>        self.A = generate_adjacency_matrix(dim_reservoir, rho, sigma)<br>        self.A = 0<br>        self.W_in = 2 * sigma * (np.random.rand(dim_reservoir, dim_system) - .5)<br>        self.W_out = np.zeros((dim_system, dim_reservoir))<br>    <br>    def advance_r_state(self, u):<br>        self.r_state = sigmoid(np.dot(self.A, self.r_state) + np.dot(self.W_in, u))<br>        return self.r_state<br>    <br>    def v(self):<br>        return np.dot(self.W_out, self.r_state)<br>    <br>    def train(self, trajectory):<br>        #trajectory has shape (n, dim_system), n is the number of timesteps<br>        R = np.zeros((self.dim_reservoir, trajectory.shape[0]))<br>        for i in range(trajectory.shape[0]):<br>            R[:, i] = self.r_state<br>            u = trajectory[i]<br>            self.advance_r_state(u)<br>        self.W_out = linear_regression(R, trajectory)<br>    <br>    def predict(self, steps):<br>        prediction = np.zeros((steps, self.dim_system))<br>        for i in range(steps):<br>            v = self.v()<br>            prediction[i] = v<br>            self.advance_r_state(prediction[i])<br>        return prediction</pre><p><strong><em>3. Define the Helper Functions</em></strong></p><pre>def sigmoid(x):<br>    return np.where(x &gt;= 0, <br>                    1 / (1 + np.exp(-x)), <br>                    np.exp(x) / (1 + np.exp(x)))<br><br>def generate_adjacency_matrix(dim_reservoir, rho, sigma):<br>    <br>    graph = nx.gnp_random_graph(dim_reservoir, sigma)<br>    graph = nx.to_numpy_array(graph)<br>    <br>    # Ensure random_array is of the same shape as the graph adjacency matrix.<br>    random_array = 2 * (np.random.rand(dim_reservoir, dim_reservoir) - 0.5)<br>    <br>    # Multiply graph adjacency matrix with random values.<br>    rescaled = graph * random_array<br>    return scale_matrix(rescaled, rho)<br><br>def scale_matrix(A, rho):<br>    eigenvalues, _ = np.linalg.eig(A)<br>    max_eigenvalue = np.amax(eigenvalues)<br>    A = A/np.absolute(max_eigenvalue) * rho<br>    return A<br><br>def linear_regression(R, trajectory, beta=0.0001):  <br>    Rt = np.transpose(R)<br>    inverse_part = np.linalg.inv(np.dot(R, Rt) + beta * np.identity(R.shape[0]))<br>    return np.dot(np.dot(trajectory.T, Rt), inverse_part)</pre><p><strong><em>4. Plot the Results</em></strong></p><p><strong>Lorenz-63 Attractor</strong></p><pre># Plot<br>ax = plt.figure().add_subplot(projection=&#39;3d&#39;)<br><br>x_data = valid_data[:, 0]<br>y_data = valid_data[:, 1]<br>z_data = valid_data[:, 2]<br><br>x_pred = predicted_data[:, 0]<br>y_pred = predicted_data[:, 1]<br>z_pred = predicted_data[:, 2]<br><br>ax.plot(x_data, y_data, z_data, lw=0.5, label=&quot;Actual&quot;)<br>ax.plot(x_pred, y_pred, z_pred, lw=0.5, label=&quot;Predicted&quot;)<br>ax.set_xlabel(&quot;X Axis&quot;)<br>ax.set_ylabel(&quot;Y Axis&quot;)<br>ax.set_zlabel(&quot;Z Axis&quot;)<br>ax.legend()<br>ax.set_title(&quot;Lorenz Attractor&quot;)<br><br>plt.show()</pre><p><strong>Predicted Data vs Actual Data as a Function of Time</strong></p><pre>fig, axs = plt.subplots(3, 1, figsize=(8, 6))  <br><br># Plot data on each subplot<br>timesteps = [*range(training_data.shape[0], data_length, 1)]<br><br>axs[0].plot(timesteps, x_data, label=&quot;x&quot;, lw=1.1)<br>axs[0].plot(timesteps, x_pred, label=&quot;x_pred&quot;, color=&#39;orange&#39;, lw=1.1)  # I changed the label to &#39;x_pred&#39; for clarity<br>axs[0].set_ylabel(&quot;x&quot;)<br>axs[0].set_title(&quot;Comparison of the Predicted Lorenz Data and Actual Data&quot;)<br>axs[0].legend()<br><br>axs[1].plot(timesteps, y_data, label=&quot;y&quot;, color=&#39;r&#39;, lw=1.1)<br>axs[1].plot(timesteps, y_pred, label=&quot;y_pred&quot;, color=&#39;orange&#39;, lw=1.1)  # I changed the label to &#39;y_pred&#39; for clarity<br>axs[1].set_ylabel(&quot;y&quot;)<br>axs[1].legend()<br><br>axs[2].plot(timesteps, z_data, label=&quot;z&quot;, color=&#39;g&#39;, lw=.9)<br>axs[2].plot(timesteps, z_pred, label=&quot;z_pred&quot;, color=&#39;orange&#39;, lw=1.1)  # I changed the label to &#39;z_pred&#39; for clarity<br>axs[2].set_ylabel(&quot;z&quot;)<br>axs[2].set_xlabel(&quot;timestep&quot;)<br>axs[2].legend()<br><br>fig.tight_layout()<br><br>plt.show()</pre><h4>Learning the Chaotic Dynamics of the Lorenz-63 System</h4><p>In the previous section, we implemented the reservoir computing architecture. At this point, we have the code required to instantiate a model, conduct training, conduct forecasting, and visualize the results. In this section, we apply the defined architecture to forecast and replicate the climate of the Lorenz-63 system. For a more detailed account of the numerical method used to generate the synthetic data by solving the Lorenz-63 system of coupled ordinary differential equations, please refer to this article:</p><p><a href="https://medium.com/@giovannyespitiag117/lorenz-63-system-integration-using-4th-order-runge-kutta-methods-in-python-778d7dbc44c1">Lorenz-63 System Integration Using 4th Order Runge-Kutta Methods in Python</a></p><ol><li><strong><em>Define the Lorenz-63 System</em></strong></li></ol><pre>def lorenz(t, x, y, z, sigma, rho, beta):<br>    dxdt = sigma * (y - x)<br>    dydt = x * (rho - z) - y<br>    dzdt = x*y - beta*z<br>    return dxdt, dydt, dzdt </pre><p><strong><em>2. Define the RK4 Numerical Method</em></strong></p><pre>def rk4(t, x, y, z, dt, sigma, rho, beta):<br>    f1x, f1y, f1z = lorenz(t, x, y, z, sigma, rho, beta)<br>    <br>    k1x = dt * f1x<br>    k1y = dt * f1y<br>    k1z = dt * f1z<br>    <br>    f2x, f2y, f2z = lorenz(t + 0.5*dt, x + 0.5*k1x, y + 0.5*k1y, z + 0.5*k1z, sigma, rho, beta)<br><br>    k2x = dt * f2x<br>    k2y = dt * f2y<br>    k2z = dt * f2z<br><br>    f3x, f3y, f3z = lorenz(t + 0.5*dt, x + 0.5*k2x, y + 0.5*k2y, z + 0.5*k2z, sigma, rho, beta)<br><br>    k3x = dt * f3x<br>    k3y = dt * f3y<br>    k3z = dt * f3z<br><br>    f4x, f4y, f4z = lorenz(t + dt, x + k3x, y + k3y, z + k3z, sigma, rho, beta)<br><br>    k4x = dt * f4x<br>    k4y = dt * f4y<br>    k4z = dt * f4z<br><br>    x += (k1x + 2*k2x + 2*k3x + k4x) / 6.0<br>    y += (k1y + 2*k2y + 2*k3y + k4y) / 6.0<br>    z += (k1z + 2*k2z + 2*k3z + k4z) / 6.0<br><br>    return x, y, z</pre><p><strong><em>3. Declare the Initial Conditions, The Integration Loop, and Partition the Data</em></strong></p><pre>#initial conditions<br>x0, y0, z0 = 1, 1, 1<br>sigma, rho, beta = 10, 28, 8/3<br>t, dt = 0, 0.01<br>#integration loop<br>x_list = []<br>y_list = []<br>z_list = []<br>for i in range(20000):<br>    x, y, z = rk4(t, x0, y0, z0, dt, sigma, rho, beta)<br>    x_list.append(x)<br>    y_list.append(y)<br>    z_list.append(z)<br>    x0, y0, z0 = x, y, z <br>    t += dt<br><br>data = []<br>for i in range(len(x_list)):<br>    u_i = [x_list[i], y_list[i], z_list[i]]<br>    data.append(u_i)<br><br>data_length = len(data) <br>training_percentage = .7<br>training_data = np.array(data[:int(data_length*training_percentage)])<br>valid_data = np.array(data[int(data_length*training_percentage):])</pre><p><strong><em>4. Instantiate the Model and Conduct Forecasting</em></strong></p><pre>dim_reservoir = 300<br>model = ReservoirComputer(3, dim_reservoir, 1.1, 0.1, 0.05)<br>model.train(training_data)<br>predicted_data = model.predict(len(valid_data))</pre><h4>Results</h4><p>In the previous section, we constructed and trained an RC with an input ,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/0*cALqD8NDV-2T8Bjl.png" /></figure><p>The reservoir was built with a sparse random Erdos — Renyi topology. Each nonzero element in the adjacency matrix is drawn independently and uniformly from <strong><em>[σ, σ]</em></strong> and <strong><em>σ &gt; 0</em></strong> is adjusted so that the spectral radius of <strong><em>A</em></strong> (the largest magnitude of its eigenvalues) has a desired value <strong><em>ρ</em></strong>. In the code, we chose these hyperparameters to be <strong><em>σ = 0.1</em></strong> and <strong><em>ρ = 1.1</em></strong>. During the training phase, <strong><em>T ≤ t ≤ 0 </em></strong>(where <strong><em>T = 14000</em></strong>), the reservoir computer evolves following <strong><em>Equation 1</em></strong> with <strong><em>dt = 0.01</em></strong>. The network was chosen to have a density equal to <strong><em>0.05</em></strong>. Moreover, the RC was trained on data generated by solving the Lorenz-63 system was integrated for a period of <strong><em>20000</em></strong> time steps. The data was partitioned to be <strong><em>70%</em></strong> training data and<strong><em> 30%</em></strong> for testing. In other words, the network was trained on <strong><em>70% </em></strong>of the <strong><em>20000</em></strong> time steps and allowed to run autonomously for the remaining <strong><em>30%</em></strong> according to <strong><em>Equation 2</em></strong>. The predicted data was then compared to the actual generated data starting on the <strong><em>14001</em></strong> time step. The following plots allows one to visualize the performance of the network in a visual manner. For a more thorough evaluation of the network, please stay tuned for the next article.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/731/1*jba_DJPT3UrPKvB6uawLIw.png" /><figcaption>Figure 3.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lDd_r1YmbBiLB_HKSkb5jw.png" /><figcaption>Figure 4.</figcaption></figure><h4><strong>Summary</strong></h4><p>RCs, a subset of the recurrent neural network (RNN) family, were introduced in 2004 by Jaeger and Haas. Unlike standard RNNs, RCs more closely resemble linear regression due to their unique characteristics. These computers initialize their reservoir — a set of nodes — randomly, which remains fixed throughout training. This stands in contrast to conventional RNNs, where internal dynamics are adjusted continuously during learning. This static nature of RCs negates the need for exhaustive optimization methods like Back Propagation Through Time (BPTT). In training RCs, the focus remains on the output layer, with the reservoir nodes’ outputs linearly combined to derive the desired result. Training is therefore analogous to a linear regression model. The brilliance of RCs in understanding nonlinear dynamics is rooted in the distinction between its intrinsic network dynamics and its training approach. By producing a dynamic response to inputs through a high-dimensional reservoir, it offers a rich set of features to recognize complex temporal sequences while maintaining linearity in training. The aim of this system is to ensure the output mirrors the actual desired output closely. During training, input data and the corresponding reservoir state are stored. The system’s parameters are then optimized to minimize the difference between the predicted and actual outputs using regularized regression. In transitioning from training to predicting, the previous output is used as the succeeding input. Ultimately, this architecture helps the “trained” reservoir computer predict the input value for subsequent time steps. In this article we further explored the practical implementation of this structure to understand the dynamics of the Lorenz-63.</p><p><strong><em>Code Availability</em></strong></p><p><a href="https://github.com/espitia01/MediumPosts/blob/main/reservoir-computer.ipynb">MediumPosts/reservoir-computer.ipynb at main · espitia01/MediumPosts</a></p><p><strong>References</strong></p><ol><li>Jaeger, H., &amp; Haas, H. (2004). Harnessing nonlinearity: predicting chaotic systems and saving energy in wireless communication. <em>Science</em>, <em>304</em>(5667), 78–80. <a href="https://doi.org/10.1126/science.1091277">https://doi.org/10.1126/science.1091277</a></li><li>Pathak, J., Lu, Z., Hunt, B. R., Girvan, M., &amp; Ott, E. (2017). Using machine learning to replicate chaotic attractors and calculate Lyapunov exponents from data. <em>Chaos</em>, <em>27</em>(12), 121102. <a href="https://doi.org/10.1063/1.5010300">https://doi.org/10.1063/1.5010300</a></li></ol><h3>Stackademic</h3><p>Thank you for reading until the end. Before you go:</p><ul><li>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq">X</a> | <a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a><strong> |</strong> <a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a><strong> | </strong><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a></li><li>Visit our other platforms: <a href="https://plainenglish.io/"><strong>In Plain English</strong></a><strong> | </strong><a href="https://cofeed.app/"><strong>CoFeed</strong></a><strong> | </strong><a href="https://venturemagazine.net/"><strong>Venture</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c166d63038dc" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/python-guide-building-a-reservoir-computer-from-scratch-c166d63038dc">Python Guide: Building a Reservoir Computer from Scratch</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Lorenz-63 System Integration Using 4th Order Runge-Kutta Methods in Python]]></title>
            <link>https://blog.stackademic.com/lorenz-63-system-integration-using-4th-order-runge-kutta-methods-in-python-778d7dbc44c1?source=rss-2fc54db6b4c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/778d7dbc44c1</guid>
            <category><![CDATA[computational-physics]]></category>
            <category><![CDATA[physics]]></category>
            <category><![CDATA[math]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[numerical-methods]]></category>
            <dc:creator><![CDATA[Giovanny Espitia]]></dc:creator>
            <pubDate>Wed, 27 Sep 2023 23:46:56 GMT</pubDate>
            <atom:updated>2024-01-17T01:20:44.764Z</atom:updated>
            <content:encoded><![CDATA[<p>The <strong>Lorenz-63 system</strong>, also known as the Lorenz attractor, was introduced by mathematician and meteorologist Edward Lorenz in 1963. Originally conceptualized as a simplistic model for atmospheric convection to forecast weather patterns, its true significance emerged as a quintessential representation of chaotic dynamical systems. Employing<strong> 4th order Runge-Kutta methods</strong>, this article delves into the numerical integration of the Lorenz-63 system using <strong>python</strong>. Throughout the subsequent sections, we will analyze how the solutions to this system of coupled ordinary differential equations manifest the iconic ‘butterfly effect’, emblematic of its butterfly-like attractor.</p><p><strong><em>Note: In this article, we will provide a brief overview of the RK4 numerical method. Instead, emphasis is placed on the python implementation. For a more detailed account, please refer to my RK4 article.</em></strong></p><h4><strong>Lorenz-63 System</strong></h4><p>The model is a system of three coupled ordinary differential equations given by,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/184/1*dWliKyBUgEufzk7x9kI_bw.png" /><figcaption>Lorenz-63 System</figcaption></figure><p>where ρ, <em>σ, </em>and<em> β </em>are system parameters proportional to the Prandtl number, the Rayleigh number, and other physical dimensions of the fluid layer. These equations were initially derived to relate the properties of a two — dimensional fluid layer. Some general properties of the system is that it is deterministic (if the state is known at <em>t, </em>then the state at any future time is known), it is nonlinear, and it is aperiodic.</p><h4>RK4</h4><p>The Runge-Kutta methods are a family of iterative methods employed to approximate solutions to ordinary differential equations (ODEs). Among these, the Fourth-Order Runge-Kutta (often denoted as RK4) stands as one of the most widely used due to its optimal balance between computational cost and accuracy.</p><p><strong><em>The Problem at Hand:</em></strong></p><p>Given an ODE of the form</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/119/1*oWGq40aszPK-lMntiJLw-A.png" /><figcaption>ODE</figcaption></figure><p>with some initial condition</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/99/1*oqX7UE87pwTbljdNZuBCdg.png" /><figcaption>Initial condition</figcaption></figure><p>our goal is to find</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/139/1*jcfZdve5S4LV0cEcfpX0cw.png" /></figure><p>that is, the state of the system at some time in the future.</p><p><strong><em>The RK4 Iterative Approach</em></strong></p><p>To achieve this, RK4 approximates the solution by advancing in discrete steps. For each step of size <em>h, </em>starting from <em>t = 0, </em>the method estimates the increment in <em>y </em>based on weighted averages of increments over the interval. The increments are computed as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/241/1*L-jEP_rFVQtZCK1H_eaijA.png" /></figure><p>These equations can be interpreted as follows:</p><ol><li>Computation of the <strong>initial slope</strong> using Euler’s method.</li><li>Computation of slope at the midpoint using k1.</li><li>Computation of the slop at the midpoint using k2.</li><li>Slope at the end point using k3.</li></ol><p>With these four increments, the RK4 method provides the next estimate for <em>y</em> as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*X_w-Z7rH23xBFdtGyP2tlA.png" /></figure><p><strong><em>Why RK4 Stands Out?</em></strong></p><p>The genius of the RK4 method is its ability to capture the behavior of the differential equation over the entire step, not just at the beginning or end. By evaluating the function <strong><em>f(t,y) </em></strong>at strategic points across the interval and assigning appropriate weights to these evaluations, RK4 achieves a higher degree of accuracy.</p><p>Moreover, the method’s fourth-order designation implies that the local truncation error per step is of the order <strong><em>O</em>(<em>h</em>5)</strong>, while the total accumulated error is of the order <strong><em>O</em>(<em>h</em>4)</strong>. This makes RK4 significantly more accurate than lower-order methods for a given step size.</p><p>In essence, the RK4 method serves as a robust, accurate, and efficient tool for approximating the solutions of ODEs. It encapsulates the behavior of the differential equation across intervals, providing a holistic view and a precise estimate of the solution trajectory.</p><h4><strong>Implementation Using Python</strong></h4><p>In this section, we show how to implement the RK4 method described above and use it to integrate the Lorenz-63 system of ODEs. Stay tuned for our implementation of machine learning algorithms to learn the chaotic dynamics of the system.</p><ol><li><strong><em>Import Dependencies</em></strong></li></ol><pre>import numpy as np<br>import matplotlib.pyplot as plt<br>from matplotlib.animation import FuncAnimation #to make animation </pre><p>2.<strong><em> Define the Lorenz-63 System</em></strong></p><pre>def lorenz(t, x, y, z, sigma, rho, beta):<br>    dxdt = sigma * (y - x)<br>    dydt = x * (rho - z) - y<br>    dzdt = x*y - beta*z<br>    return dxdt, dydt, dzdt</pre><p>3. <strong><em>Define the RK4 Method</em></strong></p><pre>def rk4(t, x, y, z, dt, sigma, rho, beta):<br>    f1x, f1y, f1z = lorenz(t, x, y, z, sigma, rho, beta)<br>    <br>    k1x = dt * f1x<br>    k1y = dt * f1y<br>    k1z = dt * f1z<br>    <br>    f2x, f2y, f2z = lorenz(t + 0.5*dt, x + 0.5*k1x, y + 0.5*k1y, z + 0.5*k1z, sigma, rho, beta)<br><br>    k2x = dt * f2x<br>    k2y = dt * f2y<br>    k2z = dt * f2z<br><br>    f3x, f3y, f3z = lorenz(t + 0.5*dt, x + 0.5*k2x, y + 0.5*k2y, z + 0.5*k2z, sigma, rho, beta)<br><br>    k3x = dt * f3x<br>    k3y = dt * f3y<br>    k3z = dt * f3z<br><br>    f4x, f4y, f4z = lorenz(t + dt, x + k3x, y + k3y, z + k3z, sigma, rho, beta)<br><br>    k4x = dt * f4x<br>    k4y = dt * f4y<br>    k4z = dt * f4z<br><br>    x += (k1x + 2*k2x + 2*k3x + k4x) / 6.0<br>    y += (k1y + 2*k2y + 2*k3y + k4y) / 6.0<br>    z += (k1z + 2*k2z + 2*k3z + k4z) / 6.0<br><br>    return x, y, z</pre><p>4. <strong><em>Setup the Initial Conditions and the Integration Loop</em></strong></p><pre>#initial conditions<br>x0, y0, z0 = 1, 1, 1<br>sigma, rho, beta = 10, 28, 8/3<br>t, dt = 0, 0.01<br>#integration loop<br>x_list = []<br>y_list = []<br>z_list = []<br>for i in range(10000):<br>    x, y, z = rk4(t, x0, y0, z0, dt, sigma, rho, beta)<br>    x_list.append(x)<br>    y_list.append(y)<br>    z_list.append(z)<br>    x0, y0, z0 = x, y, z <br>    t += dt</pre><p>5. <strong><em>Plot the Result</em></strong></p><pre>#plotting<br>fig = plt.figure()<br>ax = fig.add_subplot(111, projection=&#39;3d&#39;)<br>ax.plot(x_list, y_list, z_list, lw=.5)<br>ax.set_title(&quot;Lorenz System Trajectory&quot;)<br>ax.set_xlabel(&quot;X&quot;)<br>ax.set_ylabel(&quot;Y&quot;)<br>ax.set_zlabel(&quot;Z&quot;)<br>plt.show()</pre><h4><strong>Results</strong></h4><p>After running the code above, we obtain the following figure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LZ4cJC4q-WiuDqy9HlKt8g.png" /></figure><p>To make the result more interesting and demonstrate the non-periodicity of the system, we also made the following animation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*f705UtnEihnXlBqXIwy0NQ.gif" /></figure><h4><strong>Summary</strong></h4><p>This article unpacks the Lorenz-63 system, a foundational representation of chaotic dynamical systems. By leveraging the Fourth-Order Runge-Kutta (RK4) method, we numerically integrate the system using Python, highlighting the iconic ‘butterfly effect’. Beyond the mathematical details, we guide you through the practical implementation in Python, including the plotting of results, ensuring both beginners and experts gain value. Whether you’re interested in the theoretical underpinnings or keen on the hands-on application, this deep dive into the Lorenz system offers insights into the world of chaotic systems.</p><p><em>Code Availability</em>:</p><p><a href="https://github.com/espitia01/MediumPosts">GitHub - espitia01/MediumPosts: In this repository, I host the code associated with my Medium posts.</a></p><p><strong>References</strong></p><ol><li>Gorman, M., et al. “Nonlinear Dynamics of a Convection Loop: A Quantitative Comparison of Experiment With Theory.” <em>Physica D: Nonlinear Phenomena</em>, vol. 19, no. 2, Elsevier BV, Mar. 1986, pp. 255–67. <a href="https://doi.org/10.1016/0167-2789(86)90022-9.">https://doi.org/10.1016/0167-2789(86)90022-9.</a></li><li>Kolá, M., and Godfrey Gumbs. “Theory for the Experimental Observation of Chaos in a Rotating Waterwheel.” <em>Physical Review A</em>, vol. 45, no. 2, American Physical Society, Jan. 1992, pp. 626–37. <a href="https://doi.org/10.1103/physreva.45.626.">https://doi.org/10.1103/physreva.45.626.</a></li><li>Mishra, Aashwin, and Sanjeev Sanghi. “A Study of the Asymmetric Malkus Waterwheel: The Biased Lorenz Equations.” <em>Chaos</em>, vol. 16, no. 1, American Institute of Physics, Jan. 2006, <a href="https://doi.org/10.1063/1.2154792.">https://doi.org/10.1063/1.2154792.</a></li></ol><h3>Stackademic</h3><p>Thank you for reading until the end. Before you go:</p><ul><li>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a><strong> |</strong> <a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a><strong> | </strong><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a></li><li>Visit our other platforms: <a href="https://plainenglish.io/"><strong>In Plain English</strong></a><strong> | </strong><a href="https://cofeed.app/"><strong>CoFeed</strong></a><strong> | </strong><a href="https://venturemagazine.net/"><strong>Venture</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=778d7dbc44c1" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/lorenz-63-system-integration-using-4th-order-runge-kutta-methods-in-python-778d7dbc44c1">Lorenz-63 System Integration Using 4th Order Runge-Kutta Methods in Python</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>