<?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 Jonathan Kuo on Medium]]></title>
        <description><![CDATA[Stories by Jonathan Kuo on Medium]]></description>
        <link>https://medium.com/@jonathan-kuo?source=rss-c2bfa09e15b6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*BCt7KfpOqEsXK71HvfYQ2w.jpeg</url>
            <title>Stories by Jonathan Kuo on Medium</title>
            <link>https://medium.com/@jonathan-kuo?source=rss-c2bfa09e15b6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 08:22:03 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jonathan-kuo/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[AI Classical Music Composer — Bi-LSTM & CNN-GAN]]></title>
            <link>https://medium.com/analytics-vidhya/ai-classical-music-composer-63d983ee5fc0?source=rss-c2bfa09e15b6------2</link>
            <guid isPermaLink="false">https://medium.com/p/63d983ee5fc0</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[art]]></category>
            <category><![CDATA[music]]></category>
            <category><![CDATA[classical-music]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Jonathan Kuo]]></dc:creator>
            <pubDate>Mon, 25 Oct 2021 02:56:38 GMT</pubDate>
            <atom:updated>2021-11-10T04:38:13.661Z</atom:updated>
            <content:encoded><![CDATA[<h4>How to generate classical music for composers, musicians, or even non-specialists without prior knowledge of classical music theories and background.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gGvEAL-VIIFTYXvTxPA4ow.png" /><figcaption>2 proposed AI models</figcaption></figure><p>Note: The source code of this project can be accessed <a href="https://github.com/chiatsekuo/AI_Classical_Music_Composer">here</a>.</p><h3>1. Abstract</h3><p>Artificial Intelligence could bring music composition to another level with limitless possibilities as an assistant for human musicians or an AI musician itself. Living in a digital era, classical music plays a dominant role in commercial films, movie trailers, game soundtracks, and more. However, there are no existing works that generate classical music in different eras. To fill this gap, this project proposes an AI music generator for classical music. So that it would be possible for composers, musicians, or even non-specialists without prior knowledge of classical music theories and backgrounds could quickly compose classical music according to their favorite musical eras for many practical purposes. It uses generative models, i.e., Bi-LSTM and CNNGAN to compose classical music for some particular classical music genres and evaluate their performance respectively and collectively.</p><h3>2. Literature Review</h3><h4>2.1 Existing approaches and their limitations</h4><p>Previous studies have shown potential in generating music by implementing Markov Chain, Recurrent Neural Network, and Generative Adversarial Network. However, each study has its limitations; therefore, there are still rooms to be improved from the earlier approaches.</p><h4>2.1.1 Markov Chain</h4><p>According to specific probabilistic rules, a Markov Chain is a system that changes its state from one to another in fixed timesteps. When applying the Markov Chain to music generation, each note in the training set is assigned a unique state. The model will then generate new states (notes), learning from the past states sequentially. The most straightforward design of a Markov Chain is to limit the model to use a single previous state to predict another. It is reasonable and feasible to apply Markov Chain for assisting real-time improvisational performance like jazz as musicians usually play spontaneously.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/758/1*UloSPWFjsPGbrNEJE6W82Q.png" /></figure><p>However, when Markov Chains generated music from an existing musical corpus with full compositions, the results were not satisfying. It showed weird arrangements of notes and chords that were unmusical (Moorer, 1972).</p><h4>2.1.2 Recurrent Neural Network</h4><p>A Recurrent Neural Network (RNN) is a neural network where the current input is fed in with output from the previously hidden units. Each node of an RNN has a hidden state which allows the network to memorize a sequence of outcomes from the past. This feature of memorization means that RNN can be applied to tasks like Natural Language Processing (NLP), Time Series Pattern Predictions, and more. Since the traditional RNNs have drawbacks of not being able to 10 memorize long sequences of data and suffering from problems of exploding and vanishing gradient, most studies applied Long Short-Term Memory (LSTM, a kind of RNN) as an alternative to generate longer sequential information like text, speech, and music. Typically, an LSTM consists of a forget gate that removes useless information, an input gate that adds useful information together, and finally an output gate that extracts valuable information as an output of the current cell. Eck and Schmidhuber (2002) demonstrated that an LSTM model was able to compose novel blues music in styles that were similar to its trained (input) data. However, Hadjeres et al. (2016) commented that the music lacks flexibility and could not perform re-harmonization in Bach, for instance.</p><p>Choi et al. (2016) conducted another study that showed a text-based LSTM algorithm for automatic music composition using different characters as unique notes to learn the relationships between chord progressions and drum tracks. Nevertheless, they discovered that the character-based RNN failed to generate meaningful structures of drum tracks by producing undesired arbitrary 0’s and 1’s. as output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*zrTk7On1Nol9wdbNm_mhJw.png" /></figure><p>Boulanger-Lewandowski et al. (2012) suggested a combined approach that improved their previous study in generating polyphonic music by introducing the RNN-RBM model. Each RNN hidden unit is combined with an RBM. An RBM or Restricted Boltzmann Machine is a bidirectional connected and stochastic (or generative) system with visible nodes and a hidden node where all visible nodes are connected, but the hidden nodes do not. Each state of the RNN unit gets both inputs from its previous state and the RBM observation vector, and this allows the model to better predict the coming notes by learning from the prior timestep of notes. However, the Magenta project (Shiebler, 2016) commented that this model had difficulty generating rhythmic and melodic music for longer timesteps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/787/1*JxQksQEzYrkOq3YYQexseA.png" /></figure><h4>2.1.3 Generative adversarial network</h4><p>A Generative Adversarial Network (GAN) (Goodfellow et al., 2014) is a type of neural network that produces plausible data from scratch. There are two systems in a GAN — the generator and the discriminator. The generator tries to fool the discriminator by producing fake data while the discriminator distinguishes real and fake samples. By competing, the discriminator penalizes the generator for generating fake data, and the generator gets better at creating new instances that look real. A study by Dong et al. (2017) adopted Convolutional GAN with Wasserstein Loss to generate four bars of multi-track piano-rolls. The input data size is set as 96 (timesteps) times 84 (notes) times 5 (tracks) in piano-roll format for the model training. Akin to most image classification problems, each note on the piano-roll is considered a valid pixel indicating a note’s presence. Therefore, using convolutional layers combined with GAN’s concept, the system is like generating images from scratch then transforming them back into audio formats. The study showed that the method is feasible and can learn the structures and characteristics of short chord progressions. However, it is incapable to produce music for longer timesteps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/762/1*SJ1rxuMpblPKK64_hCX3BQ.png" /></figure><h4>2.2 Proposed Methods</h4><p>This project will evaluate two neural network architectures — the Deep Bidirectional LSTM model and a GAN model with convolutional layers. It is hypothesized that the Deep Bidirectional LSTM model could improve shortcomings of existing studies by predicting musical structures with longer timesteps and more meaningful melodies. On the other hand, the GAN models try to solve the LSTM models’ problem of getting stuck in a loop (generating the same musical structure) by developing music from scratch (random noise). Both proposed models are supposed to tackle the drawbacks of current studies, and all results will be compared and evaluated by appropriate evaluation metrics — the Fréchet Inception Distance (FID) score and nearest neighbor search — and human survey.</p><h3>3. Design, Solution, and System</h3><h4>3.1 Deep Bidirectional LSTM RNN</h4><h4>3.1.1 Deep neural networks</h4><p>It is believed that a deeper neural network is more capable of analyzing and processing thorough characteristics of information than a shallow one. Typically, a shallow neural network contains only one or two hidden layer (s), while a deep neural network consists of more than two hidden layers. Therefore, to let the proposed model have a better understanding of input data, a deep neural network is adopted in this project.</p><h4>3.1.2 LSTM Architecture</h4><p>Each LSTM layer contains blocks of LSTM cells with multiple gates to memorize sequences of information. The cell states transfer valuable information to other cells and multiple gates with unique functions to keep the LSTM network learning and memorizing information. The below figure illustrates the architecture of an LSTM cell.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/555/1*y97mhqtvktw3UNuCE_YWaA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/823/1*dK-4es0iwE8MyY6OyFdX2A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/577/1*832XLLph6eOcBNpxZAA0fg.png" /></figure><h4>3.1.3 Bidirectional LSTM</h4><p>A bidirectional LSTM model is a system containing two LSTM layers that pass-through data in opposite directions. Each output from the system receives information from both the hidden states of the backward and forward layers. Comparing with unidirectional LSTMs, bidirectional LSTMs not only learn information from the past but from the future as well. This feature allows the model 15 to predict sequential information more accurately. From the image below, we can see that it is an acyclic graph. The output for each timestep can be derived as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/835/1*B4q74R5U8Ow5PqiFADy32w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/1*Ygj6oEMM-G4t1Z9_5CNG-A.png" /></figure><h4>3.1.3 A combined approach</h4><p>A Deep Bidirectional LSTM RNN is a model of multiple bidirectional LSTM layers stacked together. It is hypothesized that combining deep neural networks and the feature of bidirectional layers will perform better than methods done by previous studies. Therefore, the first model in this project will be based on this design.</p><p>The model contains three bidirectional LSTM layers with 128 neurons each, followed by two fully connected layers to modify the input vectors’ dimension and adapt the desired output shape. The initial plan for the activation function and the optimizer is to use Rectified Linear Unit (ReLU) and RMSProp since they are most widely used for LSTM models. However, other optimizers and activation functions will be further tested during the implementation steps.</p><h4>3.2 CNN based GAN</h4><p>A GAN is made up of a generator and a discriminator with any neural network architecture that is best for classifying the training data. It is mostly used for generating images with CNN. However, other neural networks like LSTM or RNN have also been used to predict sequential data. In 16 general, the training process for GAN can be divided into two parts — training of the discriminator and training of the generator. First, randomly generated data will be fed into the generator.</p><p>The randomly generated input size does not necessarily need to be the same as the desired generated output. Since the dimension of the input data can be changed in the generator, usually a smaller size than the dimension of the output data will be used. After the generator has produced a fake (generated) output, the fake output will be passed into the discriminator to be compared with the real data. The discriminator, at this point, will learn to distinguish data between real and fake throughout all iterations of the training process according to the discriminator loss function. The generator will also learn from gradients obtained from backpropagation through both the discriminator and the generator according to the generator loss function connected to the discriminator only. The figure below is a general GAN architecture (The “Real images” represents real-world data).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/826/1*TmAgtDC51Wv1ABw6OI81hg.png" /></figure><p>This model utilizes convolutional layers as the main neural networks for both the discriminator and the generator. Since a midi file is a file with different frequencies that progress with time, each midi file can be transformed to a 2-D array where the x-axis denotes the timesteps, and the y-axis represents different pitches of notes. In this case, we can treat the 2-D arrays as images to be trained in a convolutional neural network-based GAN model easily.</p><p>The generator consists of a fully connected layer with many neurons followed by four convolutional layers that gradually modify the shape of the data vectors into the desired data shape. The final output shape of the generator will be the shape of the generated music. Here, we set the output shape to be 1000 times 84, where 1000 represents the number of timesteps in the music 17 and 84 stands for the number of pitches. It is worth noting that the number of pitches is set to be 84 in order to save computational cost. Since the notes and chords of almost all pieces fall between in midi index 24 to 108, which contains in total 84 notes, it is better to truncate the unnecessary 0s to speed up the training process. After the training and generating process, the generated pieces will then be added two arrays of 0s to become arrays of size of 1000 by 128. The kernel size for each convolutional layer is 5 by 5, with strides of either (2, 1), (1, 2), or (2, 2) to fit the final image shape. The last convolutional 2D transpose layer uses tanh as the activation function to determine the final output of each neuron.</p><p>The discriminator contains two convolutional layers and one fully connected layer. Each convolutional layer has a kernel size of 5 by 5 and a stride of (2, 2), which is similar as the generator’s settings.</p><h4>3.3 One-hot encoding on Midi files</h4><p>One-hot encoding is the process of transforming categorical information into binary form, indicating that during a specific timestep, only that information has a higher value (1) than the values (0s) of other irrelevant information. For instance, in specific timestep t, note “C4” is played, then the data vector on timestep t will contain a one at a specific position in that vector that corresponds to the note “C4” with 127 0s considering 128 unique notes. Since the notes and chords are stored categorically in all midi files, all such information will be processed through one-hot encoding for better model training performance. Both neural network models will be trained with the same set of training data using this technique.</p><h4>3.4 Evaluation metrics</h4><h4>3.4.1 Fréchet Inception Distance (FID)</h4><p>The Fréchet Inception Distance (FID) is designed for evaluating the generated results (fake data) produced by the GAN models with the real data. The equation to calculate the evaluation score is shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/501/1*tyLSIl7rasZk3gs4j8eVsA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/823/1*uG3xJTA5_2OKxBFBkpZ9uw.png" /></figure><h4>3.4.2 Pitch Histogram</h4><p>Note consistency and note diversity can be visualized by plotting the pitch histogram. A pitch histogram is plotted by summing up each unique frequency count of notes and chords in a histogram style. It is believed that it is an effective measure to classify different genres of music. In this project, it can be used as a tool to distinguish the eras among all generated pieces of music by all models.</p><h4>3.4.3 Nearest Neighbor search</h4><p>A way to check whether there is any similarity between a generated piece and the pieces from the training set is by searching the nearest neighbor of that generated piece. By calculating the root mean square error between that generated piece and all pieces from the training set, we should retrieve the closest piece by searching for the lowest error.</p><h3>4 Methodology and Implementation</h3><h4>4.1 Midi files Pre-processing</h4><p>This project uses the Music21 and Pypianoroll python libraries to extract information from all midi files into notes and chord sequences. Their pitches and octaves correspond to each time step. Since this project’s scope only covers a single instrument’s generation, the training data will only contain pieces of music played by the piano.</p><p>All training data is acquired from the GiantMIDI-Piano repository on the ByteDance GitHub repository. According to their documentation, there are 10854 midi files of classical music available. However, duplicates and empty files were found in the acquired dataset after the data cleaning and categorization process. The final dataset contains 546 pieces of baroque music, 412 pieces of classical music, 637 pieces of romantic music, and 238 pieces of modernist music.</p><p>Pieces of music from each four-category are then processed independently. Extracting and concatenating all notes and chords, the program will form a dictionary that records each unique note and chords (a combination of notes) with an index. For instance, a note “A2” is paired with the index “0”, and a chord “C#3” is paired with the index “1”. It will simplify the process of onehot encoding later.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/1*FcgkFHyoIpxMHeZ7Tddl7w.png" /></figure><p>Since LSTM models learn from given sequences and their next prediction(s), an additional process is needed to build series of sequences and their corresponding output (next forecast). This project sets the sequence length as 50, meaning that the LSTM network learns to predict the next note given its previous 50 notes or chords. First, the program will store the first 50 notes or chords, then transform them into integers according to the unique note-chord dictionary built in the previous into the input sequence array. The next corresponding note or chord of the last sequence 20 is then stored in the output array. Retrieving all sequences of notes and chords, each element in the output array is normalized between 0 and 1 for the later training process’s ease.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/798/1*8OxdiDG-PkXn0wI_MkRudw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/814/1*MUpPZTv4BntkJL71PCo8Iw.png" /></figure><p>Treating midi files like images, the CNN-based GAN model can efficiently generate music with reasonable structures both in vertical and horizontal perspectives. The input training data contains 2-D arrays, which can be considered as arrays of images with only two colors. The x-axis represents timesteps, and the y-axis denotes different pitches of notes (and chords). Suppose a note or chord occurs in any timestep, the array of that particular timestep store a ‘1’. On the other hand, empty notes are denoted by a ‘-1’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/833/1*9EzJdnCTznUWTpe1NoqFVA.png" /></figure><p>The final step is to store all images into a NumPy array with a shape of (x, y, z) where x denotes the number of unique pieces of music, y indicates timesteps of each training piece, and z means the range of notes. In this project, the array shape setting is (x, 1000, 84) for simplicity since the objective is to assess the CNN-GAN model’s capability to generate structured music and meaningful melodies instead of generating long pieces that usually require excessive computing power to finish the task. In standard Midi expression, there are 128 notes in total. However, by observing all images from the training set, most of them only have notes span from minimum C1 (index 24) to maximum C7 (index 108). This means that notes below index 24 and above index 108 can be ignored in that they are empty notes which are not conducive for the latter training process. Hence, a trimming process is done for all images before training. It results in the final input data shape of (x, 1000, 84), where x denotes the number of unique pieces of music.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/826/1*7miDh61xbLKMwa7uFy4VfA.png" /></figure><h4>4.1 Model Building</h4><p>In this project, all neural networks will be programmed in python using the TensorFlow library and its higher-level API — Keras API. The high-level Keras API allows faster implementation of any neural network. In general, only the input shape of the training data, loss functions, optimizers, and some specific hyperparameters are required to be provided by the developer.</p><h4>4.1.1 Deep Bidirectional LSTM RNN</h4><p>The current implementation for this model is to stack one bidirectional LSTM layer and two LSTM layers together. They are followed by two fully connected layers. Each LSTM layer contains 256 nodes with a dropout rate of 0.3 afterward. After the last LSTM layer and the first fully connected layer, batch normalization is added. The first fully connected layer contains 128 nodes with a rectified linear activation function (ReLU). The final layer contains x nodes where x is determined by the distinct notes or chords from the training corpus. Since it is known that if a note or chord is not within the training corpus, it will not show up or be predicted in the future by the neural network, we can safely implement the final fully connected layer in this manner to save memory and computational time. The model is compiled with a loss function of cross-entropy loss and RMSprop for its optimizer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/193/1*mBorH11j_hb333uwmtrqWA.png" /></figure><p>Similar to the training step, the prediction network possesses the same architecture as the training model. The only difference is that the optimal weights from the last epoch of the training process are added to the neural network for sequence prediction.</p><p>A random number is generated as an index determining the starting point of the prediction sequence to predict a sequence of music based on the training set. The length of the initial sequence of notes is also determined beforehand. With the above settings decided, the model can predict a single note or a chord (a set of notes) in each iteration of the prediction.</p><p>In each iteration, the model predicts the next note or chord of the input sequence by choosing the highest probability of that element (note or chord). That note or chord with the highest likelihood of being the next element of the sequence will then be concatenated to the previous sequence. At the same time, the first element of that sequence will be removed before the next iteration. This allows the window size (length of sequence) to be the same as the window sliding from the beginning of the prediction to the end.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/959/1*jGtfAAitCkgJRrNvSokGkA.png" /></figure><h4>4.2.2 CNN based GAN</h4><p>This CNN-GAN model consists of 2 neural networks — a discriminator and a generator. Both networks adopt cross-entropy loss as their loss function by computing the difference between predicted labels and true labels. Since the generator is trying to fool the discriminator by generating fake images that make it the discriminator challenging to discern the authenticity, the generator’s loss function compares the discriminator’s decisions on fake images to an array of ones. As for the discriminator, there are two steps (two losses). It compares real images with an array of ones and fake images with an array of zeros. Combining both losses yields the total loss of the discriminator’s loss.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/946/1*Z55efrRTRxbo67FdklD0Lw.png" /></figure><p>The generator’s network structure begins with introducing a small random seed as input to a fully connected layer with a much larger output size. After reshaping the output data, four transposed convolutional layers are stacked together to upsample the data. Each convolutional layer has a kernel size of 5 (both height and width) and a stride of (2, 1) or (1, 2), or (2, 2) to upsample the data to meet the same shape of the input data which is (1000, 84). The paddings are the same to preserve the original size of the data. Finally, except the last layer uses tanh as an activation function, all layers are followed by a LeakyReLU activation layer.</p><p>The discriminator, on the other hand, has a shallower layer of neurons compared with the generator. It has two convolutional layers at the beginning and each with a five-by-five kernel and a stride by 2. Finally, a fully connected layer with a single output determines whether this very input image is from the training set (real) or the generator (fake).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/919/1*gtOyIal9ojtrb-X_M5Ii9g.png" /></figure><h4>4.2 Data Conversion</h4><p>For the Bi-LSTM model, after a new sequence of numbers is generated, all elements from the sequence will first be converted to the representation of either notes or chords accordingly by referencing the unique set of notes and chords from the training set, then be converted to either notes or chords in Midi format. Here, a limit of the note number and chords need to be specified, and so does the tempo. Take modernist music as an example: a maximum of 300 notes and an offset of 0.3 between notes are good settings. Here, the offset controls the tempo of the music. When the number is larger, the tempo is slower, and vice versa.</p><p>For the CNN-GAN model, the final step is to convert the array with the size of (1000, 84) back to the size of (1000, 128), the acceptable data format by the Pypianoroll library, then convert it to a midi file. The predicted array concatenates an empty array with a size of (1000, 24), and the combined array is concatenated by the other empty array of size (1000, 20).</p><h4>4.3 Evaluation</h4><h4>4.3.1 Pitch histogram</h4><p>The purpose of using pitch histograms to analyze generated music is that this graph is an efficient way to visualize note similarities and diversities from a given piece of music. By counting the most frequent notes occurring in a piece, it is common to determine the music. However, suppose most notes fall in only a few (1 or 2) categories of note. In that case, it may indicate a failure of the generation of music since almost most pieces have a specific diversity of distribution of notes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*thHO4VY3XUy0HoyM3rvIAQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/1*1jew5GgfF3DQ2Zvqd8KGXA.png" /></figure><h4>4.3.2 FID</h4><p>There are two required components to calculate the FID scores — the set of real images and the generated image. For each genre, all music from the training set belongs to the ‘real’ image set, and the generated image belongs to the ‘generated’ image set. The features that will be extracted for both the ‘real’ and ‘generated’ sets are part of the images themselves, and only a segment of each piece will be extracted. The segments are images with a shape of (400, 48), where 400 denotes timesteps and 48 means the range of notes. The reason to set the range of notes to 48 is that from observation, most notes and chords fall in this range, and it saves a lot of computational costs to retrieve features from each piece of music from the training set. Next, the mean of all feature vectors and the covariance matrix of all feature vectors for the ‘real’ and ‘generated’ set are first calculated. The FID score can then be retrieved from the below equation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/503/1*T-Azdso54HlKiSwvyHjjeg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*jokxwC5OxOoSgIn0HL6jWQ.png" /></figure><h4>4.3.3 Survey</h4><p>Two surveys were conducted to evaluate the results of the Bi-LSTM and the GAN model, and both are hosted on a third-party surveying platform — phonic.ai. Each survey consists of eight multiple-choice questions with only one answer to each question. The respondents need to play the audio provided on each page of the survey and choose whether the music they heard is composed by a human composer or an AI algorithm. If they feel that they cannot decide, they can select the ‘I don’t know’ option. It allows the respondents to answer each question carefully and hopefully minimize their chance of guessing, which might deteriorate the survey results’ quality.</p><p>One piece from each genre and each category (‘real’ an ‘generated’) is chosen, and only an excerpt (between 15 to 30 seconds) of that piece will be available to the respondents since letting the respondents listen to the whole piece in a survey will make them fatigue and therefore deteriorate the survey result. In each survey, the number of ‘real’ and ‘generated’ music is balanced and ordered randomly for fairness. The below snippet is an example of a question.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/1*DkhWkCV9ZL5EnX9Ljzmw9Q.png" /></figure><h3>5 Results and Evaluation</h3><h4>5.1 Deep Bidirectional LSTM RNN</h4><h4>5.1.1 Note Diversity &amp; Analysis</h4><p>Below are four examples of generated music in different styles. Beginning with the Baroque, Classical styles and followed by the Romantic and Modernist styles. The results shown below demonstrate the Bi-LSTM model’s capabilities to compose novel music passages by learning from the given training set.</p><ul><li>An example of a generated Baroque style music</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/819/1*dZ_7F6mQrh57vUwT5PmrJg.png" /></figure><p>According to the pitch histogram (Figure 5–6 top left), it is evident that notes are distributed evenly in major scales, but there are not many sharps and flats. Though not until the late Baroque period did the key signature evolve to its present state, which usually has defined keys for each piece of music, the note diversity of this generated piece of music is relatively evenly, which is acceptable considering the nature of this genre of music. In addition, from the music sheet excerpt shown above, this piece of music shows signs of monody without complicated polyphonic musical structure.</p><ul><li>An example of a generated Classical style music</li></ul><p>Music in this era often uses simple harmonic melodies to fulfill a balanced musical structure. This kind of composing idea was often found in Beethoven’s music. The music generated below demonstrates a repetition of similar motifs (musical phrases or structures) that are waltz-like, which corresponds to one of the most common music composition ideas in the classical era. In my opinion, this very generated piece is one of the most successful one that resembles music from Beethoven.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/820/1*Xpj9RFhqvsKzEccidVInQA.png" /></figure><ul><li>An example of generated Romantic style music</li></ul><p>According to the Music 21 library analysis, the expected key for the below piece of music is C sharp minor with a confidence of 70.2%, which corresponds precisely to the pitch histogram below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/818/1*cP6Kj3bE255x_e1H7szhag.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/814/1*OoVnVXJTSbuzGyIiz1dyEg.png" /></figure><ul><li>An example of generated Modernist style music</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/1*5e9qQmoQwWQl9WaBn1SioQ.png" /></figure><ul><li>Pitch histogram of four generated pieces</li></ul><p>From the below figures, we can observe that all pieces have diverse distributions of pitches. No single pitch noticeably dominates the whole pieces. Thus, it can be concluded that the Bi-LSTM model handles the note diversity well and does not tend to memorize partial information from the training set.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/711/1*eTdQLkSfAUJ4yplFel8P0Q.png" /></figure><h4>5.1.2 Survey</h4><p>From the stacked column chart below, it is clear that over half of the respondents have difficulty in telling whether the given piece of music is composed by AI or human. Among all human-composed pieces, only half of which receives over fifty percentages of confidence indicating them to be composed by the AI. The results are the same for all pieces composed by the AI. Though some respondents regarded ‘real’ music as composed by AI, the statistics showing that most respondents picked ‘Real’ when they are given to listen to a piece composed by the AI. This indicates that the proposed Bi-LSTM model have the capability to trick humans’ judgment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/714/1*-vvuYqmFIoTQqPUnK_BBig.png" /></figure><h4>5.2 Generative Adversarial Network</h4><h4>5.2.1 Fréchet Inception Distance</h4><p>The four generated pieces are evaluated by the FID score. In the below table, the first row, FID, is the FID score of the generated pieces and the training set, and the second row, FID (random), is the FID score of a random piece (image), which represents the initial states of the GAN training process, and the training set. Since the lower the FID scores, the similar the pieces (images) are to the training set, we can observe that each generated piece has a far lower FID score than the random one that corresponds to it. Therefore, we can say that the generated pieces look similar to those in the training set, which means that the GAN model mimics music from the training set well.</p><p>Major things that might affect the FID score could be the number of pieces in a particular training set, the piece itself, and the features that are being extracted for the FID evaluation. Also, unlike other image generating tasks which normally use the pretrained InceptionV3 model to evaluate generated image qualities, this project does not adopt this model as part of the FID score calculation due to the project’s nature. The generated pieces are not exact the same as traditional images that have RGB color channels and have association with ImageNet labels. Hence, in this case, I consider the FID score as a reference of the model performance, instead of a hard standard to determine the goodness of a generated piece of music.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/811/1*3Azqr5byJB2-uzYtRh49vw.png" /></figure><h4>5.2.2 Note Diversity &amp; Analysis</h4><p>Below are four examples of generated music in different styles. Beginning with the Baroque, Classical styles and followed by the Romantic and Modernist styles. The results shown below demonstrate the GAN model’s capabilities to compose novel musical notes/ chords and structures by learning from the given training set.</p><ul><li>An example of a generated Baroque style music</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/811/1*XQhtkMsbtlBSHbXK_H9wCg.png" /></figure><p>From the above Baroque-1-GAN music sheet excerpt, we can observe some impressive musical structures that are more complicated than the Baroque-1-Bi-LSTM. A noticeable feature is that when looking at a single measure, both the upper and the lower stave possess their melody, or at least the lower staff acts as the companion for the upper one. In contrast, the Bi-LSTM model does not showcase this kind of feature. Instead, it combines all chords or notes coinciding as a whole and represents them as a single chord. Though this might not simplify the musical structures, the GAN model might be a better option for generating more complex musical structures and producing more readable music sheets.</p><p>A way to check whether there is any similarity between a generated piece and the pieces from the training set is by searching the nearest neighbor of that generated piece. By calculating the root mean square error between Baroque-GAN-1 and all piece from the training set, we get the closest piece by searching for the lowest error. Below is a comparison between Baroque-GAN-1 (the generated piece) and the closest piece being found by the previously mentioned calculation. Observing the melody patterns of both pieces, we could say that both pieces have similar tendencies in developing continuous arpeggios. It is a good sign of showing the GAN model’s learning capability, and not entirely copying the musical phrases from the training set.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/1*DWbKZRz28xsSZVHzwHoJCQ.png" /></figure><ul><li>An example of a generated Classical style music</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/812/1*knpKkLXK_PotUQV9VF7V4g.png" /></figure><p>From the nearest neighbor search, it appears insignificant sign of similarity between Classical-1- GAN and its closest piece.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/783/1*VoyBYAVVK3zbrVPyqz9uUg.png" /></figure><ul><li>An example of generated Romantic style music</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*KcgZcUJEYlViWgtK58fSGA.png" /></figure><p>One thing worth noting from the above music sheet is the keys boxed in red. As mentioned before in the Bi-LSTM section, it is common for romantic style music having multiple flat for sharp keys. Also, comparing Romantic-1-GAN and its nearest neighbor piece, we can observe that both pieces progress along the timesteps in rather stable pitches without much dramatically vertical pitch changes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/781/1*joUtforiB9VYfK_rb3NcFg.png" /></figure><ul><li>An example of generated Modernist style music</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/809/1*pIHdfIq2cJAJ-6o1BEH6VA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/1*AAcXExuW_qvQnngyFoGc9Q.png" /></figure><p>Most of the time, Modernist music refuses tonality. Its music does not anchor in any “key” and always tends to feel unsettled or “off.” Observing the above music sheet and listening to its soundtrack, I think the same way. Unlike other musical styles like Baroque or Classical, Modernist music does not need to follow strict rules when composing. It is encouraged to defy “the convention” by pouring innovation into music. Thus, by this proposed GAN model’s nature, we do not need to worry about the unsettling melody or rhythms of the generated music.</p><ul><li>Pitch histogram of four generated pieces</li></ul><p>According to the below pitch histogram, all four pieces have multiple dominant keys, which is a good sign of note diversity. The GAN model does not generate specific notes but predicts notes proportionally with a few keys as major ones. It is a good sign as the GAN model makes it similar to human composing styles.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*CfBtQHp8x1_rI8VtMf1UXA.png" /></figure><h4>5.2.3 Survey</h4><p>The chart below is the survey of the GAN model. Though most respondents could clearly distinguish between ‘Real’ music or ‘AI’ music, there are still a portion (33.4% on average) of respondents could not identify whether their given pieces are composed by AI or human. This is calculated by averaging the summation of the percentage of the choices — ‘Cannot tell’ and the incorrect choices (either ‘AI’ or ‘Human’) according to each given piece.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/1*x46gF0fw29lji2W6vhdjCg.png" /></figure><h3>6 Conclusion</h3><h4>6.1 Achievements</h4><p>The generated results from the Bi-LSTM model demonstrate strong capabilities in producing classical music that most human could hardly tell whether they are composed by a human or an AI. The Bi-LSTM model proves to be able to generate music that makes sense in a sequential point of view.</p><p>The novel concept of treating sequence of notes and chords as 2D arrays proves to be a feasible design for the training dataset. This kind of input data shape allows the Generative Adversarial Network to generate music in the same way as generating images. By up scaling the dimension (1000 by 84) of the training set, it could also produce music with much longer timesteps than the previous studies (4 by 128).</p><p>Among the four Classical Music eras, I found the Bi-LSTM model suitable for generating Baroque, Classical, and some Romantic Music owing to the design of the Bi-LSTM model and the nature of these musical styles. These types of music require strict rules and are less complexed than the Modernist music. The design of LSTMs works just well for doing these tasks. On the other hand, the GAN model seems to be more creative and stochastic in generating music. I therefore consider it suitable for generating Modernist Music.</p><h4>6.2 Future Improvement</h4><p>To further improve the quality of the generated music, an augmentation and additional refinement of the training set is recommended. Though this project’s training set includes hundreds of classical music pieces in midi format, most midi files are recorded live which means that some background noise might be as well recorded with the music during the original performance, and this could affect the precision of making the midi files. For instance, when visualizing some music sheets from the dataset using the ‘MuseScore’ software, it is obvious to observe excessive notes and chords comparing with the original music scores. It could be a potential cause of harming the later training process, however, further trials and examinations are needed to prove this hypothesis. Also, the data cleaning process is essential as I found many duplicate and invalid (empty) pieces of music from the dataset.</p><p>It is believed that the Bi-LSTM model outperforms the unidirectional LSTM model from the previous studies. However, a comparison of performance between the unidirectional LSTM model and the Bi-LSTM model should be made in the future to confirm this argument.</p><h3>7 References</h3><p>Boulanger-Lewandowski, N., Bengio, Y., &amp; Vincent, P. (2012). Modeling temporal dependencies in high-dimensional sequences: Application to polyphonic music generation and transcription. arXiv preprint arXiv:1206.6392.</p><p>Briot, J. P., Hadjeres, G., &amp; Pachet, F. D. (2017). Deep learning techniques for music generation — a survey. arXiv preprint arXiv:1709.01620.</p><p>Choi, K., Fazekas, G., &amp; Sandler, M. (2016). Text-based LSTM networks for automatic music composition. arXiv preprint arXiv:1604.05358.</p><p>Dong, H. W., Hsiao, W. Y., Yang, L. C., &amp; Yang, Y. H. (2017). MuseGAN: Demonstration of a convolutional GAN based model for generating multi-track piano-rolls. ISMIR Late Breaking/Demos.</p><p>Eck, D., &amp; Schmidhuber, J. (2002). A first look at music composition using lstm recurrent neural networks. Istituto Dalle Molle Di Studi Sull Intelligenza Artificiale, 103, 48.</p><p>Goodfellow, I., Pouget-Abadie, J., Mirza, M., Xu, B., Warde-Farley, D., Ozair, S., … &amp; Bengio, Y. (2014). Generative adversarial nets. In Advances in neural information processing systems (pp. 2672–2680).</p><p>Hadjeres, G., Pachet, F., &amp; Nielsen, F. (2017, July). Deepbach: a steerable model for bach chorales generation. In International Conference on Machine Learning (pp. 1362–1371). PMLR.</p><p>Hochreiter, S., &amp; Schmidhuber, J. (1997). Long short-term memory. Neural computation, 9(8), 1735–1780.</p><p>Moorer, J. A. (1972). Music and computer composition. Communications of the ACM, 15 (2), 104–113. 47</p><p>Shiebler. (2016). Magenta/magenta. GitHub. <a href="https://github.com/magenta/magenta/tree/master/magenta/reviews">https://github.com/magenta/magenta/tree/master/magenta/reviews</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=63d983ee5fc0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/ai-classical-music-composer-63d983ee5fc0">AI Classical Music Composer — Bi-LSTM &amp; CNN-GAN</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Structures at Play — Sliding-Block Puzzle and Permutation Inversions]]></title>
            <link>https://jonathan-kuo.medium.com/data-structures-at-play-sliding-block-puzzle-and-permutation-inversions-c2e1a5494d52?source=rss-c2bfa09e15b6------2</link>
            <guid isPermaLink="false">https://medium.com/p/c2e1a5494d52</guid>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[games]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Jonathan Kuo]]></dc:creator>
            <pubDate>Fri, 20 Aug 2021 06:53:56 GMT</pubDate>
            <atom:updated>2021-08-20T06:53:56.688Z</atom:updated>
            <content:encoded><![CDATA[<h3>Data Structures at Play — Sliding-Block Puzzle and Permutation Inversions</h3><p>This is a CS3334 — Data Structures course project. It was completed by <a href="https://github.com/AlexanderLuasan">Alex McVay</a>, <a href="https://github.com/chiatsekuo">Chia-Tse Kuo</a> (me), and <a href="https://github.com/psh320">Andrew Park</a>. The program code can be found <a href="https://github.com/chiatsekuo/tilepuzzle">here</a>.</p><h3>Introduction</h3><p>In the traditional 3 by 3 tile puzzle, the number of inversions is used to prove its solvability. Looking at how each move changes the inversions of the puzzle, it is possible to find when the tile puzzle can reach any other state. To calculate the inversions, we transform the tiles row by row from a two-dimensional grid to a one-dimensional list. In this form, it is easier to solve for the inversions of a state of the puzzle. The inversions of the puzzle are a way to represent how well the puzzle is solved.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/708/0*ccIFlIiGrxvLSWo7.PNG" /><figcaption>Fig.1 Transform the 2-dimensional grid into 1-dimensional array</figcaption></figure><h3>Original Puzzle</h3><p>Inversion Count for an array indicates that how distant the array is from being sorted. If the array is already solved then the inversion count is 0. If the array is sorted in reverse order, that inversion count would be the maximum. For example, we assume an array “a[ ]”: If an integer ‘i’ is less than another ‘j’, and if a[i] is greater than a[j], there exists an inversion formed by a[i] and a[j].​ In this way, when the tiles are in the solved state, the number of inversions is zero, and when the tiles are in the complete opposite order, the inversions are at the maximum: 36. In addition, the empty tile is always ignored when calculating the inversions in this game. Now, we need the concept of polarity to study the solvability of the puzzle. Numbers have the same polarity when they are both even or odd. A way to calculate this is to check if mod 2 of both numbers are the same.</p><p>​These rules help prove the solvability of the 3 by 3 puzzle by looking at how each move changes the number of inversions. When making a move to the left or right, the number of inversions does not change. Tiles can’t actually move past another tile when making these horizontal moves. Only the empty tile and that target tile (this is the one clicked on) can be swapped and they won’t change the number of inversions as the empty tile is ignored.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/726/0*_fyLy7QFajYxLQ1q.PNG" /><figcaption>Fig.2 No change of inversions when swapping tiles horizontally</figcaption></figure><p>This just leaves the vertical moves. Vertical moves on the grid translate to the swapping of an empty tile and a tile 3 steps away, as a result, it will move ahead or behind 2 other tiles and this can change the inversions. However, in all three possible cases, something special happens. If both tiles were greater than the moving tile, then two inversions are removed or added. If both were less than the moving tile, then two inversions are added. And if one is greater and the other is less, then the inversion remains the same. As a result, the polarity of the inversion in this puzzle can never change, because it always changes by two at a time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/675/0*GS5hLrEz4U0UPCiM.PNG" /><figcaption>Fig.3 Since 5 and 6 are greater than 4, the inversions added 2, and become 2</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/677/0*FWcIM1N5_7jBfLPR.PNG" /><figcaption>Fig.4 Since 2 and 3 are greater than 1, the inversions added 2, and become 4</figcaption></figure><h3>Variant Size and Board Design</h3><p>For a puzzle with different dimensions, it would be different species if the width is an even number. In these cases, vertical moves make the tile swap with a different number of tiles. In an even width game, the polarity changes with each vertical move. It is still possible to find if the puzzle is solvable by examining which row the empty tile is in and the number of rows away from the solved position. By counting the difference in rows the blank tile is away from the correct position the polarity of the number of vertical moves can be calculated as each vertical move changes the polarity. With these two values, it is possible to prove the solvability of a state.​ Now, let’s take a look at this new tile sliding game. In this game, the board is filled with tiles, so instead of moving an empty space around the board, the tiles are moved as a whole row or column wrapping around the edge as if on a torus. The solvability of this puzzle can be tackled and proved in a similar way to the original puzzle mentioned above. We will look at the game of size 3 by 3 as an example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/521/0*eviRG7C7C8z3JN4v.PNG" /><figcaption>Fig.5 Unfold the torus into a flat sheet</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/471/0*h2W0khp3oEWaNGZc.PNG" /><figcaption>Fig.6 Solved state of the Wrap Around Board mode</figcaption></figure><p>First, we focus on horizontal movement. Most tiles stay in the same order except one tile that jumps past the rest of the tiles, and this particular tile is the one that wraps around the edge of the board. This row rotation is similar to the vertical moves from the regular puzzle because each tile moves past two, meaning on the board with an odd width, the number of inversions changes is always even, and therefore the polarity does not change.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/631/0*cXw4_md6beJ2xsqp.PNG" /><figcaption>Fig.7 One horizontal move on the Wrap Around Board mode</figcaption></figure><p>Second, the vertical movement of tiles looks intimidating, but it can be divided into two simpler steps. First, look at the tiles that don’t leave the board. Each one just moves like the regular game, passing two other tiles making the change in polarity even. Since there are two tiles that are performing the movement together simultaneously, they don’t actually change the polarity. The tile that moves off the board jumps past a number of tiles: ones on the same row and to the left, all non-moving tiles in the middle row, tiles on the left on the bottom row, and also both moving tiles. This is 3 by 3 case that is always 6 giving an even number of inversions or in general (height -1) * width of the board, so as long as the height is odd or the width is even the move will also maintain polarity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/583/0*cjpb_5LlXMA1fWWt.PNG" /><figcaption>Fig.8 One vertical move on the Wrap Around Board mode</figcaption></figure><p>When looking at boards of other sizes, it starts to get complicated. For instance, expanding to a 4 by 4 grid, each move flips the polarity of the inversions. When making horizontal moves, each move takes one tile past three and vertical moves take 3 tiles past 3 and 1 tile past 12 this all ensures that each move switches the polarity. From playing around with the board I have a suspension that every state is possible because there seem to be ways to solve all but two tiles that are right next to each other. That is normally impossible with other versions of the game and it may be proof that it could be possible to create any format of the board however I currently don’t have the proof to show each state is possible.</p><h3>AI Solving Method</h3><p>As opposed to the solvability of the puzzles, the solutions cannot be determined by the number of inversions. In order to look into the solution of the puzzle, a small side project in this program is a way to solve the puzzle automatically. This is handled by a simple search algorithm. The algorithm uses two lists of game states to search for a possible solution. Initially, an Open list is filled with the starting state then each round of searching begins by selecting a state in the Open list that is closest to the solved state by Manhattan distance and also has a low number of moves from the initial position. The chosen state is moved to the closed list and every move from the state is added to the Open list. This process is repeated until the solved state is found in the closed list then the algorithm can calculate the states backward to find the step-by-step solution.</p><h3>Reference</h3><ul><li>Mark Ryan (2004) Solvability of the Tiles Game, Available at: <a href="https://www.cs.bham.ac.uk/~mdr/teaching/modules04/java2/TilesSolvability.html">https://www.cs.bham.ac.uk/~mdr/teaching/modules04/java2/TilesSolvability.html</a></li><li>Paul E. Black, “Manhattan distance”, in Dictionary of Algorithms and Data Structures [online], Paul E. Black, ed. 11 February 2019. (accessed TODAY) Available from: <a href="https://www.nist.gov/dads/HTML/manhattanDistance.html">https://www.nist.gov/dads/HTML/manhattanDistance.html</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c2e1a5494d52" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Image Search — Transfer Learning with CNN]]></title>
            <link>https://medium.com/analytics-vidhya/image-search-transfer-learning-with-cnn-convolutional-neural-network-76c5fb7b8819?source=rss-c2bfa09e15b6------2</link>
            <guid isPermaLink="false">https://medium.com/p/76c5fb7b8819</guid>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[transfer-learning]]></category>
            <category><![CDATA[object-recognition]]></category>
            <category><![CDATA[instance-search]]></category>
            <category><![CDATA[image-search]]></category>
            <dc:creator><![CDATA[Jonathan Kuo]]></dc:creator>
            <pubDate>Thu, 20 May 2021 09:47:43 GMT</pubDate>
            <atom:updated>2021-05-26T12:49:41.110Z</atom:updated>
            <content:encoded><![CDATA[<h3>Image Search — Transfer Learning with CNN</h3><p>To build an Image Search Engine that retrieves the most similar images from the database based on specific target images.</p><h3>Problem</h3><p>Given a query image (containing a specific instance) and a collection of images with different contents, we want to find the images that contain the same query instance from the collection.</p><p>The below images are two examples of query images (original + cropped).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/496/0*4Bd_QUTPP1Cz9QF7.PNG" /><figcaption>Two examples of query images.</figcaption></figure><p>The image below is the query result using ResNet transfer learning. Since I have ten query images, there are ten rows of images, with each row containing the ten most similar images to the query image. We can see that the first-row containing images of the <a href="https://en.wikipedia.org/wiki/Eiffel_Tower">Eiffel Tower</a>. The second row is images of <a href="https://en.wikipedia.org/wiki/Steve_Jobs">Steve Jobs</a>, and so on. In the following sections, we&#39;ll see how this method is implemented.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/0*lyt1Ae5Xx6lTZSt5.png" /></figure><h3>Method</h3><p>Performing <strong>transfer learning on </strong><a href="https://en.wikipedia.org/wiki/Residual_neural_network"><strong>ResNet</strong></a>. We can benefit from the exponentially shortened amount of training time compared with the time needed for training from scratch. In addition, it is used for extracting features.</p><ol><li><strong>Extract features</strong> from the query image and each image from the collection.</li><li>Calculate the <strong>similarity (or difference) scores</strong> between the query image and each image from the collection.</li><li>The query result is the images from the collection <strong>sorted</strong> by the similarity score.</li></ol><p>(Note: The code below is implemented with <a href="https://pytorch.org/">PyTorch</a>.)</p><h3>Code</h3><p>(<a href="https://github.com/chiatsekuo/computer_vision_image_processing/tree/main/instance_search">complete code @ Github</a>)</p><p>I&#39;ll skip the image loading and image preprocessing parts since they could be implemented differently depending on scenarios and libraries.</p><h4>Feature Extraction</h4><p>First, import the required libraries for PyTorch.</p><p>Notice that the PIL (<a href="https://pypi.org/project/Pillow/">Pillow</a>) python image library seems more compatible with PyTorch than <a href="https://opencv.org/">OpenCV</a> in this case.</p><p>The <a href="https://tqdm.github.io/">tqdm</a> package allows you to track the estimated processing time by displaying a dynamic progress bar.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/535b671567dbc632db293a3405ced75b/href">https://medium.com/media/535b671567dbc632db293a3405ced75b/href</a></iframe><p>Now, we can load the pre-trained ResNet18 model.</p><p>Next, we need to transform the images into our desired settings. Each image should be resized to 256 by 256 pixels since this is the default input shape of ResNet18. <strong>torchvision.transforms.CenterCrop(size)</strong> basically crops the given image at the center, and <strong>size</strong> is the desired output size of the crop. We should also normalize a tensor image with a mean and standard deviation.</p><p>The <strong>get_vector(image)</strong> function returns the features of the input image.</p><p>Finally, we need to loop through all images from the collection and compare the feature of the query image (s) with each image from the collection by calculating their <a href="https://en.wikipedia.org/wiki/Euclidean_distance#:~:text=In%20mathematics%2C%20the%20Euclidean%20distance,being%20called%20the%20Pythagorean%20distance.">Euclidean distance</a> (shown in line 45 below).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aa2db671c84d6cbf09e8c4593e1ed2d1/href">https://medium.com/media/aa2db671c84d6cbf09e8c4593e1ed2d1/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=76c5fb7b8819" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/image-search-transfer-learning-with-cnn-convolutional-neural-network-76c5fb7b8819">Image Search — Transfer Learning with CNN</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A survey of computer vision in fine-art classification]]></title>
            <link>https://medium.com/data-science/a-survey-of-computer-vision-in-fine-art-classification-9c7e60ad3fc2?source=rss-c2bfa09e15b6------2</link>
            <guid isPermaLink="false">https://medium.com/p/9c7e60ad3fc2</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[digital-art]]></category>
            <category><![CDATA[image-classification]]></category>
            <category><![CDATA[computer-vision]]></category>
            <dc:creator><![CDATA[Jonathan Kuo]]></dc:creator>
            <pubDate>Sat, 20 Mar 2021 05:09:02 GMT</pubDate>
            <atom:updated>2021-08-04T02:59:27.850Z</atom:updated>
            <content:encoded><![CDATA[<h3>A survey of Computer Vision in fine-art classification</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/969/0*1dw7hsU5cjPLvJeX" /><figcaption>Image from <a href="https://www.vcl.fer.hr/papers_pdf/Fine-tuning%20Convolutional%20Neural%20Networks%20for%20fine%20art%20classification.pdf">Cetinic et al. (2018)</a></figcaption></figure><h3>Overview</h3><p>With the emergence of online galleries and online fine-art markets, digitized fine-art painting collections have become demanding. Google Arts &amp; Culture is an excellent example of an educational and recreational online platform that brings online fine art more accessible to people — letting people even immerse in the virtual art gallery through its VR technology. Another example is Artsy, which is an online fine-art brokerage. It utilizes a search system to link works of art based on their relationships with each other. In addition, many other applications require the techniques of fine-art classification. Therefore, the enhancement of the capabilities in the search algorithms of digitized arts and the process of documenting and managing this cultural heritage remains essential and meaningful. However, there are at least a few challenges that remain to be resolved to address this problem.</p><h3>Problem</h3><p>A significant challenge is the shortage of large datasets of labeled digitized artworks. Without substantial data, even a recognized classification model will not yield a good classification result. The designs of the classification models and the implementations of model training are equivalently critical as well. Therefore, in the following sections, I will first review a data augmentation method that tries to overcome the lack of labeled fine-art data proposed by Smirnov &amp; Eguizabal (2018). Together with their approach to refining transfer learning on some renowned CNNs (Convolutional Neural Networks). Next, a novel approach that uses image patches and transfer learning to classify fine-art images introduced by Rodriguez et al. (2018) will be discussed. Finally, I will compare the aforementioned works with the design proposed by Cetinic et al. (2018). They discovered that instead of focusing on object detection for the classification task, scene recognition and sentiment prediction could generate better results for the job.</p><h3>Dataset</h3><p>The dataset being used in the three above mentioned papers are:</p><ul><li>PASCAL VOC</li><li>Painting dataset</li><li>TICC Printmaking Dataset</li><li>Web Gallery of Art (WGA)</li><li>WikiArt</li></ul><p><em>PASCAL VOC</em> includes 20 classes of annotated images taken by the cameras without further stylistic transformation for object recognition and segmentation tasks. The <em>Painting dataset</em> contains 10 classes of fine-art paintings with the labels from the <em>PASCAL VOC</em>. <em>TICC Printmaking Dataset</em> is a dataset of digitized photographic artwork reproduction on prints made on paper. WGA comprises fine-art paintings from the early 3rd to 19th centuries. Apart from WGA, <em>WikiArt</em> is one of the largest online digitized painting collections, including more than 250000 artworks by 3000 artists from the 19th to 20th centuries.</p><h3>Algorithms and Methods</h3><h4>Data augmentation</h4><p>Compared with some of the most well-known datasets, such as ImageNet (14 M+ images with 20000 categories) and Tencent ML Images (~18M images with 11166 categories), there is much less data for the fine-art paintings. Fortunately, a group of researchers has found a way to tackle this problem.</p><p>Smirnov &amp; Eguizabal (2018) proposed applying style transfer for real-world images obtained from <em>PASCAL VOC</em>. The concept combines (or multiply, in a more technical term) natural images from <em>PASCAL VOC</em> and images with specific artistic styles, such as Impressionism or Realism. Thus, it allows a wide variety of new images to be generated with the same content (object) but with different artistic styles or textures. An example of the process is shown in the below figure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/695/0*2IlBItVfiuFCI1oW" /><figcaption><em>Figure 1. An example of the style transfer process. Image (e), (f), and (g) has been applied style (b), (c), and (d) respectively. All result images present the same content of the image (a) but with unique artistic styles. Image from </em><a href="https://www.researchgate.net/profile/Stanislav-Smirnov-2/publication/330753678_Deep_learning_for_object_detection_in_fine-art_paintings/links/5db6a18292851c577eced626/Deep-learning-for-object-detection-in-fine-art-paintings.pdf">Smirnov &amp; Eguizabal (2018)</a></figcaption></figure><h4>Transfer learning with convolutional neural networks (CNNs)</h4><p>To benefit from the valuable features obtained from some pre-trained CNNs and save computational cost, all three papers adopt transfer learning methods on different CNN models to classify fine-art paintings.</p><h4>1. CaffeNet and its variations</h4><p>Cetinic et al. (2018) used the base architecture of CaffeNet, which is a slight modification of AlexNet. It is a shallow network with only eight layers. Five Three convolutional layers followed by three fully connected layers. Also, there are three max-pooling layers after the first, second, and fifth convolutional layers. They chose ReLU as the activation function for all layers, and the output layer is connected to a softmax layer. The figure below depicts CaffeNet’s architecture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/932/0*p22IkW0qjZNGnRdQ" /><figcaption><em>Figure 2. CaffeNet’s architecture. Image from </em><a href="https://medium.com/coinmonks/paper-review-of-alexnet-caffenet-winner-in-ilsvrc-2012-image-classification-b93598314160">https://medium.com/coinmonks/paper-review-of-alexnet-caffenet-winner-in-ilsvrc-2012-image-classification-b93598314160</a></figcaption></figure><p>Since transfer learning aims to take advantage of the pre-trained weights, the authors reserved the weights of the first seven layers but the last of the pre-trained CaffeNet. Instead, they replaced the last fully connected layer with a specific number of neurons corresponding to the number of targeted classes in their dataset. They also attempted to test different combinations of the frozen layers (meaning the settings and weights are kept the same as the pre-trained model) to evaluate whether they will affect the classification task&#39;s final performance. They believe that the first few CNN layers were to discover general features like obvious blobs or edges. In contrast, the rest of the layers would dive deep into each image and extract more detailed features. Interestingly, according to the below table, they found that the optimal performance is done by freezing only the first or the first two convolutional layers’ weights and re-train all other layers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Jxqehpw7qJfuFSTv" /><figcaption><em>Figure 3. Comparison of test accuracies for different fine-tuning scenarios. Figure from </em><a href="https://www.vcl.fer.hr/papers_pdf/Fine-tuning%20Convolutional%20Neural%20Networks%20for%20fine%20art%20classification.pdf">Cetinic et al. (2018)</a></figcaption></figure><p>Besides focusing on object recognition, the study also discovered that a combination of scene and object recognition using pre-trained CNNs yielded better results than merely object recognition. Furthermore, the dataset was a mixture of Places and ImageNet images. This experiment could indicate that the fine-art classification task might need the scene features to help boost the classification accuracy.</p><h4>2. Image patches or segmentation</h4><p>Rodriguez et al. (2018) suggest that each image from the dataset should be equally segmented into five pieces as the CNN model&#39;s input. Then, combining the weighted classification results from the previous step, a higher classification accuracy could be expected than classification results with unsegmented images.</p><p>The three main steps are as follows: First, each image from the training set is resized to double the current size. Each image is then segmented into five pieces in equal size, where four pieces are the corner pieces with the same height and width as the original image, and the fifth piece being the centerpiece that shares exactly twenty-five percent of each corner piece.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/787/0*I36XNe6t-3hjZvOv" /><figcaption><em>Figure 4. an example of segmenting the original image into five equal size pieces. Image from </em><a href="https://ieeexplore.ieee.org/abstract/document/8631731">Rodriguez et al. (2018)</a></figcaption></figure><p>Second, the new set of images (patch-image) is then fed into some pre-trained CNN models to classify the styles of each image segmentation. The pre-trained CNN models used in this experiment are AlexNet, VGG-16, VGG-19, GoogLeNet, ResNet-50, and InceptionV3. It is worth noting that they only replace the last three layers of these neural networks to fit the classes&#39; targeted number. Here, the focus is not on the performance of each CNN but on observing whether there is any trend or indication of a weighted image patch that could bring a higher classification accuracy.</p><p>Finally, an optimization procedure is performed for each original image to discover the optimal weights of the class probability for each segmented image according to the classification results from the previous step. Since each image patch is being classified independently, meaning all image patches from the same original image do not influence the classification process, it is possible to have different image patches from the same original image being classified into different target classes (artistic styles). Hence, they applied an optimization process, Genetic Algorithm, to iteratively search for an optimally combinatorial weighted result to finally decide the decision class for each original image. The algorithms and their processes are illustrated in the below figure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fdxNNoAFI3My8841" /><figcaption><em>Figure 5. The weight optimization process for each image patch. Image from </em><a href="https://ieeexplore.ieee.org/abstract/document/8631731">Rodriguez et al. (2018)</a></figcaption></figure><p>Here, Cn, k is the outcome of each image patch from the CNN, wn denotes the corresponding weight of Cn, k, and CTk is the total result vector of the kth original image. Now, with the optimal weight of each image patch outcome found, the final step is to find the maximum total probability vector, CTk, by the dot product operation of the optimal weight and each image patch’s probability vector. Also, there is a constraint on each image-patch weight being set to be less than or equal to 1 (100%) to guarantee no individual image-patch weights over 100% than others. The final results are shown in the below figure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2389MyQ4bPQaF3xB" /><figcaption><em>Figure 6. Style classification results of a combination of different models and scenarios. Image from </em><a href="https://ieeexplore.ieee.org/abstract/document/8631731">Rodriguez et al. (2018)</a></figcaption></figure><p>From the bar chart, we can observe that using the weighted image patches yield higher accuracies in style classification tasks than merely using original images as input data. When images are segmented, it seems helpless in solving this problem. However, considering those individual segments with optimal weights shows how an image patch could boost classification accuracy by contributing higher resolutions. Therefore, the study concluded that images with higher resolutions could add valuable information such as artistic styles for fine-arts style classification tasks.</p><h4>3. CNN fusion with SVM</h4><p>A common problem for fine-art classification tasks is the lack of data. Without enough data, it would be difficult for any classification or object detection task. To tackle this problem, Smirnov &amp; Eguizabal (2018) proposed the data augmentation method mentioned above and their training method — two CNN with an SVM. The concept is first to train two CNNs, then concatenate the result vectors from the CNNs and feed them into an SVM for final object detection. The flowchart is illustrated in the below figure. Here, one CNN is for object detection, and the other is for style classification. The PASCAL VOC dataset is trained for the object detection task, and the WikiArt image dataset is trained for style classification. And they used VGG-19 as the model for both CNNs. The weights of both CNNs are kept the same as the original pre-trained VGG-19 except for the last fully connected layer, tailor-made for later concatenation of output feature vectors from both CNNs. The test result shows that it outperforms traditional object detection and classification methods by five percent. This study demonstrates the efficacy of augmenting the fine-art image dataset by applying artistic styles to everyday-images, and the feasibility of fusing two CNNs that train on different subjects (objects and styles) with an SVM.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/0*mDC7BIwOmji185mw" /><figcaption><em>Figure 7. The flow diagram of two CNNs with SVM. Image from </em><a href="https://www.researchgate.net/profile/Stanislav-Smirnov-2/publication/330753678_Deep_learning_for_object_detection_in_fine-art_paintings/links/5db6a18292851c577eced626/Deep-learning-for-object-detection-in-fine-art-paintings.pdf">Smirnov &amp; Eguizabal (2018)</a></figcaption></figure><h3>Future research trends</h3><p>Several ways could improve the current approaches to classifying or detecting fine-art images. In the study by Cetinic et al. (2018), they recommend that besides working on fine-art image classification tasks, researchers could also discover intrinsic inter-relationships of image features between digitized artworks. Targets like emotions, quality, and aesthetics in photography and images could also be considered in future research. Besides, it is always a good idea for researchers to collaborate with fine-art historians and experts in related fields to better understand the fine-art domain.</p><p>Other studies suggest investigating other neural networks or CNNs to evaluate their computational cost and classification performance and find the optimal equilibrium for this task. For instance, though the InceptionV3 model yields higher accuracy in classifying images, it requires a longer time to train on the same dataset than AlexNet and other simple CNNs. Hence, it is an optimization topic worth investigating.</p><h3>Creativities</h3><p>A common problem found in fine-art classification is the high misclassification rate between Impressionism and Expressionism artworks. It is because the latter evolved from the former. However, I came up with an idea- a two-stage classification, to possibly tackle this problem. Initially, all images from the dataset are being classified roughly. Then, a finer classification specifically designed for distinguishing Impressionism and Expressionism digitized images is performed. Before building the second classifier, we need to know some common-known characteristics of the two art styles. Impressionism focuses on the change of lights, and Expressionism mainly pays attention to the expressions on human faces. With this prior information, we can build a classifier that extracts pixel values of images and facial expressions. If the input image shows a strong indication of facial expressions, we can assume that it belongs to an Expressionism artwork. On the other hand, if an image is being detected with abundant shifts of pixel values and without features of faces, we can say that it is a piece of artwork from Impressionism.</p><h3>Conclusion</h3><p>Computer vision in fine-art classification is an interesting topic that could bring great value to the real world. As digitized artworks become more prevalent in recent years and the booming market of online art auctions, fine-art classification has started to play a crucial role in these trends. With the technology, it would be easier for all parties to identify different artworks dating backing from ancient history to the modern world. Saving the cost of human labor to confirm, classify or even authenticate each piece of artwork. However, further studies are needed to harness the power of computer vision for humans to benefit from this technology.</p><h3>References</h3><p>Cetinic, E., Lipic, T., &amp; Grgic, S. (2018). Fine-tuning convolutional neural networks for fine art classification. <em>Expert Systems with Applications</em>, <em>114</em>, 107–118.</p><p>Rodriguez, C. S., Lech, M., &amp; Pirogova, E. (2018, December). Classification of style in fine-art paintings using transfer learning and weighted image patches. In <em>2018 12th International Conference on Signal Processing and Communication Systems (ICSPCS)</em> (pp. 1–7). IEEE.</p><p>Smirnov, S., &amp; Eguizabal, A. (2018, October). Deep learning for object detection in fine-art paintings. In <em>2018 Metrology for Archaeology and Cultural Heritage (MetroArchaeo)</em> (pp. 45–49). IEEE.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9c7e60ad3fc2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/a-survey-of-computer-vision-in-fine-art-classification-9c7e60ad3fc2">A survey of computer vision in fine-art classification</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Science — a deep analysis on “google play store apps” dataset from Kaggle]]></title>
            <link>https://medium.com/data-science/data-science-a-deep-analysis-on-google-play-store-apps-from-kaggle-8283bbc508b0?source=rss-c2bfa09e15b6------2</link>
            <guid isPermaLink="false">https://medium.com/p/8283bbc508b0</guid>
            <category><![CDATA[apps]]></category>
            <category><![CDATA[data-analytics]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Jonathan Kuo]]></dc:creator>
            <pubDate>Wed, 03 Mar 2021 08:45:14 GMT</pubDate>
            <atom:updated>2021-08-04T02:58:12.895Z</atom:updated>
            <content:encoded><![CDATA[<h3>Data Science — A comprehensive analysis on “Google Play Store Apps” dataset from Kaggle</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MbPT3hkpSbU57wnUezskNQ.jpeg" /><figcaption>Photo by <a href="https://www.pexels.com/@luckysam?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">MOHI SYED</a> from <a href="https://www.pexels.com/photo/mobile-phone-samsung-edge-samsung-galaxy-s6-edge-plus-50614/?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Pexels</a></figcaption></figure><p>Data science can be summarized into five steps: capture, maintain, process, analyze, and communicate. First, we gather the data that has meaningful variables leading to appropriate classes. Then clean the data so that it is easy for a computer to read and process modeling. Next, we apply algorithms to train the model and test it using data acquired from the Kaggle dataset and analyze the model&#39;s performance. We then view the results and attempt to extract any relevant learning or information.</p><h3>The goal of the Project</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ix8aAbuGCs0BBsOVJ-OegA.png" /><figcaption>image by Jonathan C.T. Kuo</figcaption></figure><p>Our project goal is to predict the number of installs of apps by looking at app info and its reviews. We hope that this project will help app developers predict their number of installs or investors who want to pick out the next big app. Companies may run beta focus groups, or app developers may receive feedback from testers and get certain amounts of reviews. We use this and some knowledge about the app to predict its success. Knowing the number of installs can help developers and business managers because they can predict the profit. This project&#39;s result may show the importance of reviews to apps in the market as it could be one of the determining factors for the number of installs.</p><h3>Raw Tables</h3><p>We have two datasets from Kaggle for app reviews; one is the list of apps with information. It has information such as app name, category, rating, and more. And the other is a list of reviews for each app with the sentiment if that particular content of the review was positive, neutral, or negative. Unfortunately, we could not directly use these two files as they are not joined.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tm0zWd5onl_v0O0O" /><figcaption>table for listing out apps and their information | image by Jonathan C.T. Kuo</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/894/0*IkGb99x1roe4fIpd" /><figcaption>table for list of reviews according to apps | image by Jonathan C.T. Kuo</figcaption></figure><h3>Cleaning the Table</h3><p>First, we have analyzed which information column is irrelevant to the number of installs of the app. It was done by common sense. We removed size, last updated date, current version, and android version because they are not the factor that would affect the number of installs before publishing. Also, we have removed the rating and number of reviews because they are obviously associated with app installs and would not be known before publishing. Then we also trimmed our data of any out-of-place characters.</p><p>We combined Category and Genre by categorizing common keywords and added the list of the key categories to columns so that each app’s attributes for category/genre can be expressed as true or false. Moreover, we have gathered the sentiment of reviews for each app and calculated the total number of positive, neutral, and negative percentages. Finally, we combined those three columns with the existing app list.</p><p>And now we are ready for testing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Lu_ltbatBCDatbkP-To_3Q.png" /><figcaption>image by Jonathan C.T. Kuo</figcaption></figure><h3>First Result</h3><p>This histogram shows the performance of the Decision Tree with the cleaned data. We Used the decision tree implemented by python sci-kit learn, which is the CART. CART is similar to existing decision trees like C4.5, but it locks binary decisions and information gain. We found these results a little disappointing, so we decided we should try some other model. So we took and also built some Artificial Neural Networks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cxQ5kP7y2p8hhzfy" /><figcaption>image by Jonathan C.T. Kuo</figcaption></figure><p>We can see that these networks performed a little better but only Just barely above a coin flip. However, we still felt it should be possible to surpass this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*azI5CgpcYu6Ldszf" /><figcaption>image by Jonathan C.T. Kuo</figcaption></figure><p>We know that this data contains a lot of outliers. Outliers can be difficult if not enough cases exist in both training and test sets. The model will have no way of being able to predict how to solve these cases. It is like you predict that coin flip will always head just because the first two coin flip are both heads.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*c2aUC8LkFbH2DfJP" /><figcaption>Original data — Category count | image by Jonathan C.T. Kuo</figcaption></figure><p>For Category attributes, some of the key categories are very uncommon, that very few apps have that particular category, which becomes an outlier.</p><p>To fix this, we remove a number of the most uncommon classes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1nQWHDKuJVnF_WA7" /><figcaption>Processed data — Category count | image by Jonathan C.T. Kuo</figcaption></figure><p>Take a look at the distribution of install numbers. We can see that they have been rounded and that ‘number of installs = 1000’ is very small. This can cause problems for the model to train.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZQDb2y2sNUcw1Pgm" /><figcaption>Original Class | image by Jonathan C.T. Kuo</figcaption></figure><p>To improve this, we can drop those rows to make the data more normal. We can also combine these classes, so there are no classes that appear too few times.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kRtqzILWhhW-n6-O" /><figcaption>Processed Class | image by Jonathan C.T. Kuo</figcaption></figure><p>we can proceed similarly for the other elements in our data, such as the sentiment score.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wWsJ4qQBlfaK9_Sm" /><figcaption>image by Jonathan C.T. Kuo</figcaption></figure><p>watch as we cut off the tails of these sentiment distributions at .2</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Vig1jiRQa2wMGrtf" /><figcaption>image by Jonathan C.T. Kuo</figcaption></figure><p>we do the same for negative and neutral</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sLSz2WK4ajBHN-iCb8ys2g.png" /><figcaption>image by Jonathan C.T. Kuo</figcaption></figure><p>Even after dropping the outliers, there may still be columns that will mislead the model, so we should attempt to search for the best set of attributes out of the remaining columns. We need to find what columns will be most useful in predicting the data or find which are least useful. However, we don’t want to test all possible combinations. This strategy is based on building several simple models in the training data and seeing how effective they are.</p><p>To search for a good set of columns, we first try to remove the training data&#39;s worst attributes. So from selecting all attributes, we build models where we remove one of the attributes. From their scores, we can find what attribute is the weakest. We can then continue this process by first removing the previously selected attribute and searching through the remaining attributes. We can also build up selecting the single most valuable attribute by testing every subset of one and then keeping the most valuable column. We can then test all subsets of 2 containing that single most valuable column. The first method of starting from all attributes selecting the worst attributes to remove each time I’ve called the drop method. The second method starting from nothing selecting the single best attribute does the opposite and will be called the gain method. We also separated a part of the training data to retest these subsets later.</p><p>Now once we have these lists, there are also several different ways we can apply this knowledge. We could take the best n attributes as defined by the list. This ranked approach can select what the algorithm thought the best subset is, but it might not be generalizable as it was built in its own training data. We can also look at all the subset test scores to select the best subset. These four methods: <em>ranked gain, ranked drop, best gain, </em>and <em>best drop,</em> can be applied to see which one is most effective.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/546/0*c3ayTxwiVZiTpn5_" /><figcaption>image by Jonathan C.T. Kuo</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/543/0*xgyasyK493OwU0Qe" /><figcaption>image by Jonathan C.T. Kuo</figcaption></figure><p>This graph shows that there seems to be an improvement in the testing accuracy when we remove outliers. For instance, the maximum accuracy for cleaned data is around 51%, and for the original data, the maximum accuracy is around 42%.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*t86uFO1tw3jrphek" /><figcaption>image by Jonathan C.T. Kuo</figcaption></figure><p>Same for the networks model, The maximum accuracy has increased by around 6%.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*z26VO_y4NaWt4eEa" /><figcaption>image by Jonathan C.T. Kuo</figcaption></figure><p>However, the chart does not really show the truth. We can think of the model changing from answering a multiple-choice problem to a True of False problem because we reduce the number of classes. A random guesser in multiple-choice is expected to get 25% right in true or false we should see that rise to 50%. For example, a majority class in our previous testing area contained 24%, so a majority guess should get 24%, now the majority class is 35%. Meaning the guessing majority class has improved by 11%. Since it is easier to classify the data, the accuracy should automatically rise.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VC0zlMddmKpqoNuN" /><figcaption>image by Jonathan C.T. Kuo</figcaption></figure><p>If we subtract 11% to the accuracy of cleaned data, we can see that there isn’t an improvement. Even worse, our methods seemed to lower the accuracy. So let&#39;s see what goes wrong.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZQQuZM5fMQRxTB6C" /><figcaption>image by Jonathan C.T. Kuo</figcaption></figure><p>Before removing the outliers, we can look at the sentiment scores and see if it is related to the number of installs. From the following three graphs — Positive, Neutral, and Negative Sentiment scores versus installs, we can see that each of the graphs has data clustering together. And some people would say that it is a trend.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*07d8rBBoq3ZBSB4DfYCHSg.png" /><figcaption>image by Jonathan C.T. Kuo</figcaption></figure><p>Now, once we removed the outliers. The data points are more uniformly distributed, and there seems to be no trend at all. There are two reasons behind this result. First, it might be that there is no trend at all showing relation of sentiment scores and the number of installs. Second, when we were doing the second data cleaning process, we might remove the outliers which contain all the trends. However, if the outliers are the only trend, then those shouldn’t be considered as trends.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lzsNcGkYYFPzCzTs8pjsqw.png" /><figcaption>image by Jonathan C.T. Kuo</figcaption></figure><p>The selection of columns, however, seemed to be of some use. We can look at this graph of the improvements found by the column reducing algorithms. At the same time, a majority of the reductions failed to improve the model. However, many successfully found ways to improve the model and on the extreme side up to 10%.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VEC_wXo28Gv8ab8k" /><figcaption>Effectiveness at improving Tree | image by Jonathan C.T. Kuo</figcaption></figure><p>We can see that it had a similar effect on the neural network. They suggest the most effective method of picking columns is with the best subset in the drop method, the best subset in the gain method, and ranked selection in the drop method. This seems to be the only improvement out methods found.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*l25DSuwbtE7eeKW8" /><figcaption>Effectiveness at improving ANN | image by Jonathan C.T. Kuo</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dF-UE-ajoPSHS7iOY1NJZw.png" /><figcaption>Conclusion | image by Jonathan C.T. Kuo</figcaption></figure><p>This problem was complicated as it seems nothing we did was able to increase the score. This is likely because the people don’t really know what they want, and often the best product, such as the one with the best reviews, doesn’t actually do that well. We can see from the sentiment graphing that there seemed not to be any major correlation between good reviews and installs. This project could have been more successful was an early focus on changing to a regression problem as while the data while grouped could be turned back into a number. In the end, the best we could do with all the classes was 56% with the Network, and the best tree was 42%. The best we could achieve with the reduced classes was 62% with the ANN and 52% with the Tree. Overall getting even 62% seems unsuccessful. It is not very far from just majority guessing. But we suspect it would not be easy to achieve higher results; none of the attributes seems to predict the installs well. However, calling the project a complete failure is not correct. We were able to find some methods to improve the accuracy through column selection. In contrast, we made the problem easier by reducing the number of classes. It became more consistent. An easier problem with higher success would be a safer bet for those looking to invest.</p><h4>Acknowledgment</h4><p>I would like to thank Alex McVay and Andrew Park for putting lots of effort into this group project.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8283bbc508b0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/data-science-a-deep-analysis-on-google-play-store-apps-from-kaggle-8283bbc508b0">Data Science — a deep analysis on “google play store apps” dataset from Kaggle</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to generate Word Clouds from multiple news source (with python code)]]></title>
            <link>https://medium.com/analytics-vidhya/how-to-generate-word-clouds-from-multiple-news-source-with-python-code-47a03c512fe4?source=rss-c2bfa09e15b6------2</link>
            <guid isPermaLink="false">https://medium.com/p/47a03c512fe4</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[api-development]]></category>
            <category><![CDATA[word-cloud]]></category>
            <category><![CDATA[web-scraping]]></category>
            <category><![CDATA[data-visualization]]></category>
            <dc:creator><![CDATA[Jonathan Kuo]]></dc:creator>
            <pubDate>Mon, 04 Jan 2021 05:36:51 GMT</pubDate>
            <atom:updated>2021-01-04T16:46:14.281Z</atom:updated>
            <content:encoded><![CDATA[<p>The below tutorial will be divided into two parts — retrieve news information from the News API, and the generation of word clouds.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/745/0*RZqb5qBHmfP7vuD2.png" /></figure><h3>News API</h3><blockquote><strong>News API</strong> is a simple and easy-to-use API that returns JSON metadata for headlines and articles live all over the web right now.</blockquote><p>First, head to <a href="https://newsapi.org/">News API</a> to <strong>get the API key.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*crUVDfhoZMOCnzXWDhXUGA.png" /></figure><p>Now, open your Jupyter notebook and start coding! We’ll need to first install the <a href="https://pypi.org/project/newsapi-python/">newsapi-python</a> client library.</p><pre>!pip install newsapi-python</pre><p>Then, import all required libraries for later usage. Please paste your API key in the bracket as shown below.</p><pre>import pandas as pd</pre><pre>import numpy as np</pre><pre>from datetime import *</pre><pre>from newsapi import NewsApiClient</pre><pre>newsapi = NewsApiClient(api_key=’5f921c126ca94bfc8afd8accaf02bef9&#39;)</pre><h4>Data retrieval</h4><pre>sources = newsapi.get_sources()</pre><pre>sources_list = []</pre><pre>for source in sources[‘sources’]:</pre><pre>sources_list.append(source[‘id’])</pre><pre>print(len(sources_list))</pre><pre>sources_list</pre><p>This part of code will list out all potential news source. A part of the result is as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/378/1*S-I5MkQJ7iRP6UbJl3KUEQ.png" /></figure><p>Now, you can specify the <strong>timestamp </strong>of the news articles that you intend to retrieve. For instance, all news articles published 30 days ago. In addition, the <strong>query </strong>string (“data science” for example) needs to be specified here. In my case, I only intend to retrieve news articles that are related to “data science” from the first 50 news agencies 30 days ago. All results are stored in the <em>results </em>array.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/387d134baefabd811c07346fcf22a9dc/href">https://medium.com/media/387d134baefabd811c07346fcf22a9dc/href</a></iframe><h3>Word Cloud</h3><p>Once we get our context data, we can start creating the word clouds. Here, we use the <strong>WordCloud </strong>library to create a single word cloud for each news agency. Since the <em>results </em>array stores 50 sets of news articles, there will be 50 word clouds being generated according to the below code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bcefc6873addb834bf357f21577ec097/href">https://medium.com/media/bcefc6873addb834bf357f21577ec097/href</a></iframe><p>Some examples are shown as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/468/1*AyqZ10e9P2lhRAlWttJmqw.png" /></figure><p>So this is the end of the tutorial of generating word clouds for multiple news source. The same techniques can be applied in many different use cases. Hope this simple demonstration helps!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=47a03c512fe4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/how-to-generate-word-clouds-from-multiple-news-source-with-python-code-47a03c512fe4">How to generate Word Clouds from multiple news source (with python code)</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Multiclass image classification problem — Convolutional Neural Network trains on Galaxy images]]></title>
            <link>https://medium.com/analytics-vidhya/multiclass-image-classification-problem-convolutional-neural-network-trains-on-galaxy-images-6ca6aa74e5d7?source=rss-c2bfa09e15b6------2</link>
            <guid isPermaLink="false">https://medium.com/p/6ca6aa74e5d7</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[image-classification]]></category>
            <category><![CDATA[convolutional-network]]></category>
            <dc:creator><![CDATA[Jonathan Kuo]]></dc:creator>
            <pubDate>Sat, 21 Nov 2020 03:05:20 GMT</pubDate>
            <atom:updated>2020-12-17T08:21:28.285Z</atom:updated>
            <content:encoded><![CDATA[<h3>Galaxy images classification — Convolutional Neural Network (CNN) explained with codes</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rSH01Ti3RDFcQ7SJNLg2sQ.jpeg" /></figure><p>This is a multiclass image classification problem that uses convolutional neural network with TensorFlow (Keras api) to train on the Galaxy10 dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Cw4vn1T5FkCi4nTR.png" /></figure><p>First let’s download the dataset. In this tutorial, I’m running the code in Google Colab.</p><pre>!pip install astroNN</pre><p>Next we import the libraries.</p><pre>from astroNN.datasets import galaxy10<br>from astroNN.datasets.galaxy10 import galaxy10cls_lookup</pre><pre>import keras<br>from keras.models import Sequential<br>from keras.layers import Dense, Dropout, Flatten<br>from keras.layers import Conv2D, MaxPooling2D<br>from keras.utils import to_categorical<br>from keras.preprocessing import image</pre><pre>import numpy as np<br>import pandas as pd<br>import matplotlib.pyplot as plt<br>import matplotlib.image as mpimg<br>from sklearn.model_selection import train_test_split<br>from tqdm import tqdm</pre><p>Now, we can load the data and preprocess them. Each image has a corresponding label from 0 to 9. In order to make the computation more effectively later, we can one-hot encode each label with the to_categorical() function. In addition, we normalize the image values between 0 and 1 as a good practice to speed up the computational time.</p><pre>images, labels = galaxy10.load_data()</pre><pre>labels = labels.astype(np.float32)<br>labels = to_categorical(labels)<br>images = images.astype(np.float32)<br>images = images/255</pre><p>Here we can take a look at some images with their corresponding labels from the training .</p><pre>def show_image(image_data,label):<br>    label = galaxy10cls_lookup(int(label))<br>    plt.imshow(image_data)<br>    plt.title(label)<br>    plt.show()</pre><pre>for i in range(3):<br>    show_image(images[i], i)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/310/1*ha6lD2OiVTP4yghdfEWj3w.png" /></figure><p>Next we separate the training set and the test set with the train_test_split() function from <em>sklearn</em>.</p><pre>X_train, X_test, y_train, y_test = train_test_split(images, labels, test_size = 0.15)</pre><pre>print(X_train.shape)<br>print(y_train.shape)</pre><p>(18517, 69, 69, 3)<br>(18517, 10)</p><p>Now we also know the shape of the training set. There are 18517 images with 69 by 69 pixels with 3 (RGB) channels. The shape of the test set should be the same as the training set.</p><h3>CNN model</h3><p>The first layer is a convolutional layer with 32 output nodes. We also apply a 3 by 3 filter and a Rectified Linear Unit activation function in it and the input shape. Notice that the MaxPooling layer and the Dropout layer could help prevent the network from overfitting.</p><p>Finally we flatten the output data to a shape of 1D so that in the last Dense layer the model could make a choice between 0 and 9 to determine which label an image should belong to.</p><pre>model = Sequential()</pre><pre>model.add(Conv2D(32, kernel_size=(3,3),activation=&#39;relu&#39;,<br>input_shape=(69,69,3)))</pre><pre>model.add(Conv2D(64, (3, 3), activation=&#39;relu&#39;))</pre><pre>model.add(MaxPooling2D(pool_size=(2, 2)))</pre><pre>model.add(Dropout(0.25))</pre><pre>model.add(Flatten())</pre><pre>model.add(Dense(128, activation=&#39;relu&#39;))</pre><pre>model.add(Dropout(0.5))</pre><pre>model.add(Dense(10, activation=&#39;softmax&#39;))</pre><pre>model.summary()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*_EdSmzhc8e6QNYLeUllVaQ.png" /></figure><h4>Compile and Train the model</h4><pre>model.compile(<br>loss=&#39;categorical_crossentropy&#39;,<br>optimizer=&#39;Adam&#39;,<br>metrics=[&#39;accuracy&#39;])</pre><pre>model.fit(X_train, y_train, epochs=20, <br>validation_data=(X_test, y_test))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WbrZCgpjP6ILfUImBdepMg.png" /></figure><h3>Result</h3><h4>Training and Validation loss</h4><pre>plt.plot(model.history.history[&#39;loss&#39;],color=&#39;b&#39;,<br>label=&#39;Training Loss&#39;)</pre><pre>plt.plot(model.history.history[&#39;val_loss&#39;],color=&#39;r&#39;,<br>label=&#39;Validation Loss&#39;)</pre><pre>plt.legend()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/506/1*wGcBR9hG-Ijas_YUA061WQ.png" /></figure><h4>Training and Testing accuracy</h4><pre>plt.plot(model.history.history[&#39;accuracy&#39;],color=&#39;b&#39;,<br>label=&#39;Training  Accuracy&#39;)</pre><pre>plt.plot(model.history.history[&#39;val_accuracy&#39;],color=&#39;r&#39;,<br>label=&#39;Validation Accuracy&#39;)</pre><pre>plt.legend()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/515/1*nNH92RXQqWCF5jJ5cXu3sQ.png" /></figure><h3>Conclusion</h3><p>From the accuracy plot we can see that the model might be overfitting since the training accuracy keeps going up linearly while the validation accuracy plateau at an early stage. However the model still has a nearly 75 % accuracy in classifying the images which is far greater than the result of random guessing (10%).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6ca6aa74e5d7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/multiclass-image-classification-problem-convolutional-neural-network-trains-on-galaxy-images-6ca6aa74e5d7">Multiclass image classification problem — Convolutional Neural Network trains on Galaxy images</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cactus image classification using convolutional neural network (CNN) that reaches 98%+ accuracy]]></title>
            <link>https://medium.com/data-science/cactus-image-classification-using-convolutional-neural-network-cnn-that-reaches-98-accuracy-8432e068f1ea?source=rss-c2bfa09e15b6------2</link>
            <guid isPermaLink="false">https://medium.com/p/8432e068f1ea</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[convolutional-network]]></category>
            <category><![CDATA[classification]]></category>
            <dc:creator><![CDATA[Jonathan Kuo]]></dc:creator>
            <pubDate>Fri, 13 Nov 2020 10:29:43 GMT</pubDate>
            <atom:updated>2021-03-15T03:38:29.950Z</atom:updated>
            <content:encoded><![CDATA[<h3>Cactus image classification using convolutional neural network (CNN) that reaches over 98% accuracy</h3><h4>The goal is to build a classifier to classify an image as “cactus” or “non-cactus.”</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n7ntbl-2zqCvYZO8K3tc5g.jpeg" /><figcaption>Photo by <a href="https://www.pexels.com/@pixabay?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Pixabay</a> from <a href="https://www.pexels.com/photo/landscape-mountains-sky-night-34107/?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Pexels</a></figcaption></figure><h3>Understanding the dataset</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2zX2HuNca52o1tG_HOtsDA.png" /></figure><p>This classification problem is from one of the <a href="https://www.kaggle.com/irvingvasquez/cactus-aerial-photos">Kaggle challenges</a>. The goal is to build a classifier to classify an image as “cactus” or “non-cactus.” The training set includes 17500 images, while the validation set has 4000 images. Images that have signs of cactus are in the folder named cactus and vice versa. Below are the examples from the training dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/142/1*h4WFO0wpWXd2SXuj7tDAzQ.png" /><figcaption>cactus</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/140/1*NosAx3Xl4LV_XTfUmbaO6A.png" /><figcaption>non-cactus</figcaption></figure><h3>Data preprocessing</h3><p>When we take a closer look at some of those images by simply plotting them with the Pyplot library, we can observe that they are in different sizes, not desired for the later training process. Also, notice that we have labeled all images with 1s and 0s, indicating cactus and non-cactus.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jMFwn0buxBJOqYqg3SI3Eg.png" /></figure><p>Therefore, we will need to normalize all images into the same size. According to our experiments, the optimal strategy is to crop those images to a size of 48 by 48 pixels. Below are some of the cropped images. The first row shows the original images, and the second row displays the altered ones.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5P-1odU3YdUOZnKDGIQC2w.png" /></figure><p>The benefit of this method is that it saves all the detail of the image; however, we sometimes lose the edge of the image, and if the image is too small, we need to expand the image with a black background to make it the same size as the others. Losing the edge could be a big problem as it is possible that we cut the cactus out of the image with this technique.</p><h3>CNN structure &amp; training</h3><p>The convolutional neural network contains 3 layers of convolutional layers and 2 fully connected layers. Each convolutional layer has a 3 by 3 filter that takes a stride of 2 with an output of 64 nodes. After that, the data travels through the max-pooling layer to prevent overfitting and to extract useful information.</p><pre>model = Sequential()</pre><pre>model.add(Conv2D(64, (3,3), input_shape = X_train.shape[1:]))</pre><pre>model.add(Activation(‘relu’))</pre><pre>model.add(MaxPooling2D(pool_size=(2,2)))</pre><pre>model.add(Conv2D(64, (3,3)))</pre><pre>model.add(Activation(‘relu’))</pre><pre>model.add(MaxPooling2D(pool_size=(2,2)))</pre><pre>model.add(Conv2D(64, (3,3)))</pre><pre>model.add(Activation(‘relu’))</pre><pre>model.add(MaxPooling2D(pool_size=(2,2)))</pre><pre>model.add(Flatten())</pre><pre>model.add(Dense(64))</pre><pre>model.add(Dense(1))</pre><pre>model.add(Activation(‘sigmoid’))</pre><pre>model.compile(loss=”binary_crossentropy”,</pre><pre>optimizer=”adam”,</pre><pre>metrics=[‘accuracy’])</pre><pre>history = model.fit(X_train, Y_train, batch_size=32, epochs=10, validation_split=0.1, use_multiprocessing=True)</pre><pre>model.save(‘model_48_crop’)</pre><p>Below is an overview of the model structure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/659/1*mHwAa0nhEP6zflcA5T4gXA.png" /><figcaption>Summary of the model</figcaption></figure><p>We trained the model with 10 epochs, and it showed amazing results. The first accuracy is the training accuracy in the below snippet, and the second one is the validation accuracy. Notice that we used part (10%) of the training set as our validation set before the final prediction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J610CxtGaoVMxrjTwKETew.png" /></figure><h3>Test Result</h3><p>We use the validation_set provided by Kaggle as our test set for the final prediction on our trained model.</p><pre>testdata = pd.read_pickle(“pickled_data_validation/crop_images(48, 48).pkl”)</pre><pre>test_images = testdata.loc[:, data.columns != ‘class’]</pre><pre>test_images = test_images.to_numpy()</pre><pre>test_images = test_images.reshape((len(test_images),48, 48, 3))</pre><pre>test_images = test_images/255.0</pre><pre>print(test_images.shape)</pre><pre>test_labels = testdata[‘class’]</pre><pre>test_labels = test_labels.to_numpy()</pre><pre>type(test_labels)</pre><pre>test_labels = test_labels.reshape((len(test_labels),1))</pre><pre>loss, acc = new_model.evaluate(test_images, test_labels, verbose=2)</pre><pre>print(‘Restored model, accuracy: {:5.2f}%’.format(100*acc))</pre><p>Here is the result. It reaches an accuracy rate of almost 99%, which is amazing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/461/1*yQQIqSMFYfyFmskR8rYeuA.png" /></figure><h3>Conclusion</h3><p>This post&#39;s main goal is to share with you the convolutional network structure to this kind of binary classification problem, such as cat and dog image classification. Hopefully, you can have a better understanding of this type of problem.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8432e068f1ea" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/cactus-image-classification-using-convolutional-neural-network-cnn-that-reaches-98-accuracy-8432e068f1ea">Cactus image classification using convolutional neural network (CNN) that reaches 98%+ accuracy</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Classical Music for Relaxation —Chopin]]></title>
            <link>https://jonathan-kuo.medium.com/classical-music-for-relaxation-chopin-2152a2389ca8?source=rss-c2bfa09e15b6------2</link>
            <guid isPermaLink="false">https://medium.com/p/2152a2389ca8</guid>
            <category><![CDATA[music]]></category>
            <category><![CDATA[chopin]]></category>
            <category><![CDATA[relaxation]]></category>
            <category><![CDATA[sleep]]></category>
            <category><![CDATA[classical-music]]></category>
            <dc:creator><![CDATA[Jonathan Kuo]]></dc:creator>
            <pubDate>Tue, 27 Oct 2020 01:53:09 GMT</pubDate>
            <atom:updated>2020-10-27T01:59:25.552Z</atom:updated>
            <content:encoded><![CDATA[<p>This is part of my Chopin playlist for relaxation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TAGiY3OiEsRfPW2-LSSGBQ.jpeg" /></figure><h3>Nocturne Op. 9 №.1 in B flat minor</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FZtIW2r1EalM%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DZtIW2r1EalM&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FZtIW2r1EalM%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/081a1762bf141dcfb2718af0139b2ea5/href">https://medium.com/media/081a1762bf141dcfb2718af0139b2ea5/href</a></iframe><h3>Nocturne Op.9 №.2 in E flat major</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FYGRO05WcNDk%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DYGRO05WcNDk&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FYGRO05WcNDk%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/5cb583c3eb093592109bf7a3ae477d89/href">https://medium.com/media/5cb583c3eb093592109bf7a3ae477d89/href</a></iframe><h3>Nocturne Op.27 №.1 in C sharp minor</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FQAcAWWU_0mE%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DQAcAWWU_0mE&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FQAcAWWU_0mE%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/e5d1ea13d14fadc24c705fbde2a6f087/href">https://medium.com/media/e5d1ea13d14fadc24c705fbde2a6f087/href</a></iframe><h3>Nocturne Op. 27 №.2 in D flat major</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FWJ8RVjm49hE%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DWJ8RVjm49hE&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FWJ8RVjm49hE%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/93c4d789aebbc9e6edc38cb3e1e450ba/href">https://medium.com/media/93c4d789aebbc9e6edc38cb3e1e450ba/href</a></iframe><h3>Nocturne Op.48 №.2 in F sharp minor</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FO5X4XDrsOlI%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DO5X4XDrsOlI&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FO5X4XDrsOlI%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/6f8b6253b28d55686730e319d0486863/href">https://medium.com/media/6f8b6253b28d55686730e319d0486863/href</a></iframe><h3>Nocturne Op.62 №.1 in B major</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F1FeogxNAJWY%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D1FeogxNAJWY&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F1FeogxNAJWY%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/dfd840d081bfc7604c69f04e0271e497/href">https://medium.com/media/dfd840d081bfc7604c69f04e0271e497/href</a></iframe><h3>Nocturne Op.62 №.2 in E major</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FLRZjjQxGaYQ%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DLRZjjQxGaYQ&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FLRZjjQxGaYQ%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/d946a6a5152184dc088199da2798b404/href">https://medium.com/media/d946a6a5152184dc088199da2798b404/href</a></iframe><h3>Nocturne Op.72 №.1 in E minor</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fh5_V-d8HjhU%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Dh5_V-d8HjhU&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fh5_V-d8HjhU%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/d85f61a7f1ec4f0fa92366c0c1397b6d/href">https://medium.com/media/d85f61a7f1ec4f0fa92366c0c1397b6d/href</a></iframe><h3>Nocturne Op.20 in C sharp minor</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FtVV3SIvncD4%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DtVV3SIvncD4&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FtVV3SIvncD4%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/a1d5645f63aa2f644059ac09a2b2046c/href">https://medium.com/media/a1d5645f63aa2f644059ac09a2b2046c/href</a></iframe><h3>Prelude Op.28 №.15 in D flat major</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FSh03YXzvDF4%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DSh03YXzvDF4&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FSh03YXzvDF4%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/0181f1c8750eb03849169ac8a34eb47a/href">https://medium.com/media/0181f1c8750eb03849169ac8a34eb47a/href</a></iframe><h3>Waltz Op.69 №.2 in B minor</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FcxG-kOTMgaA%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DcxG-kOTMgaA&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FcxG-kOTMgaA%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/7cac13e7943dce0396fc6842a900076e/href">https://medium.com/media/7cac13e7943dce0396fc6842a900076e/href</a></iframe><h3>Waltz Op.70 №.2 in F minor</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FeuLyQCJmCfs%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DeuLyQCJmCfs&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FeuLyQCJmCfs%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/eb58b485cc5c9af226c3d05406405507/href">https://medium.com/media/eb58b485cc5c9af226c3d05406405507/href</a></iframe><p>The list still goes on. These are just some of my favorites and I hope you enjoy listening to them.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2152a2389ca8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Artificial Intelligence at Play — Connect Four (Minimax algorithm explained)]]></title>
            <link>https://medium.com/analytics-vidhya/artificial-intelligence-at-play-connect-four-minimax-algorithm-explained-3b5fc32e4a4f?source=rss-c2bfa09e15b6------2</link>
            <guid isPermaLink="false">https://medium.com/p/3b5fc32e4a4f</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[ai-gaming]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[minimax-algorithm]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[Jonathan Kuo]]></dc:creator>
            <pubDate>Wed, 14 Oct 2020 02:56:08 GMT</pubDate>
            <atom:updated>2021-05-26T12:36:07.456Z</atom:updated>
            <content:encoded><![CDATA[<h3>Artificial Intelligence at Play — Connect Four (Mini-max algorithm explained)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/0*HqTdkytsHijhlRsd.gif" /></figure><h3>Introduction</h3><p>This is a centuries-old game even played by Captain James Cook with his officers on his long voyages. Milton Bradley (now owned by Hasbro) published a version of this game called “Connect Four” in 1974. It is also called “Four-in-a-Row” and “Plot Four.” Two players play this game on an upright board with six rows and seven empty holes. Each player has an equal number of pieces (21) initially to drop one at a time from the top of the board. Then, they will take turns to play and whoever makes a straight line either vertically, horizontally, or diagonally wins.</p><h3>Problem Statement</h3><p>The game is categorized as a zero-sum game. Therefore, the minimax algorithm, which is a decision rule used in AI, can be applied. The project goal is to investigate how a decision tree is applied using the minimax algorithm in this game by Artificial Intelligence.</p><h3>Winning Strategy</h3><h3>· Place in the middle column</h3><p>If the player can play first, it is better to place it in the middle column. Since the board has seven columns, placing the discs in the middle allows connection to go up vertically, diagonally, and horizontally. In total, there are five possible ways.</p><h3>· Make traps for the opponent</h3><p>One typical way of not losing is to try to block the opponent’s paths toward winning. For example, preventing the opponent from getting a connection of three by placing the disc next to the line in advance to block it. This strategy also prevents the opponent from setting a trap on the player.</p><h3>· Make a “7.”</h3><p>A 7 trap is a name for a strategic move where one positions his disks in a configuration that resembles a 7. With three horizontal disks connected to two diagonal disks branching off from the rightmost horizontal disk. The 7 can be configured in any way, including right way, backward, upside down, or even upside down and backward. This disk formation is a good strategy because it gives players multiple directions to make a connect-four.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/1*5DsKiI5QwLnDtjFb54yCUA.png" /><figcaption>The “7” strategy (the yellow-colored discs)</figcaption></figure><h3>Logic and Mathematics behind Connect Four</h3><h3>· Decision Tree</h3><p>A Decision tree is a tree structure, where each internal node denotes a test on an attribute, each branch represents an outcome of the test, and each leaf node (terminal node) holds a class label. In the example below, one possible flow is as follows: If a person has aged less than 30 and does not eat many pizzas, then that person is categorized as fit. On the contrary, if a person is older than 30, and does not exercise in the morning, then that person is categorized as unfit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/310/1*RQyw-Pg6UbAcm7btqIOVWg.png" /><figcaption>A simple decision tree regarding fitness</figcaption></figure><p>Decision trees can be applied in different studies, including business strategic plans, mathematics studies, and others. In addition, since the decision tree shows all the possible choices, it can be used in logic games like Connect Four to be served as a look-up table.</p><h3>· Decision tree in Connect Four</h3><p>When the game begins, the first player gets to choose one column among seven to place the colored disc. There are 7 columns in total, so there are 7 branches of a decision tree each time. After the first player makes a move, the second player could choose one column out of seven, continuing from the first player’s choice of the decision tree.</p><p>Notice that the decision tree continues with some special cases. First, if both players choose the same column 6 times in total, that column is no longer available for either player. It means that their branches of choice are reduced by one. Second, when both players make all choices (42 in this case) and there are still no 4 discs in a row, the game ends as a draw, and the decision tree stops. Finally, if any player makes 4 in a row, the decision tree stops, and the game ends.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/284/1*DBpG8c3c7BOZ5g7p1n_S5Q.png" /><figcaption>Possible moves for each iteration of the Connect Four game shown in the decision tree</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/618/1*IyyCmHRYJpVhkU7SWyuF5Q.png" /><figcaption>Decision tree of Connect Four possible moves</figcaption></figure><h3>Minimax algorithm</h3><p>Minimax algorithm is a recursive algorithm which is used in decision-making and game theory especially in AI game. It provides optimal moves for the player, assuming that the opponent is also playing optimally. For example, considering two opponents: Max and Min playing. Max will try to maximize the value, while Min will choose whatever value is the minimum. The algorithm performs a depth-first search (DFS) which means it will explore the complete game tree as deep as possible, all the way down to the leaf nodes. The algorithm is shown below with an illustrative example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/956/1*pvmXgOZ2ckxIAiWAye54eg.png" /><figcaption>minimax algorithm pseudocode</figcaption></figure><p>Initially, the algorithm generates the entire game tree and produces the utility values for the terminal states by applying the utility function. For example, in the below tree diagram, let us take A as the tree&#39;s initial state. Suppose maximizer takes the first turn, which has a worst-case initial value that equals negative infinity. Then, the minimizer will take the next turn, which has a worst-case initial value that equals positive infinity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/317/1*ILe9XxR8ofjDrJ7vG1CMLQ.png" /><figcaption>Minimax algorithm in tree format — the initial step</figcaption></figure><p>First, we consider the Maximizer with initial value = -∞. Each terminal node will be compared with the value of the maximizer and finally store the maximum value in each maximizer node. Take the third row (Maximizer) from the top, for instance.</p><p>For node D max(-1, -∞) → max(-1,4) = 4</p><p>For Node E max(2, -∞) → max(2, 6) = 6</p><p>For Node F max(-3, -∞) → max(-3,-5) = -3</p><p>For node G max(0, -∞) → max(0, 7) = 7</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/302/1*QQ5IDHasN_ydJsvBS8jfgQ.png" /><figcaption>Minimax algorithm in tree format — second step</figcaption></figure><p>Next, we compare the values from each node with the value of the minimizer, which is +∞.</p><p>toFor node B= min(4, 6) = 4</p><p>For node C= min(-3, 7) = -3</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/287/1*HNWrjcr8VAeb_aEHMr-ybQ.png" /><figcaption>Minimax algorithm in tree format — third step</figcaption></figure><p>Finally, the maximizer will then again choose the maximum value between node B and node C, which is 4 in this case. Hence, we get the optimal path of play: A → B → D → I.</p><p>For node A max(4, -3)= 4</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/278/1*mawaGslmPWazK5oaswgiNQ.png" /><figcaption>Minimax algorithm in tree format — the final step</figcaption></figure><h3>AI in Connect Four — Implementing Minimax</h3><p>Below is a python snippet of Minimax algorithm implementation in Connect Four. In the code, we extend the original Minimax algorithm by adding the Alpha-beta pruning strategy to improve the computational speed and save memory. The figure below is a pseudocode for the alpha-beta minimax algorithm.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JKIe5NUgrZStu8sbgHHjog.png" /><figcaption>minimax algorithm with alpha-beta pruning pseudocode</figcaption></figure><p><em>Note: Https://github.com/KeithGalli/Connect4-Python originally provides the code</em></p><p>I’m just wrapping up and explain the algorithms in Connect Four</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6a75411c162331d2c3e48e4a064736f1/href">https://medium.com/media/6a75411c162331d2c3e48e4a064736f1/href</a></iframe><p>Let us take the <strong>maximizingPlayer</strong> from the code above as an example (From line 136 to line 150). First, the program will look at all valid locations from each column, recursively getting the new score calculated in the look-up table (will be explained later), and finally update the optimal value from the child nodes. Notice that the alpha here in this section is the new_score, and when it is greater than the current value, it will stop performing the recursion and update the new value to save time and memory.</p><p>As mentioned above, the look-up table is calculated according to the evaluate_window function below. Here, the window size is set to four since we are looking for connections of four discs. Considering a reward and punishment scheme in this game. If four discs are connected, it is rewarded for a high positive score (100 in this case). When three pieces are connected, it has a score less than the case when four discs are connected. When two pieces are connected, it gets a lower score than the case of three discs connected. Finally, when the opponent has three pieces connected, the player will get a punishment by receiving a negative score. Indicating that it is not an optimal move for the current player.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4486157002aa750ddbae62dfcaa9009f/href">https://medium.com/media/4486157002aa750ddbae62dfcaa9009f/href</a></iframe><p>With the scoring criteria set, the program now needs to calculate all scores for each possible move for each player during the play. The function score_position performs this part from the below code snippet. The AI player will then take advantage of this function to predict an optimal move.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/603f399da896cf0e5817403388415e1c/href">https://medium.com/media/603f399da896cf0e5817403388415e1c/href</a></iframe><h3><strong>Conclusions</strong></h3><p>Looking at how many times AI has beaten human players in this game, I realized that it wins by rationality and loads of information. In this project, the AI player uses a minimax algorithm to check for optimal moves in advance to outperform human players by knowing all possible moves rationally. Interestingly, when tuning the number of depths at the minimax function from high (6 for example) to low (2 for example), the AI player may perform worse. Nevertheless, the strategy and algorithm applied in this project have been proved to be working and performing amazing results.</p><h3>References</h3><p>Galli. (n.d.). KeithGalli/Connect4-Python. GitHub. <a href="https://github.com/KeithGalli/Connect4-Python">https://github.com/KeithGalli/Connect4-Python</a></p><p>Nasa, R., Didwania, R., Maji, S., &amp; Kumar, V. (2018). Alpha-beta pruning in mini-max algorithm–an optimized approach for a connect-4 game. Int. Res. J. Eng. Technol, 1637–1641.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3b5fc32e4a4f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/artificial-intelligence-at-play-connect-four-minimax-algorithm-explained-3b5fc32e4a4f">Artificial Intelligence at Play — Connect Four (Minimax algorithm explained)</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>