<?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 Thomas Tsuma on Medium]]></title>
        <description><![CDATA[Stories by Thomas Tsuma on Medium]]></description>
        <link>https://medium.com/@tommytsuma7?source=rss-830d747c7c1b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*oGiNPp9HuoDP0fIN0ZyM8g.jpeg</url>
            <title>Stories by Thomas Tsuma on Medium</title>
            <link>https://medium.com/@tommytsuma7?source=rss-830d747c7c1b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 19:04:26 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tommytsuma7/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[GENERATIVE ADVERSARIAL NETWORKS]]></title>
            <link>https://medium.com/analytics-vidhya/generative-adversarial-networks-13fd15ba58e4?source=rss-830d747c7c1b------2</link>
            <guid isPermaLink="false">https://medium.com/p/13fd15ba58e4</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[generative-networks]]></category>
            <category><![CDATA[machine-learning-ai]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Thomas Tsuma]]></dc:creator>
            <pubDate>Wed, 22 Feb 2023 17:30:31 GMT</pubDate>
            <atom:updated>2023-02-22T17:30:31.650Z</atom:updated>
            <content:encoded><![CDATA[<h3>INTRODUCTION</h3><p>A common issue that most data-driven tasks have is when they have an underwhelming amount of data; it is nearly impossible for their models to learn trends and regularities in data. The solution to this issue was to find ways to augment our data without compromising the overall quality. The generated data should be nearly undifferentiable from the actual data. This brought about the need to come up with generative models. Contrary to discriminative models which aim to distinguish between two items, generative models seek to create new instances of data that could plausibly be part of the actual dataset.</p><p>There are several generative models that help with this:</p><ol><li>Naive Bayes.</li><li>Neural Radiance Fields (NeRF).</li><li>Boltzmann Machines.</li><li>Variation AutoEncoders (VAE).</li><li>Hidden Markov Models.</li><li>GPT-2.</li><li>Latent Dirichlet Allocation (LDA).</li><li>Gaussian Mixture Model (GMM).</li><li>Restricted Boltzmann Machine (RBM).</li><li>Deep Belief Network (DBM).</li><li>Generative Adversarial Networks.</li></ol><p>Generative Adversarial Networks(GANs) take an unsupervised learning approach to generate data. The general concept behind GANs is to learn the regularities and trends within the input dataset and generate an output that matches the input.</p><p>GANs were proposed by Ian Goodfellow in 2014 in his paper, “<a href="https://arxiv.org/pdf/1701.00160.pdf">Generative Adversarial Networks</a>”. Within this paper, Ian proposed the development of a model that could represent a probability distribution over the kinds of data that have been encountered by an AI. This means that the algorithm should be able to work with images, audio waveforms representing sound, and symbols within a corpus. He noted the success that discriminative models had attained due to the concept of backpropagation which allowed for adjustment of weights and dropout which reduced the amount of overfitting. Generative models however lacked a true measure of the correctness of the output. GANs was thus suggested to overcome this issue.</p><p>It may be worthwhile to mention that there are several types of GANS:</p><ol><li>Vanilla GAN.</li><li>Conditional Gan (CGAN).</li><li>Deep Convolutional GAN (DCGAN).</li><li>CycleGAN.</li><li>Generative Adversarial Text to Image Synthesis.</li><li>Style GAN.</li><li>Super Resolution GAN (SRGAN).</li></ol><h3>STRUCTURE OF GENERATIVE ADVERSARIAL NETWORKS</h3><p>Despite the fact that each of the aforementioned types of GANs is nuanced, they maintain the same overall concepts. For this post, we will mainly be focused on the Vanilla GANs as they represent the most common architecture. GANs comprise two sub-models; a generator and a discriminator model.</p><p>The generator takes a fixed-length random vector as input. This vector is drawn randomly from a particular Gaussian Distribution and it is used to seed the generative process. The points within the latent vector space of say, 100 dimensions, have no meaning on their own. However during training, as the generator continues to take points from the latent vector space, it assigns meaning to the points and in turn, the latent vector space. Points within the multidimensional vector space will correspond to points in the problem domain after training is done. This forms a compressed representation of the data distribution.</p><p>The discriminator on the other hand takes in data from the problem domain and data generated from the generator. Each of these sets of data is uniquely labeled and the discriminator is tasked with drawing distinctions between the two sets of data. Hence, GANs are partially framed as a supervised learning problem. The quality of data that the generator outputs is gauged by how poorly the discriminator manages to distinguish the two datasets. If the discriminator wrongly classifies the input around fifty percent of the time then the generator is deemed to be properly generating data.</p><p>The generator and discriminator are involved in a zero-sum game whereby the generator can only improve if the discriminator deteriorates. If the accuracy of the discriminator is high then the weights of the generator are adjusted accordingly.</p><p>For this model, during the evaluation of the two models we use:</p><ol><li>Loss function(Binary cross-entropy) — To determine how well the discriminator is at differentiating the two classes(real or fake).</li><li>Chi-Squared Test — To compare the association of one variable across different levels of another variable.</li><li>Kolmogorov-Smirnov Test — To ensure that the generated data lies within the same distribution as the actual data.</li></ol><h3><strong>APPLICATION OF GANS</strong></h3><ol><li>Text-to-image translation</li><li>Image-to-image translation for (style transfer, colorization, and transforming backgrounds)</li><li>Data Augmentation</li><li>Image super-resolution</li><li>Generating art</li></ol><h3><strong>USING DEEP CONVOLUTIONAL GANS TO GENERATE IMAGES.</strong></h3><p>Here, we will start by working with a simple example of how we can use Vanilla Gans to generate images from a source dataset. We will be using the MNIST dataset of digits. The MNIST handwritten digits dataset is a series of images in grayscale representing certain numbers. This rudimental example helps give an introduction to the use of Deep Convolutional Neural Networks in GANs. The aim here is to be able to generate images that could plausibly be mistaken for handwritten digits that are within the MNIST dataset.</p><h4>STRUCTURE</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/713/0*iEX9IBQqP0kDPnHc" /><figcaption>The structure of DCGAN</figcaption></figure><p>Similar to the Vanilla GAN structure, our DCGAN structure comprises:</p><ul><li>Latent Vector Space.</li><li>Generator.</li><li>Discriminator.</li><li>Real Sample Spaces.</li></ul><p>The difference however is in the fact that both the discriminator and generator use the principle of convolutional albeit in different ways.</p><h4>GENERATOR</h4><p>The Generator uses the principle of deconvolution. Its purpose is to generate images that could plausibly be from the MNIST handwritten digits dataset.</p><p>Input — A point from the latent space.</p><p>Output — Grayscale image</p><p>The latent space contains random values with 100 dimensions. From this, we transform a vector to a 2-dimensional array of say 28x28 (784) values.</p><p>First, we need to generate the latent space vectors:</p><pre>import numpy as np<br> import random<br> <br>def generate_latent_points(dims, sample)<br>dims = 100<br>samples = 25 <br>latent_point = random.randn(dims * samples)<br>latent_point = np.reshape(samples, dims)<br> return latent_space</pre><p>Now we can design our generator:</p><pre>from tensorflow.keras.models import Sequential<br>from tensorflow.keras.layers import Dense, LeakyReLU, Reshape, Conv2DTranspose, Conv2D<br><br>generator= Sequential()<br>generator.add(Dense((128*7*7), input_dim=dims)<br>generator.add(LeakyReLU(0.2))<br>generator.add(Reshape(7,7,128))<br>generator.add(Conv2DTranspose(128, (4,4), stride=(2,2), padding=’same’))<br>generator.add(LeakyReLU(0.2))<br>generator.add(Conv2DTranspose(128, (4,4), stride=(2,2), padding=’same’))<br>generator.add(LeakyReLU(0.2))<br>generator.add(Conv2D(1, (7,7),padding=’same’, activation=’sigmoid’))</pre><p>We use the Sequential model type in this case. This model type ensures that the data passes from one layer to another in the sequence specified.</p><p>The first layer is the Dense layer. It should have enough nodes such that it can represent a low-resolution version of the output we want. For example, in this case, to get half the image resolution, we can use (14*14), and for one-quarter the resolution we can use (7,7). The concept of convolution involves having several parallel filters and thus multiple parallel activation maps. Therefore, we need to generate several parallel versions of the input by multiplying the nodes by a certain factor. In our case, we have used 128.</p><p>We use LeakyReLU with a slope of 0.2</p><p>The third step is to add a Reshape layer. The purpose here is to reshape the activations so far into an image-like activation that can be passed into the convolutional neural network. In our case, we will end up with 128 (7x7) outputs.</p><p>Next is to perform <strong>deconvolution </strong>on the output so far. Deconvolution is the process of recovering the image after a filter has been applied. Essentially making deconvolution the opposite of convolution. In our case, however, we won’t be retrieving the original input since we had performed certain transformations on it first. Hence we will only be converting a low-resolution image into a high-resolution image. For this, we use the Conv2DTranspose layer. This serves as a combination of an Upsample layer (reverses the effect of the pooling layer) and a Conv2D layer. We set a stride of 2x2 to quadruple the area of the input feature maps. We also need to ensure that the kernel size is a factor of the stride so as to avoid a <a href="https://distill.pub/2016/deconv-checkerboard/">checkerboard pattern</a> being formed. Repeating these steps reverts us back to our original image shape of 28x28</p><p>Finally, we add a Conv2D layer. We set the number of filters to 1. The kernel size is 7x7. The padding is set to ‘same’.</p><p>To generate fake samples we can use the function:</p><pre>def generate_fake_samples(generator, dims, samples):<br> x_input = generate_latent_points(dims, samples)<br> X = generator.predict(x_input)<br> y = zeros((samples, 1))<br> return X, y</pre><h4>DISCRIMINATOR.</h4><p>Our discriminator is tasked with determining whether an image came from the MNIST dataset or from our generator. Here we use the concept of convolution, which as stated above is breaking down of an image into smaller discernable chunks using filters.</p><p>Input: Image vector</p><p>Output: 0(MNIST Image) or 1(Generated Image)</p><p>The design for our discriminator is as follows:</p><pre>from keras.models import Sequential<br>from keras.layers import Dense, Conv2D, Flatten, Dropout, LeakyReLU<br><br>discriminator = Sequential()<br><br>discriminator.add(Conv2D(64, (3,3), strides=(2,2), padding=”same”, input_shape(28,28,))<br>discriminator.add(LeakyReLU(0.2))<br>discriminator.add(Dropout(0.4))<br>discriminator.add(Conv2D(64, (3,3), strides=(2,2), padding=”same”))<br>discriminator.add(LeakyReLU(0.2))<br>discriminator.add(Dropout(0.4))<br>discriminator.add(Flatten())<br>discriminator.add(Dense(1, activation=”sigmoid”))</pre><p>We need to define an optimization function at the end. Here’s how we do that:</p><pre>from keras.optimizers import Adam<br><br>Opt = Adam(lr=0.0002, beta_1=0.5)</pre><p>Finally, we can compile the discriminator model using:</p><pre>discriminator.compile(loss=”binary_cross_entropy”, metrics=[“binary_accuracy”], optimizer=opt)</pre><p>To further visualize how each layer breaks down its inputs into outputs, we can do:</p><pre>discriminator.summary()<br><br>OUTPUT:<br>Model: &quot;sequential&quot;<br>_________________________________________________________________<br> Layer (type)                Output Shape              Param #   <br>=================================================================<br> conv2d (Conv2D)             (None, 14, 14, 64)        640       <br>                                                                 <br> leaky_re_lu (LeakyReLU)     (None, 14, 14, 64)        0         <br>                                                                 <br> dropout (Dropout)           (None, 14, 14, 64)        0         <br>                                                                 <br> conv2d_1 (Conv2D)           (None, 7, 7, 64)          36928     <br>                                                                 <br> leaky_re_lu_1 (LeakyReLU)   (None, 7, 7, 64)          0         <br>                                                                 <br> dropout_1 (Dropout)         (None, 7, 7, 64)          0         <br>                                                                 <br> flatten (Flatten)           (None, 3136)              0         <br>                                                                 <br> dense (Dense)               (None, 1)                 3137      <br>                                                                 <br>=================================================================<br>Total params: 40,705<br>Trainable params: 40,705<br>Non-trainable params: 0<br>_________________________________________________________________<br><br></pre><p>Let’s break down the layers of the discriminator:</p><p>It comprises two consecutive sequences of a Conv2D layer, followed by a LeakyReLU layer and a Dropout layer.</p><p>The Conv2D layer has 64 filters and a small kernel size of 3 x 3. The strides are all set to 2,2. The input shape is essentially the shape of the images from the discriminator or from the MNIST dataset.</p><p>The common practice in GANs is to use LeakyReLU rather than ReLU so we maintain that trend and set the alpha to 0.2.</p><p>The Dropout Layer is added to avoid overfitting and the slope is set to 0.4</p><p>We then add a Flatten layer to convert our output so far into a one-dimensional tensor.</p><p>Finally is our Dense layer whose purpose is to give us a fully-connected neural network. Since this is a binary classification problem at this point, it only has one node. We use the sigmoid activation function as part of our output layer.</p><p>Now onto the optimization function:</p><p>The optimizer is used to adjust the parameters of the model so as to minimize the loss function.</p><p>In this case, we specified the Adam optimizer which computes the adaptive learning rate for each parameter in our model. It uses the first and second moments of gradient(beta_1 and beta_2) to provide a running estimate of the mean and variance of the gradients.</p><p>Finally, we compiled our model:</p><p>We specified the binary_cross_entropy as our loss function. As indicated in the name, it is used for binary classification problems. The concept therein is a calculation of the true class as a negative log-likelihood.</p><h4>THE GANS MODEL</h4><p>The process goes deeper than just defining how the generator and discriminator models are designed and trained. As was mentioned before, the two models learn through an adversarial process. The generator generates fake samples and the discriminator determines whether it is real or fake. This begs the question, “How do we pit these two models against each other?”.</p><p>This would involve two processes of training:</p><ul><li>Training of the discriminator using outputs from the generator and the MNIST dataset.</li><li>Training of the generator using the classifications from the discriminator.</li></ul><p>Let’s explain the first process. We need to first have a generator and a discriminator. The generator will come up with n fake samples that will be passed to the discriminator along with real samples from the MNIST dataset. For this process, our aim is to minimize the loss function of the discriminator. We pay little interest to the output from the generator.</p><p>The second process is what we essentially refer to as generating a GAN. Let’s delve into what the GAN comprises:</p><p>Input — Input vector</p><p>Output — Classification</p><p>Here, we stack the discriminator on top of the generator. This is such that the generator receives the random input vector and generates an image and outputs an image which is then taken in by the discriminator so that the final output is a classification of whether it is real or fake.</p><p>There are a few tricks involved here.</p><p>First, we specify that the parameters of the generator are trainable whereas the discriminator is frozen. This means that during <a href="https://www.machinelearningnuggets.com/tensorflow-lstm/#backpropagation-through-time">backpropagation</a>(which is the process of adjusting the gradients in a neural network based on the error attained), the weights of the generator will be adjusted whereas the weights of the discriminator will remain stagnant. Our aim in all this is to ensure that the discriminator performs poorly whereas the generator improves.</p><p>The second trick is to change the labels that we were using for the generated samples. If we were using 1 to represent the generated samples initially we change it to 0 and vice versa. The point here is to necessitate a large shift in weights.</p><p>To properly explain this, I have to explain briefly what the sigmoid activation function does. The graph of a sigmoid function is an S-curve that ranges from y=0 to y = 1. The closer the value is to either one or zero determines its classification.</p><p>So if in the initial step where our concern was to train the discriminator, we set the 0 to be the generated samples and 1 to be the real samples, we flip it such that the generated samples are 1. When the discriminator receives this sample, it will output a value closer to zero than one. This causes a larger update in the weights of the generator.</p><p>Here is the code for the first step:</p><pre>from sklearn.metrics import classification_report<br>import numpy as np<br><br>X = [ ]<br>y = [ ]<br><br>(X_train, y_train),  (X_test, y_test)= mnist.load_dataset()<br><br>samples, classes = generate_fake_samples(generator, dims, len(X_train))<br>y_train = np.ones(len(y_train))<br><br>X = [*X_train, *samples]<br>y = [*y_train, *classes]<br><br>discriminator.fit(X,y,verbose = 1)<br><br>samples_test, classes_test = generate_fake_samples(generator, dims, len(X_test))<br>y_test = np.ones(len(y_test))<br>X = [*X_test, *samples_test]<br>y = [*y_test, *classes_test]<br>y_preds = discriminator.predict(X)<br><br>print(classification_report(y, y_preds))</pre><p>For the second step:</p><pre>def gan(generator, discriminator):<br> generator.trainable = True<br> discriminator.trainable = False <br> gan = Sequential()<br> gan.add(generator)<br> gan.add(discriminator)<br> optimizer = Adam(lr=0.0002, beta_1=0.5)<br> gan.compile(loss=’binary_cross_entropy’, optimizer = optimizer)<br> print(gan.summary())<br> return gan <br><br>OUTPUT:<br>Model: &quot;sequential_3&quot;<br>_________________________________________________________________<br> Layer (type)                Output Shape              Param #   <br>=================================================================<br> sequential_2 (Sequential)   (None, 28, 28, 1)         1164289   <br>                                                                 <br> sequential_1 (Sequential)   (None, 1)                 40705     <br>                                                                 <br>=================================================================<br>Total params: 1,204,994<br>Trainable params: 1,164,289<br>Non-trainable params: 40,705<br><br><br>def train_gan(gan, dims):<br> epochs = 100<br> batch_size = 32<br> for i in epochs:<br>  X = generate_latent_points(dims, batch_size)<br>  y = np.ones((batch_size, 1))<br>  gan.train_on_batch(X, y)<br></pre><p>Worth noting here is that our only concern for this composite model is the generated samples. That’s why we only work with the output of the generator.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=13fd15ba58e4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/generative-adversarial-networks-13fd15ba58e4">GENERATIVE ADVERSARIAL NETWORKS</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 GROWING TREND IN I.T : SELLING PRODUCTS YOU DON’T OWN.]]></title>
            <link>https://tommytsuma7.medium.com/a-growing-trend-in-i-t-selling-products-you-dont-own-1d093dcdc4aa?source=rss-830d747c7c1b------2</link>
            <guid isPermaLink="false">https://medium.com/p/1d093dcdc4aa</guid>
            <dc:creator><![CDATA[Thomas Tsuma]]></dc:creator>
            <pubDate>Sat, 17 Apr 2021 10:47:01 GMT</pubDate>
            <atom:updated>2021-04-17T10:47:01.479Z</atom:updated>
            <content:encoded><![CDATA[<h3>A GROWING TREND IN I.T : SELLING PRODUCTS YOU DON’T OWN.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/292/1*-014KBfp3uDeWUR_7spbzw.jpeg" /></figure><h4>business model</h4><p><em>noun</em></p><p>a plan for the successful operation of a business, identifying sources of revenue, the intended customer base, products, and details of financing.</p><p>During the Anti-Trust hearing with Mark Zuckerberg in April 2018, we got to watch Zuckerberg explain the Internet to lawmakers of the United States. One Senator, Orrin Hatch seemed especially confused by how exactly Facebook managed to buy Zuckerberg his expensive suit. Zuckerberg explained how advertisements form the backbone of Facebook’s return revenue. Orrin however didn’t seem to catch the drift as he proceeded to ask, “How do you maintain a business model whereby your users do not pay for the services?”. To which Mark promptly answered, “We run ads.”</p><blockquote>This would probably be funnier if you saw it yourself.</blockquote><h3><strong>ABSTRACTION</strong></h3><p>Now this particular interaction, entertaining as it was, got me asking myself, “What exactly <strong>is</strong> Facebook’s business model?”. A common growing trend in C.I.T is developing business models with a certain level of abstraction between the products and the customers. This essentially means one of three things:</p><ol><li>The product is oblivious to the fact that it is so.</li><li>The customer is oblivious to the fact that it is so.</li><li>Neither of them is conscious of their particular states.</li></ol><p>So now let us define who the oblivious customer and products are.</p><h4>customer</h4><p>/ˈkʌstəmə/</p><p><em>noun</em></p><ol><li>a person who buys goods or services from a shop or business.</li></ol><p>As stated up above, Facebook earns its green by running ads that are paid for by the advertisers. This may not be the most shocking news you receive upon reading this article but it’s worth noting that Facebook does not run ads for free.</p><p>To truly understand how much ads cost one need only understand two terms:</p><ol><li>Cost per Click (CPC)</li><li>Cost per Thousand Impressions(CPM)</li></ol><p>Cost per Click refers to the amount owed for each time that a user clicks on an ad that they view. Using the CPC measuring system, Facebook advertising costs on average about $0.27 per click.</p><p>Cost per Thousand Impressions (Also known as Cost per Mile) refers to the amount owed for every thousand views of an ad. If you’re measuring CPM, Facebook advertising costs on average about <strong>$7.19.</strong></p><p><strong>product</strong></p><p>/ˈprɒdʌkt/</p><p><em>noun</em></p><ol><li>an article or substance that is manufactured or refined for sale.</li></ol><p>Now, this is where all this starts to look like a conspiracy theory. The product that Facebook has to offer is the users who endlessly scroll through Facebook, unintentionally viewing ads that they did ask to see and will probably not need to see but will enjoy seeing anyway. As stated earlier, Facebook will charge for each time a user of Facebook clicks on the ads. Just so you understand, Facebook records a click-through rate of 0.8429% which may seem minuscule until you actually think about how many people actually use Facebook has which is roughly 2.7 billion and on average, an ad may reach even 2.14 billion of these. Worth noting is that even if you click on one of each 1.5 thousand ads you still end up clicking on at least 11 each month.</p><p>Let’s talk about how Facebook refines its users(product) for sale. My favourite part of writing articles is detailing how Artificial Intelligence plays a part in all of it. Facebook uses Sentiment Analysis to determine a user’s reaction to a particular post whether it is positive, negative or indifferent. You are therefore mostly only shown the ads that correlate with posts that induce positive sentiments. This allows Facebook to deliver a seamless browsing experience. While it may be unclear to me whether or not they use NLTK for sentiment analysis or their own modules and algorithms, what is a fact is that sentiment analysis is definitely in play. So next time before you click on ‘Like’ or double-tap on a post, think about the implications and why social media sites have them on there. Ask yourself what they stand to gain.</p><p>So in summary, advertisers pay through the nose to have users delivered to them.</p><p>With all this in mind, you’ve probably already got in mind yet another website which you may not pay to use but is always trying to get you hooked on it, YouTube. Unless you’ve employed the services of an ad-block software then you’re are probably YouTube’s product. It delivers said product in form of ads that show up before, during and after the video you’re watching of how a dolphin can kick a shark’s ass.</p><h3>THE UBER EXAMPLE</h3><p>It’s ingenious to sell products that you don’t own. In the aforementioned cases of Facebook and YouTube, they sell users as products. But there are other examples of companies that employ such business models albeit with less abstraction.</p><p>Take Uber, the company that in a way, sells cars that it does not own. Drivers are charged 25% for each trip that they make. They essentially become the customers of Uber. The products in this case become the passengers who are delivered to them through the Uber app.</p><h3>TAKE IT A STEP FURTHER</h3><p>Upon reading this article, my hope is that it gets you thinking of how you can exploit this type of business model.</p><p>So let’s give an example of Amazon, the world’s largest supermarket. It is owned by Jeff Bezos, whose sole purpose in life is to be a magnet for customers but ironically looks more like Charles Xavier than Magneto.</p><p>Amazon is direct in telling who its customers are, the customers.</p><p>But what if we altered this a bit. We wish to attract people to our online shopping company, let’s call it Azanom. Now that’s not original at all so we should make our company a little different, let’s make our website a resell company. So there’ll be people selling second-hand goods and people buying them.</p><p>We could make this idea even more intriguing and mouth-watering for users, let’s make our website <strong>ABSOLUTELY FREE. </strong>That’s right, neither the sellers nor buyers need to pay a cent to the company to conduct their transactions.</p><p>Now that begs the question, how will the company make money to maintain its website?</p><p>We could collect and sell data from our website. A company that produces clothes could buy data on how often its clothes are resold or what state they are resold on. Even the price of reselling could be important to them when they are pricing their clothes or determining the amount of each clothes that should be produced.</p><p>The customer thus is the third party company and the data becomes our product. Oh, our labor force which is totally free is the sellers and buyers using the app. (How’s that for abstraction)</p><h3>IMPLICATIONS</h3><p>The end result of applying this form of abstraction is two business-changing factors:</p><ol><li>Infinite production rate.</li><li>Infinitessimal production cost.</li></ol><p>Facebook has well over 2.7 billion users. The production cost of which is very little because the cost of adding users is very little.</p><p>Uber only needs to host its app whereby passengers can create an account. An infinite number of passengers and almost no money put in to create the users of the app.</p><p>The trend of selling products that one does not own is nothing short of revolutionary. The added abstraction in between ensures that users who are unaware of their state are kept hooked thus increasing production. FOMO, Fear Of Missing Out, is especially a dangerous tool being exploited in this type of business model. Think about how your favorite rapper posts a picture with designer clothing and ropes you into buying the same just to look trendy. People with FOMO are easy marks for Instagram’s owner, Mark Zuckerberg.</p><p>A glorious piece of irony is that in this business model, the seller is often the customer.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1d093dcdc4aa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[COCA-COLA BOTTLE IMAGE RECOGNITION.]]></title>
            <link>https://medium.com/analytics-vidhya/coca-cola-bottle-image-recognition-63a1830a220e?source=rss-830d747c7c1b------2</link>
            <guid isPermaLink="false">https://medium.com/p/63a1830a220e</guid>
            <dc:creator><![CDATA[Thomas Tsuma]]></dc:creator>
            <pubDate>Tue, 02 Feb 2021 17:37:46 GMT</pubDate>
            <atom:updated>2021-02-02T17:37:46.610Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/299/1*qKlU3GDTPMvam_7gWEdICA.jpeg" /></figure><p>The Coca-Cola company has embraced the reuse of its bottles and all the environmental and monetary benefits that come with that. When customers buy a Coke drink in glass bottles, they are rewarded upon returning the empty bottle. This got me thinking about all the plastic bottles and cans that do no warrant a reward leading to them being tossed and wasted. There should be a way of automatically identifying Coca Cola bottles for reuse within the company.</p><p>Coca Cola bottles are easily discernable using the labels that have a large, “Coca Cola “ print on them. The print is usually in white. We can get the label by isolating the color white and training the model on the segmented images.</p><h4>THE DEPENDENCIES</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8b05e4cabf1233dd89360a18f61f1fc0/href">https://medium.com/media/8b05e4cabf1233dd89360a18f61f1fc0/href</a></iframe><p>From the top:</p><p>Numpy is used to manipulate array data.</p><p>Matplotlib is used to visualize the images and to show how discernable a color is in a particular range of colors.</p><p>OS is used to access the file structure.</p><p>CV2 is used to read the images and convert them into different color schemes.</p><p>Keras is used for the actual Neural Network.</p><h4>CONVERTING THE COLOR SCHEME</h4><h4>DETERMINING THE APPROPRIATE COLOR SCHEME:</h4><p>To be able to isolate the colors, we need to check how well the colors are discernable in different color schemes. We can use 3D plots for this</p><p>First, we can visualize the image in RGB color format in 3D space:</p><p>Here, we essentially split the image into its components which in this case are red, green, and blue then we set up the 3D plot. The next thing is to reshape the image after which we normalize the image which reduced the range from 0–255 up to 0–1. Finally, the scatter() function is used to create the scatter plot and then we label the axes accordingly.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c37d22e415d882b42d3a734b7f800366/href">https://medium.com/media/c37d22e415d882b42d3a734b7f800366/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*J0NcNYjZlMjh3bIXiugENQ.png" /></figure><p>HSL and HSV schemes often serve better for image segmentation. We can plot 3D plots for the image in the HSL scheme.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/35354bb3d48f5e0e2c32a56022cf4b52/href">https://medium.com/media/35354bb3d48f5e0e2c32a56022cf4b52/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*Sgeb6Hs3OSGjizcES_3Ltg.png" /></figure><blockquote>To note is that particular colors are not as jumbled up in the second plot as in the first.</blockquote><h4>CONVERTING THE COLORS</h4><p>CV2 by default reads images in the BGR scheme.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e36eb81a4678ff798f344bd5ec98696b/href">https://medium.com/media/e36eb81a4678ff798f344bd5ec98696b/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*nQz9DcPoaLzKHgcCVAiMLA.png" /></figure><p>This image needs to be converted to RGB format first</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2f77f76e826a76f6f9842ea994f1f10e/href">https://medium.com/media/2f77f76e826a76f6f9842ea994f1f10e/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*R693jXtKbXD9QoLf6o-gBg.png" /></figure><p>Finally, this image should be converted to an HLS scheme to allow for ease of discernment of colors. HSL is the description of the Hue, Saturation, and Lightness of an image.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/83b473e666439366e1501f0095ff2718/href">https://medium.com/media/83b473e666439366e1501f0095ff2718/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*3SxyRZMLqCrB3ob6xLCwIg.png" /></figure><h4>ISOLATE COLOR WHITE:</h4><p>We specify the lower and higher threshold values for the color white then specify a mask using cv2.inRange() that thresholds the HSL image. This returns 0’s and 1’s. We then impose the mask upon the original RGB image using a bitwise_and function. The implication here is that it will retain the pixel value if the corresponding value of the mask is 1. A Gaussian Blur is applied to smooth out the edges.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0864c18ec856381558bc983d21bcf97f/href">https://medium.com/media/0864c18ec856381558bc983d21bcf97f/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*K5jL2F-_mmEHTIiAnTjbtA.png" /></figure><h4>TRANSFER LEARNING WITH INCEPTIONV3</h4><p>Some models can take very long to train and eventually still have unimpressive predictive accuracy. While it is entirely noble to want to create a model from scratch, transfer learning employs the use of models that have yielded great results on ImageNet images. In this particular project, I will show how to use InceptionV3.</p><p>We define the model to be used including the weights, and input shape then fit the values of X into the model and save the resultant values in a variable called “bottle_neck_features_train”.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9dd00beb7cb68b47b9b1f9998fb986f9/href">https://medium.com/media/9dd00beb7cb68b47b9b1f9998fb986f9/href</a></iframe><p>The shape of the resultant features is ((n, 8, 8, 2048)), n being the number of images used. We then save the values in a file called ‘inception_features_train.npz’ to avoid repetitive pre-training. The above is a binary classification problem (A bottle is either a Coca Cola Bottle or it isn’t). It follows that the labels can be either 0 for “Coke” or 1 for “Not Coke”(or any other combination of number pairs). The training labels can be cooked up by creating a series of zeros equal to the number of images of Coke bottles followed by ones for the rest of the images.</p><h4>THE NEURAL NETWORK</h4><p>A neural network can be described as a series of algorithms that solve a problem by mimicking the way the human brain works.</p><p>Here, we employ the Keras Sequential model.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/906c66a9ac59132f187d1f52811e2d85/href">https://medium.com/media/906c66a9ac59132f187d1f52811e2d85/href</a></iframe><p>The input layer is a Convolutional Layer. Parameters used for this layer are the number of filters which is 32, the kernel size which is 3 by 3, the activation function which is Rectified Linear Unit, the input shape which is the shape of one image, and the padding. The input of the first conv2d layer is always a 4D array. The first three dimensions are of the image input and the last is the channels.</p><p>Rectified Linear Unit is a non-linear activation function although it acts and appears to be a linear function. It performs calculations that may yield the value added as input or it may yield zero.</p><p>MaxPooling is used for feature extraction. In this case, we set a pool size of 3,3 meaning that the model will extract a 3,3-pixel image and get the maximum value in that pool.</p><p>Dropout is used to prevent overfitting. It randomly sets the outgoing edges of hidden units to 0 at each update of the training phase. The difference between overfitting, underfitting, and properly fitted is illustrated below.</p><p>The Flatten layer converts input data to a 2D array.</p><p>The Dense layer ensures that each node of one layer is connected to each other node of the next layer.</p><p>We use the Sigmoid activation function for the output layer. The input is converted to a value between 0.0 and 1.0. Inputs that are much larger than 1.0 are transformed to the value 1.0, similarly, values much smaller than 0.0 are snapped to 0.0. The shape of the function for all possible inputs is an S-shape from zero up through 0.5 to 1.0.</p><p>To save the model and the weights at particular intervals, we use ModelCheckpoint along with model.fit. Setting ‘save_best_only’ to true ensures that only the model that produced the best results is saved. Finally, we compile the model and fit the data.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/92560158d6526a2d6c879fee67f5e21e/href">https://medium.com/media/92560158d6526a2d6c879fee67f5e21e/href</a></iframe><h4>PERFORMING PREDICTIONS</h4><p>Since we need to use data that is similar to the data that was input to the classifier, we can write a function that will do the conversion then make the predictions.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/83c93c53aa5709649f52619239d40c4f/href">https://medium.com/media/83c93c53aa5709649f52619239d40c4f/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=63a1830a220e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/coca-cola-bottle-image-recognition-63a1830a220e">COCA-COLA BOTTLE IMAGE RECOGNITION.</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[LUNG CANCER DIAGNOSIS: MAKING MACHINES THAT THINK LIKE HUMAN BEINGS]]></title>
            <link>https://medium.com/analytics-vidhya/lung-cancer-diagnosis-making-machines-that-think-like-human-beings-6463ca8e33d7?source=rss-830d747c7c1b------2</link>
            <guid isPermaLink="false">https://medium.com/p/6463ca8e33d7</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Thomas Tsuma]]></dc:creator>
            <pubDate>Mon, 02 Nov 2020 13:22:28 GMT</pubDate>
            <atom:updated>2020-11-17T16:11:28.315Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://github.com/TomiTsuma/Lung-Cancer-Diagnosis/blob/master/Core%26Outline%20Lung%20Cancer%20Diagnosis.ipynb">TomiTsuma/Lung-Cancer-Diagnosis</a></p><p>Lung Cancer is the leading cancer killer in both men and women in America. It claims more lives than breast, colon, and prostate cancer combined. Like all the other kinds of cancer, a nodule in the lungs is what is indicative of cancer.</p><p>CT scans taken of the lungs are what the doctors usually use to determine the presence of nodules in the lungs. To note is that several images are drawn from a single patient such that a 3D image of the lungs can be formed. The images are of the saggital, coronal and axial view. Hence for a single instance of a patient scan, we can have even 600 images produced. The doctor’s duty is to identify nodules in these images. The nodules have to be palpable.</p><blockquote>A tumor can either be termed ‘Benign’ or ‘Malignant’ depending on the size.</blockquote><p>Benign tumors are more easily treatable but could easily as well develop into malignant tumors (in which case you are said to have cancer) if not spotted and treated early enough.</p><p>The point of this article is to show how I designed a Neural Network that can be used to classify CT scans from a patient as either having nodules or lacking them.</p><h4>THE MODULES REQUIRED</h4><p>As is my habit, I made sure to have all my import statements at the very first cell of the notebook.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/92b2195cf831914d46bf815e56b08b09/href">https://medium.com/media/92b2195cf831914d46bf815e56b08b09/href</a></iframe><p>From the top:</p><ol><li>A numpy array is the acceptable input type for the keras classifier.</li><li>Pandas is used to read data from the <a href="https://wiki.cancerimagingarchive.net/display/Public/LIDC-IDRI">lidc-idri nodule counts (6–23–2015).xlsx</a> file.</li><li>Matplotlib is used to plot a graph of cumulative explained variance against the number of components.</li><li>Os is used to access the file structure of windows and to read files.</li><li>Shutil is used to copy and move files to the appropriate folders for categorization.</li><li>CV2 is used to read and write pixel data from and into images.</li><li>Pydicom is used to read data from the .dcm files, especially pixel data.</li></ol><p>The layers of the keras classifier will be detailed later.</p><p>8. Adam optimizer will be used for the classifier.</p><p>9. Backend will be used to check if “channel_last” is added to the input shape we enter.</p><p>10. ImageDataGenerator is going to be used to augment the images so as to match the number of images in each category.</p><p>11. PCA is used to determine only the columns that have a variance so as to avoid unnecessary data.</p><h4>EXPLORATORY DATA ANALYSIS</h4><p>We must first perform some EDA to make sure our data is correct before we can extract the necessary data for our model.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2c9d064755efcfd72d87db5d9be30f05/href">https://medium.com/media/2c9d064755efcfd72d87db5d9be30f05/href</a></iframe><p>We create a DataFrame and call it nodCount. I then sought to eliminate all the columns and rows with null values.</p><p>There’s so much more to be done as far as EDA is concerned but we won&#39;t go into details into that as of now.</p><h4>CATEGORIZING THE PATIENTS’ FILES</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7ab1973bb04dba091f68da84eab3e013/href">https://medium.com/media/7ab1973bb04dba091f68da84eab3e013/href</a></iframe><p>The above is a binary classification problem. Hence we want to create two folders, “Zero Nodules” and “Potentially Cancerous”. These will house the .dcm files of the patients with no recorded nodules and those that had at least one recorded nodule respectively.</p><h4>CREATING THE IMAGES FOR THE CLASSIFIER</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/487a7cc09da0638dea7165fbde309214/href">https://medium.com/media/487a7cc09da0638dea7165fbde309214/href</a></iframe><p>CT scans are usually saved as .dcm files. These usually contain all the patient data all conveniently stored as single files. Within these .dcm files is the pixel data that we can use to create images.</p><p>Since the files have already been separated into two folders, we need to write two functions.</p><blockquote>“Need ” isn’t actually accurate, I just chose to do things in an arbitrary way. We can actually use just one function whose parameters are the folder locations for the patient .dcm files and the location to store the images.</blockquote><p>I have used iterative looping whereby the initial loop does so for all the folders of the patients in each category and the second, loops over all the .dcm files in each patient folder.</p><p>We read the .dcm file using:</p><p>ds = dicom.dcmread((“patient id”),force = False)</p><p>“force” is set to false to ensure it only reads .dcm files.</p><p>The pixel data is accessed using:</p><pre>pixel_array_numpy = ds.pixel_array</pre><p>This is then written to a newly created image file using:</p><pre>cv2.imwrite(img,pixel_array_numpy)</pre><p>I hope it’s already obvious that these two functions need to be called or they are useless.</p><h4>IMAGE AUGMENTATION</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5b0dab7e7f71f9c981a23a27c138636e/href">https://medium.com/media/5b0dab7e7f71f9c981a23a27c138636e/href</a></iframe><p>There is a huge imbalance in the number of patients with nodules recorded as compared to those without (Which, by the way, is cause for great alarm). If we were to train our model with this imbalance it would end up predicting, “no nodules” each time. The solution, therefore, is to augment the images of the lesser one so as to match the numbers. Augmentation involves zooming, rotating, flipping, etc.</p><h4>PREPARING THE TRAINING DATA</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4e6d9c61263cf7ba7e56f8cc8f8220d1/href">https://medium.com/media/4e6d9c61263cf7ba7e56f8cc8f8220d1/href</a></iframe><p>Here we create two arrays. X will contain the training data whereas y will contain the target data. We encode “Potentially Cancerous” as 0 and “Zero Nodules ” as 1. We then need to convert both X and Y into numpy arrays.</p><p>The next step is to normalize the dataset. This means that we divide X by 255 so as to reduce the difference in variance of the columns of X. This in turn ensures that no single column affects the result more than the other due to a higher variance. Normalization essentially brings all the data closer to zero. The term for this is Feature Scaling.</p><p>Finally I printed the shape of only one instance of X so as to get the input shape for the Neural Network.</p><h4>DESIGNING THE NEURAL NETWORK</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dccb7a42c52d0cfc19dcda1c5888c1db/href">https://medium.com/media/dccb7a42c52d0cfc19dcda1c5888c1db/href</a></iframe><p>The implication of using Sequential is that we create a layered neural network whereby at each layer different operations are done on the data.</p><p>The first layer, the convolutional layer, is set up to extract the features of the image dataset. That is where we detail the input shape of the data which is X[0] or (512,512,3). Worth noting also is that to this shape is added the channel number hence technically the input is (512,512,3,1). We check if the channel is added using:</p><pre><strong>from</strong> <strong>tensorflow.keras</strong> <strong>import</strong> backend <strong>as</strong> K<br>print(K.image_data_format())</pre><pre><br>This will output&quot;channels_last&quot;</pre><p>Next is adding the pooling layer of the model. For this case we are going to use MaxPooling which takes in the values of the pixels in the width and height set and then get the maximum value. Using AveragePooling reduced the accuracy by 4%.</p><p>What follows is a Flatten layer that converts our 4d input array into a 2d array.</p><p>Finally our output layer is a Dense layer which is a fully connected NN.</p><blockquote>For an NN to be fully connected each neuron of one layer must be connected to each neuron of the next layer.</blockquote><p>The output_shape is set to 1 because this is a binary classification problem. Sigmoid activation function is also necessary here. Using Rectified Linear Unit will not work.</p><p>The summary() function outputs the model being used, the layers along with the input shape of each layer and the number of parameters on each layer.</p><p>We train the model with X and y and set verbose to 1 to give extra details on the accuracy and loss.</p><h4>SEEKING OPTIMALITY</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3a57a60b3dee7f3c20a5a64e370d1436/href">https://medium.com/media/3a57a60b3dee7f3c20a5a64e370d1436/href</a></iframe><p>Logically, the after completion is to find an optimal solution for the problem at hand. So what I did was I got data from each plane of the 4d dataset we had and used graphs of explained cumulative variance against number of components so as to get the components that account for certain percentages if the variance.</p><blockquote>To put into perspective the thinking here, imagine if we were to determine why some women wear make up and some don’t and the only data we had was that they are all women. Data that remains in a unary state is not beneficial when determining changes in data.</blockquote><p>We can see that around 50 components out of 512 account for any variance in the dataset. So we reduce X2 and X3 to 50 components using PCA.</p><p>We can then retrain the model using this new data.</p><h4>MAKING PREDICTIONS</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/274/1*Ea5c8yxckQk45u6EKgFDPg.jpeg" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/80d55ffec1fb079dce2887127f05bfc0/href">https://medium.com/media/80d55ffec1fb079dce2887127f05bfc0/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/274/1*Ea5c8yxckQk45u6EKgFDPg.jpeg" /></figure><p>To make predictions, we need to set the directory for where the images are and create a new array which we are calling Xpred. We then normalize Xpred and use predict() function.</p><p>Any instance of Xpred that yields a value of 1 which is code for potentially cancerous means that the person has a 91% chance of having cancerous nodules in their lungs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6463ca8e33d7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/lung-cancer-diagnosis-making-machines-that-think-like-human-beings-6463ca8e33d7">LUNG CANCER DIAGNOSIS: MAKING MACHINES THAT THINK LIKE HUMAN BEINGS</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[UNDERSTANDING PRINCIPAL COMPONENT ANALYSIS]]></title>
            <link>https://tommytsuma7.medium.com/understanding-principal-component-analysis-2be385b0f7fe?source=rss-830d747c7c1b------2</link>
            <guid isPermaLink="false">https://medium.com/p/2be385b0f7fe</guid>
            <dc:creator><![CDATA[Thomas Tsuma]]></dc:creator>
            <pubDate>Tue, 15 Sep 2020 07:37:05 GMT</pubDate>
            <atom:updated>2020-09-15T07:37:05.023Z</atom:updated>
            <content:encoded><![CDATA[<p>As a recent believer of the works of dimensionality reduction and noise filtering, I would be averse to keep myself from preaching the good word of PCA.</p><p>Principal Component Analysis, like most other ML models, is self descriptive. Take it to mean that we are taking the principal(or most important) components of the data that is provided to us. Thusly, PCA is essentially a dimentionality reduction algorithm.</p><h4>PCA is also used for noise reduction, feature extraction and feature engineering.</h4><h4>ADDING PRINCIPAL COMPONENT MODULE TO OUR PROJECT</h4><p>from sklearn.decomposition import PCA</p><p>pca = PCA()</p><h4>DIMENSIONALITY REDUCTION</h4><h4>While it is entirely possible to learn ML with an arbitrary understanding of Mathematical concepts such as Linear Algebra, it is absolutely paramount to develop a deep understanding of the aforementioned concept so as to truly grasp the ins and outs of ML.</h4><p>Higher dimension data can be reduced to lower dimensionality by zeroing some of the components(principal). The purpose is mainly to maintain maima data variance.</p><p>pca = PCA(n_components = 2)</p><p>pca.fit(X)</p><p>X_pca = pca.transform(X)</p><p>In this case we have opted to have two principal components and reduced the data to a two dimensional dataframe as such.</p><p>In doing this the model learns some quantities from the data such as the ‘component’ values and the ‘explained variance’</p><p>The components are obtained using pca.components_ while the explained variance is obtained using pca.explained variance</p><p>Worth noting however, is that PCA does not just totally entail discarding elements of a dataset. Such naive dimensionality reduction is avoided because it may end up distorting the data. Instead PCA chooses optimal basis functions such that adding a few of them up ends up in adequate dimensionality reduction while still maintaining an ability to reconstruct the bulk of the elements of the dataset.</p><h4>HOW TO CHOOSE THE NUMBER OF COMPONENTS</h4><p>Think of the cumulative sum of the explained variance ratio as a function of the number of components and vice versa.</p><p>The explained_variance_ratio would give us the components that have the most variance, least variance and possibly those with no variance.</p><p>We just need to make a line plot using plt.plot(np.cumsum(pca.explained_variance_ratio_)) whereby the cumulatice explained variance would comprise the y-axis while the components would comprise the x-axis. Such a plot helps put in perspective how unimportant some of the data provided is.</p><h4>Basically you would have to estimate the number of components necessary by checking for where the line graph flattens off. This represents a variance of zero.</h4><h4>NOISE FILTERING</h4><p>The concept involved in this is that any components with a variance high enough that it is larger than the noise effect, will be remain relatively undistorted by the effect of the noise.</p><p>Basically we get the data that contains half or a slightly higher ratio of the variance</p><p>pca = PCA(0.50).fit(noisy_data) From this we can see how many components are involved by using pca.n_components_</p><p>Now we reduce the data to filter out noise by using X_transform = pca.transform(noisy_data) and then find the inverse so as to reconstruct the filtered data using filtered_data = inverse_transform(X_trainsform)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2be385b0f7fe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PREDICTING HOUSE PRICES USING DATA SCIENCE.]]></title>
            <link>https://tommytsuma7.medium.com/predicting-house-prices-using-data-science-aabd7cc3c424?source=rss-830d747c7c1b------2</link>
            <guid isPermaLink="false">https://medium.com/p/aabd7cc3c424</guid>
            <category><![CDATA[house-prices]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[real-estate]]></category>
            <category><![CDATA[predictions]]></category>
            <dc:creator><![CDATA[Thomas Tsuma]]></dc:creator>
            <pubDate>Wed, 08 Jul 2020 05:28:09 GMT</pubDate>
            <atom:updated>2020-07-08T05:28:09.502Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong>PREDICTING HOUSE PRICES USING REGRESSION</strong></h4><p>One of the playground datasets for Data Scientists is the House Prices dataset. I will use this to demonstrate how to go about completing a data science project involving Regression.</p><h4>HOW TO TELL WHAT ML TECHNIQUE TO USE</h4><p>Before taking up any DS project, one should always try to get an understanding of what exactly the output of the project should be. You can do that in a couple of ways:</p><p>1. Check the sample submission files</p><p>2. Determine the target data</p><p>Doing this helps you determine whether you will employ the services of a Supervised or Unsupervised ML technique. If there is a target data (like in this case) then you will probably use Supervised ML techniques like Regression or Classification. Our target data is the SalePrice of the house.</p><p>The SalePrice is a continuous variable thus we need to use Regression. Classification would be appropriate if the data were ordinal, nominal, or dichotomus.</p><p>So it’s settled, we will employ supervised regression ML techniques.</p><h4>OUR DEPENDENCIES</h4><p>I have a habit of wanting all my import statements at the top. It doesn’t necessarily mean that you need to know everything you need before you start (I sure as hell don’t).</p><p>For the handling of DataFrames and Series:</p><blockquote><strong><em>import pandas as pd</em></strong></blockquote><p>For the arrays:</p><blockquote><strong><em>import numpy as np</em></strong></blockquote><p>To enable us to replace Categorical variables with numerical variables for our ML model:</p><blockquote><strong><em>from sklearn.preprocessing import LabelEncoder</em></strong></blockquote><p>For feature scaling:</p><blockquote><strong><em>from sklearn import preprocessing</em></strong></blockquote><p>To create our ML Regression model:</p><blockquote><strong><em>from sklearn.ensemble import RandomForestRegressor</em></strong></blockquote><p>To determine the accountability of our model:</p><blockquote><strong><em>from sklearn.metrics import accuracy_score</em></strong></blockquote><p>LOADING OUR DATA</p><p>The following three lines of code will load the data into variables as pandas DataFrames:</p><blockquote><em>train = pd.read(“train.csv”)</em></blockquote><blockquote><em>test = pd.read(“test.csv”)</em></blockquote><blockquote><em>sample_submission = pd.read(“sample_submission.csv”)</em></blockquote><p>To note is that any transformation done to the training data must be reiterated on the test data. This is because once the model has been trained it needs to acquire the same type of data.</p><p>Let’s have a look-see at our data then:</p><blockquote><em>train.head(20)</em></blockquote><blockquote><em>test.head(20)</em></blockquote><blockquote><em>sample_submission.head(20)</em></blockquote><p>This will display the first twenty rows in the data under their respective column heads. We see here that train.csv contains 81 columns whereas test.csv contains 80 columns. The SalePrice column has been excluded since it is what we need to predict. The sample_submission.csv contains two columns that are the Id and SalePrice.</p><h4>Data Exploration: Dealing with null values</h4><p>Let us check for null values</p><blockquote><em>train.isnull().any()</em></blockquote><p><em>Id False</em></p><p><em>MSSubClass False</em></p><p><em>MSZoning False</em></p><p><em>LotFrontage True</em></p><p><em>LotArea False</em></p><p><em>…</em></p><p><em>MoSold False</em></p><p><em>YrSold False</em></p><p><em>SaleType False</em></p><p><em>SaleCondition False</em></p><p><em>SalePrice False</em></p><p><em>Length: 81, dtype: bool</em></p><p>This will return a list of the columns with either True or False depending on whether there are null values in that column.</p><p>To get the total number of empty columns per column:</p><blockquote><em>train.isnull().sum().head(50)</em></blockquote><p><em>Id 0</em></p><p><em>MSSubClass 0</em></p><p><em>MSZoning 0</em></p><p><em>LotFrontage 259</em></p><p><em>LotArea 0</em></p><p><em>Street 0</em></p><p><em>Alley 1369</em></p><p><em>LotShape 0</em></p><p><em>LandContour 0</em></p><p><em>Utilities 0</em></p><p><em>LotConfig 0</em></p><p><em>LandSlope 0</em></p><p><em>Neighborhood 0</em></p><p><em>Condition1 0</em></p><p><em>Condition2 0</em></p><p><em>BldgType 0</em></p><p><em>HouseStyle 0</em></p><p><em>OverallQual 0</em></p><p><em>OverallCond 0</em></p><p><em>YearBuilt 0</em></p><p><em>YearRemodAdd 0</em></p><p><em>RoofStyle 0</em></p><p><em>RoofMatl 0</em></p><p><em>Exterior1st 0</em></p><p><em>Exterior2nd 0</em></p><p><em>MasVnrType 8</em></p><p><em>MasVnrArea 8</em></p><p><em>ExterQual 0</em></p><p><em>ExterCond 0</em></p><p><em>Foundation 0</em></p><p><em>BsmtQual 37</em></p><p><em>BsmtCond 37</em></p><p><em>BsmtExposure 38</em></p><p><em>BsmtFinType1 37</em></p><p><em>BsmtFinSF1 0</em></p><p><em>BsmtFinType2 38</em></p><p><em>BsmtFinSF2 0</em></p><p><em>BsmtUnfSF 0</em></p><p><em>TotalBsmtSF 0</em></p><p><em>Heating 0</em></p><p><em>HeatingQC 0</em></p><p><em>CentralAir 0</em></p><p><em>Electrical 1</em></p><p><em>1stFlrSF 0</em></p><p><em>2ndFlrSF 0</em></p><p><em>LowQualFinSF 0</em></p><p><em>GrLivArea 0</em></p><p><em>BsmtFullBath 0</em></p><p><em>BsmtHalfBath 0</em></p><p><em>FullBath 0</em></p><blockquote><em>train.isnull().sum().tail(30)</em></blockquote><p><em>HalfBath 0</em></p><p><em>BedroomAbvGr 0</em></p><p><em>KitchenAbvGr 0</em></p><p><em>KitchenQual 0</em></p><p><em>TotRmsAbvGrd 0</em></p><p><em>Functional 0</em></p><p><em>Fireplaces 0</em></p><p><em>FireplaceQu 690</em></p><p><em>GarageType 81</em></p><p><em>GarageYrBlt 81</em></p><p><em>GarageFinish 81</em></p><p><em>GarageCars 0</em></p><p><em>GarageArea 0</em></p><p><em>GarageQual 81</em></p><p><em>GarageCond 81</em></p><p><em>PavedDrive 0</em></p><p><em>WoodDeckSF 0</em></p><p><em>OpenPorchSF 0</em></p><p><em>EnclosedPorch 0</em></p><p><em>3SsnPorch 0</em></p><p><em>ScreenPorch 0</em></p><p><em>PoolArea 0</em></p><p><em>PoolQC 1453</em></p><p><em>Fence 1179</em></p><p><em>MiscFeature 1406</em></p><p><em>MiscVal 0</em></p><p><em>MoSold 0</em></p><p><em>YrSold 0</em></p><p><em>SaleType 0</em></p><p><em>SaleCondition 0</em></p><p><em>SalePrice 0</em></p><p><em>We can see there are a number of columns with an alarmingly large number of null values since the total number of rows are 1459. Let’s go to data_description.txt to figure out what these columns represent and how to deal with the null values.</em></p><blockquote><em>Alley: Type of alley access to the property. Gravel, Paved or No Alley access.</em></blockquote><blockquote><em>1369/1459 null values.</em></blockquote><blockquote><em>PoolQC: Pool quality which could be</em></blockquote><blockquote><em>Ex Excellent</em></blockquote><blockquote><em>Gd Good</em></blockquote><blockquote><em>TA Average/Typical</em></blockquote><blockquote><em>Fa Fair</em></blockquote><blockquote><em>NA No Pool</em></blockquote><blockquote><em>1453/1459 null values</em></blockquote><blockquote>Fence: Fence quality</blockquote><blockquote>GdPrv Good Privacy</blockquote><blockquote>MnPrv Minimum Privacy</blockquote><blockquote>GdWo Good Wood</blockquote><blockquote>MnWw Minimum Wood/Wire</blockquote><blockquote>NA No Fence</blockquote><blockquote>1179/1459 null values</blockquote><blockquote>MiscFeatures: Miscellanous features not covered in other columns</blockquote><blockquote>Elev Elevator</blockquote><blockquote>Gar2 2nd Garage (if not described in garage section)</blockquote><blockquote>Othr Other</blockquote><blockquote>Shed Shed (over 100 SF)</blockquote><blockquote>TenC Tennis Court</blockquote><blockquote>NA None</blockquote><blockquote>1406/1459 null values.</blockquote><p>Due to the overwhelmingly large number of null values in these columns we cannot autofill these columns since doing so will skew our results way too much for our liking. It would make more sense to do away with these columns.</p><blockquote><em>train.drop(“Alley”, axis = 1,inplace = True)</em></blockquote><blockquote><em>train.drop(“PoolQC”, axis = 1,inplace = True)</em></blockquote><blockquote><em>train.drop(“Fence”, axis = 1,inplace = True)</em></blockquote><blockquote><em>train.drop(“MiscFeatures”,axis = 1,inplace = True)</em></blockquote><p>Now let’s continue</p><p>LotFrontage: Linear feet of street-connected to the property</p><p>259 null values.</p><p>This column contains continuous values hence we should fill it with the median or mean value.</p><blockquote><em>median = train[‘LotFrontage’].median()</em></blockquote><blockquote><em>train[‘LotFrontage’].fillna(median, inplace = True)</em></blockquote><p><em>BsmtQual: Evaluates the height of the basement</em></p><p>This column contains discrete variable hence we can autofill using the modal value</p><blockquote>mode = train[‘BsmtQual’].mode()</blockquote><blockquote>train[‘BsmtQual’].fillna(mode, inplace = True)</blockquote><p><em>BsmtCond: Evaluates the general condition of the basement</em></p><p>Requires the same operations as the BsmtQual</p><p><em>BsmtExposure: Refers to walkout or garden level walls</em></p><p><em>Requires the same operations as BsmtQual</em></p><p><em>GarageYrBlt: Year garage was built</em></p><p>It would make sense to set this to the same date the house was built.</p><p><strong>FEATURE TRANSFORMATION</strong></p><p>We can replace the YrBuilt and YrRemodAdd columns with values that represent the actual time since.</p><blockquote><em>trainYrsSinceBuild = []</em></blockquote><blockquote><em>trainYrsSinceRenov = []</em></blockquote><blockquote><em>testYrsSinceBuild = []</em></blockquote><blockquote><em>testYrsSinceRenov = []</em></blockquote><blockquote><em>for i in train[‘YearBuilt’]:</em></blockquote><blockquote><em>ageSinceBuild = 2020 — i</em></blockquote><blockquote><em>trainYrsSinceBuild.append(ageSinceBuild)</em></blockquote><blockquote><em>for i in train[‘YearRemodAdd’]:</em></blockquote><blockquote><em>ageSinceRenov = 2020 — i</em></blockquote><blockquote><em>trainYrsSinceRenov.append(ageSinceRenov)</em></blockquote><blockquote><em>train[‘YrsSinceBuild’] = trainYrsSinceBuild</em></blockquote><blockquote><em>train[‘YrsSinceRenov’] = trainYrsSinceRenov</em></blockquote><blockquote><em>train.drop([‘YearBuilt’,’YearRemodAdd’],axis = 1, inplace = True)</em></blockquote><p>Our ML model can only accept numerical values. Hence we need to change the Non-numerical values. This can be accomplished by label encoding.</p><p>First, we need to obtain a subset of the training dataset containing only object datatype values.</p><blockquote><em>train_categorical_cols = train.select_dtypes(‘object’)</em></blockquote><p>Then we use LabelEncoder class to transform the values.</p><blockquote><em>lblEncoder = LabelEncoder()</em></blockquote><blockquote><em>train_categorical_cols = train_categorical_cols.apply(lblEncoder.fit_transform)</em></blockquote><p>We can then return the values back to the training dataset by getting the columns that aren’t strings and joining them with the ‘train_categorical_cols’ that solely contained object type columns.</p><blockquote><em>trainMinusStrings = train.select_dtypes(exclude = ‘object’)</em></blockquote><blockquote><em>train = pd.concat([train_categorical_cols,trainMinusStrings], axis = 1)</em></blockquote><h4>Correlation Coefficient.</h4><p>We can now look at how each column correlates with the target dataset. Let us try and create a new dataset containing the columns with a high positive or high negative correlation coefficient and simultaneously train a separate model using only these columns to see how it would affect performance.</p><p>To extract these columns heads:</p><blockquote>count = 0<br>cols_with_high_corr = []<br>for i in columns:<br> <br> corr = new_train[i].corr(prices)<br> if(corr &gt;= 0.50): <br> print(i)<br> print(corr)<br> cols_with_high_corr.append(i)<br> count+=1<br> <br> elif(corr &lt;= -0.50):<br> print(i)<br> print(corr)<br> cols_with_high_corr.append(i)<br> count+=1<br> else:<br> count = count<br>print(cols_with_high_corr)</blockquote><blockquote>high_corr_train = pd.DataFrame()</blockquote><blockquote>for i in cols_with_high_corr:<br> high_corr_train[i] = new_train[i]</blockquote><h4>Feature Scaling</h4><p>We need to avoid letting data with a higher variance obtain more control in determining the SalePrice. So we need to scale the data such that the variance in each column is the same. In our situation we will reduce our data to a -1,+1 range.</p><p>First let us drop the ID column because it should have no bearing on what the SalePrice should be.</p><blockquote>train.drop(‘Id’ ,axis = 1, inplace =True)</blockquote><p>Then let us drop the SalePrice column:</p><blockquote>saleprice = train[‘SalePrice’]</blockquote><blockquote>train.drop(‘Id’, axis = 1, inplace = True)</blockquote><p>Now let us scale the data:</p><blockquote>DF_train = preprocessing.minmax_scale(train)</blockquote><h4><strong>Training our model</strong></h4><blockquote>model = RandomForestRegressor()</blockquote><blockquote>model.fit(DF_train,prices)</blockquote><blockquote>predictions = model.predict(test)</blockquote><blockquote>predictions_df = pd.DataFrame()</blockquote><blockquote>predictions_df[‘ID’] = test[‘Id’]</blockquote><blockquote>predictions_df[‘SalePrice’] = predictions</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aabd7cc3c424" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What we owe each other…]]></title>
            <link>https://tommytsuma7.medium.com/what-we-owe-each-other-97cea3213dad?source=rss-830d747c7c1b------2</link>
            <guid isPermaLink="false">https://medium.com/p/97cea3213dad</guid>
            <dc:creator><![CDATA[Thomas Tsuma]]></dc:creator>
            <pubDate>Tue, 05 May 2020 15:43:21 GMT</pubDate>
            <atom:updated>2021-10-07T20:00:43.732Z</atom:updated>
            <content:encoded><![CDATA[<p>Riddle me this, what probably has two thumbs but is definitely the reason why you are so screwed up mentally? The answer, your African parent.</p><p>I recently decided to go for therapy after I had suffered an intense bit of depression. I can’t lie, things were looking pretty bleak for me. Let’s delve a bit into what was happening with me. My mind was in shambles since I had basically gone a whole year studying and working with no breaks and I was experiencing burnout. I started having flashbacks of my father’s death. Anyway, you get the picture. Life was pretty shitty.</p><p>So back to therapy. Her name was Felicia( a pretty erotic name but maybe I’m just weird like that). My therapist sat me down and the session started. Her first question was “Could you tell me a bit about your parents”. I immediately started rambling and needless to say, we had already found the root of all my problems.</p><p>If it isn’t obvious by now, this is a rant on the utter garbage that is African parenting methods.</p><p>What do our parents owe us? An apology would be nice. Maybe open ears. Some attention and focused love wouldn’t hurt that much either. Or maybe just read a book or do some research on parenting methods.</p><h4>RAISING YOUR VOICE DOESN’T MAKE THE MESSAGE CLEARER.</h4><p>A study on African parenting is a study on ignorance, to put it plainly.</p><p>The constant yelling and belittling of your children does nothing to help their self esteem and I have no idea why anyone would think that it does. I remember I learned the word “daft” from when my dad was irate and summarized me based on my actions with that, surprisingly descriptive, word. Now how about you guess which of these things happened to me after being called ‘daft’:</p><ol><li>I grew as person and never made the same mistake again.</li><li>I vowed never to use that word because of how hurtful it was.</li></ol><p>If you guessed neither then you are absolutely right. All that happened was that it matured into a genuine fear of making tough decisions. The consequences to both myself and my subordinates became terrifying for me. Not only did I put myself in a bad situation but also my brother and cousin. So now let me ask, is it worth traumatizing your child to say things that will hurt their feelings? Absolutely not.</p><p>The constant yelling is easily the theme of a lot of parent-child relationships. Nothing ever seems to be a conversation especially if there was some wrong-doing on the child’s part. Rather than talk out things to get to the root of the problem they resort to raising their voices hurling insults and all sorts of demeaning sentiments. The emotional abuse will absolutely yield it’s results which are in the lines of speech impediment, weakened resolve to do the right things, lack of self-confidence, lowered receptivity to correction, anxiety and aggression just to name a few.</p><h4>HOW ABOUT MAKING A CHILD A PRIMARY DECISION MAKER IN THEIR OWN LIFE</h4><p>micromanage</p><p>/ˈmʌɪkrəʊmanɪdʒ/</p><p><em>verb</em></p><p>gerund or present participle: <strong>micro-managing</strong></p><ol><li>control every part, however small, of (an enterprise or activity)</li></ol><p>Sound familiar? If not then let me explain that this is what it means when your parent says that you will do a seven year course in Medicine whether you like it or not.</p><p>While it comes from a good place, micro-managing does more harm than good unless if it coincides with a person’s natural interests (If only this happened more often). A lack of passion and interest in a task you are being asked to do will surely lead to a disinterest in doing the aforementioned task.</p><p>Every African child has fallen victim to a parent who would beat you cripple, before letting you flunk any classes. They sit you down and make sure you are studying round the clock. Some swear they crossed volcanoes and fought dragons just to get to school to read from a single textbook that was written in Kling’on (I’m obviously just exaggerating their already exaggerated stories for dramatic effect). But does it work? How many children actually get beaten or just read because they are told to? Why is it that some children are bookworms whereas some just don’t have it in them to take a moments studying about levers?</p><p>The much better alternative to micromanaging is to give your child choices and make them understand the more logical one. Lead them to the right path. That last two statements are easily the least African things I’ve ever said but I stand by them.</p><p>Rather than making sure your child is studying or commanding them to study, why don’t you take time to show them why they should study. Show up for Career’s day at their school, do some research and talk to them about their future, show them the land or property you wish they will become educated enough to manage. Basically, give them a goal. That works so much better than any whipping you can accord them.</p><p>A shoutout goes to my hot-head cousin, Karegi. She embodied what every strong-minded person should when she skipped a job interview that she was essentially forced to go to and instead chose to follow her passion.</p><h4>MAYBE TRY LISTENING SOMETIMES</h4><p>A friend of mine once scoffed at the suggestion of therapy because she already knew that her parents would never go for it. They were obviously going to opt to therapize her themselves so she was definitely not going to get to see an actual professional.</p><p>The irony lies in the hilarious fact that her parents are easily the reason why she needs a therapist in the first place.</p><p>Her situation speaks an alarming amount about the level of communication that is involved within households. It is quite possibly exclusively one-way, from their mouth to your ears.</p><p>Contrary to what is thrown out in the open, children suffer an extreme amount of stress from pent up rage, fear, hurt among other negative feelings. The fact that a parent doesn’t know about their own child’s struggles should be concerning to them right…right?</p><p>It should but it doesn’t. Most parents don’t know that their child is bullied, scared, peer pressured, hurt physically or maybe even mentally ill. That is because most African parent treat these as low-rent problems completely disregarding the permanent effects that come with them.</p><p>Which leads me to a particularly scary story of a personal ordeal of mine. I had made a habit of visiting a certain video game store where I would pay by the hour. One day my father came storming into the place huffing and puffing like the greedy wolf, busted me out of there but not before throwing hands at the store owner. Unbeknownst to me, the video store owner was a sexual predator who got a high from getting it on with little boys. It sucks to say that I was on his lap and would have possibly been his next victim if it weren’t for my father’s Naruto-like heroics.</p><p>The point? Listen to your children at all times. Make them know that their opinion is important. Learn where they like to go and why they go there. Figure out why your child is sad. Ask a lot of questions and cool it with the judgemental attitude. Make it known that everything can be discussed and that a solution can always be found by talking to each other and coming together as a family.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=97cea3213dad" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MAKING COMPUTERS THAT THINK LIKE HUMAN BEINGS : NEURAL NETWORKS & TENSORFLOW]]></title>
            <link>https://tommytsuma7.medium.com/making-computers-that-think-like-human-beings-neural-networks-tensorflow-abd0fa421ba?source=rss-830d747c7c1b------2</link>
            <guid isPermaLink="false">https://medium.com/p/abd0fa421ba</guid>
            <dc:creator><![CDATA[Thomas Tsuma]]></dc:creator>
            <pubDate>Tue, 11 Feb 2020 05:56:13 GMT</pubDate>
            <atom:updated>2020-02-11T12:55:58.868Z</atom:updated>
            <content:encoded><![CDATA[<p>A neural network can be described as a series of algorithms that solve a problem by mimicking the way the human brain works. Neural networks adapt to different inputs without having to change the algorithm.</p><h3>Biological Inspiration</h3><p>My lack of expertise in human Biology keeps me from delving too deep into the human brain. However, I believe it’s pretty much obvious that when we’re talking about neural networks, the inspiration comes from the neuron in human beings.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/180/1*YaRUvxSivTTTh5ldAaQwGw@2x.jpeg" /></figure><p>The main parts of a neuron are</p><ul><li>Cell body</li><li>Axons</li><li>Dendrites</li></ul><h3>NEURON MODEL</h3><h3>Annotations</h3><p>Neurons take in inputs (p).</p><p>The input is weighted using a weight function (w).</p><p>A bias (b) is used to shift the activation function to the left or to the right to better fit the data.</p><p>Activation function (f) determines the output of the neural networks.</p><p>To maintain the simplicity of this text I will not dive deep into activation functions. Just to mention that there are Linear and Non-linear activation functions. Under the Non-linear activation functions we see the Log-Sigmoid function, Tanh function and Rectified Linear Unit, my personal favorite.</p><p>All this may seem to be popping out of nowhere but the next section ought to clear up any mistiness as to what these inputs, biases etc are about.</p><h3>Single Input Neuron</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/205/1*IvV0dF2_EBUWbtrsOJinZA@2x.jpeg" /></figure><p>The structure of the single input neuron is pretty straightforward and simple. The trade off of course is that it is inapplicable for most projects that one would want to undertake. It will serve as our starting point nonetheless.</p><p>We can implement this using Python TensorFlow.</p><h4>Define the input:</h4><blockquote>input = tf.constant(0.5, name = “input”)</blockquote><p>The input is defined as a constant</p><h4>Define the weight:</h4><blockquote>weight = tf.variable(1.0, name = “weight”)</blockquote><p>The weight varies during the training phase of the neural network hence is defined as a variable.</p><h4>Define the expected output:</h4><blockquote>expected_output = tf.constant(0.0, name = “expected_output”)</blockquote><p>This is the value that we expect to get after the learning phase of the network.</p><h4>Define our model:</h4><blockquote>model = tf.mul(input,weight,”model”)</blockquote><blockquote>mul_ = tf.multiply(constant_A,constant_C)</blockquote><p>The model is the output we wish to compute and is the product of the inputs and the weights.</p><p>Next we need to tell our neuron how it needs to learn from the data.</p><h4>Define the loss function:</h4><blockquote>loss_function = (model — expected_value)**2</blockquote><p>This is a measure of how much the obtained value differs from the expected value.</p><h4>Define our optimization function:</h4><blockquote>optim = tf.train.AdamOptimizer(learning_rate=0.025)</blockquote><p>There are several optimization functions. In this case we have used the Adam Optimizer, a very popular optimization function.</p><p>The method computes individual adaptive learning rates for different parameters from estimates of first and second moments of the gradients. Adam combines the benefits of using AdaGrad (Adaptive Gradient Algorithm) and RMSPROP (Root Mean Square Propagation). The two are other extensions of Stochastic Gradient Descent , all these are topics to be discussed in another forum.</p><p>Another optimization function one could elect to use is the GradientDescentOptimizer.</p><h3>Multiple Input Neuron</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/179/1*zBlym19h2YEycpLG2H4Spw@2x.jpeg" /></figure><p>We can have a single neuron that takes in several inputs where p is a set comprising inputs 1,2,3…,n i.e p{Input1, Input2,…,Inputn}, each of which are weighted using particular Weights{W1,1 , W1,2 ,…, W1,3}. This simply means the Weight of the first neuron on the n-th input.</p><h3>Multi Layered Neural Network</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/158/1*QNdDQyT4KeOfCHNkWFU90Q@2x.jpeg" /></figure><p>Above is an illustration of a multi-layered neural network that comprises three layers. To the leftmost side is the input layer where our hyper parameters are entered in for processing and to the rightmost side is the output side for outputting results.</p><p>At the middle is the hidden layer. We can have more than one hidden layer. A general rule is that the more the number of layers , the deeper our neural network is and the more information it can grasp.</p><p>For this text we will focus on using TensorFlow’s tf.layers package to utilize layers in neural networks.</p><p>We will be implementing the following Multi-layered perceptron that is the equivalent of the one above.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/491/1*ptEV-h2hejxSuUAeR6WBKw@2x.jpeg" /></figure><p>We are going to make this a fully connected neural network(all the neurons of a layer are connected to each neuron of the proceeding layer)</p><p>We import Keras API from TensorFlow</p><blockquote>import tensorflow.contrib.keras as keras</blockquote><h4>Initialize model</h4><blockquote>model = keras.model.Sequential()</blockquote><h4>Set up an input layer</h4><blockquote>model.add(keras.layers.Dense( units=50,activation=’tanh’) )</blockquote><p>In some cases one would prefer to use Keras.layers.Flatten(). This is if you would prefer to have a 2D array as your input. The activation function used here is tanh.</p><h4>Set up a hidden layer</h4><blockquote>model.add(keras.layers.Dense(units=50,input_dim=50,activation=’tanh’))</blockquote><h4>Set up an output layer</h4><blockquote>model.add(keras.layers.Dense( units=y_train,activation=’softmax’) )</blockquote><h3>REFERENCES</h3><ul><li><a href="https://towardsdatascience.com/introduction-to-multilayer-neural-networks-with-tensorflows-keras-api-abf4f813959">Introduction to Multilayer Neural Networks with TensorFlow’s Keras API</a></li><li><a href="https://learning.oreilly.com/library/view/deep-learning-with/9781786469786/dc52805c-7b9f-4423-ab4f-091f982b028e.xhtml">Deep Learning with TensorFlow</a></li><li><a href="http://www.isikdogan.com/blog/how-to-design-a-convolutional-neural-network.html">How to Design a Convolutional Neural Network</a></li><li><a href="https://missinglink.ai/guides/neural-network-concepts/7-types-neural-network-activation-functions-right/">7 Types of Activation Functions in Neural Networks: How to Choose?</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=abd0fa421ba" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CLASSIFYING TUMORS OF THE BREAST]]></title>
            <link>https://tommytsuma7.medium.com/diagnosing-breast-canser-patients-677086ad2dc9?source=rss-830d747c7c1b------2</link>
            <guid isPermaLink="false">https://medium.com/p/677086ad2dc9</guid>
            <dc:creator><![CDATA[Thomas Tsuma]]></dc:creator>
            <pubDate>Wed, 29 Jan 2020 08:53:59 GMT</pubDate>
            <atom:updated>2020-02-20T20:42:07.908Z</atom:updated>
            <content:encoded><![CDATA[<p>For this we will use the Breast Cancer Wisconsin Dataset.</p><p>The aim here is to classify tumors of the breast as either ‘Malignant’ or ‘Benign’.</p><p>Firstly, I feel it is important to decide whether we need a Supervised or Unsupervised Machine Learning technique. Supervised ML techniques are used when we need to feed the algorithm with the target dataset (Usually labelled y_train) whereas in Unsupervised ML one does not assign the algorithm the target dataset but instead allows it to form associations of its own and classifies the datasets using the aforementioned associations.</p><p>The aim is clearly to classify the Cancer as Malignant or Benign so we need to use Supervised Learning techniques.</p><p>So now let’s get to it.</p><p>Let us import our modules:</p><p>import numpy as np</p><p>import pandas as pd</p><p>import matplotlib.pyplot as plt</p><p>from sklearn.metrics import accuracy_score</p><p>from sklearn.preprocessing import StandardScaler</p><p>from sklearn.ensemble import RandomForestClassifier</p><p>from sklearn.model_selection import train_test_split</p><p>The role of numpy, pandas and matplotlib will be apparent within the next sections of the project.</p><p>Let us look at the Sci-kit Learn modules used within our project.</p><h3>accuracy_score:</h3><p>Used to determine the accuracy of the model based on the predictions the models made measured versus the actual values of the target data in the dataset we have.</p><h3>StandardScaler:</h3><p>An important aspect of Data Science is preparing your dataset. One of the activities involved in this is Feature Scaling. Feature Scaling is about normalization of data which essentially means that we will be bringing the data closer to zero.</p><h3>RandomForestClassifier</h3><p>Here is the main part. Our classification algorithm that is the basis of our model.</p><h3>train_test_split</h3><p>We have all our data in one csv file. This needs to be split into train and test data. For those who may not know, we do not use our training data as our testing data for the obvious reason that the computer will have already seen the data during training hence while testing it may record a 100 percent accuracy.</p><p>Let us now load our dataset shall we?</p><p>df = pd.read_csv(“data.csv”)</p><p>Next we should display the dataframe to get a look-see at what we are working with.</p><p>df.head()</p><p>We need to determing what columns we are dealing with.</p><p>columns = df.columns</p><p>print(columns)</p><p>count = 0</p><p>for column in columns:</p><p>count+=1</p><p>print(count)</p><p>Index([‘id’, ‘diagnosis’, ‘radius_mean’, ‘texture_mean’, ‘perimeter_mean’,</p><p>. ‘area_mean’, ‘smoothness_mean’, ‘compactness_mean’, ‘concavity_mean’,</p><p>. ‘concave points_mean’, ‘symmetry_mean’, ‘fractal_dimension_mean’,</p><p>. ‘radius_se’, ‘texture_se’, ‘perimeter_se’, ‘area_se’, ‘smoothness_se’,</p><p>. ‘compactness_se’, ‘concavity_se’, ‘concave points_se’, ‘symmetry_se’,</p><p>. ‘fractal_dimension_se’, ‘radius_worst’, ‘texture_worst’,</p><p>. ‘perimeter_worst’, ‘area_worst’, ‘smoothness_worst’,</p><p>. ‘compactness_worst’, ‘concavity_worst’, ‘concave points_worst’,</p><p>. ‘symmetry_worst’, ‘fractal_dimension_worst’, ‘Unnamed: 32&#39;],</p><p>. dtype=’object’)</p><p>33</p><p>Forgive my use of this noobish counting method. We can see here that our dataset consists of 33 columns. The columns themselves are displayed above.</p><p>How about the data types contained in the columns…</p><p>df.dtypes</p><p>id. int64</p><p>diagnosis. object</p><p>radius_mean. float64</p><p>texture_mean. float64</p><p>perimeter_mean. float64</p><p>area_mean. float64</p><p>smoothness_mean. float64</p><p>compactness_mean. float64</p><p>concavity_mean. float64</p><p>concave points_mean. float64</p><p>symmetry_mean. float64</p><p>fractal_dimension_mean. float64</p><p>radius_se. float64</p><p>texture_se. float64</p><p>perimeter_se. float64</p><p>area_se. float64</p><p>smoothness_se. float64</p><p>compactness_se. float64</p><p>concavity_se. float64</p><p>concave points_se. float64</p><p>symmetry_se. float64</p><p>fractal_dimension_se. float64</p><p>radius_worst. float64</p><p>texture_worst. float64</p><p>perimeter_worst. float64</p><p>area_worst. float64</p><p>smoothness_worst. float64</p><p>compactness_worst. float64</p><p>concavity_worst. float64</p><p>concave points_worst. float64</p><p>symmetry_worst. float64</p><p>fractal_dimension_worst. float64</p><p>Unnamed: 32. float64</p><p>All the columns are in floating point decimals except id which is in integer values and diagnosis which contains String characters.</p><p>The id columns has no bearing on our classification so we need to drop it.</p><p>df = df.drop(‘id’ , axis = 1)</p><p>Let us check how many unique values are in the diagnosis column so that we can decide how to code them</p><p>in: _ = df[‘diagnosis’]</p><p>in: print(_.unique())</p><p>out: [‘M’,’B’]</p><p>We will code M for Malignant as 1 and B for Benign as 2.</p><p>Since it is a dichotomus variable column, we could code them manually using the following code:</p><p>df.replace(‘M’, 1, inplace. = True)</p><p>df.replace(‘B’, 2, inplace. = True)</p><h3>MISSING VALUES</h3><p>Missing values can come about due to a couple of reasons like users forgetting to fill in. a field, data loss during transfer or programming errors. There are different types of missing data but we shall not delve into all that.</p><p>We deal with missing values by either entering. median or mean value into that feature or by simply ignoring the whole instance if the number of missing values is few.</p><p>Let us check the number of missing values for each feature.</p><p>in: print df.isnull().sum()</p><p>out: diagnosis. 0</p><p>radius_mean. 0</p><p>texture_mean. 0</p><p>perimeter_mean. 0</p><p>area_mean. 0</p><p>smoothness_mean. 0</p><p>compactness_mean. 0</p><p>concavity_mean. 0</p><p>concave points_mean. 0</p><p>symmetry_mean. 0</p><p>fractal_dimension_mean. 0</p><p>radius_se. 0</p><p>texture_se. 0</p><p>perimeter_se. 0</p><p>area_se. 0</p><p>smoothness_se. 0</p><p>compactness_se. 0</p><p>concavity_se. 0</p><p>concave points_se. 0</p><p>symmetry_se. 0</p><p>fractal_dimension_se. 0</p><p>radius_worst. 0</p><p>texture_worst. 0</p><p>perimeter_worst. 0</p><p>area_worst. 0</p><p>smoothness_worst. 0</p><p>compactness_worst. 0</p><p>concavity_worst. 0</p><p>concave points_worst. 0</p><p>symmetry_worst. 0</p><p>fractal_dimension_worst. 0</p><p>Unnamed: 32. 569</p><p>From this we can ascertain that there are no missing. values in any of the columns except in the last column which exclusively has null values. Let us drop this column.</p><p>df.rename(columns = {‘Unnamed: 32&#39;: ‘Last Column’}, inplace = True)</p><p>df.drop(‘Last Column’, axis = 1)</p><p>Our features dataset will be called X whereas our target data is y</p><p>in: X = df.drop([‘diagnosis’], axis = 1)</p><p>in: y = df[‘diagnosis’]</p><h3>FEATURE SCALING</h3><p>We previously discussed what feature scaling is all about. The point of bringing all the variables closer to zero is to ensure that the variance of all of the features is brought closer together. If one feature was to have a greater variance then the ML model would be led to believe that this feature has a greater effect on determining the target dataset.</p><p>For our example we use StandardScaler.</p><p>in: X = StandardScaler().fit_transform(X)</p><h3>SPLITTING THE DATA</h3><p>At this stage we will split the data into training and test data for the reasons stated previously.</p><p>X_train, X_test, y_train, y_test = train_test_split(X,y, test_size = 0.4, random_state = 0)</p><h3>ADDING OUR CLASSIFICATION ALGORITHM TO THE MIX.</h3><p>Declare a variable called model and assign it the Classification algorithm</p><p>model = RandomForestClassifier()</p><p>Fit the data into out model using the .fit() function</p><p>model.fit(X_train,y_train)</p><p>Make some predictions using the .predict() method</p><p>pred = model.predict(X_test)</p><p>Now we can check the accuracy of our model</p><p>in:accuracy = accuracy_score(pred, y_test)</p><p>in: print(accuracy)</p><p>out : 0.9429824561403509</p><p>In my first attempt I made a couple of mistakes lie failing to Standardize the data and leaving the id column in. This affected the accuracy of my model. I think it helps to receive insights from a Data Scientist who is not very experienced because I explain things in a way that is easily understandable.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=677086ad2dc9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An Outline of the Modules in Data Science]]></title>
            <link>https://tommytsuma7.medium.com/anyone-who-has-ever-had-a-conversation-on-programming-with-me-knows-how-i-love-to-spam-the-phrase-84fb06875e3a?source=rss-830d747c7c1b------2</link>
            <guid isPermaLink="false">https://medium.com/p/84fb06875e3a</guid>
            <dc:creator><![CDATA[Thomas Tsuma]]></dc:creator>
            <pubDate>Mon, 27 Jan 2020 14:34:03 GMT</pubDate>
            <atom:updated>2020-01-29T09:04:23.679Z</atom:updated>
            <content:encoded><![CDATA[<p>Anyone who has ever had a conversation on programming with me knows how I love to spam the phrase, “You have to be ready not to know anything”. Looking back I can still remember being a total greenhorn (Forgive my use of this cliché) on matters concerning DS. I am by no measure an expert on the matter but I wouldn’t count myself as a slouch either.</p><p>A lot of experts recommend a top-down approach when trying to learn Data Science and Machine Learning and I feel the same. Let me paint you a brief picture of what you are going to do in any DS or ML classes.</p><p>Import your modules.</p><p>This probably seems really obvious to anyone who uses Python. After doing multiple projects and binge-ing countless YouTube tutorials these almost become as song to you.</p><p>import numpy as np</p><p>import pandas as pd</p><p>import matplotlib.pyplot as plt</p><p>from sklearn.(insert sub-module) import …</p><p>These are absolutely essential before starting your project. However, one may need a lot more than these if you are a Pythonista such as myself.</p><p>So what are these modules and what are they for? I will take a unique (and frowned upon) method to try and describe what they are and what they do.</p><ol><li>Pandas</li></ol><p>I can feel the experts sucking their teeth in pre-discontent already. Pandas is the fourth most used library/framework in the world and although this has no bearing on why I feel like this should be the first module to be taught in any Data Science class or publication it still should, in my opinion. What comes after import statements is usually to add the dataset that is to be worked on to your current project. For the newbies, the datasets used in DS are usually downloaded externally as .csv or .xlsx files. One needs to use the pandas functions: pd.read_csv(“File location of .csv file”) or pd.read_xlsx(“File location of .xlsx file”) so as to read the dataset. The dataset is entered as a dataframe hence it is common practice to save it in a variable called df. It’ll look a little like this:</p><p>import statements…</p><p>…</p><p>df = pd.read_csv(“C:/Users/UserName/Dataset.csv”)</p><p>or</p><p>df = pd.read_xlsx(“C:/Users/UserName/Dataset.xlsx”)</p><p>Next is to see what your dataset contains. For this we use the .head() or .tail() functions of pandas to display the first five and last five elements, respectively, of a dataset</p><p>df.head()</p><p>Data exploration functions in pandas such as .corr(), .scatter_matrix(), .hist() and .bar() must always be at the tip of your tongue also.</p><p>Numpy</p><p>This is usually taught first and don’t get me wrong, there are solid reasons why it should be taught first. A majority of DS and ML involves working with arrays and it is important to learn how to work with numpy arrays.We create a numpy array using by using the numpy.array() function.</p><p>Take the following example of the code below:</p><p>…</p><p>stations = np.array(df[‘Stations’])</p><p>unique(stations)</p><p>Now the first line is done so as to add the column with the header, ‘Stations’ to an numpy array called ‘stations’.</p><p>The juicy part is the second line. The ‘unique()’ function is used in scenarios where a column contains nominal, dichotomus or ordinal values. The unique() function is pretty useless when the columns contain contain continuous variables.</p><p>Don’t fret. I’m going to tell you exactly what the previously mentioned value types are.</p><p>1. Nominal Variable-Columns</p><p>These are columns that contain unique values that can be represented by numbers. To note however is that the numbers representing them do not necessarily represent a higher value or lower value. For example, take a column contained any single permutation of the values: “up”, ”down”, ”left”, ”right” . The unique() function would display a list of only a single one of each of these values.</p><p>2. Dichotomus Variable-Columns</p><p>These are columns that contain only two types of values that can be coded as any two numbers. For example, when diagnosing Breast Cancer patients, the target data(usually called y_train) contains the type of diagnosis (Benign or Malignant). One could chose to code ‘Benign’ as ‘1’ and ‘Malignant’ as ‘2’.</p><p>3. Ordinal Variable-Columns</p><p>While these may be very similar to Nominal, they bear the difference that a change in the code also represents a higher or lower value.</p><p>Numpy arrays provide an ease of manipulation and swiftness of computation that normal lists just cannot.</p><p>A useful numpy function is the np.arange() function. Whereby we enter the start value, end value and and step value as parameters.</p><p>The numpy shape() function is used to show the number of columns and rows in the numpy array and the reshape() function is used to change the shape of the array by changing the rows to columns and vice versa. For this we use a permutation of. 1 and -1 as parameters.</p><p>Matplotlib</p><p>An intricate part of DS or ML is being able to visualize your dataset and solutions. As a matter of fact, data visualization is regarded as the most important skill by some. This is because one needs to be able to explain what they are doing and graphs, charts and scatterplots do exactly that for you.</p><p>The simplest function is the .plot() functions that takes two arrays of continuous values as its parameters. It draws a line-graph with the second array as the y-axis and the first variable as the x-axis.</p><p>One can change the x-axis label, y-axis label and title using the .xlabel(), .ylabel(), .title() functions respectively.</p><p>A scatterplot is drawn using the .scatter() function.</p><p>Bar graphs are drawn using the .bar() function.</p><p>Matplotlib is even used to display images in case you are a Tensorflow image classification man like myself.</p><p>Sci-kit-learn</p><p>Finally, sklearn, the ‘beef’ of ML. Where do I even start? I suppose I should just talk about Supervised versus Unsupervised Learning. In Supervised learning, the Machine Learning model you choose is handed the features of the dataset along with the target data to be used for training. In Unsupervised learning however, the ML model. is fed with the features of the dataset but the target data is excluded. This forces the model to form associations of its own.</p><p>There are quite a number of models contained in sklearn but since this is the heart of ML I won’t get deep into things but will instead classify them because I think it’s a better way to introduce them.</p><p>In my personal opinion, it’s absolutely paramount to understand clustering,classification and regression models and their points of application.</p><p>Clustering algorithms are applied in Unsupervised learning to group the instances into a finite number of classes based on their features or patterns. In Python, one would employ the services of KMeans clustering or MeanShift. The difference between the two being that in KMeans you specify the number of groups of classification.</p><p>Classification algorithms are used in Supervised learning where, as previously mentioned, the labels have been predefined (Usually as a variable y). RandomForestClassifier is probably your easiest bet for a good classification algorithm in Python. The anatomy of the aforementioned is quite complex but boils down to having an aggregate of a series of Decision Trees.</p><p>Regression algorithms are used in situations whereby the target dataset contains a set of continuous variables. An example is with a dataset that requires us to determine the house prices in different neighborhoods. Knowledge of Linear Regression is a clear prerequisite to this obviously. Of the top of my head, I would recommend the RandomForestRegressor as your go-to for a regression problems.</p><p>Feel free to criticize this work. It is my first and I am sure it has as many errors as some of the code on your programs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=84fb06875e3a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>