<?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 Henok Tilaye on Medium]]></title>
        <description><![CDATA[Stories by Henok Tilaye on Medium]]></description>
        <link>https://medium.com/@tilaye.henok?source=rss-f21bd4116248------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*EgZnTLHOyQXqAwLt</url>
            <title>Stories by Henok Tilaye on Medium</title>
            <link>https://medium.com/@tilaye.henok?source=rss-f21bd4116248------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 15:21:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tilaye.henok/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[My First Data Warehouse]]></title>
            <link>https://medium.com/@tilaye.henok/my-first-data-warehouse-855cd3713fba?source=rss-f21bd4116248------2</link>
            <guid isPermaLink="false">https://medium.com/p/855cd3713fba</guid>
            <category><![CDATA[redash]]></category>
            <category><![CDATA[airflow]]></category>
            <category><![CDATA[data-warehousing]]></category>
            <category><![CDATA[docker-compose]]></category>
            <category><![CDATA[dbt]]></category>
            <dc:creator><![CDATA[Henok Tilaye]]></dc:creator>
            <pubDate>Sat, 23 Jul 2022 20:56:10 GMT</pubDate>
            <atom:updated>2022-07-24T20:45:41.342Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/851/0*iYDmI--6WdmNu1IV.jpg" /><figcaption>source: <a href="https://open-traffic.epfl.ch/index.php/downloads/">https://open-traffic.epfl.ch/index.php/downloads/</a></figcaption></figure><h3>What is a data-warehouse?</h3><p>I like the definition on <a href="https://en.wikipedia.org/wiki/Data_warehouse#Facts">Wikipedia</a> for this. I have paraphrased it a bit.</p><blockquote>Data-Warehouses are central repositories of integrated data from one or more disparate sources. It is a system used for <a href="https://en.wikipedia.org/wiki/Business_reporting">reporting</a> and <a href="https://en.wikipedia.org/wiki/Data_analysis">data analysis</a> and is considered a core component of <a href="https://en.wikipedia.org/wiki/Business_intelligence">business intelligence</a>. They are mostly used for creating analytical reports.</blockquote><h3>The Data Being Stored</h3><p>It was taken from <a href="https://open-traffic.epfl.ch/">pNEUMA</a>, an open dataset of naturalistic trajectories of half a million vehicles collected by a swarm of drones in a congested downtown area of Athens, Greece. This was initially a video feed from 10 drones tracking different vehicles on the road. Then this was turned into a trajectory describing format. In this data the vehicles are described with 4 columns, and the trajectories are described with 6 repeating columns that change with approximately 4 second time interval.</p><p>This data was collected on multiple hours for multiple days. And it can easily be downloaded as a CSV file from <a href="https://open-traffic.epfl.ch/index.php/downloads/">here</a>. For each CSV file the following apply:</p><ul><li>Each row represents the data of a single vehicle</li><li>The first 10 columns in the 1st row include the columns’ names<br>(track_id; type; traveled_d; avg_speed; lat; lon; speed; lon_acc; lat_acc; time)</li><li>The first 4 columns include information about the trajectory like the unique trackID, the type of vehicle, the distance traveled in meters and the average speed of the vehicle in km/h</li><li>The last 6 columns are then repeated every 6 columns based on the time frequency. For example, column_5 contains the latitude of the vehicle at time column_10, and column­­­_11 contains the latitude of the vehicle at time column_16.</li><li>Speed is in km/h, Longitudinal and Lateral Acceleration in m/sec2 and time in seconds.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SYDhJO4topR1Wjk2RP4BIw.png" /><figcaption>Sample of the CSV</figcaption></figure><p>As shown in the above image the column labels’ stop after the tenth column. But if we look closely at the data, its pattern will repeat every sixth column.</p><p>One row represents a single vehicle. And the duration for which the vehicles were tracked was not equal for all of them. This gives the CSV an odd shape where some rows would have smaller column counts. Which indicates that they were tracked for a smaller time span. Try to remember this since I will come back to it in the system design section.</p><h3>System Design</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/922/0*ShIkmYCOF6u7txvT" /><figcaption>System Diagram</figcaption></figure><p>The system has five main components: The data extraction and loading module, a PostgreSQL database, dbt for creating transformation, redash for dashboards, and finally Airflow for orchestrating different workflows. All of them will be running in docker containers for easy deployment.</p><p>Let’s start with the data extraction and loading module. This module is just a few Python scripts for reading the CSV files and dumping the data into the database. As I mentioned earlier, the data doesn’t have a rectangular shape. Some rows have shorter columns. And the columns label’s stop after some point. Pandas wasn’t reading it for me, so I wrote a simple parser that would read the CSV files and create pandas dataframes.</p><p>Yes, dataframes.</p><p>I decided to treat the data as two separate but related tables. One describing the vehicles and the other showing their trajectories. This two tables would be connected with a foreign key that is unique to the vehicles table and is also present in the trajectories table.</p><p>For each row from the original CSV, I took the first four columns and put them in the vehicles data-frame. I also added a 5th column that is a unique_id. After that, I took the rest of the columns from that row and created a new row with every next six subset of the columns. This makes up the trajectories data-frame. For each row created here I added the unique_id I created when taking out the vehicle information.</p><p>At the end, I will get two pandas.DataFrames that have the following shapes.</p><ul><li>vehicles: 5 columns, n rows where n is the original CSV’s row count</li><li>trajectories: 7 columns, n rows here n is sum of all columns in all rows in the original CSV describing the trajectory divided by 6.</li></ul><p>Finally, this module saves these two dataframes into their respective database tables. I used SQLAlchemy for the connection to the database. To make it easy to work with Airflow and not deal with dependencies, I containerized the whole module.</p><h4>Airflow</h4><p>I am running Airflow with docker from the <a href="https://airflow.apache.org/docs/apache-airflow/stable/start/docker.html">official sites</a> <a href="https://airflow.apache.org/docs/apache-airflow/2.3.3/docker-compose.yaml">docker-compos</a>e file. This compose file already used PostgreSQL for saving DAG metadata, so I decided to use it as my data store. I used a docker <a href="https://hub.docker.com/r/lmmdock/postgres-multi">image</a> that allowed me create separate database user accounts. I didn’t need to do this, but I wanted to separate the two users. <a href="https://hub.docker.com/r/lmmdock/postgres-multi">This</a> was the docker Image I used. I also modified the docker-compose file to use a custom docker network. This is to easily connect all the other components and use their container names as a URL for any request.</p><p>The first workflow is the containerized data extraction and loading module. Since the module has been containerized, I am able to used the <a href="https://towardsdatascience.com/using-apache-airflow-dockeroperator-with-docker-compose-57d0217c8219">DockerOperator</a> to easily run the module as a DAG. The next one runs my dbt transformations.</p><h4>dbt</h4><p>Next up, we have the dag transformation scripts. Once these are prepared, they will be run using Airflow. They will work on the data in the database and create new transformed views of the data. This new views can be saved to the database or be fed to some other process directly. For now, I will be saving it to the database.</p><h4>Redash</h4><p>The final component is the Redash tools. This will help in creating dashboards that visualize different kinds of insights that we will draw from the data and the transformations created by dbt. This will allow anyone to better understand the data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q6hNG3t9AFSN68xCwYeiKQ.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=855cd3713fba" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Location-Based-Refunding-Smart-Contract]]></title>
            <link>https://medium.com/@tilaye.henok/location-based-refunding-smart-contract-89d7893f5322?source=rss-f21bd4116248------2</link>
            <guid isPermaLink="false">https://medium.com/p/89d7893f5322</guid>
            <category><![CDATA[web3]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[geolocation]]></category>
            <category><![CDATA[smart-contracts]]></category>
            <dc:creator><![CDATA[Henok Tilaye]]></dc:creator>
            <pubDate>Mon, 18 Jul 2022 13:46:26 GMT</pubDate>
            <atom:updated>2022-07-19T04:05:00.436Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*F3zEoj0iIHkzE-vq.jpg" /><figcaption>Source: <a href="https://www.opensourceforu.com/2022/05/blockchain-developing-smart-contracts-using-standards-and-open-source-libraries/">https://www.opensourceforu.com/2022/05/blockchain-developing-smart-contracts-using-standards-and-open-source-libraries/</a></figcaption></figure><h3>Introduction</h3><p>The problem this will solve is compliance checking for some conditions and performing payment if the condition is fulfilled. There are a lot of similar scenarios that happen in our daily lives that fall into the above description. One example would be a delivery company delivering goods to a destination. The compliance to be checked might be that the goods get delivered before a specified time. Or we might check the condition of the goods like temperature, structural intactness, etc. Once these have been verified, a payment transaction will happen.</p><p>In this project, I have tried to capture the checks and transactions that are required for the above general scenarios using WEB 3 technologies. In the following sections, I will describe some concepts that are required to understand and replicate the project. Then, I will describe a more specific business problem I tried to solve. And Finally, I will explain the systems I built in detail.</p><h3>Topics to understand for this project.</h3><p>In this section, I will go over basic terminologies and concepts that are essential for understanding the implementation of the system. This will include the basics of blockchain, how it’s applied in projects such as this, and various components that are needed.</p><h3>What is a blockchain?</h3><p>It is a digital, distributed, cryptographically secure, immutable database or ledger of transactions. The transactions get collected until they reach some maximum size and get bundled into blocks. This block is then appended to the previous one in the chain. The contents of any of the blocks are all visible to anyone that wants to explore them. It is also close to impossible to change anything that is written on the chain. The ledger is also distributed on thousands of machines (nodes), which removes any single point of failure. All these properties enable a lot of cool applications. These include digital currency, very fast global transactions, keeping of permanent and transparent records, performing zero trust transactions, autonomous organizations, and digital assets. For a better understanding, I recommend <a href="https://www.investopedia.com/terms/b/blockchain.asp">this</a> blog.</p><h3>What is Ethereum?</h3><p>Ethereum is one implementation of a block-chain that was the first one to allow the execution of arbitrary programs on the network. These programs are known as smart-contract and are executed using the Ethereum virtual machine (EVM). The EVM is a software layer that runs on all nodes in the network and executes the programs on the network. There is an associated cost with every transaction. This cost is known as the gas fee. It is usually shown as a denomination of the native currency. The native currency of the network is known as Ether (ETH) and this denomination is 1 * 10 ^ -18 of one ETH.</p><h3>What are smart contracts?</h3><p>Smart-Contracts are small programs that help us specify conditions for a transaction to occur on the chain. This is the language we use to codify the rules for a contract. In the case of Ethereum, we have a language known as Solidity. Syntactically, It is very similar to any bracket-based language like C++ and JavaScript. Once a smart contract is written, it needs to be deployed to the blockchain we are working with. In the case of Ethereum, once it is deployed the EVM will convert the code into bytecode and run it on the network.</p><p>For any blockchain, there are usually two versions of the network. One is the MainNet and the other is the TestNet. Smart-Contracts are usually deployed first on the TestNet for testing purposes before deploying on the MainNet. Since it is impossible to make changes or push updates to the program once it is deployed, special care must be given to the testing of any smart-contract code. Any flaw or bug could have devastating financial consequences.</p><h3>What are dApps?</h3><p>These are applications that use decentralized infrastructures or a blockchain as their back-end. The app functionalities are endless just like the normal apps we all know and use. They are powered by smart contracts that live on the blockchain. These apps will send transactions to the smart contract to perform the functionalities they need. The functionalities could be social networks, file sharing, digital asset management, decentralized autonomous organizations (DAOs), etc.</p><h3>Transactions, Accounts, and Wallets</h3><p><a href="https://ethereum.org/en/developers/docs/transactions/">Transactions</a> on a blockchain are signed messages that result in a state change of the network. The signing of the messages is done using keys associated with accounts. These are public and private keys. This means public key cryptography is used here.</p><p><a href="https://ethereum.org/en/developers/docs/accounts/">Accounts</a> are entities that live on the global shared state of the network. Each account has a state associated with it. It also has a 20-byte address and can interact with other addresses. There are two types of accounts. Externally-Owned and Contract Accounts: The first one has no code associated with it and it is controlled by a private key. Any person that has the private key can transact with that account. The latter type has code that controls it. It is created from a special transaction that an Externally-Owned account makes, but Contract Accounts are also able to create other contract accounts.</p><p><a href="https://corewallet.trimplement.com/architecture/wallet-accounting-structure">Wallets</a> are a higher-level abstraction for accounts and also serve as a container for controlling multiple accounts. They can also be thought of as a gateway to many of the applications that come with the rise of WEB 3.</p><h3>Business need</h3><p>This project is aimed to be used when one party, for example, an employer, agrees to pay another party, for example, an employee, for being present in a certain geographic area for a certain duration. The employee’s phone sends its GPS location to a smart contract at a certain interval. Based on the agreed contract codified in an Ethereum smart contract, a cryptocurrency payment is executed when all the agreed conditions are met.</p><p>If at any point, the GPS sensor indicates that an employee is outside the range of the agreed GPS area, the contract state will be updated to indicate that it is out of compliance. The GPS data will be gathered from the participant’s phone sensor through a companion mobile app. The app will not require much interaction once it is installed. It will send out geographic location data at random hours throughout the day.</p><h3>System Design</h3><p>The system has three main components: A solidity smart-contract code, a react-native mobile app, and a react based web-app. The web app will be used by the employer to interact with the smart contract for adding new employees, specifying the required conditions (location, radius, payment amount, job duration) for the payment to happen. And the mobile app will be used by the employee to automatically send the location data to the smart contract. The smart contract would keep a record of employees and their requirements. It would also decide if an employee should be paid or not and perform the payment.</p><h3>Web-App</h3><p>The Employer will be the one using the Web-App. He/She can add employees to the smart contract with the specific condition that they must fulfill to get paid. The conditions are the following:</p><ul><li>The employees’ wallet address</li><li>The location of the job. This is described by a center point and a radius that will be a circle. The center point will be the latitude and longitude coordinates of the point.</li><li>The payment amount in Ether</li><li>The duration that the job will continue. This could be in days or hours.</li><li>The number of successful check-ins required</li></ul><p>They are also able to query the same condition for an employee using the employee’s public key. Both, the adding and querying will be a transaction this front-end client makes to the smart contract.</p><h3>Mobile-App</h3><p>This will be used for monitoring the employee’s location at random hours during the day. The interaction with the user is very minimal here. For this version of the app, once it has the location access permission, It will automatically send it to the smart contract. In a later iteration, I will make the user interact with the app to make sure that the phone is actually with them. For now, the only interaction is seeing where they are required to be and allowing the app to access their locations.</p><h3>Solidity-Contract</h3><p>This is where all the magic happens. The employee’s public addresses and job specifications come from the employer. Once those are recorded on the blockchain by the smart contract, the employees can send their locations to do the check-ins. The verification works by calculating the distance between the coordinates in the job specification and the last entered entry. If the distance is smaller than the radius, I update a counter variable on the employee’s profile. When creating this specification, the employer has to specify the minimum amount of successful verification that is required for an employee. The smart contract will use that number as a threshold to decide if the employee should be paid or not. If the counter state that is updated on each successful verification is greater than the set minimum amount, the funds will be transferred. If not, that amount is refunded to the employer.</p><p>For now, the payment doesn’t happen at the end of the set time. Once the job period has passed, the employee has to make a “pay me” request to the smart contract from the app. The smart contract would do the final check of comparing the counter state with the minimum required count state to see if they should get paid.</p><p>Regarding access to the functions, I am using the <a href="https://www.educative.io/answers/what-is-restricted-access-in-solidity"><strong>Guard check pattern</strong></a><strong>. </strong>These are custom access modifiers that allow me to restrict access to the functions to only the employer and employees. The employer has access to the function that allows adding of new employees. And the employee only has access to the function that takes in their coordinates and performs the check and state update. This stops any unauthorized person or smart contract from accessing the functionalities.</p><h3>Conclusion</h3><p>This same system can also be done without dealing with blockchain concepts. But we would have to use centralized services like Google to store the employees’ location data. The solution here allows us to keep all of that out of the hands of those companies and allow us to get the functionalities we want. You can find the implementation for this project on my <a href="https://github.com/Hen0k/Location-Based-Refunding-Smart-Contract">GitHub</a>. I am also working on a lot more things, check out my other <a href="https://medium.com/@tilaye.henok">blogs</a> and connect with me on <a href="https://www.linkedin.com/in/henok-tilaye-b18840151/">LinkedIn</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=89d7893f5322" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Speech-to-Text Data Collection with Kafka, Airflow, and Spark]]></title>
            <link>https://medium.com/@tilaye.henok/data-engineering-speech-to-text-data-collection-with-kafka-airflow-and-spark-115fe5d74321?source=rss-f21bd4116248------2</link>
            <guid isPermaLink="false">https://medium.com/p/115fe5d74321</guid>
            <category><![CDATA[airflow]]></category>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[nlp]]></category>
            <dc:creator><![CDATA[Henok Tilaye]]></dc:creator>
            <pubDate>Sat, 09 Jul 2022 20:58:13 GMT</pubDate>
            <atom:updated>2022-07-10T12:06:10.989Z</atom:updated>
            <content:encoded><![CDATA[<h3>Data Engineering: Speech-to-Text Data Collection with Kafka, Airflow, and Spark</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FEXevj-Kc1GVxG3O66jhLw.png" /><figcaption>source: <a href="https://www.makeuseof.com/mac-screen-recorder-no-audio/">https://www.makeuseof.com/mac-screen-recorder-no-audio/</a></figcaption></figure><h3>Introduction</h3><p>These days, having a good machine learning dataset is considered an asset. There are a lot of datasets for different ML related tasks. Image Classification, audio recognition, and object detection are just a few of these tasks. In this particular project, we were tasked to build a system that allows us to collect audio data for any language where text samples are available for. We will be using it for the Amharic language.</p><p>In a previous post, I talked about a Speech-to-Text (STT)model that I helped build while training at 10 Academy. This project would help the machine learning engine that we built then to retrain when there is new data available.</p><h3>Project Objective</h3><p>The main aim of this project is to build a large-scale, stream processing based distributed system that enables data collection for a STT model. This tool would allow the continuous retraining of a STT model whenever new samples are available. It would allow any volunteer to recite a sentence and send the text-audio pair to our system. The general approach we have chosen to proceed with is described in the next section.</p><h3>Tech Stack Used</h3><p>The main tools we used in these project are <a href="https://kafka.apache.org/">Apache Kafka</a>, <a href="https://airflow.apache.org/">Apache Airflow</a>, and <a href="https://spark.apache.org/">Apache Spark</a>. In this section, I will describe what each one does and that will show why needed to use them.</p><p>Kafka provides a unified, high-throughput, low-latency, horizontally scalable platform. It is used in production in thousands of companies. We have chosen Kafka because it is a pretty fast stream processing solution. In this project, Kafka is used for publishing and subscribing to streams of audio and text records/messages. It serves as a data bus which all other components use to communicate. And it also reduces the complexities that would have arisen if we had adopted the request response paradigm. It reduces the number of communication lines that would have been used.</p><p>The next component is Spark. “Spark is a unified engine for large-scale data analytics”. It is a distributed task execution engine that can be used to execute complex workflows on a large scale dataset. It also has a<a href="https://data-flair.training/blogs/apache-spark-lazy-evaluation/"> lazy evaluation</a> nature, making it very fast. This just means spark won’t actually execute the operations until an action triggers it. Using spark allows us to perform our data transformation in a batched/stream manner without decreasing our systems performance.</p><p>The last main component is Airflow. This is another tool from Apache that helps us orchestrate the different tasks in our systems. It allows us to define the sequence in with operation will be performed. It also provides a nice User interface where we can easily monitor the status of each task in the system. I will explain what this task are in a future section, but to mention a few: fetching data from a data lake, publishing data to the Kafka brokers, getting data out of Kafka and running the spark transformations, storing processed data to a data lake.</p><h3>Dataset and Exploratory Data Analysis (EDA)</h3><p>We used the<a href="https://github.com/IsraelAbebe/An-Amharic-News-Text-classification-Dataset/tree/main/data"> Amharic news text classification dataset</a> in this work. The dataset is primarily used as a source for the text part of the final dataset. These will be displayed to the users on the front-end and allow them to record the text’s audio equivalent and send it back to us.</p><p>The dataset contains various news data collected from various sources, with the goal of classifying Amharic news using machine learning classifiers. The data was obtained from a previous work of a researcher, <a href="https://github.com/IsraelAbebe/An-Amharic-News-Text-classification-Dataset/tree/main/data">Israel Abebe</a> and consists of six columns: headline, category, data, views, article, and link.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LzDP52o_4sZO2t9_" /><figcaption>The first five rows of the dataset</figcaption></figure><p>Since our goal is to extract sentences for building our STT dataset, we took tow columns from this dataset: category and article. The reason for choosing these fields is that we can get a number of sentences from a single article by segmenting it with sentence end marks. And we kept the category to allow a user to choose the text the want to recite. For each article, we have six defined possibilities of text category as shown in the following bar plot; sport, politics, business, entertainment, national, and international news.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*b4Zi4bk8dzdqRAr8" /><figcaption>Bar Char showing distribution of sentences in the available text categories</figcaption></figure><p>While processing the data, we discovered that there are no missing values and that all of the fields contain only string object type data. We segmented out and took texts that included less than 15 words associated with their category to get precise sentences that fit our requirements. Following that, we saved our transcription text data in our project data folder for the upcoming processes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8sNQTWR7g9EHIdq9" /></figure><h3>What was Implemented?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*04M2T6W_5BwATl8hK4ORyg.jpeg" /><figcaption>Our STT System Design Diagram</figcaption></figure><p>We started our implementation with the front-end part of the system. This was a react based user interface that the users would interact with. It would allow a user to fetch a sentence, skip and fetch another sentence, record an audio, listen to the audio, clear and re-record the audio, and finally send the audio and sentence to the back-end. All these functionalities were implemented using the ReactJS front-end framework.</p><p>The front-end interacts with a Flask back-end API. It is from this API that the front-end get’s new sentences and also sends the text-audio pairs. In addition to the front-end, this API communicates with a Kafka instance that is the central bus of our system. When a request comes from the front-end, the back-end consumes one message from a Kafka topic. That one message is a sentence that was already published on that particular topic. The back-end then sends the message to the front-end. The API also acts as a publisher client because it sends the text-audio pairs it gets from the front-end to another Kafka topic.</p><p>We are using a dockerized version of Kafka. In our current configurations, there are two zookeeper instances and two brokers. Everything else is interacting with the exposed ports of the brokers. The docker-compose file we are using for this, also starts up a Kafka visualization web-app known as <a href="https://github.com/obsidiandynamics/kafdrop">Kafdrop</a>. This allows us to have an intuitive interface where we can easily check the status of our Kafka instance. This includes seeing if messages are published on the topics, checking whether the brokers are up and running, seeing when new messages come in, etc.</p><p>Another component is the spark jobs that clean and validate the audio in the text-audio pairs. The spark job gets initialized by using airflow. The spark component first receives a list of audio text pairs and loads them to a spark data frame where they will be distributed among various spark clusters. We first remove long silences in the audio clips and then remove any noise. Finally the list of cleaned audio text pairs gets stored in amazon s3 bucket.</p><h3>Lessons learned</h3><p>In this work we have been learning about creating and setting-up Apache Kafka clusters like creation of a Kafka topic in the Kafka cluster and working with Apache Airflow and Apache Spark. We have been using the airflow for orchestration of workflows and understand the use of directed acyclic graphs (DAGs) in Airflow. In Addition to this, We have got ideas of Structured Streaming to process streaming data. Furthermore, we got a chance to transform and load speech data from the Kafka cluster using Spark. We’ve learned how Spark is used as a stream processing system.</p><h3>Future plans</h3><p>Developing a robust and fault tolerant pipeline to store speech and text can pave a way for training a good Machine Learning Model. In this project we have managed to collect text and audios of Amharic language and store them in s3 bucket. Currently available audios and transcripts for Amharic language are few to develop an accurate machine learning speech recognition model.</p><p>Putting this into account, we can collect a larger amount of text files and request for volunteers to record audios of those text files. Hence, the collected data will be stored in an S3-bucket and ready to be trained to a model.</p><p>The other thing is our front-end can access the text from the flask API which accesses from the Kafka consumer, but when it accesses from the Kafka consumer we want it to access a text randomly from the Kafka cluster. In future, we plan to make this possible.</p><p>You can find the implementation of this project in <a href="https://github.com/Hen0k/Speech_to_text_data_collector">my GitHub repository</a>.</p><h4>References</h4><ul><li><a href="https://acloudguru.com/hands-on-labs/installing-a-kafka-cluster-and-creating-a-topic">Installing a Kafka Cluster and Creating a Topic — Hands-on Labs | A Cloud Guru</a></li><li><a href="https://dev.to/florimondmanca/breaking-news-everything-is-an-event-streams-kafka-and-you-2n9j">Breaking News: Everything Is An Event! (Streams, Kafka And You) — DEV Community</a></li><li><a href="https://cloudblogs.microsoft.com/opensource/2018/07/09/how-to-data-processing-apache-kafka-spark/">How to process streams of data with Apache Kafka and Spark (microsoft.com)</a></li><li><a href="https://medium.com/vantageai/keeping-your-ml-model-in-shape-with-kafka-airflow-and-mlflow-143d20024ba6">Keeping your ML model in shape with Kafka, Airflow and MLFlow | by Mike Kraus | VantageAI | Medium</a></li><li><a href="https://towardsdatascience.com/why-apache-airflow-is-a-great-choice-for-managing-data-pipelines-48effcce3e41">Why Apache Airflow Is a Great Choice for Managing Data Pipelines | by Kartik Khare | Towards Data Science</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=115fe5d74321" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Beyond Correlation: Causal Inference]]></title>
            <link>https://medium.com/@tilaye.henok/beyond-correlation-causal-inference-955ce155e0c6?source=rss-f21bd4116248------2</link>
            <guid isPermaLink="false">https://medium.com/p/955ce155e0c6</guid>
            <category><![CDATA[bayesian-machine-learning]]></category>
            <category><![CDATA[causal-inference]]></category>
            <category><![CDATA[causality]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[breast-cancer]]></category>
            <dc:creator><![CDATA[Henok Tilaye]]></dc:creator>
            <pubDate>Sat, 02 Jul 2022 20:45:11 GMT</pubDate>
            <atom:updated>2022-07-03T23:25:47.747Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rc4qNGyfi05OCcQcva2Vaw.png" /><figcaption>Causal Graph from features in the Breast Cancer dataset</figcaption></figure><h3>Literature review</h3><h3>What is causal inference?</h3><p>Causal inference is the process of answering questions with a “why” nature. this is to mean determining reasons for why a variable exists or is somehow manipulated. This relation is far stronger than correlation. Correlations are just the co-evolution of variables for a long period of time. But in the case of causality, co-evolution alone is not enough.</p><p>Let’s take the following example: A school wants to increase its students’ exam grades. And since we are in the age of technology, they want to provide each student with a tablet computer. Now, just looking at the grades for students with and without tablets we might see an increase. But that doesn’t mean it is caused by the tablets the student’s were given.</p><p>There is one more variable that we are not considering here. And that is, the schools that are able to afford to buy each of their students tablet’s are financially strong enough to provide all required facilities and hire the best teachers. This is called a confounding variable. A third variable that is affecting the first two variables, students grades and them owning tablets. In order to make this experiment legitimate, we need to keep this and all confounding variables constant.</p><h3>Methodologies</h3><p>Generally speaking, we can classify methodologies related to causal inference into three categories:</p><ul><li>Experiment/Field study/Randomized-Controlled Trials: Actively divide subjects into control and treatment groups randomly to evaluate the causal link between treatment and outcome of interest. Randomness is key to ensure trustworthy results.</li><li>Quasi-Experiment: Causal inference based on observational data. Since there are intentional or unintentional randomness in the data, researchers need to choose methodologies carefully with specific assumptions.</li><li>Natural Experiment: Empirical studies that expose subjects to treatment and control groups taking advantage of natural events, like <a href="https://www.jstor.org/stable/2006669">lottery draw</a>, <a href="https://www.jstor.org/stable/2937954">birth of the month</a>,<a href="https://davidcard.berkeley.edu/papers/mariel-impact.pdf"> immigration law</a>, etc. Since the randomness mainly comes from the natural events that have already happened, researchers can analyze the causal link with observational data.</li></ul><h3>Overview of the data source and formats</h3><p>The data provided is from a researcher on Breast Cancer Diagnosis and Prognosis Via Linear Programming. I downloaded the dataset from Kaggle. The features in the columns are computed from a digitized image of a fine needle aspirate (FNA) of a breast mass. They describe characteristics of the cell nuclei present in the image.</p><p><strong>Attribute Information:</strong></p><p>1. ID number</p><p>2. Diagnosis (M = malignant, B = benign)</p><p>Ten real-valued features are computed for each cell nucleus:</p><p>a. radius (mean of distances from center to points on the perimeter)</p><p>b. texture (standard deviation of gray-scale values)</p><p>c. perimeter</p><p>d. area</p><p>e. smoothness (local variation in radius lengths)</p><p>f. compactness (perimeter² / area — 1.0)</p><p>g. concavity (severity of concave portions of the contour)</p><p>h. concave points (number of concave portions of the contour)</p><p>i. symmetry</p><p>j. fractal dimension (“coastline approximation” — 1)</p><p>The mean, standard error and “worst” or largest (mean of the three largest values) of these features were computed for each image, resulting in 30 features. For instance, field 3 is Mean Radius, field 13 is Radius SE, field 23 is Worst Radius. All feature values are recorded with four significant digits.</p><p>The data had a column with null values. It also has an ID column that doesn’t contribute valuable information to the problem at hand. For this reason I have removed these two columns. Afterwards, there were no null values in the data. The next thing I did was looking at the distribution of the diagnosis in the dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/431/0*3WlmjHy47HtjmWRu" /></figure><p>Next up was bi-variate and multivariate analysis of the different variables. For the bi-variate analysis, I used pair plots. But, since the number of columns was too big, I had to create the plots in groups. For the multi-variate analysis, I calculated the correlation of the variables.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pFbQ0BonPgmjWfI2" /></figure><p>But since we are not interested in which variable is correlated with which one, I removed one for every pair of correlated variables that had a correlation index of greater than 90. Another reason for doing this is to reduce the number of columns for computational efficiency. Also by keeping one of the correlated variables, I ensure that I am not losing a lot of information.</p><p>This is the correlation heat map for the variables I am left with.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gvbFOi7DWBPcCE9e" /></figure><p>Up To now, I have removed columns that don’t contribute a lot to the analysis and I am left with 16 columns from the original 32. From now on, I will be using this version of the dataset.</p><h3>Techniques used to perform causal inference</h3><p>Common frameworks for causal inference include the causal pie model (component-cause), Pearl’s structural causal model (causal diagram + do-calculus), structural equation modeling, and Rubin causal model (potential-outcome), which are often used in areas such as social sciences and epidemiology.</p><p>The <strong>causal pie model </strong>is used in epidemiology to figure out the causes for different diseases. As its name suggests, It uses pie charts. Each slice of the pie will be the different contributing causes for an event or a theoretical causal mechanism. This is called a sufficient cause. These slices are made up of component factors, otherwise known as component causes. A component cause that appears in every pie is called a necessary cause as the outcome cannot occur without it.</p><p>Pearl’s structural causal model uses a causal diagram to visualize causal relationships. This diagram is a directed acyclic graph that has events (causes/effects) as vertices and their causal relationships depicted as the edges with directions. This graph can first be generated using expertise in the phenomena being discussed. There are also algorithms for generating the diagrams from the available data.</p><p>For this project, I used the causal-graph to visualize the causal relationship between the above stated variables in the data. I used the <a href="https://causalnex.readthedocs.io/en/latest/">Causalnex</a> library to learn the graph structure from the data. If it were possible to get an expert in the matter, I could have created the graph manually based on the experts opinion. But since there is none for now, I have generated it based on the data.</p><p>I first split the data into a training and testing set. Then I used versions of the training set to learn the causal-graph structure. I started with all the columns to get a baseline graph. Then, I used slices of the training data to check the stability of the baseline graph. The idea was to use gradually increasing portions of the training data, then generating a graph using the portions, and finally checking its similarity with the baseline graph. This is calculated as the Jaccard index or Intersection over Union (IoU) of the graph edges. The following is the baseline causal-graph.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3rTKBZsuKjw7MMyb9mDpXg.png" /><figcaption>Baseline Causal-Graph with all columns of training data.</figcaption></figure><p>The portion sizes I used were 40% and 70%. And when calculating the IoU between each, I got the following.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/470/1*h7BnNYwxiUYTeK-kgb-y5Q.png" /><figcaption>IoU between the causal-graphs</figcaption></figure><p>The above values are not that good. My opinion is that there are too many columns. So, the next step is to keep only the columns that had a direct relation to the “diagnosis” column in all three causal-graphs which are shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/470/1*z8Y_qmmUlcQqyrBmaCJICQ.png" /><figcaption>Columns I kept</figcaption></figure><p>The graphs generated with only the above columns were more cleaner, and they had better IoU value among themselves. But there is still room for improvement. Below is the new baseline generated using the above columns.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qi7YnmBUFRNI6O6fA4ErxA.png" /><figcaption>New-Baseline causal-graph with a subset of the original columns</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/464/1*cPrF7-qUtbRs43GV0nKh9g.png" /><figcaption>IoU values of the causal-graphs with the subset data</figcaption></figure><p>The next step was to train a Bayesian Network model using these graphs. But before that I discritized my columns using the automated discritizer available in the <a href="https://medium.com/quantumblack/whats-new-in-causalnex-v0-10-67b16005e596">causalnex</a> library. This automatically creates bins for where each value in a column would fall in and only return the index of the bin. For a better explanation read <a href="https://medium.com/quantumblack/whats-new-in-causalnex-v0-10-67b16005e596">this</a> blog.</p><p>After training the Bayesian models on these new smaller graphs, I evaluated their performances on the test dataset I created earlier. The metric results were very close. This confirms our previous point about the graphs stability.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/873/1*h15FE_yUgzazxGUoEnAOfg.png" /><figcaption>Metrics for the model with the new baseline causal-graph</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/692/1*XSDxUQgboAaDD8u9Uf8a_g.png" /><figcaption>Metrics for the model with the new causal-graph using 40% of the data</figcaption></figure><h4>Conclusion</h4><p>This project was my first introduction to the world of causality. And as such, I might not have all the concepts right. Feel free to drop me a comment about anything that is not clear. I will be updating the blog if my understand changes. You can find all the code in my <a href="https://github.com/Hen0k/causal-inference">github</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=955ce155e0c6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An End-to-End Web3 dApp with the Algorand Blockchain]]></title>
            <link>https://medium.com/@tilaye.henok/an-end-to-end-web3-dapp-with-the-algorand-blockchain-d91cefe13dbc?source=rss-f21bd4116248------2</link>
            <guid isPermaLink="false">https://medium.com/p/d91cefe13dbc</guid>
            <category><![CDATA[algorand]]></category>
            <category><![CDATA[nft]]></category>
            <category><![CDATA[web3]]></category>
            <category><![CDATA[certification]]></category>
            <category><![CDATA[blockchain]]></category>
            <dc:creator><![CDATA[Henok Tilaye]]></dc:creator>
            <pubDate>Sat, 18 Jun 2022 20:51:43 GMT</pubDate>
            <atom:updated>2022-06-19T19:25:12.322Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JdjWN6f1G2jp6MVRqZ01vA.png" /><figcaption>source: <a href="https://www.weforum.org/agenda/2022/02/web3-transform-the-internet/">https://www.weforum.org/agenda/2022/02/web3-transform-the-internet/</a></figcaption></figure><h3>WEB3 Overview</h3><p>WEB3 is a decentralized internet where users will have a say in who owns data, content, and platforms. Compared to WEB2, it provides more interoperability between systems than WEB2 does. There is no vendor lock-in. Puts a lot of the trust from third parties in smart contracts allowing individuals to transact without depending on mutual trust.</p><p>Enabling all of these cool features is an underlying technology known as Blockchain. A public ledger of transactions that are stored on multiple nodes in a tamper-proof manner. When we bring smart contracts into the equation we enable transactions to occur without middlemen. Smart contracts are on-chain logic programs that execute when a set of conditions are fulfilled. Reducing the effect of bad faith by putting the burden on fulfilling the conditions and not on trust.</p><p>Users get access to the world of WEB3 using digital wallets. WEB3 enables products and experiences that adapt to peoples’ wallet inventories. Wallets are interfaces to systems, They are a form of identity, that can be used to create site accounts and authenticate users. They are like portals or passports for the new world that is WEB3.</p><p>Wallets don’t hold any assets. They hold records of ownership associated with your wallet’s address on a public decentralized ledger. When making a transaction on the blockchain (adding entries on the ledger) you will have to sign a message that verifies you possess the wallet’s keys. Wallets can be thought of as a personal and unique cryptographic key with 3 main components:</p><p>1. public wallet address</p><p>2. secret phrase</p><p>3. private cryptographic key</p><h3>The WEB3 Technology Stack</h3><p>The WEB3 stack is not as mature as what we have for WEB2. It will keep evolving into something that will encompass even newer aspects of development paradigms. But, as of now, in June 2022, we have four layers in the stack. I will be exploring each layer going from bottom to top. The order is as follows. Protocol Layer, Infrastructure / Category Primitives, Use Case Layer, and Access Layer.</p><p>Inside the protocol layer, we have all the different types of blockchains and cross-chain bridges that facilitate value transfer between different blockchain networks. Next are Infrastructure / Category Primitives. These are interoperable building blocks that have very specialized functionalities. The functionalities include communication protocols, data analytics platforms, decentralized data storage, and much more. All of this relies on the protocol layer or the blockchains and bridges.</p><p>The use case layer is where all the protocol and infrastructure layer systems come together. This is where systems that rely on both of the below layers reside. For example, the decentralized blogging platform <a href="https://mirror.xyz/">Mirror</a> uses the storage protocol <a href="https://www.arweave.org/">Arweave</a> to store data. At the top of the stack is where we will find user-friendly interfaces to the world of WEB3. These include wallets, browsers with integrated wallets like Brave, and web2 sites like Reddit and Twitter where crypto enthusiasts exist. Making this web2 site a gateway for new users.</p><h3>Problem Description</h3><p>I’m building a system that would allow 10 Academy to mint and distribute NFT certifications to its trainees once they fulfill the requirements. And for this, I will need a front-end where the team from 10 Academy would verify trainees, where trainees would opt-in for the NFTs. A back-end system that would handle most of the logic and a blockchain that would allow me to mint and assign ownership of the NFTs to the students. I will be using Algorand for my blockchain, Flask for the back-end, and ReactJS for the front-end. Next, I will explore what each component would handle.</p><p>The front-end will allow all users (trainees and staff) to authenticate using an email and a password. Once logged in, a person connects their wallet. They would then be presented a view corresponding to the role their public key or email is assigned. Staff members can receive opt-in requests from the trainees and approve or decline the requests for the certifications based on some criteria. If a trainee fulfills the criteria they (the staff) can mint and send them their NFT. For the trainee, the front-end would allow them to place their opt-in request and monitor the status of their request.</p><p>The backend handles the business logic of the app. This includes identifying the roles of the users and allowing the staff to mint the NFTs and distribute them. It will take requests from the front-end and also make requests to the blockchain. There is also a database for holding the user credentials and trainees’ status.</p><h3>The Algorand Blockchain</h3><p>Algorand is a <strong>Proof of Stake (POS)</strong> based blockchain that is capable of hosting other decentralized applications. Making it similar to Ethereum. It makes creating and transferring any instrument of value such as fungible tokens, NFTs, and security tokens a lot easier since it doesn’t require writing a smart contract for them. They can be created with a single transaction. It also has a very fast transaction throughput, finalizing a transaction in about four seconds. You can learn a lot more about it from <a href="https://developer.algorand.org/docs/">here</a>.</p><p>It has a native currency known as ALGO. There are more than 26 million accounts on the Algorand network. This number has been having a sharp increase since July of 2020. At the time of this blog, it had a circulating supply of 14 Billion and a market capital close to 2 Billion. I found these stats on the Algorand blockchain explorer site located <a href="https://algoexplorer.io/top-statistics">here</a>.</p><p>The reason I am working with Algorand for this project is because of the ease with which I can mint the certification NFTs, and also the valuable support that the team is providing. I also find their documentation quite useful.</p><h3>Transactions</h3><p>Before explaining the workflow, I will explain the different types of transactions on the blockchain that are required to mint and transfer an NFT on Algorand. These are creating the asset (NFT), opting in, and sending the asset. For making all these transactions, I will be using the python SDK provided by Algorand</p><p>The asset creation step is a single transaction where I specify properties of the NFT to be minted. This includes four accounts; manager, reserve, freeze, and clawback that have permission to perform future actions. This is also where I specify where the certificate PDF or JPEG would be located. Once, these parameters are filled, The creator (staff) would sign on the transaction and submit it to the blockchain. Once this is successfully carried out, the staff account would be the owner of the certificate.</p><p>The next transaction we need is opt-in. This is made before accepting any new asset into our accounts. Opting in on Algorand is a single transaction where an account would request a transfer of an asset from a holder account to their account. One interesting parameter to note in this transaction is the amount of the asset we request. It has to be set to zero. Once, this transaction is submitted and finalized, the account that opted in (the trainees) is ready to accept the asset.</p><p>The last transaction is a transfer transaction, which is again a single transaction performed to make the transfer of ownership from the staff to the trainee’s account.</p><p>Now, let’s dive into the app’s workflow.</p><h3>dApp Workflow</h3><p>The users first need to create an account and connect their Algorand wallets to the dApp. On the trainees’ front end there will be a call to action button that would allow them to opt-in for the certification. This is just a simple post request to the back-end sending the trainee’s public key. Once this is done, the staff would be able to see the request and approve or decline it. This also sends a simple post request with the staff’s public key and metadata for the NFT.</p><p>Once these two steps are done, the back-end would first generate the NFT creating transaction, setting the staff public key as the creator, and using the metadata sent earlier. At first, this is just an unsigned transaction. It will be sent to the staff to be signed with their wallet’s private key. Once signed, it will be submitted to the blockchain using the back-end. This workflow of generating unsigned transactions by the back-end, sending them to the user front-end to be signed with their wallet, and finally submitting them to the blockchain by the back-end follows for all transactions.</p><p>Once the NFT is minted, the next transaction will be the opt-in transaction. For this, the back-end uses the trainees’ wallet public key for the receiver field, the NFT asset id, and the staff public key as a sender. Then following the above workflow, the transaction is signed and submitted.</p><p>The next and final step is to make the asset transfer transaction. This also uses the same workflow of generating the transaction on the back-end, signing it with the staff wallet, and submitting it. After this step succeeds, the trainee will have their certification NFT in their wallet.</p><h3>My Progress</h3><p>So far I have implemented some parts of the above-described workflow. I will split this into front-end and back-end sections.</p><p>On the front-end, I was able to create two forms for signing up new users and signing in. These two forms have been integrated with the back-end. Once the user logs in, they will land on a page allowing them to carry out the workflows. But for now, I only have the staff’s view where they have a form for submitting the NFTs metadata.</p><p>I still need to add the following features:</p><ul><li>Add a view for the trainee to opt-in and monitor the progress</li><li>Add a view for the staff showing them who has opted in</li><li>Proper usage of React-Routes for the different role-based views</li><li>Integrating a wallet for signing all the transactions</li></ul><p>On the back-end side, I have set up API endpoints for sign-up, log-in, and log-out. I have also managed to generate NFTs, opt-in, and transfer the NFT to a separate account using the Algorand sandbox. The sandbox is connected to the Algorand testnet. These transactions are performed assuming that I have all the wallet information of the user. Meaning both the private and public keys. This doesn’t follow the workflow described above. Once I have the wallet integration on the front end, this will be replaced.</p><p>These are features I am still adding to the back-end:</p><ul><li>More endpoints to handle requests from the trainee and staff views</li><li>Integrating the standalone transaction scripts to the proper endpoints</li></ul><h3>Lessons Learned</h3><p>When starting this project I only knew the basics of seeing up flask APIs. In just a single week, I was able to learn a lot more concepts and implementation details. I have listed them out below.</p><ul><li>Basics of setting up a React Project</li><li>Setting up a Flask project using a factory design pattern</li><li>User authentication and authorization using JWT tokens (still learning)</li><li>Creating React components for forms</li><li>What WEB3 is, why we need it, how it works</li><li>The WEB3 stack</li><li>Why wallets matter in WEB3</li><li>How wallets can be used as a single sign-on for WEB3 dApps</li><li>What a blockchain is, How Algorand is different</li><li>Performing transactions on the Algorand blockchain</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d91cefe13dbc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Amharic-Speech-To-Text]]></title>
            <link>https://medium.com/@tilaye.henok/amharic-speech-to-text-c2bcb4aaf4ee?source=rss-f21bd4116248------2</link>
            <guid isPermaLink="false">https://medium.com/p/c2bcb4aaf4ee</guid>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[speech-to-text-api]]></category>
            <category><![CDATA[bi-lstm]]></category>
            <dc:creator><![CDATA[Henok Tilaye]]></dc:creator>
            <pubDate>Thu, 09 Jun 2022 20:55:52 GMT</pubDate>
            <atom:updated>2022-06-12T03:17:12.364Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*y4DGCEeSHPJJ4ePz" /></figure><h3>Abstract</h3><p>This report explains how a speech to text system can be built for Amharic and Swahili languages. The following steps were taken to finish this project. Data collection, cleaning, featurizing, modeling, and deployment. I will be explaining each step in their respective sections.</p><h3>Motivation</h3><p>Speech recognition technology allows for hands-free control of smartphones, speakers, and even vehicles in a wide variety of languages. The World Food Program wants to deploy an intelligent form that collects nutritional information of food bought and sold at markets in two different countries in Africa — Ethiopia and Kenya. The design of this intelligent form requires selected people to install an app on their mobile phone, and whenever they buy food, they use their voice to activate the app to register the list of items they just bought in their own language. The intelligent systems in the app are expected to live to transcribe the speech-to-text and organize the information in an easy-to-process way in a database.</p><h3>Review of previous works</h3><p>All the architectures I was able to find have similar preprocessing and cleaning steps. Some of these cleaning methods are resampling using a standard sampling rate, resizing the length of the audio inputs to an equal length, and applying filters for noise removal. There are also some data augmentation techniques used to make the model generalize better. These include shifting the pitch to either direction, changing the speed, shifting the clip in time, and adding some background noise to simulate a real world environment. Most preprocess the data in similar ways. There is usually a feature extraction stage where some form of representation of the audio is generated. It might be a simple spectrogram, a Mel-Spectrogram or a Mel Frequency Cepstral Coefficients (MFCC).</p><p>Once data is prepared using the above steps, It is fed to the model. The model might be a Convolutional Neural Network (CNN) based model that takes the spectrogram features and tries to predict probability of the characters at each time step. Or It could also be any variant of a Recurrent Neural Network (RNN) model. This would take in a sequence of the generated features and then generate a text sequence as a transcription for the input. A good example for this is Google’s Listen Attend Spell (LAS) model.</p><p>Performance wise, it is better to use a combination of both a CNN and an RNN model. This would first have a CNN model taking in the features extracted from the audio. These then get converted into a latent representation by the CNN, and get fed to the RNN model. Which then gives its outputs to a fully connected artificial neural network with a softmax output layer. This final layer would predict the probability of each character in our target data. These family of architectures use the Connectionist Temporal Classification (CTC) loss function to get a proper alignment of the part of the speech input with the target character or word.</p><p>The target here is text, which needs to be converted into an index to word or character mapping of each element in our dataset’s targets. After having this mapping, we can make our model try to predict the indexes of the words or characters at each time step.</p><h3>Data and Preprocessing Techniques Used</h3><p>The data comes from <a href="https://github.com/getalp/ALFFA_PUBLIC">this</a> github repository. The original source has speech and transcriptions for five African languages. This includes the Amharic language, which is the focus of this project. It has around 20hr of transcribed audio. This has been already split into a training and testing set.</p><p>Since we can’t feed the audio signal directly to our model, we used some feature extraction techniques. This was extracting the spectrogram and MFCC features of the audio signals. This was done after sampling the audio using a standard sampling frequency and resizing the signals to a similar size. For this first iteration of the project we haven’t tried incorporating data augmentation techniques.</p><h3>Model Architecture</h3><p>As stated in the review of the previous works section, most of the existing models have a CNN layer or an RNN layer or they might incorporate both. We have also tried experimenting with all three variants. First we took the spectrogram images of our audio data and passed it through a CNN model that had a softmax activation at the last layer. This model was the perfect starting place for the experiment, since our extracted features were an image-like metrix. CNNs are famous for extracting underlying features in image data. As we expected the performance of this model was not that good.</p><p>Next, we tried using an RNN model. This was chosen since RNNs work better for data that has a temporal feature. From the different variants available we chose to work with LSTMs since they generally perform better for these types of problems. For even better performance, we went with bi-directional LSTM layers. This means information is passed to both the front and the back of the sequences. The results from this model were good, but we wanted to improve it even better. So, next we tried combining the CNN based model and the RNN based model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/753/1*RhEwFmgJsy9q2vrPzntNXQ.png" /><figcaption>RNN based Architecture</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/465/1*-WO4OONbcmTZ5MlTaG3J4Q.png" /><figcaption>RNN based model sample predictions</figcaption></figure><p>The combination of the above two models gave the best performance. This was also the result we were expecting after doing the review of the previous works in the area. The final model we ended up with had the following layers. It had 3 basic components. Preprocessor, CNN layers, and Bi-directional LSTM layers.</p><p>The preprocessing layer is a custom tensorflow layer we wrote to compute the log-magnitude or the mel-scaled spectrograms for the input audio signals. This layer outputs a matrix and that is then passed to the CNN based section of the model.</p><p>This is a standard CNN block connecting a 2D CNN layer, a nonlinear activation layer, batch normalization layer, and finally a pooling layer. In our case we had 3 of these blocks which used different convolution kernel sizes. The output of these layers is flattened and passed to the next section in the model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/423/1*tbV_mcx-vwfd2xUOA_2Cgg.png" /><figcaption>CNN section of the model</figcaption></figure><p>Its output is fed to Bi-Direcional LSTM based model. The flattened output from the CNN based section passes through the LSTM layers. After this comes the time distributed dense layer that will take in the LSTM’s output and pass it to the softmax activation function. It is at the softmax layer that the probability of the characters being paired with the current slice of the input sequence is calculated. The model is trained using the Connectionist Temporal Classification (CTC).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/411/1*BcKnxuHOTN0CQUX4dg2bwQ.png" /><figcaption>BI-Directional LSTM section of the model</figcaption></figure><p>This is the final models architecture printed using keras.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/331/1*AdD1QkL1UFPbpQYpbpuirA.png" /><figcaption>Final model compact view</figcaption></figure><p>And these are sample predictions made with the final model</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/411/1*jLLkMXsvMMIz146rFNvFOg.png" /><figcaption>predictions with final model</figcaption></figure><h3>Loss Function and Evaluation Metrics</h3><p>The CTC loss is a good function when the input is continuous (audio) and the output is discrete (word or character). It helps with aligning the feature slice with the appropriate discrete target. It trains the model to maximize its probability of generating a sequence of targets that is the same to the ground truth.</p><p>It first adds a new character to the target vocabulary. This would represent slices where there is no target. When the probabilities for an input are generated, It filters out probabilities that are not in the target. Then it checks the order of the predicted targets against the ground truth. It then keeps the ones with the proper order. Finally, it removes the null character using the following rule. If a character is repeated without a null character breaking it, only one is kept. If there is a null character between a repetition of characters, they will be considered as separate occurrences. Once this is done, the null characters are removed.</p><p>The metric for evaluation is the word-error-rate. It is calculated by counting the occurrences of deletion, addition, and substitution in the model’s predictions. Additions are words the model fails to generate, but are in the target. Deletions are the opposite. Substitution is when the prediction is not fully correct. The sum of these three divided by the length of our vocabulary gives us our word/character-error rate.</p><h3>MLOps Setup</h3><p>The MLOps tools used in these projects are DVC for data versioning, MLFlow for tracking the hyperparameter search and model training, and CML for sharing results of an experiment on each pull request. The data versioning wasn’t utilized effectively enough. It was used more for giving access to the data when working in the team. We used one personal Google Drive as a remote for DVC. Then, when any team member wanted to set up their environment, they clone the repository and run the dvc pull command to get the data. Since we were doing the preprocessing steps as part of the model, we didn’t need to save a preprocessed version of our data.</p><h4>WebApp Demo</h4><p>We build an interface where users can either record an audio sample or upload a short clip. Then the webapp would display the model generated transcriptions. Bellow here is a video showing the app in action. One more thing to note here is that the model performs poorly on when using the live recording instead of the test data. This suggest our model hasn’t yet generalized to out of distribution samples.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FBI4tAmCqf40%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DBI4tAmCqf40&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FBI4tAmCqf40%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/d9981cf76f6244d9454ffa6e8479f92d/href">https://medium.com/media/d9981cf76f6244d9454ffa6e8479f92d/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FFdiNjeLWWNY%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DFdiNjeLWWNY&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FFdiNjeLWWNY%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/a4887aba44a413614618c10fb1c1b714/href">https://medium.com/media/a4887aba44a413614618c10fb1c1b714/href</a></iframe><h3>Future Work</h3><p>There are also Github Actions for running unit tests and generating a pull request report from an experiment log folder. For now, the CML report has the current trained model architecture.</p><h3>Future Work</h3><p>Because of time limitations, we didn’t get to explore all avenues for improving our model. In this section, I will list out things we would have worked on had we had enough time.</p><ul><li>Better utilization of MLOps tools</li><li>Better hyperparameters exploration for type of model we tested</li><li>An in depth analysis of the model regarding bias and fairness</li><li>Integration with alex skills</li></ul><p>You can find the entire project on my <a href="https://github.com/Hen0k/Speech-to-Text">GitHub</a></p><h4>References</h4><ol><li><a href="https://towardsdatascience.com/audio-deep-learning-made-simple-part-1-state-of-the-art-techniques-da1d3dff2504">https://towardsdatascience.com/audio-deep-learning-made-simple-part-1-state-of-the-art-techniques-da1d3dff2504</a></li><li><a href="https://towardsdatascience.com/audio-deep-learning-made-simple-part-2-why-mel-spectrograms-perform-better-aad889a93505">https://towardsdatascience.com/audio-deep-learning-made-simple-part-2-why-mel-spectrograms-perform-better-aad889a93505</a></li><li><a href="https://towardsdatascience.com/audio-deep-learning-made-simple-part-3-data-preparation-and-augmentation-24c6e1f6b52">https://towardsdatascience.com/audio-deep-learning-made-simple-part-3-data-preparation-and-augmentation-24c6e1f6b52</a></li><li><a href="https://towardsdatascience.com/audio-deep-learning-made-simple-automatic-speech-recognition-asr-how-it-works-716cfce4c706">https://towardsdatascience.com/audio-deep-learning-made-simple-automatic-speech-recognition-asr-how-it-works-716cfce4c706</a></li><li><a href="https://github.com/bonaventuredossou/fonasr">bonaventuredossou/fonasr: End2End Automatic Speech Recognition Model in PyTorch for Fon (github.com)</a></li><li><a href="https://github.com/tilayealemu/MelaNet">tilayealemu/MelaNet: Amharic speech recognition using Deep Learning (github.com)</a></li><li><a href="https://heartbeat.fritz.ai/the-3-deep-learning-frameworks-for-end-to-end-speech-recognition-that-power-your-devices-37b891ddc380">https://heartbeat.fritz.ai/the-3-deep-learning-frameworks-for-end-to-end-speech-recognition-that-power-your-devices-37b891ddc380</a></li></ol><ul><li>Testing the effect of using different preprocessing methods</li><li>Restructuring the repository focusing on maintainability and ease of use.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c2bcb4aaf4ee" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Project Based Introduction to Time Series Forecasting]]></title>
            <link>https://medium.com/@tilaye.henok/a-project-based-introduction-to-time-series-forecasting-7ed3c4231d37?source=rss-f21bd4116248------2</link>
            <guid isPermaLink="false">https://medium.com/p/7ed3c4231d37</guid>
            <category><![CDATA[lstm]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[sales-forecasting]]></category>
            <category><![CDATA[time-series-analysis]]></category>
            <category><![CDATA[mlops]]></category>
            <dc:creator><![CDATA[Henok Tilaye]]></dc:creator>
            <pubDate>Sat, 28 May 2022 19:56:03 GMT</pubDate>
            <atom:updated>2022-05-30T20:24:31.490Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8oLrzkunZ8lrN8yRW2eGyg.png" /></figure><p>Wondering about our future or questioning what comes next is common for Humans. Accurately predicting future events is essential for many aspects of our lives. These could range from choosing the type of cloth we wear based on the weather outside to being able to make (or lose) a lot of money by analyzing trends in the market. It is what I will be exploring in this blog, Time-series forecasting, or the prediction of a future state by studying consecutive historical data that varies over time.</p><p>The following is a list of topics I will be going over in this blog.</p><p>1. Why am I writing this blog?<br>2. An introduction to Time Series Analysis (TSA)<br>3. Different approaches to TSA<br>4. A walk-through of the project I have been working on</p><h3>1. Why am I writing this blog?</h3><p>I am currently attending an intensive training program that would make me job-ready for one of the following roles. The roles are Machine Learning Engineer, Data Engineer, and Web3 Engineer. As part of my learning journey, I will be writing about the things I am learning. Doing this would help me solidify the concepts I am learning, and it might also help someone else who wants to know about these topics.</p><h3>2. An introduction to Time Series Analysis (TSA)</h3><p>[<a href="https://en.wikipedia.org/wiki/Time_series">1</a>]Time series is a sequence of data points that have a temporal dimension. This means that the data points show some type of evolution over time. The time at which a data point was collected matters and is considered a feature of the data. Most time-series data is collected at successive and equally spaced time intervals. Some examples of time series data are weather data, heights of ocean tides, and the daily closing price of Bitcoin.</p><p>Analyzing time-series data is done to find some pattern within the data that would allow us to find interesting trends, and forecast what will happen at a future point in time. This is what makes TSA powerful and useful. [<a href="https://www.analyticssteps.com/blogs/5-applications-time-series-analysis">2</a>]Geologists use it to study earthquake patterns, and financial analysts utilize TSA to make informed decisions about the market. It is also used in astronomy and astrophysics for studying objects’ trajectories in the vastness of space. In medicine, it is used for heart rate monitoring (EKG) and brain signal monitoring (EEG)</p><h3>3. Different approaches to TSA.</h3><p>The Analysis can take different routes depending on what we want to understand from the data. [<a href="https://www.tableau.com/learn/articles/time-series-analysis#:~:text=Time%20series%20analysis%20is%20a,data%20points%20intermittently%20or%20randomly">3</a>] These might be identifying different categories within our data, studying relationships between variables in the data, and extracting causes and effects in the data. We also might be interested in identifying seasonality, trends, and other patterns in our data. All these would help us have a better understanding of our data.</p><p>One essential task we do with time-series data is forecasting. There are numerous traditional methods and we can also use machine-learning-based methods to come up with more accurate predictions.[<a href="https://machinelearningmastery.com/time-series-forecasting-methods-in-python-cheat-sheet/">4</a>] One of the classical forecasting methods is Auto-Regression (AR)[<a href="https://en.wikipedia.org/wiki/Autoregressive_model">5</a>]. It uses a linear function to predict the next step in the sequence based on previously observed data points. Another example would be using the moving average modeling (MA model) of our data to predict what comes next [<a href="https://en.wikipedia.org/wiki/Moving-average_model">6</a>]. This one models the next step in the sequence as a linear function of the residual errors from a mean process at prior time steps.</p><p>Whenever we are making some forecast It is like saying “I know the system that is generating these data points so well, that I can predict what it will output in the next sequence”. And machine learning models are used for roughly the same problems. They are always trying to find a model or a function that represents the data they are given. So, we can also utilize ML to first have a model that understands our data, and then make predictions.</p><p>Regression-based models are perfect examples of these. Based on some input features, they give estimations of a target variable. We can set the inputs as different attributes collected at the same points in time as the target is collected. Here the target is the variable we want to make predictions about. Another recent method would be using Long Short Term Memory or LSTM to model our data. [<a href="https://karpathy.github.io/2015/05/21/rnn-effectiveness/">7</a>] These are variants of Recurrent Neural Networks that are better at remembering features in previous time stamps. Enough introduction, let’s see the project I have working on.</p><h3>4. A Walk-through of the project I have been working on</h3><h3>Objective</h3><p>The main objective of the project is to predict sales at multiple stores for the pharmaceutical company known as Rossmann Pharmaceuticals.</p><p>I was provided with two CSV files. One has attributes related to the different stores, and the other was the time-series data that contained the sales value for each store on each day. I started by doing exploratory data analysis on the given datasets to have a better understanding of the data I had. Then I used a Random Forest Regression model from scikit-learn to model and generate forecasts. I then tried to use an LSTM model I built with TensorFlow to do the same thing. I was also supposed to explore the data using the Prophet model by Facebook. but I haven’t done this last part. I will try doing it soon and update the blog with my findings.</p><h3>The data</h3><p>The sales data spanned from 2013–01–01 up to 2015–07–31, which is a total of 942 days. There were 1115 unique stores in the data. The store’s data had attributes such as the store’s assortment type, Whether it was running a promotion or not, a store type, and a unique store identifier. The following screenshot shows the columns in the store data.</p><figure><img alt="A list of columns contained in the store’s dataset. This is a printout from the pandas info method on dataframes." src="https://cdn-images-1.medium.com/max/472/1*niD08vF5Aui-1UBVgt_ckg.png" /><figcaption>Store’s data columns</figcaption></figure><p>The sales data, which is the time series data in the project looked like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/649/1*Hv87WAiZr-dZkaW4QQvWdQ.png" /><figcaption>Sales data columns</figcaption></figure><p>I started by cleaning the data. This included changing some columns’ data types to the appropriate types. For example the date columns on both need to be converted from an object (string) to pandas DateTime format. The next step in my cleaning process was filling in any missing values in the data. The sales data doesn’t have any missing entries but the store’s data had some.</p><p>For the missing values in the competition distance column, I used the median of the column. I decided median because the values in that column had many outliers and so I couldn’t use the mean. I used a simple box plot to check for outliers. And for the “Promo2Since[Year/Week]” and “Promo2Interval” imputed the missing values with 0’s and None. I decided on this after noticing that all the rows with missing values in these 3 columns had their “Promo2” column value set to 0. This means, the stores didn’t run Promo2, so they didn’t have those columns. For the “CompitionOpenSince[Year/Month]” columns I randomly sampled the non-null values in their respective columns and imputed the missing values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/474/1*RDn_-984FGb9aoLZCqrVZQ.png" /><figcaption>A Box Plot of the CompetitionDistance column</figcaption></figure><p>Next, I plotted the sores distributions after grouping them by StoreType and Assortments.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/662/1*MGOnaEwAfdavoEB4gKq84A.png" /><figcaption>Bar chart showing StoreType distribution</figcaption></figure><p>There are a lot more stores of type ‘a’ and on the other side there are a small number of stores of type ‘b’</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/676/1*cfF1SwBZWBgOH6HdbkXKBQ.png" /><figcaption>Bar chart showing Assortment distribution</figcaption></figure><p>Before continuing with my analysis, I merged the two datasets using the Store columns as a common column. Then, I extracted the following sales-related insights. The first one is the sales of the stores on each day of the week throughout the whole time span of our data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/694/1*UlQcffP27tOyYmDMs4iMCA.png" /><figcaption>Bar chart for Sales on each day of the week throughout the entire time span</figcaption></figure><p>The above plot tells us that the sales on Sundays (where the x-axis is 7), are significantly lower than on other days. This is because most of the stores are closed on Sundays. Next, I wanted to see what the sales for each store type looked like throughout the data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/392/1*dtDAZKtgJhzW9J3ZlRy-zQ.png" /><figcaption>Sales for each Store Type</figcaption></figure><p>The next plot to showing the distribution of the sales values. Before making the plot I filtered the data to only plot values where the sales were not zero. This is done to not skew the graph towards the zero values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/574/1*C74yOPJ-_q1v_CP2CnyYkA.png" /><figcaption>Sales distribution across the whole dataset</figcaption></figure><p>This shows us that most stores have a daily sales of around 10,000 and that there are stores with sales up to 40,000.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7ed3c4231d37" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>