<?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 Kaavya Mahajan on Medium]]></title>
        <description><![CDATA[Stories by Kaavya Mahajan on Medium]]></description>
        <link>https://medium.com/@kaavyamaha12?source=rss-d7b4cf89685e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*wLGZdMpmub8y6S1tJYhnvQ.jpeg</url>
            <title>Stories by Kaavya Mahajan on Medium</title>
            <link>https://medium.com/@kaavyamaha12?source=rss-d7b4cf89685e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 18:44:22 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kaavyamaha12/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[Training a TensorFlow model for predicting the Genres of Popular Songs]]></title>
            <link>https://kaavyamaha12.medium.com/training-a-tensorflow-model-for-predicting-the-genres-of-popular-songs-4286d87d71f6?source=rss-d7b4cf89685e------2</link>
            <guid isPermaLink="false">https://medium.com/p/4286d87d71f6</guid>
            <category><![CDATA[music]]></category>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Kaavya Mahajan]]></dc:creator>
            <pubDate>Thu, 02 Nov 2023 14:25:12 GMT</pubDate>
            <atom:updated>2023-11-02T14:25:12.939Z</atom:updated>
            <content:encoded><![CDATA[<p>This post is a part of a series where I detail the entire process of making a Genre Classification App using Machine Learning:</p><ol><li>Finding the audios to be classified, i.e. <strong>finding the top 50 songs for the last 5 decades </strong><a href="https://kaavyamaha12.medium.com/finding-the-trendiest-audios-for-the-last-50-years-b6583d4bbf20"><em>(find it here)</em></a></li><li>Finding the training data, extracting features from the trendy audios using <strong>Librosa</strong> (a Python library) <em>(</em><a href="https://kaavyamaha12.medium.com/extracting-audio-features-using-librosa-3be4ff1fe57f"><em>find it here</em></a><em>)</em></li><li>Training the <strong>Machine Learning (Tensorflow)</strong> model <em>(you’re here!)</em></li><li><strong><em>Coming Soon — </em></strong>Creating the <strong>Plotly-Dash Application</strong> to make a website for the model</li><li><strong><em>Coming Soon — </em></strong>Deploying the completed app to <strong>AWS EC2</strong></li></ol><h3>The goal</h3><p>The aim in this post is to detail the process of building a Genre Classification Model in TensorFlow, as well as the different steps in preparing the data to be used in this model. This is quite a lengthy post because I’ve tried to explain as much of the process in detail as possible. Hope this is truly helpful for those interested!</p><h3>The process</h3><h4>A brief recap</h4><p><em>If you’ve seen the last 2 posts, feel free to skip this section as I’ll just be sharing across the basic background.</em></p><p>Firstly, I got the top 50 songs from the Billboard Year-End Hot 100 singles for the years 1973–2022. I retrieved this data, and found the YouTube URLs for these songs. Then, from the URLs, I downloaded these songs onto my local machine, to perform further analysis. To check out the step-by-step process for this, please visit the <a href="https://kaavyamaha12.medium.com/finding-the-trendiest-audios-for-the-last-50-years-b6583d4bbf20"><em>first post</em></a> in the series.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RvTcsHeacCoX9d70iFDZBw.png" /></figure><p>Next, I analysed these audio files using Librosa (Python’s audio library), and extracted the following features: <a href="https://librosa.org/doc/latest/generated/librosa.feature.chroma_stft.html#librosa.feature.chroma_stft"><em>chroma_stft</em></a><em> , </em><a href="https://librosa.org/doc/latest/generated/librosa.feature.chroma_cqt.html"><em>chroma_cqt</em></a><em>, </em><a href="https://librosa.org/doc/latest/generated/librosa.feature.chroma_cens.html"><em>chroma_cens</em></a><em>, </em><a href="https://librosa.org/doc/latest/generated/librosa.feature.tonnetz.html"><em>tonnetz</em></a><em>, </em><a href="https://librosa.org/doc/latest/generated/librosa.feature.mfcc.html"><em>mfcc</em></a><em>, </em><a href="https://librosa.org/doc/latest/generated/librosa.feature.rms.html"><em>rmse</em></a><em>, </em><a href="https://librosa.org/doc/latest/generated/librosa.feature.zero_crossing_rate.html"><em>zcr</em></a><em>, </em><a href="https://librosa.org/doc/latest/generated/librosa.feature.spectral_centroid.html"><em>spectral_centroid</em></a><em>, </em><a href="https://librosa.org/doc/latest/generated/librosa.feature.spectral_bandwidth.html"><em>spectral_bandwidth</em></a><em>, </em><a href="https://librosa.org/doc/latest/generated/librosa.feature.spectral_contrast.html"><em>spectral_contrast</em></a><em>, </em><a href="https://librosa.org/doc/latest/generated/librosa.feature.spectral_rolloff.html"><em>spectral_rolloff</em></a></p><p>This the DataFrame that is finally obtained. For the complete process, as well as the code and more information about the above features, please visit the <a href="https://kaavyamaha12.medium.com/extracting-audio-features-using-librosa-3be4ff1fe57f"><em>second post</em></a> in this series.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tJI9ONQstscHkLMa8EVdCQ.png" /></figure><h3>The model</h3><p>Perfect, we’re all caught up. The above DataFrame is what we will be running our predictions on, and is created in the exact same way as the training dataset obtained from the <a href="https://github.com/mdeff/fma">mdeff/fma</a> dataset.</p><p>Now, we can get to the exciting bit, building the actual TensorFlow model to use all of these features to predict the Genre of our songs.</p><p>My artificial intelligence model is a neural network based on deep learning, and it would be best if you had some level of familiarity with the general ideas before jumping into this section. This articles is a wonderful resource on understanding the basics:</p><p><a href="https://towardsdatascience.com/intro-to-deep-learning-c025efd92535">The Complete Beginners Guide to Deep Learning</a></p><p>Now, since my training data provided me with the genres of the songs, alongside their features, I chose to use Supervised Learning. Supervised Algorithms perform, primarily, two different types of tasks:</p><ol><li>Regression Tasks — These tasks involve predicting a number or a value on a continuous distribution.</li><li>Classification Tasks — This involves, as the name suggests, categorising the input data into one or more of the provided labels.</li></ol><p>The task I’m trying to perform is, of course, Genre <strong>Classification. </strong>This means that my model will try to find the likelihood that any data I input, belongs to one of these labels or <strong>classes </strong>from my training data, which are: <strong>Blues, Classical, Country, Electronic, Experimental, Folk, Hip-Hop, Instrumental, International, Jazz, Old-Time/Historic, Pop, Rock, Spoken.</strong></p><p>Now, for setting up the model:</p><h4>Step 1: Loading and Preprocessing the Data</h4><p>So, I use Pandas and Scikit-learn (sklearn) here for these tasks.</p><pre>features = pd.read_csv(&#39;/fma-master/data/fma-metadata/features.csv&#39;, header=[0,1,2], index_col=0)<br>tracks = pd.read_csv(&#39;/fma-master/data/fma-metadata/tracks.csv&#39;, header=[0,1], index_col=0)<br><br>tracks = tracks[tracks[&#39;track&#39;, &#39;genre_top&#39;].notna()]<br>tracks = tracks[(tracks[&#39;track&#39;, &#39;genre_top&#39;] != &quot;Easy Listening&quot;) &amp; (tracks[&#39;track&#39;, &#39;genre_top&#39;] != &quot;Soul-RnB&quot;)]</pre><p>The first 2 lines load up the required dataset and the next two lines clean up the dataeset. I drop the data points where the genre is not specified, and where the genres are “Easy Listening” and “Soul-RnB” because there was far too few data points in these genres, and I felt that this was an appropriate bargain to make for increased accuracy.</p><p>Next, I used a few columns, and ran a preprocessor on the data. It performs 3 primary functions,</p><ol><li>Encodes all the classes (genres), using <a href="https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.LabelEncoder.html">sklearn.preprocessing.LabelEncoder</a>, which essentially labels all the classes from 0 to the no_of_classes-1</li><li>Applies the <a href="https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.StandardScaler.html">sklearn.preprocessing.StandardScaler</a>, which allows me to scale all my features, and prevents higher or lower value extremes from having a significant influence on the model just by virtue of their numerical values.</li><li>Runs the <a href="https://scikit-learn.org/stable/modules/generated/sklearn.feature_selection.VarianceThreshold.html">sklearn.feature_selection.VarianceThreshold</a>, which allows us to remove all features with variance below a certain threshold, and in this, case I used 0.5 as my limit. This prevents features where the data is far too similar for it to have a meaningful impact on the model calculations.</li></ol><p>The latter 2 are clubbed together in an <a href="https://scikit-learn.org/stable/modules/generated/sklearn.pipeline.Pipeline.html">sklearn.pipeline.Pipeline</a> construct that allows us to streamline the processes.</p><p>The code for implementing the above is, shown here:</p><pre>columns = [&#39;mfcc&#39;, &#39;spectral_contrast&#39;, &#39;chroma_cens&#39;, &#39;spectral_centroid&#39;, &#39;zcr&#39;, &#39;tonnetz&#39;]<br>features_indexed = features.loc[tracks.index]<br><br>def preprocess_2(tracks, features, columns):<br>  enc = LabelEncoder()<br>  labels = tracks[&#39;track&#39;, &#39;genre_top&#39;]<br>  X = features[columns].sort_index()<br>  y = tracks[&#39;track&#39;, &#39;genre_top&#39;].sort_index()<br>  X, y = shuffle(X, y, random_state=12)<br><br>  X_train, X_test,y_train, y_test = train_test_split(X, y, random_state=42, test_size=0.2)<br><br>  y_train = enc.fit_transform(y_train)<br>  y_test = enc.transform(y_test)<br><br>  pipe = Pipeline([<br>      (&#39;scaler&#39;, StandardScaler(copy=False)),<br>      (&#39;feature_selection&#39;, VarianceThreshold(threshold=0.5)),<br>  ])<br><br>  X_train = pipe.fit_transform(X_train, y_train)<br>  X_test = pipe.transform(X_test)<br><br>  return y_train, y_test, X_train, X_test, enc, pipe<br><br>y_train, y_test, X_train, X_test, enc, pipe = preprocess_2(tracks, features_indexed, columns)<br><br>joblib.dump(pipe, &#39;pipe.joblib&#39;)<br>joblib.dump(enc, &#39;enc.joblib&#39;)</pre><p>I save the pipeline and encoder used to ensure that I can transform and perform predictions on any new piece of data, at a later date, using the <a href="https://joblib.readthedocs.io/en/stable/"><em>joblib</em></a> module.</p><p>After the data has been run, I get X_train, X_test, y_train and y_test, with the shapes of these arrays as:</p><pre>X_train.shape = (39519, 329)<br>X_test.shape = (9880, 329)<br>y_train.shape = (39519,)<br>y_test.shape = (9880,)</pre><p>This means that I have almost 40000 training data points with 329 features for each of them, and 10000 testing data points.</p><h4>Step 2: Imbalanced Datasets, and how to deal with them</h4><p>While exploring the data, I found the number of data points in the training data for each class:</p><pre>tracks.loc[:, [(&#39;track&#39;, &#39;genre_top&#39;)]].value_counts()<br><br>#And this is the result I obtained<br>(track, genre_top) <br>Rock                   14182<br>Experimental           10608<br>Electronic              9372<br>Hip-Hop                 3552<br>Folk                    2803<br>Pop                     2332<br>Instrumental            2079<br>International           1389<br>Classical               1230<br>Jazz                     571<br>Old-Time / Historic      554<br>Spoken                   423<br>Country                  194<br>Blues                    110<br>dtype: int64</pre><p>This is clearly an imbalanced dataset, the number of data points for the top 2 categories are almost 10 times that of the lowest category. This kind of imbalance in the dataset can lead to skewed results in the model, making it biased towards always predicting the classes that are present in a larger number.</p><blockquote>This is especially problematic because the model tries to predict everything to be a part of the majority class, and because most of its predictions will be correct, since most of the points do in fact belong to the majority class, it will appear to have a high accuracy, despite making major errors in choosing other classes.</blockquote><p>Now, how do we fix this? There are a couple of ways:</p><ol><li><strong>Changing our data, through undersampling or oversampling:</strong> Undersampling is using less data from the majority classes, and trying to balance the dataset by reducing the overall number of observations. Oversampling is trying to increase the number of data points in the minority classes, and this is done by extrapolating from the available data points.</li><li><strong>Telling the model to weigh the lower classes more:</strong> In a TensorFlow model, the optimizations are made based on how much the error between the actual and predicted labels is, and as I just explained above, the accuracy appears to be high because the model doesn’t consider misclassifying the minority classes as a big problem. So, we tell the model to weigh incorrect predictions against the minority classes more strongly in its calculation of the error, and thus, weigh these classes more.</li></ol><p>Both of these options have their pros and cons and after experimenting with the <strong>oversampling</strong> and <strong>undersampling</strong>, and <strong>class weights technique,</strong> I found that the latter worked better for me.</p><p>Now there’s a lot of ways to find the weight that should be assigned to the different classes, but it is generally a variation on max_count/class_count , this would make the weights of all classes ≥1. With a little experimentation I found that for my case, this was the formula that worked best.</p><pre>classes, counts = np.unique(y_train, return_counts=True)<br>max_count = counts.max()<br>weights = {}<br><br>for i in range(len(counts)):<br>  count = counts[i]<br>  weights[i] = math.ceil(max_count/(count)+1) #the +1 creates a buffer in the weights</pre><p>Alright, now that we’ve figured out a way to deal with the imbalance in the dataset, let’s get into the model.</p><h4>Step 3: The TensorFlow Model FINALLY!</h4><p>Alright, so hoping that you have a basic understanding of AI, let’s finally discuss the model.</p><p>With a lot of experimentation, this was the model architecture I found to have the best performance. I did start off with a normal ANN architecture, but my data was structured in a way that gave me the idea that I could use a Convolutional Architecture.</p><blockquote>Convolutional layers consist of filters, which are used to detect improtant patterns. These are normally used for images, and is used to identify curves or textures. These filters lead to a lot of data being produced, as these filters perform multiple ocmplex operations over all the available data. After the ConvLayer, Pooling layers are added to help reduce the amount of data that has to be dealt with, while keeping the essential information intact.</blockquote><blockquote>To learn more about the Convolutional Neural Network, check out <a href="https://towardsdatascience.com/covolutional-neural-network-cb0883dd6529">https://towardsdatascience.com/covolutional-neural-network-cb0883dd6529</a></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XFRekt2tiW2NIJVHXDI0dg.png" /></figure><p>Now, while I don’t have images, which normally use a 2D Convolutional Network, I could instead use the 1-Dimensional Filter Layer.</p><p>My CNN has multiple layers of filters, and they learn by adjusting the filter parameters during training to recognize complex features. Multiple layers of the convolution, also allows for hierarchical feature extraction. This is the structure that gave me the best results:</p><pre>model = tf.keras.Sequential()<br>model.add(Input(shape=(X_train.shape[1])))<br>model.add(Reshape((X_train.shape[1], 1)))<br>model.add(Conv1D(128, 12, activation=&#39;relu&#39;)) #mod_4 had 128 mod_5 had 64<br>model.add(MaxPooling1D())<br>model.add(Conv1D(64, 12, activation=&#39;relu&#39;))<br>model.add(Flatten())<br>model.add(Dense(512, activation=&#39;relu&#39;))<br>model.add(Dropout(0.5))<br>model.add(Dense(64, activation=&#39;relu&#39;))<br>model.add(Dense(32, activation=&#39;relu&#39;))<br>model.add(Dense(len(np.unique(y_train)), activation=&#39;softmax&#39;))</pre><p>For a little more context:</p><ol><li><em>tf.keras.Sequential</em>, which is used to initialise the model is basically a paradigm that allows you to add layers into the model in a sequential manner.</li><li>The following are all part of the <em>tf.keras.layers</em> submodule:</li></ol><ul><li>the <em>Input</em> layer is defined with the input_shape expected being obtained from the X_train shape, so that it can interpret the number of features in the data point</li><li>the <em>Reshape</em> layer is required to make sure that my data can be used in the Convolutional layer next</li><li>the <em>Conv1D</em> and <em>MaxPooling1D</em> basically perform the functions for convolution as I explained above.</li><li>the <em>Flatten</em> layer, in effect, undoes the effect of the Reshape layer and allows the flattened data to be used in regular Dense layers</li><li>the <em>Dense</em> layers, are layers with a given number of units, and in this layer, we have all the units connected to each other, and the weights can be changed.</li><li>the <em>Dropout</em> layer, essentially disables a few of the weights that makes the model more efficient and lighter (PS: this is not nearly a complete explanation)</li></ul><p>And now, we just set up the specific settings, such as the optimisers, losses and hyperparameters and we’re ready to go! The code for the same is:</p><pre>adam = tf.keras.optimizers.Adam(learning_rate=0.001)<br>model.compile(loss=tf.keras.losses.SparseCategoricalCrossentropy(),<br>              optimizer=adam)</pre><p>There are two things worth explaining here, the optimizer Adam and the loss Sparse Categorical Cross Entropy. The loss essentially signifies the cost or error between the accurate label and the predicted label. The reason for choosing this specific loss is because my labels are one-hot encoded categories. Now one we’ve calculated the loss, we use the optimizer, in this case, Adam, to figure out how the model needs to change to reduce the losses.</p><blockquote>For more on Optimizers and Adam: <a href="https://towardsdatascience.com/optimizers-for-training-neural-network-59450d71caf6">https://towardsdatascience.com/optimizers-for-training-neural-network-59450d71caf6</a></blockquote><blockquote>For more on losses: <a href="https://towardsdatascience.com/what-is-loss-function-1e2605aeb904">https://towardsdatascience.com/what-is-loss-function-1e2605aeb904</a></blockquote><p>Now, to reiterate, the choice of optimizers, the values for the hyperparameters, and the architecture of the model are a result of extensive experimentation, and work differently for different use-cases for AI models.</p><p>Alright then, just one last step now, let’s run the model!</p><pre>es_callback = keras.callbacks.EarlyStopping(monitor=&#39;val_loss&#39;, patience=5)<br>checkpoint = ModelCheckpoint(filepath,monitor=&#39;val_loss&#39;,mode=&#39;min&#39;,save_best_only=True)<br><br>history = model.fit(X_train, y_train,<br>                    class_weight=weights,<br>                    validation_split = 0.1,<br>                    batch_size=2048,<br>                    epochs=100, verbose=1, <br>                    callbacks=[es_callback, checkpoint])</pre><p>The model is <strong>fitted </strong>with the data we have, using an <a href="https://keras.io/api/callbacks/early_stopping/">EarlyStopping</a> and <a href="https://keras.io/api/callbacks/model_checkpoint/">ModelCheckpoint</a> as measures to improve the recording and accuracy of the model. Check out the links to learn more about them.</p><p>Now, here we use the <strong><em>X_train</em></strong> and <strong><em>y_train</em></strong> datasets that we’ve created along with the <strong><em>weights</em></strong> created to counter the imbalance in the dataset. The <strong><em>batch_size</em></strong> here is rather high that makes the training resource-intensive and time-consuming, but it’s well worth the wait. The <strong><em>epochs</em></strong> signifies the number of times the model should train, and the <strong><em>verbose</em></strong> argument being set to 1 ensures I can see the progress as the model is trained.</p><p>We can see the progress in training as:</p><pre>plt.plot(history.history[&#39;loss&#39;])<br>plt.plot(history.history[&#39;val_loss&#39;])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JyBFmqrNpWBJI2BtrtUHjg.png" /></figure><p>In my graph the training loss remains higher than the validation loss, but they are both consistently reducing. The reason for this difference is because of the way my data is structured, and the imbalance I was dealing with.</p><h4>Step 4: Checking the model</h4><p>As I mentioned in the section on imbalanced dataset, it is often difficult to debug the accuracy of the model on such datasets, but there are metrics such as the ROC_AUC_Score that is considered a fairly good bechmark for balanced and imbalanced data alike.</p><blockquote>Learn more about the metric at:</blockquote><blockquote><a href="https://towardsdatascience.com/imbalanced-data-stop-using-roc-auc-and-use-auprc-instead-46af4910a494">https://towardsdatascience.com/imbalanced-data-stop-using-roc-auc-and-use-auprc-instead-46af4910a494</a></blockquote><blockquote><a href="https://machinelearningmastery.com/roc-curves-and-precision-recall-curves-for-imbalanced-classification/">https://machinelearningmastery.com/roc-curves-and-precision-recall-curves-for-imbalanced-classification/</a></blockquote><p>To implement it, I had to first run my model on the test dataset to get predictions, and convert it into a usable format for the metric using the <a href="https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.LabelBinarizer.html">sklearn.preprocessing.LabelBinarizer</a>.</p><pre>preds_test = model.predict(X_test)<br>preds_test = np.argmax(preds_test, axis=1)<br><br>from sklearn.preprocessing import LabelBinarizer<br><br>label_binarizer = LabelBinarizer().fit(y_train)<br>y_onehot_test = label_binarizer.transform(y_test)<br>preds_onehot_test = label_binarizer.transform(preds_test)</pre><p>Now, to run the metric, there are two options to run it that I considered, the average=None provides a list of the roc_auc_score for each class in a list, and the average=&#39;weighted&#39; provides the average of all the scores weighted by their class number.</p><pre>print(roc_auc_score(y_onehot_test, preds_onehot_test, average=None))<br>print(roc_auc_score(y_onehot_test, preds_onehot_test, average=&#39;weighted&#39;))<br><br>#and this is the result that I obtained:<br>[0.72444219 0.88212985 0.79329675 0.79628912 0.78339301 0.82810634<br> 0.86196564 0.69422879 0.78670436 0.76173557 0.98794697 0.64119238<br> 0.85371012 0.85083461]<br>0.808511463879435</pre><p>In this particular run, I got a 0.782 weighted accuracy, with eatleast 70% accuracy for all but one of the classes. Analysing the exact distribution of the classes can be done using a Confusion Matrix:</p><pre>from sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay<br>cm = confusion_matrix(y_test, preds_test)<br>disp = ConfusionMatrixDisplay(confusion_matrix=cm)<br>fig, ax = plt.subplots(figsize=(8,8))<br>disp.plot(ax=ax)</pre><p>A Confusion Matrix essentially shows the number of predictions with the true_label mapped against the predicted_label for each class. Ideally, the primary diagonal should be the brightest, which does show up in this diagram, however, for some classes, the accuracy still remains poor. It is important to note that because the data is imbalanced, the colors do not quite show strongly on the diagonal, but it is easy to check that the value on the diagonal is the highest for all the predictions for any label. This is the result we get:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LPTgIJxfDpOW6EZoWww97g.png" /></figure><p>While this was the latest iteration of my model, it wasn’t the best, however I ensured version control, and maintained a record of the one’s with the best accuracy. I would do this by saving the trained model, and mapping it to its metrics.</p><p>So, once we’re done with the final training and we’re comfortable with our model, let’s save this model in a h5py file: model.save(&#39;model.h5&#39;)</p><p>And that’s it! We’ve created a TensorFlow model, and we’ve measured it’s accuracy, and saved it for future use!</p><h3>The Debugging</h3><p>Alright, I know that this post ahs already grown quite large, but I still have a few important points to make about all of the things I’ve discussed on this post:</p><ol><li>Be sure to explore your data in as many different ways as possible. It is critical that you know what problems may arise if your data is of certain types, like dealing with an imbalanced dataset in my example.</li><li>Be ready to experiment with the different ways of solving your problems. The reason I shared the under- and over-sampling techniques despite not using them in my final run is because it was a step that I took, and then I had to entirely drop the idea, after experimenting with just undersampling or oversampling or a combination of both. It is important that we try and make mistake and find the answer that suits us best.</li><li>Be willing to try a new paradigm — if I had remained stuck to the resular dense ANN structure, I would not have been able to reach the accuracy I have now.</li><li>Try out different options— there are a lot of variables to change.</li></ol><ul><li>For example, in the preprocessing, I could tweak the variance in the feature_selection that I performed with VarianceThreshold, or I could use an entirely different technique, and I did — I tried using a function called SelectKBest, which tries to select k best predictors for the label, again, here I tweaked the value of k multiple times.</li><li>The optimizer I used is Adam, but I also experimented with simple Stochastic Gradient Descent. Again, in the Adam optimizer, the learning_rate was an important parameter in the performance of the model.</li><li>The weights for the classes were found out of atleast a hundred of the different variations I had created while mapping and comparing the performance with regards to each of the classes using the Confusion Matrix.</li><li>And finally, the model is never right in the first go, or even on the 10th try. Keep trying and pushing the architecture, but understand what errors could be occuring and learn how to solve them. A simple example would be if your training loss while plotting is getting smaller while your validation loss in training stagnates, you might be overfitting the model.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D6jdhOVm0ojgLP31_8Kegg.png" /><figcaption>This is a part of the JSON file I used while I was keeping track of my models and their performances. This is a snap from when I was using the old architecture! The JSON has been converted to a table view using <a href="https://jsongrid.com/json-grid">https://jsongrid.com/json-grid</a></figcaption></figure><p>That’s all I have for you all now! Next time, I’ll be explaining a few caveats with the interprettation of the results of my model and will be using this model to run predictions on my collected data and show you how to create a Dashboard using Plotly to show this data and share the model on your website!</p><p>Visit the complete list of stories for this project at:</p><p><a href="https://kaavyamaha12.medium.com/list/5c134b5ff913">A Genre Classification App using Tensorflow, Dash and AWS</a></p><p>The code with the data and how to collect it, along with the code for the model is available at:</p><p><a href="https://github.com/Kaavya12/top-50-audios">GitHub - Kaavya12/top-50-audios: Repository with code to collect top 50 songs from the Billboard Top 50 Ratings for the last 50 years.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4286d87d71f6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Extracting audio features using Librosa]]></title>
            <link>https://kaavyamaha12.medium.com/extracting-audio-features-using-librosa-3be4ff1fe57f?source=rss-d7b4cf89685e------2</link>
            <guid isPermaLink="false">https://medium.com/p/3be4ff1fe57f</guid>
            <category><![CDATA[genre-classification]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-collection]]></category>
            <dc:creator><![CDATA[Kaavya Mahajan]]></dc:creator>
            <pubDate>Fri, 20 Oct 2023 03:32:34 GMT</pubDate>
            <atom:updated>2024-05-05T12:15:21.674Z</atom:updated>
            <content:encoded><![CDATA[<p>From the top 2500 audios of the last 50 years, I extract a few relevant features using Librosa, for the model I have trained.</p><p>This post is a part of a series where I detail the entire process of making a Genre Classification App using Machine Learning:</p><ol><li>Finding the audios to be classified, i.e. <strong>finding the top 50 songs for the last 5 decades </strong><a href="https://kaavyamaha12.medium.com/finding-the-trendiest-audios-for-the-last-50-years-b6583d4bbf20"><em>(find it here)</em></a></li><li>Finding the training data, extracting features from the trendy audios using <strong>Librosa</strong> (a Python library) <em>(you’re here!)</em></li><li>Training the <strong>Machine Learning (Tensorflow)</strong> model (<a href="https://medium.com/@kaavyamaha12/training-a-tensorflow-model-for-predicting-the-genres-of-popular-songs-4286d87d71f6">find it here</a>).</li><li><strong><em>Coming Soon — </em></strong>Creating the <strong>Plotly-Dash Application</strong> to make a website for the model</li><li><strong><em>Coming Soon — </em></strong>Deploying the completed app to <strong>AWS EC2</strong></li></ol><h3>The goal</h3><p>In my last post, I explained how I obtained the testing audio for my project, to classify the genres of the top 50 songs for each of the last 50 years. This time, I start with the raw audio files, and work up to the extracted features. I also show the process for training the tensorflow model used for the classification.</p><h3>The process</h3><h4>Extracting audio features</h4><p>The training dataset that I had decided to use was obtained from the <a href="https://github.com/mdeff/fma">FMA dataset</a>. The metadata of this repo, is shared at <a href="https://os.unil.cloud.switch.ch/fma/fma_metadata.zip">fma_metadata.zip</a>.</p><p><strong>The labels for the training data, i.e. the Genres, </strong>were found in <em>tracks.csv</em> in the FMA Metadata, and the code to extract them is shown in the section for training the model.</p><p><strong>For the features for training, </strong>I used the <em>features.cs</em>v file that has been collected in the file shared in the FMA Metadata. The <em>features.csv</em> when loaded into a Pandas DataFrame can be seen here:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2QdS8ZfGH0u5CBhSY81a8Q.png" /></figure><p>The structure of <em>features.csv </em>is essentially a calculation for 7 moments (‘mean’, ‘std’, ‘skew’, ‘kurtosis’, ‘median’, ‘min’, ‘max’) for each batch of the features below:</p><ol><li><a href="https://librosa.org/doc/latest/generated/librosa.feature.chroma_stft.html#librosa.feature.chroma_stft"><strong>chroma_stft</strong></a><strong> </strong>— an audio chromagram, which essentially tries to map the changes in pitch, categorised in 12 different bins, this can be considered as mapping what note of music (as we perceive it) is being struck in the audio at that moment.</li><li><a href="https://librosa.org/doc/latest/generated/librosa.feature.chroma_cqt.html"><strong>chroma_cqt</strong></a><strong> — </strong>using the constant Q-transform alongside chroma features.</li><li><a href="https://librosa.org/doc/latest/generated/librosa.feature.chroma_cens.html"><strong>chroma_cens</strong></a><strong> —chroma energy normalized statistics (CENS); </strong>taking statistics over large windows to smooth local deviations in tempo, articulation, and musical ornaments such as trills and arpeggiated chords.</li><li><a href="https://librosa.org/doc/latest/generated/librosa.feature.tonnetz.html"><strong>tonnetz</strong></a><strong> — </strong>the tonal centroid features (tonnetz), projects chroma features onto a 6-dimensional basis representing the perfect fifth, minor third, and major third each as two-dimensional coordinates.</li><li><a href="https://librosa.org/doc/latest/generated/librosa.feature.mfcc.html"><strong>mfcc</strong></a><strong> — </strong>the Mel Scale is a logarithmic transformation of a signal’s frequency, and Mel Frequency Cepstral Coefficients (MFCCs) represent timbre quite well.</li><li><a href="https://librosa.org/doc/latest/generated/librosa.feature.rms.html"><strong>rmse</strong></a><strong>- </strong>the root-mean-square energy (RMS) value for each frame</li><li><a href="https://librosa.org/doc/latest/generated/librosa.feature.zero_crossing_rate.html"><strong>zcr</strong></a><strong> —</strong> the number of times the energy hits a value of 0 in that time frame</li><li><a href="https://librosa.org/doc/latest/generated/librosa.feature.spectral_centroid.html"><strong>spectral_centroid</strong></a><strong> — e</strong>ach frame of a magnitude spectrogram is normalized and treated as a distribution over frequency bins, from which the mean (centroid) is extracted per frame.</li><li><a href="https://librosa.org/doc/latest/generated/librosa.feature.spectral_bandwidth.html"><strong>spectral_bandwidth</strong></a><strong> — </strong>Compute p’th-order spectral bandwidth.</li><li><a href="https://librosa.org/doc/latest/generated/librosa.feature.spectral_contrast.html"><strong>spectral_contrast</strong></a><strong> — </strong>each frame of a spectrogram is divided into sub-bands and the energy contrast is estimated by comparing the mean energy in the top quantile (peak energy) to that of the bottom quantile (valley energy).</li><li><a href="https://librosa.org/doc/latest/generated/librosa.feature.spectral_rolloff.html"><strong>spectral_rolloff</strong></a><strong> — </strong>the roll-off frequency is defined for each frame as the center frequency for a spectrogram bin such that at least roll_percent (0.85 by default) of the energy of the spectrum in this frame is contained in this bin and the bins below.</li></ol><p>The numbers of the batch for the different features are: chroma_stft=12, chroma_cqt=12, chroma_cens=12, tonnetz=6, mfcc=20, rmse=1, zcr=1, spectral_centroid=1, spectral_bandwidth=1, spectral_contrast=7, spectral_rolloff=1</p><p>Next, I had to actually extract the features from each of the 2500 audios that I had scraped earlier (read more about it in the previous post in the series). This is the function that performs that task, which is obtained entirely from the Github Repo, in the <a href="https://github.com/mdeff/fma/blob/master/features.py">features.py</a> file. This is the relevant section, edited a little to suit my specific needs and data structure:</p><pre>def columns():<br>    feature_sizes = dict(chroma_stft=12, chroma_cqt=12, chroma_cens=12,<br>                         tonnetz=6, mfcc=12, rmse=1, zcr=1,<br>                         spectral_centroid=1, spectral_bandwidth=1,<br>                         spectral_contrast=7, spectral_rolloff=1)<br>    moments = (&#39;mean&#39;, &#39;std&#39;, &#39;skew&#39;, &#39;kurtosis&#39;, &#39;median&#39;, &#39;min&#39;, &#39;max&#39;)<br><br>    columns = []<br>    for name, size in feature_sizes.items():<br>        for moment in moments:<br>            it = ((name, moment, &#39;{:02d}&#39;.format(i+1)) for i in range(size))<br>            columns.extend(it)<br><br>    names = (&#39;feature&#39;, &#39;statistics&#39;, &#39;number&#39;)<br>    columns = pd.MultiIndex.from_tuples(columns, names=names)<br><br>    return columns.sort_values()<br><br>def compute_features(audio_path, year=None, rank=None, track_index=None):<br><br>    features = pd.Series(index=columns(), dtype=np.float32)<br>    warnings.filterwarnings(&#39;error&#39;, module=&#39;librosa&#39;)<br>    <br>    if year and rank:<br>        features[&quot;year&quot;] = year<br>        features[&quot;rank&quot;] = rank<br>    elif track_index:<br>        features[&quot;track_index&quot;] = track_index<br><br>    def feature_stats(name, values):<br>        features[name, &#39;mean&#39;] = np.mean(values, axis=1)<br>        features[name, &#39;std&#39;] = np.std(values, axis=1)<br>        features[name, &#39;skew&#39;] = stats.skew(values, axis=1)<br>        features[name, &#39;kurtosis&#39;] = stats.kurtosis(values, axis=1)<br>        features[name, &#39;median&#39;] = np.median(values, axis=1)<br>        features[name, &#39;min&#39;] = np.min(values, axis=1)<br>        features[name, &#39;max&#39;] = np.max(values, axis=1)<br><br>    try:<br>        filepath = audio_path<br>        x, sr = librosa.load(filepath, sr=None, mono=True)  # kaiser_fast<br><br>        f = librosa.feature.zero_crossing_rate(x, frame_length=2048, hop_length=512)<br>        feature_stats(&#39;zcr&#39;, f)<br><br>        cqt = np.abs(librosa.cqt(x, sr=sr, hop_length=512, bins_per_octave=12,<br>                                 n_bins=7*12, tuning=None))<br>        assert cqt.shape[0] == 7 * 12<br>        assert np.ceil(len(x)/512) &lt;= cqt.shape[1] &lt;= np.ceil(len(x)/512)+1<br><br>        f = librosa.feature.chroma_cqt(C=cqt, n_chroma=12, n_octaves=7)<br>        feature_stats(&#39;chroma_cqt&#39;, f)<br>        f = librosa.feature.chroma_cens(C=cqt, n_chroma=12, n_octaves=7)<br>        feature_stats(&#39;chroma_cens&#39;, f)<br>        f = librosa.feature.tonnetz(chroma=f)<br>        feature_stats(&#39;tonnetz&#39;, f)<br><br>        del cqt<br>        stft = np.abs(librosa.stft(x, n_fft=2048, hop_length=512))<br>        assert stft.shape[0] == 1 + 2048 // 2<br>        assert np.ceil(len(x)/512) &lt;= stft.shape[1] &lt;= np.ceil(len(x)/512)+1<br>        del x<br><br>        f = librosa.feature.chroma_stft(S=stft**2, n_chroma=12)<br>        feature_stats(&#39;chroma_stft&#39;, f)<br><br>        f = librosa.feature.rms(S=stft)<br>        feature_stats(&#39;rmse&#39;, f)<br><br>        f = librosa.feature.spectral_centroid(S=stft)<br>        feature_stats(&#39;spectral_centroid&#39;, f)<br>        f = librosa.feature.spectral_bandwidth(S=stft)<br>        feature_stats(&#39;spectral_bandwidth&#39;, f)<br>        f = librosa.feature.spectral_contrast(S=stft, n_bands=6)<br>        feature_stats(&#39;spectral_contrast&#39;, f)<br>        f = librosa.feature.spectral_rolloff(S=stft)<br>        feature_stats(&#39;spectral_rolloff&#39;, f)<br><br>        mel = librosa.feature.melspectrogram(sr=sr, S=stft**2)<br>        del stft<br>        f = librosa.feature.mfcc(S=librosa.power_to_db(mel), n_mfcc=20)<br>        feature_stats(&#39;mfcc&#39;, f)<br><br>    except Exception as e:<br>        print(&#39;{}: {}&#39;.format(audio_path, repr(e)))<br><br>    return features</pre><p>All of these are simple functions available in the Librosa library, which is used for audio analysis.</p><p>Following from the code I had last time, which resulted in folders with 2500 audios saved with years and the rank of the audio as the name of the file, this is how I built on it to get a final csv.</p><pre>import os<br>directory = &#39;/audios&#39;<br>file_locations = []<br><br>for subdir, dirs, files in os.walk(directory):<br>    for file in files:<br>        if file[-4:] == &quot;.mp3&quot;:<br>            file_locations.append(os.path.join(subdir, file))<br><br>for i in file_locations:<br>    index = i[:-4].split(&quot;/&quot;)[-1]<br>    series_list.append(compute_features(track_index=index, audio_path=i))<br>    print(len(series_list))<br><br>muse_features = pd.concat(series_list, axis=1).T<br>muse_features[&#39;track_index&#39;] = pd.to_numeric(muse_features[&#39;track_index&#39;])<br>muse_features = muse_features.set_index(&quot;track_index&quot;)<br>muse_features = muse_features.sort_index()<br>muse_features.to_csv(&quot;test_features.csv&quot;)</pre><p>Finally, this results in a CSV file with a similar structure to the one seen above, with information on the year and rank of the audio to be able to uniquely identify it at a later date. Here we have 2493 songs, with a total of 518 columns.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QQ0sV-WFDSoZedPgKgK-3w.png" /></figure><p>We have the features for these audios, and the next step now is to build the classification model.</p><h3>The debugging (and a few thoughts)</h3><p>Of all the sections of my project, I believe this one had the smoothest sailing. Well, the code part at least, the hard part was finding appropriate data.</p><p>I’d like to emphasise that I went into the research process with just an idea, and nothing more. I spent days learning about the different kinds of audio features, and how they could be used. I could see 2 ways of implementing the project I was considering — using extracted features about the audio files, or processing and running models on the original audio files themselves. Due to the lack of processing capabilities on my end — as I was simply using only my laptop for all of the processing tasks, albeit, sometimes with a little outsourcing to Google Colab — I ended up pursuing the first track.</p><p>Extracted audio features, while also very resource-intensive, was an effective enough strategy for my task, maintaining enough precision while balancing the requirements.</p><p>Finding the data took at least a week of concerted efforts, diving into link after link, with 50 tabs open on my browser with the hopes that one of them would give me the data I needed. And then, I stumbled upon the one that did, and it was perfect. Not to mention, the accessible code I found at the FMA repo that I only slightly had to modify to suit my purposes!</p><p>Over the years, I’ve used Kaggle as a source for any and all kind of data, and I have been very very grateful to everyone who contributes to the data that we collect and use for ML and Data Science, and I am proud that I have something to contribute and give back to the community, with respect to data.</p><p>I have shared not only the data I collected previously, which is just basic information on the popular singles over the last 50 years, in a compiled CSV file, but also all of the features that I have extracted from the audios that I collected to be used by anyone who is interested in exploring the field further. In the future, I might be able to collect all of the raw audio files I have collected as well — in which case, this blog will be the first place to be updated.</p><p>On that note, find the data that I collected and all the pertinent code to do it yourself over at:</p><p><a href="https://github.com/Kaavya12/top-50-audios/tree/main">GitHub - Kaavya12/top-50-audios: Repository with code to collect top 50 songs from the Billboard Top 50 Ratings for the last 50 years.</a></p><p>And find the FMA Repo at:</p><p><a href="https://github.com/mdeff/fma">GitHub - mdeff/fma: FMA: A Dataset For Music Analysis</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3be4ff1fe57f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Finding the trendiest audios for the last 50 years!]]></title>
            <link>https://kaavyamaha12.medium.com/finding-the-trendiest-audios-for-the-last-50-years-b6583d4bbf20?source=rss-d7b4cf89685e------2</link>
            <guid isPermaLink="false">https://medium.com/p/b6583d4bbf20</guid>
            <category><![CDATA[dash-plotly]]></category>
            <category><![CDATA[music]]></category>
            <category><![CDATA[web-scraping]]></category>
            <category><![CDATA[genre-classification]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Kaavya Mahajan]]></dc:creator>
            <pubDate>Sat, 14 Oct 2023 13:43:20 GMT</pubDate>
            <atom:updated>2024-05-05T12:15:07.195Z</atom:updated>
            <content:encoded><![CDATA[<p>This post is a part of a series where I detail the entire process of making a Genre Classification App using Machine Learning:</p><ol><li>Finding the audios to be classified, i.e. <strong>finding the top 50 songs for the last 5 decades</strong> <em>(you’re here!)</em></li><li>Finding the training data, extracting features from the trendy audios using <strong>Librosa</strong>, a Python library (<a href="https://kaavyamaha12.medium.com/extracting-audio-features-using-librosa-3be4ff1fe57f">find it here</a>).</li><li>Training the <strong>Machine Learning (Tensorflow)</strong> model (<a href="https://medium.com/@kaavyamaha12/training-a-tensorflow-model-for-predicting-the-genres-of-popular-songs-4286d87d71f6">find it here</a>).</li><li><strong><em>Coming Soon —</em></strong> Creating the <strong>Plotly-Dash Application</strong> to make a website for the model</li><li><strong><em>Coming Soon —</em> </strong>Deploying the completed app to <strong>AWS EC2</strong></li></ol><h3>The goal</h3><p>For my project, I wanted to be able to classify the genre of the top 50 songs over the last 50 years. Here, I understand that choosing which list to pick the top songs from is a matter of subjective opinion, and there are a myriad lists out there to choose from - from different nations, to different languages, however, I choose the Billboard Top 50 lists, as they provide a consistent source of information, and are obtained from the same individual source.</p><h3>The process</h3><p>The first step was to find the details of the top 50 songs. This was fairly simple, as Wikipedia has the <strong>Billboard Year-End Hot 100 Singles Charts, </strong>easily available with the information categorised clearly. Here’s a snapshot of the page we’ll be scraping:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yw8WHdTlGIHpjcesypP39w.png" /><figcaption>Billboard’s Hot 100 Singles for the Year 1974</figcaption></figure><p>The url for this page is formatted as <a href="https://en.wikipedia.org/wiki/Billboard_Year-End_Hot_100_singles_of_1974"><em>https://en.wikipedia.org/wiki/Billboard_Year-End_Hot_100_singles_of_1974</em></a>, and changing the year appearing at the end of the URL can get us the singles for the different years, which allows us to scrape the content easily.</p><p>Using just these few lines of code, we can create a Pandas DataFrame, albeit without the singer’s names, which I add in, during the final display process.</p><pre>#importing libraries<br>import requests<br>from bs4 import BeautifulSoup<br>import pandas as pd<br><br>#Creating base variables<br>years = list(range(1973,2023))<br>base_url = &quot;https://en.wikipedia.org/wiki/Billboard_Year-End_Hot_100_singles_of_&quot;<br>songs = {}<br>singers = {}<br><br>#Looping and Scraping <br>for year in years:<br>  names = []<br>  singer_names = []<br>  r = requests.get(f&quot;{base_url}{year}&quot;)<br>  soup = BeautifulSoup(r.content)<br>  table = soup.findAll(&#39;table&#39;, {&#39;class&#39;: &#39;wikitable&#39;})[0]<br>  for row in table.findAll(&#39;tr&#39;):<br>    links = row.findAll(&#39;a&#39;)<br>    if links:<br>      if len(links) &gt; 2:<br>        song = links[0].contents[0]<br>        singer = &quot;&quot;<br>        for link in links[1:]:<br>          singer += f&quot;{link.contents[0]},&quot;<br>      elif len(links) == 2:<br>        song, singer = links[0].contents[0], links[1].contents[0]<br>      else:<br>        song, singer = links[0].contents[0], None<br>      names.append(song)<br>      singer_names.append(singer)<br>  songs[year] = names<br>  singers[year] = singer_names<br><br>&quot;&quot;&quot;<br>#Uncommenting this docstring will allow you to see the top song for each year<br>for year, hits in songs.items():<br>  print(f&quot;{year}: {len(hits)} - Top: {hits[0]}&quot;)<br>&quot;&quot;&quot;<br><br>songs_df = pd.DataFrame(songs).transpose()<br>songs_df.columns = [i for i in range(1,101)]<br>singers_df = pd.DataFrame(singers).transpose()<br>singers_df.columns = [i for i in range(1,101)]<br><br>songs_df = songs_df.stack()<br>singers_df = singers_df.stack()<br>song_details = pd.concat([songs_df, singers_df], axis=1, keys=[&quot;song&quot;, &quot;singer&quot;])<br>song_details.to_csv(&quot;song_details.csv&quot;)</pre><p>Let’s break this code down</p><ul><li>First, we import the libraries we need — <strong>requests</strong> and <strong>BeautifulSoup</strong> for web scraping and parsing the retrieved data and <strong>pandas</strong> for organising the data-frame</li><li>Next, we set up the years list, enumerating the years we want data for and the base URL, that can be edited for each year we wish to scrape for</li><li>Next, we do the important work — scraping the data. We loop over each year, and append the base URL to give us the required year, and pass it into the GET method from the requests library.</li><li>Then, we use the bs4 library to get a formatted version of the HTML content of the file, and find all the tables in the page with the class “wikitable”, then selecting the first one. The background information for which class and which tag to scrape I learnt from exploring the Wiki Page first, and then performing the queries.</li><li>Once I’d gotten the table, I looped over all it’s rows, and found the link tags. This is useful because as is visible in the screenshot, most of the songs and singers have their own pages that are linked to, and the ‘a’ tag makes querying more specific and streamlined.</li><li>I then added all of the pieces of data, and used a few DataFrame transformations, and produced a final dataframe that appears as:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1010/1*3KwkNCyji-DozrGdtBqlGg.png" /><figcaption>Song Details scraped from Billboards Top 50</figcaption></figure><p>Now that we have these details, we can get the audio files for these songs. The way I approached the issue was to find the YouTube links for these songs, and then used a library called yt_dlp (youtube_dl) to find the audios.</p><p><strong>Step 1: To find the YouTube URLs:</strong></p><p>I ran a Google Search with the query having the name of the song, the singer, and the year the song was released. This is the code used and the page that appears:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KmsgOOKqtKOqiIB6UIqPfw.png" /></figure><p>I then looked for all the links on the page, and found the one that matches the YouTube format, and saved the URL. I created a function that I could use on each row of the Data Frame that I had created above using the <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.apply.html">pd.DataFrame.apply()</a> method:</p><pre>def fetch_yt_urls(item):<br>  song = item[&quot;song&quot;]<br>  singer = item[&quot;singer&quot;]<br>  year = item.name[0]<br>  song_search = &quot;+&quot;.join(song.split())<br>  r = requests.get(f&quot;https://www.google.com/search?q={song_search}+{year}+{singer}+song&quot;)<br>  d = {<br>      &quot;%20&quot;:&quot; &quot;, &quot;%21&quot;:&quot;!&quot;, &quot;%22&quot;:&#39;&quot;&#39;, &quot;%23&quot;:&quot;#&quot;, &quot;%24&quot;:&quot;$&quot;, &quot;%25&quot;:&quot;%&quot;, &quot;%26&quot;:&quot;&amp;&quot;, &quot;%27&quot;:&quot;&#39;&quot;, &quot;%28&quot;:&quot;(&quot;, &quot;%29&quot;:&quot;)&quot;, &quot;%2A&quot;:&quot;*&quot;, &quot;%2B&quot;:&quot;+&quot;, &quot;%2C&quot;:&quot;,&quot;, &quot;%2D&quot;:&quot;-&quot;, &quot;%2E&quot;:&quot;.&quot;, &quot;%2F&quot;:&quot;/&quot;, &quot;%3A&quot;:&quot;:&quot;, &quot;%3B&quot;:&quot;;&quot;, &quot;%3C&quot;:&quot;&lt;&quot;, &quot;%3D&quot;:&quot;=&quot;, &quot;%3E&quot;:&quot;&gt;&quot;, &quot;%3F&quot;:&quot;?&quot;<br>    }<br>  soup = BeautifulSoup(r.content)<br>  for link in soup.findAll(&#39;a&#39;):<br>    if link[&#39;href&#39;].startswith(&quot;/url?q=https://www.youtube.com/watch&quot;):<br>      src_link = link[&#39;href&#39;][7:]<br>      for key, value in d.items():<br>        src_link = src_link.replace(key, value)<br>      src_link = src_link.partition(&quot;&amp;&quot;)[0]<br>      return src_link<br>      <br>  return None<br><br>yt_urls = song_details.apply(fetch_yt_urls, axis=1)<br>all_data = pd.concat([song_details, yt_urls], axis=1)<br>all_data.columns = [&quot;song&quot;, &quot;singer&quot;, &quot;urls&quot;]<br><br>top_50 = all_data[np.in1d(all_data.index.get_level_values(1), range(1,51))]<br><br>&quot;&quot;&quot;<br>here, I had to individually search the URLs for 5 out of the 2500 songs that <br>could not be scraped<br><br>This is an example of one of those:<br>top_50.loc[(1994, 24), &quot;urls&quot;] = &quot;https://www.youtube.com/watch?v=a02dBbBGSPg&quot;<br>&quot;&quot;&quot;<br><br>top_50.to_csv(&quot;../top_50_data/top_50s_chart.csv&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YKY5OGZ1rffw1i6bwKxUpA.png" /><figcaption>This is the Data Frame with the URLs of the YouTube Videos for the Songs</figcaption></figure><p><strong>Step 2: To download the audio files:</strong></p><p>The following is used to save all the audios into a folder named usingthe year and rank of the song. I was able to download all but 7 audio files.</p><pre>&quot;&quot;&quot;<br>This is to be run in the terminal to access the library<br>!pip3 install --force-reinstall https://github.com/yt-dlp/yt-dlp/archive/master.tar.gz<br>&quot;&quot;&quot;<br><br>import yt_dlp as youtube_dl<br>from __future__ import unicode_literals<br><br>def save_audios(row):<br>  year = row.name[0]<br>  rank = row.name[1]<br>  ydl_opts = {<br>      &#39;format&#39;: &#39;bestaudio/best&#39;,<br>      &#39;postprocessors&#39;: [{<br>          &#39;key&#39;: &#39;FFmpegExtractAudio&#39;,<br>          &#39;preferredcodec&#39;: &#39;mp3&#39;,<br>          &#39;preferredquality&#39;: &#39;192&#39;,<br>      }],<br>      &#39;outtmpl&#39;: f&#39;audios/{year}/{rank}&#39;<br>    }<br>  <br>  try:<br>    with youtube_dl.YoutubeDL(ydl_opts) as ydl:<br>      ydl.download([row[&quot;urls&quot;]])<br>  except:<br>    pass<br><br>top_50.apply(save_audios, axis=1)</pre><p>Now, I had 2,493 audio files that needed to be analysed, and the features to be extracted so that I could predict their genres.</p><h3>The debugging</h3><p>Of course, to find out the 106 lines of code that worked, I had to experiment with over 1000s of lines of code, wait hours on end as the audios downloaded, and sometimes, even lost a lot of progress due to code or technical errors. I hope what I’ve learned from my missteps can be useful to all of you, so I’ll point out a few recurring issues I had, and how I resolved them.</p><ol><li>Applying any functions on a huge DataFrame can be difficult, so the pd.DataFrame.apply() function that I mentioned above is very useful, but it is important to keep in mind the structure of your DataFrame. In the code snippet above where I compiled my data for the songs while scraping them, I hadn’t realised that I would need to structure it a certain way to be able to run the function to fetch YouTube URLs on it, so before you start scraping data, I’d suggest you try to have as clear of any idea on the next functions with the data and how, if any, transformations would need to be applied.</li><li>Web scraping can be blocked or restricted sometimes, and while I did sometimes run into this issue, I could normally just resume my code from where it stopped, however, for larger-scale scraping, it is always best to use Selenium.</li><li>I would also strongly recommend not using Google Colab for scraping and other intensive tasks as it is easy to lose the progress in such cases. Especially with downloading the audios, because it is time-consuming and Colab might get maxed out with its resources. However, if you must use Google Colab, try to use it concurrently. What I did was to split the code into batches of 10 years, and ran 5 separate files simultaneously. This is a patched-together solution, and using your local machine is always advisable.</li><li>In a similar vein to point 1, some functions with DataFrames, and their transformations (even with the docs in some cases) can be difficult to understand, so StackOverflow proves to be a very useful resource, as someone has most likely already encountered the issue you’re facing. In addition, while this is definitely common practice, I cannot stress how much just using the print statement helped me when formulating my code and debugging because it allowed me to get a better grasp on the problem I was facing, be it with DataFrame structures, functions, or really anywhere throughout the code.</li></ol><h3>Conclusion</h3><p>I hope this helps all of you!</p><p>The source code and Data Frames are shared across at <a href="https://github.com/Kaavya12/top-50-audios.git">top-50-audios</a>.</p><p><a href="https://github.com/Kaavya12/top-50-audios/tree/main">GitHub - Kaavya12/top-50-audios: Repository with code to collect top 50 songs from the Billboard Top 50 Ratings for the last 50 years.</a></p><p>Visit the next post in this series to see the training data I used as well as how I extracted the features from the songs that I have just collected. Follow along on this journey of creating a completely functional AI model and Dash App from scratch.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b6583d4bbf20" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How companies follow us around the internet — Cookies, Privacy and Advertising]]></title>
            <link>https://kaavyamaha12.medium.com/how-companies-follow-us-around-the-internet-cookies-privacy-and-advertising-64df31795540?source=rss-d7b4cf89685e------2</link>
            <guid isPermaLink="false">https://medium.com/p/64df31795540</guid>
            <dc:creator><![CDATA[Kaavya Mahajan]]></dc:creator>
            <pubDate>Wed, 19 Apr 2023 16:28:56 GMT</pubDate>
            <atom:updated>2023-04-21T12:36:31.049Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*wXZGTqbGGljUbTbfYa12uw@2x.jpeg" /></figure><p>It is truly amazing how companies like Amazon are able to give us an ad for something we were just thinking about, maybe something we looked up on a completely different platform. Maybe even an ad we accidentally clicked on on Facebook or Instagram that is now hounding us everywhere?</p><p>This seemingly magical omniscience of large tech companies is due to data. And there has been a lot of talk about the importance of data, especially with Artificial Intelligence tools being developed to analyse all of this data, and creating some truly astounding results.</p><blockquote>Consumer data analytics is essentially a practice businesses use to monitor us, their customers &amp; find the best way to maximise their profits — they analyse our data and try to understand our behaviours, and cater to them. This technique is used regularly and on very large scales.</blockquote><p>Now, there is the question of how these companies get this data. There are multiple ways of going about doing this, the most prominent being tracking us on the internet. One of the ways they do this is by using cookies. Cookies were invented as necessary elements of modern web design. They are the reason websites can remember our browsers, so that we don’t have to keep logging in every time we close a window, or maybe leave the tab for a little while and return to it after a few minutes.</p><p>This kind of cookie, when implemented by a website it was created on, is a first-party cookie. There is, however, another type of cookie, a third-party cookie — and this is the one that is being talked about all around the world today. In fact we can see them at work right now, on this Medium article you’re reading, if you’re on your computer, scroll back up to the top of this article and see the icons of Twitter, Facebook, LinkedIn — all of these buttons link to these different websites, who also have their cookies on the Medium website to enable you to share an article you like by just clicking a button, using the cookies to recognise you and do all the logging-in work in the background.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/523/1*JHinEcqxiD575b3tMvK3AQ@2x.jpeg" /></figure><p>And these websites have cookies over a wide area of the web, each cookie picking up some information about you, a tiny breadcrumb, gathering one data point at a time, that is all put together by these corporations to create a sense of who you are and how you behave.</p><blockquote>Actually, let’s do a small exercise. If you’re on a Chrome browser, I’d like you to click on the 3-dot menu at the top-right corner of your screen, and click on the Settings tab. [Fig 1]</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/223/1*1Z6XfFttKMjiqp0ZTERR8Q@2x.jpeg" /></figure><blockquote>From here, type out the following onto your search bar — “See all site data and permissions”. This leads us to a page where we can find all the active cookies in our browser. This is the tab we then click on: [Fig 2]</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/476/1*FUbNi4VVSfrd8Er-E6i9Nw@2x.jpeg" /></figure><blockquote>These are the companies that have the most cookies in my browser — an astounding 1.7 GB of data stored by these sites. [Fig 3]</blockquote><blockquote>In fact, you can find a more detailed analysis of these cookies, for every individual website. [Fig 4]</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/1*B5UNUDRsn4hymLLrqqw8bQ@2x.jpeg" /></figure><p>It is quite astonishing just how much data these companies have about us, and the impact it has on our privacy. In fact, a lot of you may already be familiar with third-party cookies because of the notifications that pop up on websites that need you to choose your cookie settings. This has been the result of new privacy regulations being set in place in the European Union through the GDPR (General Data Protection Regulation). This requires companies to make sure that the user is aware of the data they are sharing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/489/1*2QNL88ENHu1DicTneLCMog@2x.jpeg" /></figure><p>And while it is definitely a step in the right direction that we are being provided with the option of choosing whether to share our data, the choice is often presented in a very leading way. In fact, most of us just click on the<strong> “Accept All” </strong>button to avoid having to go through the trouble of making specific choices just because we want to make our lives easier, I mean we only just want to get a sneak peak at that article after all.</p><p>This growing awareness of the importance of privacy has prompted companies like Apple and Google to shift towards the removal of third-party cookies. Apple, with their iOS 14.5 will be adopting a stricter policy on third-party cookies. Google, which is the world’s largest ad platform (and for whom ads are a major source of revenue) are also now working to develop alternative advertising techniques that rely not on cookies, but on machine learning. One idea is that they are going to make overall high-level analyses of the topics you are interested in, and provide ads along those lines. They are in the process of developing these techniques through a project called the <strong>Privacy Sandbox</strong>. You can learn more about the same at: <a href="https://privacysandbox.com/">https://privacysandbox.com/</a></p><p><a href="https://privacysandbox.com/">The Privacy Sandbox: Technology for a More Private Web.</a></p><p>Policies on data collection, and privacy are constantly evolving, and it is imperative that we are careful with our information. To advertisers, we are a mere collection of data points that can be targeted and advertised to, but the fact that they understand us so well and have so much information about us makes us a system ripe for abuse — especially if the targeting being done is malicious, or to promote hate and intolerance.</p><p>For now, we can take steps to ensure that our information stays secure — customise our cookies, in some cases, block 3rd party cookies, and stay updated on the latest regulations, adopt the new software paradigms, and adopt browsers that promote privacy.</p><p>Image Credits</p><ul><li><a href="https://www.internetcookies.com/">All You Need to Know About Internet Cookies &amp; Your Security</a></li><li><a href="https://www.cookieyes.com/blog/gdpr-cookie-consent-banner-examples/">10 Effective GDPR Cookie Consent Examples - CookieYes</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=64df31795540" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why you can’t stop scrolling through social media and what to do about it.]]></title>
            <link>https://kaavyamaha12.medium.com/why-you-cant-stop-scrolling-through-social-media-and-what-to-do-about-it-1e76967866c3?source=rss-d7b4cf89685e------2</link>
            <guid isPermaLink="false">https://medium.com/p/1e76967866c3</guid>
            <category><![CDATA[social-media]]></category>
            <category><![CDATA[social-media-addiction]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[ethical-ai]]></category>
            <dc:creator><![CDATA[Kaavya Mahajan]]></dc:creator>
            <pubDate>Sun, 13 Nov 2022 11:34:51 GMT</pubDate>
            <atom:updated>2022-11-13T11:34:51.604Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3cq86OOUjDkKaRbslm_teQ.jpeg" /><figcaption>Image by Freepik</figcaption></figure><p>The average person spends around <strong>2.5 hours </strong>engaged on some social media platform every day. What initially started as a way to stay connected with friends and family has now morphed into one of the most prominent activities of our day.</p><p>How many of us check social media the first thing in the morning and the last thing before we go to sleep? How about YouTube Shorts or Instagram Reels or Tiktok?</p><blockquote>How many of us just open these up or decide to check out the “For You Page” for just a few minutes, only to find out that 30 minutes or maybe even an hour has passed just scrolling like that?</blockquote><p>I think most of us have experienced this, and every day we vow to not continue the same cycle the next day only to find ourselves scrolling all over again – right back to square one. I have certainly done this enough times to recognise that this problem is pervasive and then I asked myself a simple question – <strong><em>Why</em></strong>?</p><p>Turns out there’s an abundance of resources that answer this exact question and here’s what it boils down to. (I will be sharing the links for these resources down below for those interested). So, the answer, of course, lies within the <strong>design of the AI algorithms</strong> that run these platforms. To be fair though, this is not some master plan of technology to take over us, it is only doing what it has been designed to do. The design of these platforms <em>exploits the fundamental way in which our brain has evolved</em>. This is not a new concept, the only issue is that AI has become capable of understanding us so well that it is disturbingly good at captivating us.</p><p>Here’s the basic principle – our brains are programmed to take actions that can lead to rewards. Common sense, right? Great. So, these rewards can range from “getting energy to do life stuff” which is linked to the action of “eating good food” to “getting social approval or seeing something funny” which is linked to the action of “checking social media”. Simple enough (for now, at least; the reality is certainly more complex).</p><p>There’s just one more piece of the story we need and then we can put it all together. <strong>Social media companies do not care about the content. </strong>They only care about time spent on the platform. Why?</p><blockquote>Because the more time you spend on their app, the more ads they can show you. You can see where I’m going here –the more ads, means more money and these companies are well, companies, and so the money must come.</blockquote><p>Right, so let’s catalogue what we know:</p><ol><li>our brains take actions that promise rewards</li><li>getting social approval through likes or seeing something we like (we find funny, interesting, engaging) is a reward</li><li>social media companies want us to stay on their platform for as long as possible</li></ol><p>Seems straightforward then, to assume that these companies just show you what the algorithm thinks you’ll like best (probable cute cat pictures) and that doesn’t sound too bad. Only, this is not what happens. I mean, the human brain is hardly straightforward. There is a complex reward prediction error system at play here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/607/1*EgmTc7E2dMgngAbfp-cfQQ@2x.jpeg" /><figcaption>Reward-prediction cycle in our brain</figcaption></figure><p>In essence, the algorithms have mastered a technique called <strong>intermittent variable rewards</strong>. So, I’m going to use the above image as a reference and try to explain this idea. The first step is that for any action, we make/use a prediction of a reward. Then, we get the actual outcome of the action. If this action produces a positive reward (which is our prediction), then we keep the prediction and action unchanged. This is analogous to a scenario in which you are only shown the content you like. Here, you are able to create a fairly accurate sense of reward (satisfaction) that you will get out of checking social media, and in my opinion, would be more likely to be able to control and manage your time.</p><p>Right, so back to the image – when your reward is not equal to your prediction, you change your behaviour. Here’s the thing. The series of experiments conducted by psychologist BF Skinner on Operant Conditioning, which helped us get this idea of changing our actions based on rewards also included a part on “variable rewards”.</p><blockquote>Variable rewards as the name suggests does not give you a positive reward every time you perform an action, instead it creates a constantly changing reward system for the same action. This variability means that we are unable to predict what reward we might get. And this unpredictability, combined with the fact that checking social media is an extremely low-effort task means that we are likely to often check these apps.</blockquote><p>We feel that the reward is delivered at random, and so, why not just check if we’re lucky this time? Oh no, no interesting posts? Never mind. It’s been 5 minutes now, should I check again? Sure, and there it is- some funny post and sweet reward right here.</p><p>How exactly is this variable reward schedule implemented? Well, first off, there is the fact that <strong>the platform intersperses curated content with posts you are unlikely to enjoy</strong>. Now this next bit is personal experience (take it with a grain of salt) – I have noticed that often, after I have scrolled for a very long while, I am shown a string of posts that I find uninteresting which leads me to log off the platform and around 15 minutes later, Instagram can read my mind perfectly again. Might have happened to some of you as well.</p><p>The other thing that these platforms do is that they <strong>withhold likes on your posts</strong>. This basically means that while in real time, after you have posted, within the next few hours, there is a steady trickle of likes on your posts, these likes will not appear as they are sent. Instead, for a while there will be no likes to speak of, and this will make you want to keep checking your phone, it is very little effort for</p><p>(I took a break here in the middle of this sentence to check out YouTube for a bit, it has been 30 minutes, the ironic value of this is just brilliant)</p><p>Anyway, as I was saying, the lack of likes will make you constantly check your phone, and since it is hardly any effort for you, you will do this constantly. This happens a few times, and then just when you have almost given up on checking your post, there it is – an influx of all the likes that your post has garnered. There you go, there’s your reward for constantly checking social media. You know what you have to do now, don’t you? Of course, you have to keep going. Welcome to the oh-so-vicious cycle of social media.</p><p>Social Media addiction is a real thing, and while the majority of us are not nearly as engrossed as to be truly addicted (in the scientific sense), it is clear that we are emulating some of the behaviours typical of addiction. Social Media has been compared to gambling machines, and your phone is often called <strong>“the slot machine in your pocket”</strong>.</p><blockquote>This is because casinos, and slot machines in particular, use exactly this technique of intermittent rewards to keep you hooked and playing.</blockquote><p><strong><em>Social media increases anxiety, reduces self-esteem, creates a dependency on your device, creates a feeling of Fear of Missing Out (FoMO) that can be crippling and often makes you less social in real life. </em></strong>The machine does not care about you. The machine cares about the time you spend and the ads you see, and therein lies the problem. AI has become very efficient at solving certain narrowly-scoped problems, and I feel it has mastered the art of conditioning us. This is a problem of AI that is not human-centric, because honestly, it is the companies that are the ones behind this, the technology is only the medium. And these companies know what they are doing. They just don’t care, and that is what horrifies me.</p><p>AI has massive potential, but if that potential is used against people for the sake of money, it has the massive potential to be disastrous. Legislation has fallen way behind on dealing with matters like these, and I do not know if there will ever be regulations regarding this, and even if it does happen, if it will be enough.</p><p><strong>This is not to say that social media platforms are the devil incarnate, they have their uses.</strong> I have learnt most of what I know through open-source information platforms. I enjoy a good meme or a joke just as much as the next person. But I am worried about what social media does to me. And if you are worried too, we’ve got to do something about this.</p><p>Institutional change is needed, but whether that is practical or possible is something that is really beyond my scope. I just know that to me it seems like it’ll be a long wait before the responsibility is taken up by corporations and governments to adhere to principles of creating AI for the betterment of people. Regardless, what can we do, as individuals, for ourselves?</p><blockquote><strong>Be more aware, value your time and understand how you spend it. This is difficult, I know, I have scrolled through hundreds of posts mindlessly and it is difficult to understand and quantify how exactly time vanishes into thin air. Still, the next time you open social media, think about why you are there, think about what you intend to do on the platform, and think about the time you spend there.</strong></blockquote><p>Also, if you can, connect with the people around you. Use social media to meet different people, and stay in touch with those you can’t meet physically, but also build stronger connections (this is especially for teenagers, we suffer some serious negative consequences from these platforms, and we need all the support we can get!)</p><p>As a side note: if any of you are interested, try experimenting with the algorithm. I did this once. So, I am not a very big cat person, like I don’t dislike them, but I don’t particularly like them either – this is just context to explain that I do not have cats on my feed anywhere (except a stray picture occasionally of course). Anyway, one day, I decided to see how fast the algorithm adapts and I looked up cat pictures on Instagram. Scrolled through a few and liked them. I refreshed the For You page; the cats had entered, but were still a minority. The next time I opened up the app, I did something similar. By the third time, my For You page had all the cats I would ever need to see. After that, I resumed my apathy to cat pictures (it is rather difficult I have to admit), and soon enough, they were gone from my feed.</p><p>There are a lot of things that about social media and AI that I haven’t talked about, but I hope I have been able to share at least something helpful with you. Stay aware and the next time you feel like you want to mindlessly scroll, instead go take a stroll 😀</p><p>Resources, Links and References:</p><p><a href="https://sites.psu.edu/aspsy/2019/03/16/mindless-scrolling/">Mindless Scrolling | Applied Social Psychology (ASP)</a></p><p>This link is a great overview on the topic:</p><ul><li><a href="https://datascienceathome.com/the-dark-side-of-ai-social-media-and-the-optimization-of-addiction/">The dark side of AI: social media and the optimization of addiction</a></li><li><a href="https://sitn.hms.harvard.edu/flash/2018/dopamine-smartphones-battle-time/">Dopamine, Smartphones &amp; You: A battle for your time - Science in the News</a></li></ul><p>This paper provides a very nice analogy to understand the variable reward schedule:</p><p><a href="https://www.ncbi.nlm.nih.gov/pmc/articles/PMC4826767/">Dopamine reward prediction error coding</a></p><p>And lastly, this is a very sobering and thought-provoking piece that is truly worth the read:</p><p><a href="https://www.theguardian.com/technology/2019/aug/23/social-media-addiction-gambling">The machine always wins: what drives our addiction to social media</a></p><p>Image credits:</p><ul><li><a href="https://www.freepik.com/free-vector/person-addicted-social-media_6596992.htm#query=social%20media%20addiction&amp;position=2&amp;from_view=keyword">Free Vector | A person addicted to social media</a></li><li><a href="https://www.ncbi.nlm.nih.gov/pmc/articles/PMC4826767/">Dopamine reward prediction error coding</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1e76967866c3" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>