<?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 gezahegn wondachew on Medium]]></title>
        <description><![CDATA[Stories by gezahegn wondachew on Medium]]></description>
        <link>https://medium.com/@enggezahegn.w?source=rss-ddfe514fac3d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*g4jSrn8JTaO3Eziu.jpg</url>
            <title>Stories by gezahegn wondachew on Medium</title>
            <link>https://medium.com/@enggezahegn.w?source=rss-ddfe514fac3d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 10:10:28 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@enggezahegn.w/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[End-to-End Web3 dApps: certificate generation, distribution, and value transfer with Algorand NFTs…]]></title>
            <link>https://medium.com/@enggezahegn.w/end-to-end-web3-dapps-certificate-generation-distribution-and-value-transfer-with-algorand-nfts-e8c83f0dd8c?source=rss-ddfe514fac3d------2</link>
            <guid isPermaLink="false">https://medium.com/p/e8c83f0dd8c</guid>
            <dc:creator><![CDATA[gezahegn wondachew]]></dc:creator>
            <pubDate>Sat, 18 Jun 2022 20:35:46 GMT</pubDate>
            <atom:updated>2022-06-18T20:35:46.636Z</atom:updated>
            <content:encoded><![CDATA[<h3>End-to-End Web3 dApps: certificate generation, distribution, and value transfer with Algorand NFTs and smart contracts (Part-one)</h3><p><strong>Objective</strong></p><p>The main objective of this project is to build end-to-end Web3 dApps on Algorand Blockchain that will help 10 Academy generate and distribute Non-Fungible Tokens (NFTs) certificates that will represent the successful completion of a weekly challenge to trainees, and allow trainees with NFTs to interact with a smart contract to perform pre-defined actions.</p><p>NB: There are many technologies used to build the front-end and back-end of a web3 application. For this project HTML and CSS are used for the front-end and python is used backend with the flask framework.</p><p><strong>Introduction</strong></p><p>A blockchain is a public ledger (or file) of transactional data, distributed across multiple computers (“nodes”) in a network. All of these nodes work together, using the same set of software and rules, to verify transactions to add to the finalized ledger.</p><p><strong>How will blockchain benefit my application?</strong></p><p>Blockchain, at its core, is a technology that innovates on how we transfer value. So, if your application exchanges value in some way, blockchain may be a candidate technology to bring your application to the next level.</p><p>Below are some of the characteristics of blockchains that make them attractive technologies for value-based applications.</p><p><strong>Algorand Blockchain</strong></p><p>In reality, not all blockchains are created equal, and not all of them can provide the same degree of benefit.</p><p>Algorand was founded by Silvio Micali, a Turing award winner, co-inventor of zero-knowledge proofs, and a world-renowned leader in the field of cryptography and information security. He founded Algorand with a vision to democratize finance and deliver on the blockchain promise.</p><p><strong>The consensus protocol:</strong></p><p>The problem with many blockchains is they sacrifice at least one of the key properties of security, scalability, and decentralization, known as the blockchain trilemma. Silvio and his team solved the blockchain trilemma by inventing a new Pure Proof of Stake (PPoS) consensus protocol, which is the protocol that the Algorand blockchain uses.</p><p>Algorand’s consensus protocol works by selecting a block proposer and a set of voting committees at each block round, to propose a block and validate the proposal, respectively. The proposer and committees are randomly chosen from the pool of all token holders (the accounts that hold algos), and the likelihood of being chosen is proportional to the account’s stake in the network (i.e. how many algos it has relative to the whole). There are a bunch of really cool cryptographic algorithms that go into this process, with fancy names like “verifiable random functions” and “cryptographic sortition” to ensure that the vote is fair, no one can collude, and that the overall system is highly secure.</p><p><strong>Proof-of-stake versus proof-of-work</strong></p><p>Simply put, a proof-of-stake blockchain gives users who have more stake (who hold more of the underlying currency in the system) more influence in proposing and validating new blocks, usually through some sort of voting mechanism.</p><p>In proof-of-work, nodes race to solve a challenging cryptographic puzzle and serve up their solution alongside a new block proposal (this is referred to as “mining” and these nodes are called “miners”). The winner is rewarded with some of the underlying currency of the system and their block becomes part of the chain.</p><p><strong>Accounts on Algorand</strong></p><p><strong>Keys and Addresses</strong></p><p>Algorand uses Ed25519 high-speed, high-security elliptic-curve signatures. The keys are produced through standard, open-source cryptographic libraries packaged with each of the SDKs. The key generation algorithm takes a random value as input and outputs two 32-byte arrays, representing a public key and its associated private key. These are also referred to as a public/private key pair. These keys perform important cryptographic functions like signing data and verifying signatures.</p><p><strong>Transformation: Public Key to Algorand Address</strong></p><p>The public key is transformed into an Algorand address, by adding a 4-byte checksum to the end of the public key and then encoding it in base32. The result is what both the developer and end-user recognize as an Algorand address. The address is 58 characters long.</p><p><strong>Transformation: Private Key to base64 private key</strong></p><p>A base64 encoded concatenation of the private and public keys is a representation of the private key most commonly used by developers interfacing with the SDKs. It is likely not a representation familiar to end-users.</p><p><strong>Transformation: Private Key to 25-word mnemonic</strong></p><p>The 25-word mnemonic is the most user-friendly representation of the private key. It is generated by converting the private key bytes into 11-bit integers and then mapping those integers to the bip-0039 English word list, where integer n maps to the word in the nth position in the list. By itself, this creates a 24-word mnemonic. A checksum is added by taking the first two bytes of the hash of the private key and converting them to 11-bit integers and then to their corresponding word in the word list. This word is added to the end of the 24 words to create a 25-word mnemonic.</p><p>This representation is called the private key mnemonic. You may also see it referred to as a passphrase.</p><p><strong>Wallets</strong></p><p>Wallets, in the context of Algorand developer tools, refer to wallets generated and managed by the Key Management Daemon (kmd) process. A wallet stores a collection of keys. kmd stores collections of wallets and allows users to perform operations using the keys stored within these wallets. Every wallet is associated with a master key, represented as a 25-word mnemonic, from which all accounts in that wallet are derived. This allows the owner of the wallet to only need to remember a single passphrase for all of their accounts. Wallets are stored encrypted on a disk.</p><p><strong>Accounts</strong></p><p>Accounts are entities on the Algorand blockchain associated with specific on-chain data, like a balance. An Algorand Address is an identifier for an Algorand account.</p><p>After generating a private key and corresponding address, sending Algos to the address on Algorand will initialize its state on the Algorand blockchain.</p><p><strong>What is AlgoSigner?</strong></p><p>A non-custodial, Algorand Wallet extension for the Chrome browser Users can create and import Algorand accounts whose keys never leave their system and are securely stored Send funds, opt-in to assets, transfer as an interface with dApps Built under a grant from the Foundation, algoSigner is open-source and security audit</p><p><strong>Build Web3 dApp using Algorand Blockchain Technology</strong></p><p><strong>Steps 1:</strong></p><p>a. Build A user login web that is capable to accept 25 strings as an input</p><p><strong>Steps 2:</strong></p><p>b. Connect the page to the Algorand network</p><p>Steps to Interact with the Algorand Network</p><p>1. Create an account on Purestake and get API Key(Token) using the following link <a href="https://testnet-algorand.api.purestake.io/">https://testnet-algorand.api.purestake.io/</a></p><p>2. Interacting with the Algorand client using the API key from purestake.</p><p>This step allows us to generate a TestNet account and save the passphrase for future use and we need to convert the account passphrase into its public key — the address — in order to check the balance.</p><p><strong>Steps 3:</strong></p><p>We have already connected to the Algorand client so we will try to send transactions with the Algod client</p><p>1. Build web pages that are capable to present Balance, Transactions, sending Algos, and Create Assets</p><p>2. Since our balance is empty we will use the following link and we can add more Algorand tokens to our account on the TestNet using the following Algorand Dispenser link <a href="https://bank.testnet.algorand.network/">https://bank.testnet.algorand.network/</a>.</p><p>3. See the transaction and follow to create assets. To do so open an account on Algosign wallet using testNet using the following link. <a href="https://arc3.xyz/mint%20.the">https://arc3.xyz/mint .the</a> link will create an asset using our TestNet account on Algorand and the algosign extension must be installed on our browser and active to login.</p><p>4. Create mint</p><p>5. Check your asset, you will find your assent in your development pages</p><p>The overall Implementation of the application is found in the following link.</p><p><a href="https://github.com/gezish/E2E_Web3_dApps_Algorand">https://github.com/gezish/E2E_Web3_dApps_Algorand</a></p><p>Future Updates:</p><p>Add the algosign to the main page</p><p>Ø Add mint to the main page</p><p>Ø Apply full features of React and Django for front-end and back-end respectively</p><p>Ø Add wallet for mobile and add QR-CODE to the application.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e8c83f0dd8c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[African language Speech Recognition (Speech-to-Text)]]></title>
            <link>https://medium.com/@enggezahegn.w/african-language-speech-recognition-speech-to-text-4d96443279bb?source=rss-ddfe514fac3d------2</link>
            <guid isPermaLink="false">https://medium.com/p/4d96443279bb</guid>
            <dc:creator><![CDATA[gezahegn wondachew]]></dc:creator>
            <pubDate>Thu, 09 Jun 2022 19:17:15 GMT</pubDate>
            <atom:updated>2022-06-21T04:44:41.920Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*7cUpparwkhM9Z0Y2.png" /></figure><p><strong>Abstract:</strong></p><p>Speech is the most natural form of communication for us — it’s second nature to us. And now, our machines have started to recognize our speech and they’re getting better and better at communicating with us. In general speech recognition, also known as automatic speech recognition (ASR), simply is the ability of devices to respond to spoken commands. Speech recognition enables hands-free control of various devices and equipment, provides input to automatic translation, and creates print-ready dictation.</p><p>This project aims to implement an end-to-end African language Speech Recognition-Speech-to-Text subsystem by focusing on the class of applications starting with a clip of spoken audio in Amharic language and extracting the words that were spoken, as text.</p><p><strong>1.</strong> <strong>Introduction</strong></p><p>Current voice assistants and devices like Amazon Alexa and Google Home are getting more and more popular each month — they are changing the way we interact with our devices and even each other. The first speech recognition software was developed in the 1950s and we’ve come a long way since then.</p><p><strong>2.</strong> <strong>Motivation</strong></p><p>The World Food Program wants to collect nutritional information on food bought and sold at markets in two different countries in Africa — Ethiopia and Kenya.</p><p>The speciﬁc need of this project is that Tenacious data science consultancy is in agreement with the World food program (WFP) to deliver speech-to-text technology for two languages: Amharic and Swahili using an app that can use their voice to activate the app to register the list of items they just bought in their own language.</p><p><strong>3.</strong> <strong>Review of previous works</strong></p><p>Development of Automatic Speech Recognition System-Speech corpus is the basic requirement for the development of automatic speech recognition (ASR) system, it should be done with much accuracy in order to enhance the performance of the system. This paper describes the proposed procedure to abide while collecting the speech corpus of the Swahili language from the native and non-native speakers for the development of the Automatic Speech Recognition system in the Swahili language.</p><p>On the other hand, a paper made was made by Tilaye Yismaw Alemu. Its core idea is to have a network of interconnected nodes (also known as Neural Networks) where each node computes a function and passes information to the nodes next to it. Every node computes its output using the function it was conﬁgured to use, and some parameters. The process of learning updates these parameters. The function itself will not change. Initially, the parameters are randomly initialized. Then training data is passed through the network, making small improvements to the parameters on every step. There are some well-understood functions and network architectures. In the case of speech recognition, Recurrent Neural Networks (RNN) is used as their output depends not just on the current set of inputs, but on previous inputs too. It’s crucial in speech recognition because predicting what has been said at a particular window of time becomes much easier if what has been said before is known.</p><p><strong>4.</strong> <strong>Data and Preprocessing Techniques</strong></p><p>Data preprocessing is a step-by-step process that transforms the audio data for deep learning models. The techniques used are listed below.</p><p><strong>I. Importing important libraries&#39;:</strong></p><pre>import librosa #for audio processing<br>import IPython.display as ipd<br>import matplotlib.pyplot as plt<br>import numpy as np<br>import pandas as pd<br>from scipy.io import wavfile #for audio processing<br>import warnings<br>warnings.filterwarnings(“ignore”)<br>import wave<br>import librosa.display<br>import sklearn<br>import json<br>import sys, os<br>warnings.filterwarnings(‘ignore’)<br>from IPython.display import Audio<br>from os.path import exists</pre><p><strong>II. Load Audio ﬁles:</strong> The input data are audio ﬁles of the spoken speech that are in the audio format “.wav” and the transcription to the audio.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*nHUL89RGTZA6WfWoLOPEoA.png" /><figcaption>Transcription Loader</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*DZriz6ZH2SA4YF9L0KMSZQ.png" /><figcaption>Transcription file</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*qkyRkcQlkxCrYOEQgykHWQ.png" /><figcaption>Audio File</figcaption></figure><p><strong>III. Resample</strong> <strong>the audio ﬁles:</strong> so as to have uniform sample rates for each item.</p><pre># we will use the first wav file to visualize its characteristics<br>#librosa load returns by default time-series as numpy array and with the default sample rate of 22KHZ so we just changed it to 44kHZ<br>samples, sample_rate = librosa.load(train_changed_wav_location+’tr_1_tr01001.wav’, sr=44100)<br>print(samples)<br>print(sample_rate)<br><strong>Output<br></strong>[-0.00502738 -0.00577551 -0.0046026  ... -0.00579655 -0.00516981<br>  0.        ]<br>44100</pre><p><strong>IV. channels Convert: </strong>all the items should have the same number of channels. The channels could be mono (one channel) or stereo (2 channels). Our data has mono channels.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k066dKKrJhraTQVynttMFg.png" /><figcaption><strong>channel conversion snippet and output</strong></figcaption></figure><p><strong>V. Duration Convert:</strong> all items should have the same duration, which involves padding the shorter audio ﬁles and truncating the longer ones.</p><pre>def resize_audio(audio: np.array, size: int) -&gt; np.array:<br> <br> resized = librosa.util.fix_length(audio, size, axis=1)<br> print(f”Audio resized to {size} samples”)<br> return resized</pre><p>VI. Time Shift our audio left or right randomly by a small percentage, or change the Pitch or the Speed of the audio by a small amount so as to add noise to our audio ﬁles.</p><h3><strong>Visualizations:</strong></h3><p><strong>Spectrogram:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*93Gw8Esw_jhkbjMdTkxVcw.png" /><figcaption>spectrogram of pre-processed signal</figcaption></figure><p><strong>The Short-time Fourier transform (STFT)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ysjjXUNExdZxC2O9jvG0bQ.png" /></figure><h3><strong>spectral Centroid</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GUv3LZQq5eGoX4BiSXYJ4Q.png" /></figure><h3><strong>Spectral Bandwidth</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GypbjRfl6Q-_tz8SPcQrlg.png" /></figure><h3>Data Augmentation by Time shifting</h3><p>code to apply augmentation by time-shifting:</p><p>def plot_spec(data: np.array, sr: int) -&gt; None:<br> ‘’’<br> Function for plotting spectrogram along with amplitude wave graph<br> ‘’’</p><pre>fig, ax = plt.subplots(1, 2, figsize=(15, 5))<br> ax[0].title.set_text(f’Shfiting the wave by Times {sr/10}’)<br> ax[0].specgram(data, Fs=2)<br> ax[1].set_ylabel(‘Amplitude’)<br> ax[1].plot(np.linspace(0, 1, len(data)), data)<br> # fig.savefig(‘spectogramamplitude.png’)<br>wav_roll = np.roll(samples, int(sample_rate/10))<br>plot_spec(data=wav_roll, sr=sample_rate)<br>ipd.Audio(wav_roll,rate=sample_rate)<br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lnw8ZNDa-hnBYvHFZ_TgEg.png" /><figcaption>autput</figcaption></figure><h3><strong>Adding noise</strong></h3><pre>noise_added = audio_augmenter.add_noise(samples, noise_factor=0.0001)<br>librosa.display.waveshow(noise_added, sr=sample_rate)<br>ipd.Audio(data=noise_added, rate=sample_rate)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/637/1*7dG4ER2bJW5FOnZA-k_iHg.png" /></figure><h3><strong>applying using pitch shift</strong></h3><pre>pitch_shifted = audio_augmenter.change_pitch(samples, sample_rate, pitch_factor=0.1)<br>librosa.display.waveshow(pitch_shifted, sr=sample_rate)<br>ipd.Audio(data=pitch_shifted, rate=sample_rate)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/618/1*r9upoqL7HeHTvOXk1dk9mw.png" /></figure><h3>Feature Extraction</h3><p><strong>VII</strong>. Convert the raw audio ﬁles to<strong> Mel Spectrograms </strong>which capture the nature of the audio ﬁles as images by decomposing them into sets of frequencies.</p><pre>plt.figure(figsize=(20, 5))<br>mfccs = librosa.feature.mfcc(time_shifted, sr=sample_rate)<br>librosa.display.specshow(mfccs, sr=sample_rate, x_axis=’time’)<br>print(mfccs.shape)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2tJ-zhPcCKTp66uaNO8WiA.png" /></figure><p>The Mel Spectrograms are converted to Mel Frequency Cepstral Coeﬃcients (MFCCs) which is important when dealing with human speech. This is because MFCCs correspond to the frequency ranges at which humans speak.</p><p><strong>Preparing the metadata for the transcriptions</strong></p><p>We used the librosa package to preprocess our audio ﬁles. By default, librosa converts all audio ﬁles to mono and resamples the ﬁles to 22050 Hz when loading the audio ﬁles, unless other arguments are passed in the load function. Now that we have our input features(the preprocessed audio ﬁles) and our target labels (the preprocessed transcriptions), we build a deep neural network that accepts the preprocessed data as input and returns a predicted transcription of the spoken language as the output.</p><pre>## save extracted data to a data frame<br>filenames, target, duration_of_recordings,mode ,rmse,spec_cent,spec_bw,rolloff,zcr,mfcc,rate = meta_data(transcription, train_wav_location)<br>data_am = pd.DataFrame({‘key’: filenames, ‘text’: target,<br> ‘duration’: duration_of_recordings, ‘mode’: mode , ‘rate’: rate ,’rmse’: rmse,’spec_cent’ :spec_cent,’spec_bw’: spec_bw,”rolloff” :rolloff,”zcr”: zcr,”mfcc”: mfcc})<br>data_am</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ymAyxpyb0TTWRV6tgFvpJw.png" /><figcaption><strong>output of the audio dataset with features</strong></figcaption></figure><p><strong>The deep learning architecture</strong></p><p>Convolutional Neural Network(CNN) plus Recurrent Neural Network (RNN): CNN encodes the information from the voice features. This data is sent to a convolution layer with a kernel which also acts as a fully connected layer. This ﬁnally gives softmax probabilities of each character that can be placed in the transcription</p><p>An RNN model consists of a Bidirectional LSTM that processes the feature maps as a series of distinct timesteps or ‘frames’ that correspond to our desired sequence of output characters. In other words, it takes the feature maps which are a continuous representation of the audio and converts them into a discrete representation.</p><p>Feature maps -&gt; Bidirectional LSTM A linear layer with softmax that uses the LSTM outputs to produce character probabilities for each timestep of the output linear layers that sit between the convolution(CNN) and recurrent networks(RNN). It helps to reshape the outputs of one network to the inputs of the other.</p><p>Bidirectional LSTM -&gt; Linear Layer-&gt; softmax -&gt; character probabilities for each timestep in that Spectrogram The CNN encodes the information from the image and sends that data to the RNN based decoder which decodes the data and outputs the corresponding text from the image.</p><p><strong>MLOPs setup</strong></p><p>MLOps is an ML engineering culture and practice that aims at unifying ML system development (Dev) and ML system operation (Ops). Practicing MLOps means that you advocate for automation and monitoring at all steps of ML system construction, including integration, testing, releasing, deployment, and infrastructure management.</p><p><strong>Modeling results</strong></p><p><strong><em>CTC:</em></strong></p><p>For our model, we will use the CTC loss as the base loss function. When the input is continuous and the output is discrete, and there are no clear element boundaries that can be used to map the input to the elements of the output sequence, CTC is used to align the input and output sequences.</p><p>The Keras CTC loss function takes as arguments y true, y pred, input length, and label length. The issue with our data is that the input length varies by batch. We can calculate the input length by dividing the audio length by the hop size.</p><p>Another point to consider is that if we use Convolutional or Max Pooling layers in our model, we must recompute input length because they can reduce the dimensions of the feature maps.</p><p>Finally, the input length (number of time slices) should be greater than two times the transcription length plus one. The CTC paper makes mention of this. Aside from these points, we can calculate CTC loss by simply following Keras’ documentation.</p><pre>def ctc_lambda_func(args): y_pred, labels, input_length, label_length = args return K.ctc_batch_cost(labels, y_pred, input_length, label_length) def input_lengths_lambda_func(args): input_length = args return tf.cast(tf.math.floor(input_length / hop_size)-1, dtype=”float32&quot;) def add_ctc_loss(model_builder): the_labels = Input(name=’the_labels’, shape=(None,), dtype=’float32&#39;) input_lengths = Input(name=’input_length’, shape=(1,), dtype=’float32&#39;) label_lengths = Input(name=’label_length’, shape=(1,), dtype=’float32&#39;) input_lengths2 = Lambda(input_lengths_lambda_func)(input_lengths) if model_builder.output_length: output_lengths = Lambda(model_builder.output_length)(input_lengths2) else: output_lengths = input_lengths2 # CTC loss is implemented in a lambda layer loss_out = Lambda(ctc_lambda_func, output_shape=(1,), name=’ctc’)( [model_builder.output, the_labels, output_lengths, label_lengths]) model = Model(inputs=[model_builder.input, the_labels, input_lengths, label_lengths], outputs=loss_out) return model</pre><p><strong>Modeling</strong></p><p>On the modeling part, I plan to use a model similar to the Deep Speech 2 architecture. There will be two main neural network modules in the model. To learn the relevant audio features, three layers of Residual Convolutional Neural Networks were used. Then, to leverage the learned audio features, a set of Bidirectional Recurrent Neural Networks is used. Let’s take a look at how the model is implemented in Keras.</p><pre>def preprocessin_model(fft_size, hop_size, n_mels, mfcc=False):     input_data = Input(name=&#39;input&#39;, shape=(None,), dtype=&quot;float32&quot;)    spec = LogMelgramLayer(        num_fft=fft_size,        hop_length=hop_size,        num_mels=n_mels,        sample_rate=sr,        f_min=0.0,        f_max=sr // 2,        eps=1e-6)(input_data)    x = BatchNormalization(axis=2)(spec)    # x = Permute((2, 1, 3), name=&#39;permute&#39;, dtype=&quot;float32&quot;)(x)    model = Model(inputs=input_data, outputs=x, name=&quot;preprocessin_model&quot;)     return model</pre><pre>def cnn_output_length(input_length, kernel_list, pool_sizes, cnn_stride, mx_stride):    output_length = input_length    for i, j in zip(cnn_stride, pool_sizes):        output_length = (output_length)/i        if j != 0: output_length = (output_length - j)/mx_stride + 1                    return tf.math.ceil(output_length)</pre><pre>def block(filters, inp):    x = BatchNormalization()(inp)    x = LeakyReLU(.1)(x)    x = Dropout(.4)(x)    x = Conv2D(filters, (3,3), padding = &#39;same&#39;)(x)    x = BatchNormalization()(x)    x = LeakyReLU(.1)(x)    x = Dropout(.4)(x)    x = Conv2D(filters, (3,3), padding = &#39;same&#39;)(x)    return(x)</pre><pre>def resnet( input_dim, output_dim=224, units=256, num_birnn=2): filters = [32, 32, 32] kernels = [3, 3, 3] pool_sizes = [0, 0, 2] cnn_stride = [1, 1, 1] mx_stride = 2 input_data = Input(name=’the_input’, shape=(None, input_dim)) x = Reshape((-1, input_dim, 1), dtype=”float32&quot;)(input_data) x = Conv2D(filters[0], (3,3), padding = ‘same’)(x) x = MaxPooling2D((1,2), strides=(1, 2), padding = ‘same’)(x) x = Add()([block(filters[0], x),x]) x = Add()([block(filters[0], x),x]) x = Add()([block(filters[0], x),x]) x = Conv2D(filters[1], (3,3), padding = ‘same’)(x) x = MaxPooling2D((1,2), strides=(1, 2), padding = ‘same’)(x) x = Add()([block(filters[1], x),x]) x = Add()([block(filters[1], x),x]) x = Add()([block(filters[1], x),x]) x = Conv2D(filters[2], (3,3), padding = ‘same’)(x) x = MaxPooling2D((1,2), strides=(1, 2), padding = ‘same’)(x) x = Add()([block(filters[2], x),x]) x = Add()([block(filters[2], x),x]) x = Add()([block(filters[2], x),x]) # x = MaxPooling2D((2,2), strides=2, padding = ‘same’)(x) x = AveragePooling2D((2, 2), strides=2, padding=’same’)(x) x = Reshape((-1, x.shape[-1] * x.shape[-2] ))(x) # GRULayer for i in range(num_birnn): x = Bidirectional(GRU(units=units, return_sequences=True, implementation=2, name=’rnn_{}’.format(i)))(x) x = Dropout(.4)(x) x = LeakyReLU(.1)(x) x = BatchNormalization(name=’bn_rnn_{}’.format(i))(x) x = TimeDistributed(Dense(output_dim))(x) y_pred = Activation(‘softmax’, name=’softmax’)(x) model = Model( inputs=input_data, outputs=y_pred, name=”custom_model” ) output_length_calculater = lambda x: cnn_output_length(x, kernels, pool_sizes, cnn_stride, mx_stride) return model, output_length_calculater</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/716/0*XhgDJvwsIXNe0fOw.png" /></figure><p>This visualization depicts the model’s performance over time. Using only one GPU, the training took about 8 hours. I kept training the model, but the validation loss did not improve significantly. One thing to keep in mind is that the loss is calculated not only for the clean data but also for the augmented versions.</p><p><strong>Result</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oSDlkcQuMNKMm0B8.png" /></figure><p>Reference</p><p>· <a href="http://ainsightful.com/index.php/2018/11/27/deep-learning-for-amharic-speech-recognition/"><strong>http://ainsightful.com/index.php/2018/11/27/deep-learning-for-amharic-speech-recognition/</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4d96443279bb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pharmaceutical Sales Prediction Across Multiple Stores]]></title>
            <link>https://medium.com/@enggezahegn.w/pharmaceutical-sales-prediction-across-multiple-stores-99a254933024?source=rss-ddfe514fac3d------2</link>
            <guid isPermaLink="false">https://medium.com/p/99a254933024</guid>
            <dc:creator><![CDATA[gezahegn wondachew]]></dc:creator>
            <pubDate>Sat, 28 May 2022 20:37:29 GMT</pubDate>
            <atom:updated>2022-08-04T08:20:23.478Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/593/1*V7GBUQtqP9ovDkw21oN2rw.png" /><figcaption>Correlations of Metrcics</figcaption></figure><h3>1. Introduction</h3><p>The data scientists at Rossmann Pharmaceuticals have collected three years of sales data for different products across four stores in a different location. Also, certain statistics attributes of sales in each store have been defined. The aim is to build a predictive model and predict sales of all their stores across several cities six weeks ahead of time.</p><h3>2. Dive into the detail</h3><p>The data team identified factors such as promotions, competition, school and state holidays, seasonality, and locality as necessary for predicting the sales across the various stores.</p><p>The major task here is to build and serve an end-to-end product that delivers this prediction to analysts in the finance team.</p><h3>3. Data and Features</h3><p><strong>Feature Descriptions of the Data</strong></p><p>The following are descriptions of <strong>Rossmann Pharmaceuticals’</strong> data set.</p><ul><li><strong>Id</strong> - an Id that represents a (Store, Date) duple within the test set</li><li><strong>Store</strong> - a unique Id for each store</li><li><strong>Sales</strong> - the turnover for any given day (this is what you are predicting)</li><li><strong>Customers</strong> - the number of customers on a given day</li><li><strong>Open</strong> - an indicator for whether the store was open: 0 = closed, 1 = open</li><li><strong>StateHoliday</strong> - indicates a state holiday. Normally all stores, with few exceptions, are closed on state holidays.</li></ul><p><strong>Note that</strong> all schools are closed on public holidays and weekends. a = public holiday, b = Easter holiday, c = Christmas, 0 = None</p><ul><li><strong>SchoolHoliday</strong> - indicates if the (Store, Date) was affected by the closure of public schools</li><li><strong>StoreType</strong> - differentiates between 4 different store models: a, b, c, d</li><li><strong>Assortment</strong> - describes an assortment level: a = basic, b = extra, c = extended. Read more about assortment here</li><li><strong>CompetitionDistance</strong> - the distance in meters to the nearest competitor store</li><li><strong>CompetitionOpenSince[Month/Year]</strong> - gives the approximate year and month of the time the nearest competitor was opened</li><li><strong>Promo</strong> - indicates whether a store is running a promo on that day</li><li><strong>Promo2</strong> - Promo2 is a continuing and consecutive promotion for some stores: 0 = store is not participating, 1 = store is participating</li><li><strong>Promo2Since[Year/Week]</strong> - describes the year and calendar week when the store started participating in Promo2</li><li><strong>PromoInterval</strong> - describes the consecutive intervals Promo2 is started, naming the months the promotion is started anew. E.g. &quot;Feb, May, Aug, Nov&quot; means each round starts in February, May, August, or November of any given year for that store</li><li>The data for this challenge can be found <a href="https://www.kaggle.com/competitions/rossmann-store-sales/data">https://www.kaggle.com/competitions/rossmann-store-sales/data</a>.</li></ul><p>This article will take you through everything you need to know in order to engage in such tasks or challenges. It will take you through the following steps and different sections;</p><ul><li>Data Loading</li><li>Data preprocessing</li><li>Feature engineering</li><li>Building a model</li><li>Making a Prediction</li></ul><h3>4. The Highway to The Solution</h3><p><strong>4.1. Exploration of customer purchasing behavior</strong></p><p><strong>Exploratory data analysis</strong></p><p>It is the lifeblood of every meaningful machine learning project. It helps us unravel the nature of the data and sometimes informs how you go about modeling. A careful exploration of the data encapsulates checking all available features, checking their interactions and correlation as well as their variability with respect to the target.</p><p>In this task, I will explore the behavior of customers in the various stores. and to achieve this goal, I am going to input my raw data into some <strong>pre-processing</strong> steps. The <strong><em>data cleaning process </em></strong>will involve <strong><em>building pipelines to detect and handle outliers and missing data will be conducted</em></strong>.</p><p><strong>importing important library</strong></p><pre>import warnings<br> import numpy as np<br> import pandas as pd<br> import seaborn as sns<br> import matplotlib.pyplot as plt<br> import sys,os</pre><pre>sys.path.append(os.path.abspath(os.path.join(‘../modules’)))<br> warnings.filterwarnings(“ignore”)<br> sns.set()</pre><p><strong>Loading the data</strong></p><pre>#stored_df = file_loader.read_csv(‘../data/store.csv’)<br> train_df = file_loader.read_csv(‘../data/train.csv’, missing_values)<br> test_df = file_loader.read_csv(‘../data/test.csv’, missing_values)<br> stored_df = file_loader.read_csv(‘../data/store.csv’, missing_values)<br> print(“\n### General data Structure ###\n”)</pre><pre>print(“Stored data:”,stored_df.shape)<br> print(“Train data:”,train_df.shape)<br> print(“Test data:”,test_df.shape)</pre><p><strong>output</strong></p><pre><strong>### General data Structure ###</strong><br> <br> Stored data: (1115, 10)<br> Train data: (1017209, 9)<br> Test data: (41088, 8)</pre><h3>Get the Information Stored on each dataset</h3><pre>stored_df.info()</pre><pre><strong>output</strong><br> RangeIndex: 1115 entries, 0 to 1114<br> Data columns (total 10 columns):<br> # Column Non-Null Count Dtype <br> — — — — — — — — — — — — — — — <br> 0 Store 1115 non-null int64 <br> 1 StoreType 1115 non-null object <br> 2 Assortment 1115 non-null object <br> 3 CompetitionDistance 1112 non-null float64<br> 4 CompetitionOpenSinceMonth 761 non-null float64<br> 5 CompetitionOpenSinceYear 761 non-null float64<br> 6 Promo2 1115 non-null int64 <br> 7 Promo2SinceWeek 571 non-null float64<br> 8 Promo2SinceYear 571 non-null float64<br> 9 PromoInterval 571 non-null object <br> dtypes: float64(5), int64(2), object(3)<br> memory usage: 87.2+ KB</pre><pre>train_df.info()</pre><p><strong>output</strong></p><pre>&lt;class ‘pandas.core.frame.DataFrame’&gt;<br> RangeIndex: 1017209 entries, 0 to 1017208<br> Data columns (total 9 columns):<br> # Column Non-Null Count Dtype <br> — — — — — — — — — — — — — — — <br> 0 Store 1017209 non-null int64 <br> 1 DayOfWeek 1017209 non-null int64 <br> 2 Date 1017209 non-null object<br> 3 Sales 1017209 non-null int64 <br> 4 Customers 1017209 non-null int64 <br> 5 Open 1017209 non-null int64 <br> 6 Promo 1017209 non-null int64 <br> 7 StateHoliday 1017209 non-null object<br> 8 SchoolHoliday 1017209 non-null int64 <br> dtypes: int64(7), object(2)<br> memory usage: 69.8+ MB</pre><pre>test_df.info()</pre><p><strong>output</strong></p><pre>&lt;class ‘pandas.core.frame.DataFrame’&gt;<br> RangeIndex: 41088 entries, 0 to 41087<br> Data columns (total 8 columns):<br> # Column Non-Null Count Dtype <br> — — — — — — — — — — — — — — — <br> 0 Id 41088 non-null int64 <br> 1 Store 41088 non-null int64 <br> 2 DayOfWeek 41088 non-null int64 <br> 3 Date 41088 non-null object <br> 4 Open 41077 non-null float64<br> 5 Promo 41088 non-null int64 <br> 6 StateHoliday 41088 non-null object <br> 7 SchoolHoliday 41088 non-null int64 <br> dtypes: float64(1), int64(5), object(2)<br> memory usage: 2.5+ M</pre><h3>Data Preprocessing tasks</h3><p><strong>Cleaning</strong></p><pre>store_overview <strong>=</strong> DfOverview(stored_df)</pre><pre>store_overview.getOverview()</pre><p><strong>Observations:-</strong></p><ul><li>From the 10 columns, 6 have a null value.</li><li>The column with minimum missing values is in <strong>CompetitionDistance.</strong> and those can be filled with a median value.</li><li><strong>PromoInterval, Promo2SinceYear, and Promo2SinceWeek</strong> column has an equal number of counts and missed values which are 544.</li><li><strong>CompetitionOpenSinceYear, CompetitionOpenSinceMonth</strong> column has an equal number of counts and missed values.</li></ul><p>After fixing those errors in the data set we have saved the clean data and fed it to EDA visualizations.</p><pre>Stor_file.save_csv(stored_df, ‘../data/store.csv’)<br> Stor_file.save_csv(train_df, ‘../data/train.csv’)<br> Stor_file.save_csv(test_df, ‘../data/test.csv’)</pre><h3>Exploratory Data Analysis(EDA)</h3><p>Here we are going to visualize various features and the interaction between features. This step is necessary for clearly communicating our findings and insights using necessary plots.</p><p><strong><em>The Train and Test data set distribution</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/781/1*L9H91vIumi0C2JrkWNftjg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/707/1*rR7WdBCjQNVNbPaSp-9_yA.png" /></figure><p><strong><em>Sales behavior before, during, and after holidays(2013/14)</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7t7DPofUvNoz5tOx0q-8YA.png" /></figure><p><strong><em>Seasonal (Christmas, Easter, etc) purchase behaviors</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/390/1*MsO-AFuG8okVNUZYWaNhtg.png" /><figcaption><strong>Store type B has a higher number of customers than other store types.</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/1*2WUcakkdBIJIBh0NAMZ6pg.png" /><figcaption><strong>The stores have similar average sales and average customer count throughout the three years</strong></figcaption></figure><p><strong>Correlation between sales and the number of customers</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/928/1*1HPTu3WH8ug8kpClEPJxTg.png" /></figure><pre>● There is a strong positive correlation between sales and Customers.</pre><pre>● Promo has a positive correlation with sales and customers.</pre><pre>● State holidays and Days of the week have a negative correlation with sales and customers.</pre><p><strong>Trends of customer behavior during store open and closing times</strong></p><pre>● Customer behavior during store open counts 844,392 and customer behavior during store closed counts 172,817.</pre><pre>● Store ‘type B’ is the most opened store type on all weekdays and has its highest sales on Sundays than on the other days.</pre><p><strong>Impact of assortment type on sales and customers</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rp2aSrhOzE6iDzKETT3Bzw.png" /></figure><pre>● Store type B has the most selling and crowded assortment</pre><pre>● Assortment a and b are the most opened assortments on all weekdays and have their highest sales on Sundays than on the other days.</pre><p><strong>Affect sales by the distance of the next competitor</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fgSjhZ9i0s9KxnFX9a_7sA.png" /></figure><pre>● Stores with the smallest competition distance have the highest sales.</pre><pre>● The stores are located in the city center or near hospitals.</pre><pre>● Even though having a large distance between competitors is ideally considered great for sales, stores located in city centers will still get more sales regardless of competitors’ distance as there are more customers in city centers.</pre><p><strong>Average daily sales</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KqRuWJeURlh8Ai5Vg0iFAw.png" /></figure><pre>● Here we can see there is a very similar trend throughout the month between store A, C, and D.</pre><pre>● Store B has more sales but still, but the variation pattern is still similar.</pre><p><strong>Average daily customer</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EWtKcGHksBLfSAIsRV3kcw.png" /><figcaption><strong>● We can observe there is a similarity between the average sales and the average number of customers.</strong></figcaption></figure><p><strong>Summary of EDA Results</strong></p><p>● Store type B has a higher number of customers and sales from other store types.</p><p>● Store type B has the most selling and crowded assortment.</p><p>● Sales are highly correlated to customers.</p><p>● Promotion leads to an increase in Sales and Customers in all store types but the impact is not that match in-store type B.</p><p>● Store ‘type B’ is the most opened store type on all weekdays and has its highest sales on Sundays than on the other days.</p><p>● Assortment a and b are the most opened assortments on all weekdays and have their highest sales on Sundays than on the other days. The number of customers increases dramatically on Sundays for assortment a while it is similar to other weekdays for assortment b.</p><p>● Sales are increased during Christmas week, especially the week before. This might be due to the fact that people buy more beauty products or some common medicines for precaution during the Christmas celebration.</p><p>● Stores with the smallest competition distance have the highest sales. This indicates that the stores are located in the city center or near hospitals. Even though having a large distance between competitors is ideally considered great for sales, stores located in city centers will still get more sales regardless of competitors’ distance as there are more customers in city centers.</p><p><strong>5. Predictions</strong></p><p>LSTM</p><p>Load data</p><pre>train_sales = file_loader.read_csv(“../data/train.csv”)<br>data = train_sales.groupby(&quot;Date&quot;).agg({&quot;Sales&quot;: &quot;mean&quot;})<br>data</pre><p><strong>Output</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/177/1*aKQICBi-ygV46gMvb4NQIQ.png" /></figure><pre>scaler = StandardScaler()<br>scaled_array = scaler.fit_transform(data)<br>data[‘DataScaled’] = scaled_array</pre><pre>SIZE = len(data.DataScaled)<br>WINDOW_SIZE = 48<br>BATCH_SIZE = SIZE — WINDOW_SIZE * 2<br>EPOCHS = 200</pre><pre>DateTrain = data.index.values[0:BATCH_SIZE]<br>DateValid = data.index.values[BATCH_SIZE:]<br>XTrain = data.DataScaled.values[0:BATCH_SIZE].astype(‘float32’)<br>XValid = data.DataScaled.values[BATCH_SIZE:].astype(‘float32’)</pre><pre># Obtain shapes for vectors of size (,1) for dates series</pre><pre>DateTrain = np.reshape(DateTrain, (-1, 1))<br>DateValid = np.reshape(DateValid, (-1, 1))</pre><pre>print(“Shape of the training set date series: “, DateTrain.shape)<br>print(“Shape of the validation set date series: “, DateValid.shape)<br>print()<br>print(“Shape of the training set logarithm of sales series: “, XTrain.shape)<br>print(“Shape of the validation set logarithm of sales series in a stateless LSTM: “, XValid.shape)</pre><p><strong>output</strong></p><pre>Shape of the training set date series:  (846, 1)<br>Shape of the validation set date series:  (96, 1)<br><br>Shape of the training set logarithm of sales series:  (846,)<br>Shape of the validation set logarithm of sales series in a stateless LSTM:  (96,)</pre><pre><strong>output</strong><br>TensorShape([846, 1])</pre><pre># create tensor from each individual element<br>dataset = tf.data.Dataset.from_tensor_slices(series)<br>dataset</pre><pre># takes a window_size + 1 chunk from the slices<br>dataset = dataset.window(WINDOW_SIZE + 1, shift=1, drop_remainder=True)</pre><pre>datasetEx = tf.data.Dataset.from_tensor_slices(tf.range(10))<br>datasetEx = datasetEx.window(5, shift=1, drop_remainder=True)<br>for window in datasetEx:<br> print([elem.numpy() for elem in window])</pre><pre><strong>output</strong><br>[0, 1, 2, 3, 4]<br>[1, 2, 3, 4, 5]<br>[2, 3, 4, 5, 6]<br>[3, 4, 5, 6, 7]<br>[4, 5, 6, 7, 8]<br>[5, 6, 7, 8, 9]</pre><pre>dataset = dataset.flat_map(lambda window: window.batch(WINDOW_SIZE + 1))</pre><pre>dataset = dataset.map(lambda window: (window[:-1], window[-1:]))</pre><pre>dataset = dataset.batch(BATCH_SIZE).prefetch(1)</pre><pre>def windowed_dataset(series, window_size=WINDOW_SIZE, batch_size=BATCH_SIZE):<br> series = tf.expand_dims(series, axis=-1)<br> dataset = tf.data.Dataset.from_tensor_slices(series)<br> dataset = dataset.window(window_size + 1, shift=1, drop_remainder=True)<br> dataset = dataset.flat_map(lambda window: window.batch(window_size + 1))<br> dataset = dataset.map(lambda window: (window[:-1], window[-1:]))<br> dataset = dataset.batch(batch_size).prefetch(1)<br> return dataset</pre><pre>DatasetTrain = windowed_dataset(XTrain)<br>DatasetVal = windowed_dataset(XValid)</pre><pre>model.summary()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/529/1*6-mrdAYVEw2EpGtwCU8TXA.png" /></figure><pre>mlflow.set_experiment(“LSTM”)<br>mlflow.tensorflow.autolog()<br>history = model.fit(DatasetTrain, epochs=EPOCHS, validation_data=DatasetVal, verbose=1)</pre><p>fig = plt.figure()<br>plt.plot(history.history[‘loss’], label=”loss”)<br>plt.plot(history.history[‘val_loss’], label=”val_loss”)<br>plt.legend()<br>plt.show()</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/418/1*zG_Gc_31CbsqnEF_QjloHA.png" /></figure><p>For more: <a href="https://github.com/gezish/pharma_sales_pridiction">https://github.com/gezish/pharma_sales_pridiction</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=99a254933024" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Twitter-Data-Analysis]]></title>
            <link>https://medium.com/@enggezahegn.w/twitter-data-analysis-280d4e21cb9c?source=rss-ddfe514fac3d------2</link>
            <guid isPermaLink="false">https://medium.com/p/280d4e21cb9c</guid>
            <dc:creator><![CDATA[gezahegn wondachew]]></dc:creator>
            <pubDate>Fri, 29 Apr 2022 14:51:47 GMT</pubDate>
            <atom:updated>2022-05-03T06:32:01.625Z</atom:updated>
            <content:encoded><![CDATA[<p>I was participating in the pre-training challenge of 10Academy. It was a nice opportunity to learn how to extract, visualize, do sentiments, train and test machine learning models, build dashboards, deploy models, and so on within five days. So I am writing this article to share with you guys what I learn and which procedure I followed, and some of the results I got during my analysis.</p><h3>Introduction</h3><p>Twitter is one of the biggest social media platforms which allows many people to interact with each other by posting their thoughts called tweets, about certain topics or issues. Analyzing the tweets helps to track what’s being thought and can give interesting insights, into the sentiments of people, their opinions towards a particular topic, product, service, and the general trends in the community.</p><h3><strong>Objective</strong></h3><p>The main objective of this task is:</p><ul><li>To find the sentiment of the text data. That is to identify if the tweets have a Negative, Positive, or Neutral sentiment.</li><li>Train, test, and validate machine learning model</li><li>Deploy the best model which fits the data and build a dashboard</li></ul><h3><strong>Data set Overview</strong></h3><p>The data comes in two parts.</p><ol><li>The first will be around 100mb of a raw twitter data dump in JSON format. This data is collected using the following keywords: [‘inflation’, ‘fuelprice’, ‘fuelpricehike’, ‘ fuelprices’, ‘fuelshortage’, ‘foodprice’, ‘oilprice’, ‘oilprices’, ‘cookingoilprice’, ‘unemployment’, ‘unemploymentrate’, ‘economiccrisis’, ‘economichardship’],</li></ol><p>2. The second one will be around 300mb of the same format, but collected based on the original keyword plus country specific geocodes included e.g. ‘0.0263,37.9062,530km for Kenya’.</p><p>The data contains 24625 rows and 15 columns. Of which columns 4 have int, 9 have object and 2 have a float data type.</p><p><strong>Columns</strong>=[‘created_at’, ‘source’, ‘original_text’, ‘polarity’, ‘subjectivity’,’lang’, ‘favorite_count’, ‘retweet_count’, ‘original_author’,’followers_count’, ‘friends_count’, ‘possibly_sensitive’, ‘hashtags’, ‘user_mentions’, ‘place’]</p><h3><strong>Preprocessing</strong></h3><p>The data contained missing values. The number of missing value(s) are: 23665 and Columns having missing valueare: [‘possibly_sensitive’, ‘place’]. So I filled in missing values using the fillna method. We can observe that the column hashtags, hashtags_in_tweets, screen_name, and device have data type objects but they may contain numbers or other so it is good to change them to strings in order to have consistent data set</p><p>I did the preprocessing first by checking and removing if there is any duplication and cleaning the original text data. But the data indicates there aren’t don’t have duplicate values. Here to clean text I did the following step by step: removing non-English tweets, removing links, Punctuations, Numbers, and Special Characters and after all, I get the following.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*FcT4RCoTSQGkcVD0I8jP-Q.png" /></figure><h3><strong>Data Exploration and visualization</strong></h3><p>I try to group the data set using the original author, device, score (get using polarity), subjectivity_score ( gets using subjectivity). The following are the results:</p><ul><li>the tweets were made by 500 users. Most of them had made 50 tweets and one person had made 1 tweet.</li><li>most tweets were from android mobile device</li><li>neutral tweets are more retweeted, people with more followers and friends had made a neutral tweet.</li></ul><p><strong>Graphically:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/430/1*3KMfAS16RAaNw8ET-T3sjw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/528/1*QXbcweh2HOKXag-QWphXGA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/991/1*oNoxwa1fASOhjpbceFzOAw.png" /></figure><p>Here we can see tweets coming from device name android, web app, iphone have some negative tweets. Tweets from agorapulse app are positive. The following code gives:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/808/1*2vzBE_ly5QBm50WvSQsNPQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/467/1*eHFtHtJCvvUmq-OP0enMoQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/483/1*esrYbYpOvTkLQLMXOk32hw.png" /></figure><p>From the plots above we observe that:</p><ul><li>the user with more favorite_count have negative tweets</li><li>the user with more friends_count have very subjective tweets</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/494/1*Hfh3azd-LuYz4b59zEm3Mw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/719/1*_f_SCoPmypjfjBwTGB3cpQ.png" /></figure><p>From the plot above we can see that favorite_counts are created in between Jan 2022 and Jul, 2022. The diagram below represents a correlation between, friends_count,favorite_count_ followers_count vs subjectivity_score.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*JVGWpDEUgwsn8liB3HAOVw.png" /></figure><p>The following pictures below are word clouds of positive, negative, and neutral sentiments respectively.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*fCHwedawxqS3INgUTzAYwg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*BlUmk1y1rh3jgJJ8h-VGtw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/1*X0ZpGQ4i4clDLHWJOqhnXw.png" /></figure><h3>Topic modeling and sentiment analysis</h3><p><strong>Topic modeling</strong>:</p><p>Topic modeling is an unsupervised machine learning technique that’s capable of scanning a set of documents, detecting word and phrase patterns within them, and automatically clustering word groups and similar expressions that best characterize a set of documents. Since topic modeling doesn’t require training, it’s a quick and easy way to start analyzing your data. However, you can’t guarantee you’ll receive accurate results, which is why many businesses choose to invest time training a topic classification model.</p><p><strong>Sentiment Analysis</strong></p><p>Sentiment analysis is the process of detecting positive or negative sentiment in text. It’s often used by businesses to detect sentiment in social data, gauge brand reputation, and understand customers. Sentiment analysis focuses on the polarity of a text (positive, negative, neutral) but it also goes beyond polarity to detect specific feelings and emotions (angry, happy, sad, etc), urgency (urgent, not urgent), and even intentions (interested v. not interested). Depending on how you want to interpret customer feedback and queries, we can define and tailor your categories to meet your sentiment analysis needs. The following are the most popular types of sentiment analysis:</p><ul><li>Graded Sentiment Analysis </li><li>Emotion detection </li><li>Aspect-based Sentiment Analysis</li></ul><p><strong>Steps to Topic modeling and sentiment analysis with outputs</strong></p><ol><li><strong>Feature Extraction</strong></li></ol><p>After importing useful libraries and loading data, feature extraction is made by selecting(creating a data set) related or important features (rows and columns ) for topic modeling</p><p>2. <strong>Data Pre-processing</strong></p><p>This step includes the following major tasks: </p><ul><li>Stop words removal: words do not really signify any importance as they do not help in distinguishing two documents </li><li>Tokenization: Splitting the sentence into words </li><li>Lower casing: Converting a word to lower case </li><li>Lemmatization: lemmatization reduces the words to a word existing in the language</li></ul><p>3. <strong>Modeling</strong></p><p>It is a process of creating a dictionary of words with Id or corpora.</p><p><strong>LDA Model</strong></p><p>Latent Dirichlet Allocation (LDA) is an unsupervised algorithm that assigns each document a value for each defined topic. After LDA is applied the model is Checked using Perplexity which is used as an evaluation metric for language models.</p><p>In our analysis, I got <strong>Perplexity: -10.972058569345505 </strong>which is I think the model is good because the lower the score the better the model will be.</p><p><strong>Check the Coherence Score</strong></p><p>The Ldamodel Coherence Score on the given Tweets is approximately 0.485. And the LDA model (lda_model) we have created above can be used to compute the model’s perplexity, i.e. how good the model is. The lower the score the better the model will be The LDA model (lda_model) we have created above can be used to compute the model’s coherence score i.e. the average /median of the pairwise word-similarity scores of the words in the top</p><pre>Ldamodel Coherence Score/Accuracy on Tweets:  0.48474655206387596</pre><p>4. <strong>Data Visualization</strong></p><p>For visualization topic model exploration tool libraries (pyLDAvis ) are imported and applied to the modeled data so the result shows(bellow pic), that the bubbles on the left side represent a topic and the larger the bubble, the more prevalent is that topic. The topic model will be good if the topic model has big, non-overlapping bubbles scattered throughout the chart.</p><p>For our case I get this plot</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/659/1*dS-58wKjD7BgILSYXlIzGw.png" /></figure><p>5. <strong>Sentiments</strong></p><p>Analysis Polarity-based analysis results in the following table with no duplicates.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*SG8zkL3GeF7psGWlRLHdyA.png" /></figure><p>6. <strong>Train the data</strong></p><p>After scoremap is created data is spitted as training and test using sklearn. <strong>Stochastic Gradient Descent — Classifier (SGD-Classifier)</strong>:</p><ul><li> SGD Classifier is a linear classifier (SVM, logistic regression, a.o.) optimized by the SGD.</li><li> While SGD is an optimization method, Logistic Regression or linear Support Vector Machine is a machine learning algorithm/model. </li></ul><p>Here I used it to vectorize my train text data and finally, the data was trained and provided the following</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/487/1*yIvBXZdeOYNCluNkYVv9Dg.png" /></figure><h3>Conclusion</h3><p>Since the objective of the Training Score value leads to a generalization of the mode based on the results, it can be fitted or overfitted. Here the result shows 1.0 and it is a good value that leads to the generalization of the model. We can say the model is fit for such type of data.</p><p>On the other hand, since the value of the Validation Score is 84% and is still an experimental part Our model is yet to call the final model in this phase. Changing our model until we are satisfied with the validation score we get is expected.</p><p>Finally the next will see the Test Score which assure as the model is ready and for this phase, we had a Higher score and can be generalized as a better model.</p><p>You can find all codes in my <a href="https://github.com/gezish/Twitter-Data-Analysis">github</a></p><p>Thanks for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=280d4e21cb9c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>