<?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 Yididiya Samuel on Medium]]></title>
        <description><![CDATA[Stories by Yididiya Samuel on Medium]]></description>
        <link>https://medium.com/@yidisam18?source=rss-6f96426a180a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*9A-_NKNLSSxhkrPAh8Nw7g.jpeg</url>
            <title>Stories by Yididiya Samuel on Medium</title>
            <link>https://medium.com/@yidisam18?source=rss-6f96426a180a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 15:35:54 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@yidisam18/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[Scalable Data warehouse using Airflow, DBT, & Postgres in docker container]]></title>
            <link>https://medium.com/@yidisam18/scalable-data-warehouse-using-airflow-dbt-postgres-b26105d45d50?source=rss-6f96426a180a------2</link>
            <guid isPermaLink="false">https://medium.com/p/b26105d45d50</guid>
            <category><![CDATA[containers]]></category>
            <category><![CDATA[airflow]]></category>
            <category><![CDATA[data-warehouse]]></category>
            <category><![CDATA[dbt]]></category>
            <dc:creator><![CDATA[Yididiya Samuel]]></dc:creator>
            <pubDate>Sat, 23 Jul 2022 20:03:14 GMT</pubDate>
            <atom:updated>2022-07-27T13:12:54.831Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*-EBqWJ5ah_JcpQYgUQfBxw.png" /></figure><h3>Objective</h3><p>Different organizations collect data from multiple sources using sensors and IoT devices. The type of organization I tried to work on deploys sensors to businesses, and collects data from all activities in a business — people’s interaction, traffic flows, and smart appliances installed in a company, the objective is to help organizations obtain critical intelligence based on public and private data they collect and organize.</p><p>I will be using the ELT(Extract -&gt; Load -&gt; Transform) pipeline which will first load the data into the preferred destination compared to ETL which will first do the transformation before loading the data.</p><ul><li>Extraction: Data from the source system is copied at this initial stage.</li><li>Loading: The pipeline replicates data from the source into the destination system, which might be a data warehouse or data lake, during the loading process.</li><li>Transformation: Organizations can do any necessary transformations after the data is in the destination system. In order to use raw data with various tools or business processes, businesses frequently alter it in a variety of ways.</li></ul><p>Before loading data into a destination, ETL tools need processing engines to conduct transformations. ELT, on the other hand, enables organizations to effectively convert data within the target system itself by utilizing the processing engines in the destinations. The data loading procedure is made more efficient by eliminating the intermediary phase. When a destination demands a particular data format, ETL is the best technique since it converts data before the loading stage. This could occur when the supported data types at the source and destination are not aligned when a destination has a slow processing speed constraint, or when security concerns prevent the storage of raw data there.</p><p>ELT is a preferable strategy, though, when the final destination is a cloud-native data warehouse like Amazon Redshift, Google BigQuery, Snowflake, or Microsoft Azure SQL Data Warehouse. Rather than as a phase in the data pipeline, organizations are free to alter their raw data whenever and as needed for their use case.</p><p>ELT pipeline delivers faster data ingestion because data is not sent to a secondary server for restructuring. In fact, with ELT, data can be loaded and transformed simultaneously. The raw data retention of ELT creates a rich historical archive for generating business intelligence. As goals and strategies change, BI teams can re-query raw data to develop new transformations using comprehensive datasets.</p><h3>Data Used</h3><p>The data was collected from a public source and I will be specifically working on pNEUMA data which is an open large-scale dataset of naturalistic trajectories of half a million vehicles that have been collected by a one-of-a-kind experiment by a swarm of drones in the congested downtown area of Athens, Greece.</p><h3>The Tech stack implementation</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ePT8LBQ5DY5oPCuDNrI-FA.png" /></figure><p>Apache Airflow</p><p>Apache Airflow is an open-source tool to programmatically author, schedule, and monitor workflows. It is one of the most robust platforms used by Data Engineers for orchestrating workflows or pipelines. Apache Airflow is capable of scheduling tasks and running those tasks on a scheduled basis. It can be used to run tasks in bash, python, Postgres, and multiple others using an operator specific to the class. I will be using the Postgres Operator from airflow.providers to interact with the Postgres database.</p><p>DBT</p><p>DBT is a development framework that combines modular SQL with software engineering best practices to make data transformation reliable and fast. It makes data engineering activities accessible to people with data analyst skills to transform the data in the warehouse using simple select statements, effectively creating your entire transformation process with code.</p><p>Datawarehouse</p><p>I used Postgres as my data warehouse that will be running in the Docker container.</p><p>To prepare my environment for the necessary tech stacks, I first configured my environment. The environment could be manually built up, but it would be difficult to control. So, I used <a href="https://github.com/jedisam/Scalable_DataWarehouse/blob/main/docker-compose.yml">docker</a> for my environment and spinned up my container with Airflow, DBT, Redash, and Postgres.</p><p>Initializing the airflow with the specified user was the next step after preparing the docker-compose file. Execute the command below to achieve that.</p><pre>docker-compose up airflow-init</pre><p>If this is the first time launching the container, it can take some time. Then you should see the following message if it was successful.</p><pre>docker-compose up airflow-initairflow-init_1       | Upgrades done<br>airflow-init_1       | Admin user airflow created<br>airflow-init_1       | 2.1.0<br>start_airflow-init_1 exited with code 0</pre><p>The final step is to start the whole container</p><pre>docker-compose up</pre><p>This will start all the containers, and you can view airflow running if you visit localhost:8080.</p><p>I placed the necessary CSV file in the data folder of the root directory so that the airflow could ingest the data and load it into the data warehouse. A docker volume was mounted with the directory. The data from the specified path will now be ingested by the airflow when it runs and loaded into the data warehouse.</p><p>Here is a sample of the airflow script:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/454/1*H_SezmfSHck6PMsFKb-4mw.png" /></figure><p>I placed separate SQL scripts in the same directory and the airflow PostgresOperator was able to run that on the scheduled basis.</p><p>After the data was loaded the EL part of the pipeline was completed and the transformation part came into play. For the transformation, I used dbt, which was also launched in the docker container. To communicate with the container that was running and execute dbt commands, I used dbt-cli.<br>To start an interactive shell of DBT run the following command:</p><ul><li>List the running containers</li></ul><pre>docker ps</pre><p>There you should find dbt-cli container running, copy the id of the container and run:</p><pre>docker exec -it &lt;dbt-cli-id&gt; /bin</pre><p>This will start an interactive bash shell to interact with DBT. The first step is to initialize the dbt. Execute the following command in the interactive shell.</p><pre>dbt init </pre><p>After DBT has been initialized you will have all of generated directories and files in the directory. Make sure that the profiles.yml file also exists in the root directory. You now can create a .env file in the directory and put your credentials for the profiles.yml.</p><pre>AIRFLOW_UID=&lt;airflow-uid&gt;<br>AIRFLOW_GID=0<br>DB_HOST_DEV=&lt;airflow-host-name&gt;<br>DB_PORT_DEV=&lt;airflow-port&gt;<br>DB_USER_DEV=&lt;airflow-user&gt;<br>DB_PASSWORD_DEV=&lt;aiflow-password&gt;<br>DB_NAME_DEV=&lt;airflow-db&gt;</pre><p>Most transformations done in this phase are used for analytics purposes. In my case, I first transformed some columns into the desired data type, then performed aggregations on the data returned. The aggregations I used count the total number of grouped vehicle types, their max speeds, and the total number of traveled distances.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/454/1*hr64OKBqDlq3oKAhswq9fw.png" /></figure><p>The DBT script will take the data loaded in the first phase as input and make the necessary transformations and create a new table/view to insert the transformed data. The DBT was being triggered by airflow on a daily basis to make the transformation on the coming data.</p><p>The last step on the DBT implementation was to generate the dbt docs and look at the lineage.</p><p>On the DBT cli I used the following command to generate the docs.</p><pre>dbt run #to run the dbt scripts<br>dbt docs generate #this will generate the docs in html page<br>docs serve --port 8001 #to serve it on a port 8001</pre><p>Now, one can go to <a href="http://localhost:8001/">http://localhost:8001</a> and view the dbt documentation as well as the leanage. I deployed the generated on <a href="https://scalable-datawarehouse.netlify.app/">netlify</a>.</p><p>The last step in the project implementation was to connect the data to redash and do some analytics. Redash was also running in the Docker container. I then connected it to the data warehouse and performed some analytics on the transformed data.</p><h3>Future works</h3><p>This was a one-week project; in the future, more work can be done on the transformation phase. I was having a bit of a challenge on the data handling part as it consisted of a large number of timestamp columns. I will be working on formating and putting it into a separate table and doing a join using DBT transformation.</p><p>Github Link: <a href="https://github.com/jedisam/Scalable_DataWarehouse">https://github.com/jedisam/Scalable_DataWarehouse</a></p><p>References:</p><p><a href="https://www.astronomer.io/blog/airflow-dbt-2">https://www.astronomer.io/blog/airflow-dbt-2</a><br><a href="https://docs.getdbt.com/reference/commands/cmd-docs">https://docs.getdbt.com/reference/commands/cmd-docs</a><br><a href="https://analyticsmayhem.com/dbt/apache-airflow-dbt-docker-compose/">https://analyticsmayhem.com/dbt/apache-airflow-dbt-docker-compose/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b26105d45d50" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Refund by location DAPP mobile app using Solidity]]></title>
            <link>https://medium.com/codex/refund-by-location-dapp-mobile-app-using-solidity-8f82a619ee75?source=rss-6f96426a180a------2</link>
            <guid isPermaLink="false">https://medium.com/p/8f82a619ee75</guid>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[dapps]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[solidity]]></category>
            <dc:creator><![CDATA[Yididiya Samuel]]></dc:creator>
            <pubDate>Sat, 16 Jul 2022 18:49:34 GMT</pubDate>
            <atom:updated>2022-07-19T13:23:33.199Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xg01kiomYuZW44qdcgVujQ.jpeg" /></figure><p><strong>Introduction</strong><br>Simply put, smart contracts are blockchain-based algorithms that execute when certain criteria are met. They are often used to automate the implementation of an agreement so that all parties can be certain of the conclusion right away, without the need for an intermediary or additional delay. They can also automate a workflow such that when circumstances<br>are met, the following action is executed. Smart contracts work by following simple “if/when…then…” statements that are written into code on a blockchain. A network of computers executes the actions when predetermined conditions have been met and verified. These can entail paying out money to the right people, registering a car, sending out notices, or writing a ticket. When the transaction is finished, the blockchain is then updated. As a result, the transaction cannot be modified, and only parties to whom permission has been granted can view the outcome.</p><blockquote>Main Benefits of Smart Contracts:<br>- Trust and transparency: Since there is no involvement of a third party and participants share encrypted records of transactions, there is no need to question if the information has been altered for one participant’s personal gain. Since none of the work is done on the basis of trust, they are sometimes referred to as trustless apps.<br>- Speed, efficiency, and accuracy: The contract is promptly carried out if a condition is satisfied. Smart contracts are digital and automated, so there is no paperwork to complete or time spent fixing mistakes that frequently occur when documents are filled out manually.<br>- Security: Because the blockchain transaction records are encrypted, they are incredibly difficult to hack. Additionally, hackers would need to alter the entire chain in order to change a single record on a distributed ledger because each record is linked to the records that came before and after it.</blockquote><p><strong>Our Business Use case</strong><br>Our application is mostly for employer-to-employee-based scenarios. 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 pre-agreed contract codified in an Ethereum smart contract, a cryptocurrency payment is executed when all the agreed conditions are met. 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 suggested use case may have numerous real-world applications. One example is a delivery system, in which employers hire people to deliver items, and the workers may only be paid once they arrive at the destination.</p><p>Another application area would be a surveying system in which company X employs a firm to gather data. Only when the employees are present at the designated location where the survey will be taken will the company or even the agency be able to pay the employees.</p><p><strong>Block-chain I used: Ethereum</strong><br>Ethereum is an open source, distributed software platform that is based on blockchain technology. It has its own native cryptocurrency called Ether and a programming language called Solidity. The blockchain network is used by Ethereum. Nodes are the computers of volunteers who mine for coins and make up the network. The mining provides the cryptography that underpins the money, while the nodes produce the Ether tokens. Miners are paid with Ether since mining is a resource-intensive use of a computer.</p><p>The Ethereum platform offers the computationally complete Ethereum Virtual Machine (EVM). EVM runs scripts on its network of dispersed public nodes all over the world. These nodes offer the network’s decentralized applications created by developers the processing power they need<br>to function. Developers may buy Ether to pay for the use of the network, or they can mine for the tokens themselves, becoming a part of the network. An internal mechanism called Gas sets the pricing of transactions on the network. Currently, Ethereum is using Proof of work for validation. Ethereum 2.0 — also known as ETH 2.0 of Serenity which is going to be a major update to Ethereum is said to be released this year and it is believed that it will be using proof of stake as its protocol.</p><p><strong>Components of Ethereum<br></strong>● Nodes: There are the mining nodes that are responsible for writing all the<br>transactions that have occurred in the Ethereum network and the EVM nodes in which the smart contracts are implemented.<br>To ensure that all participants on the Ethereum network maintain a synchronized state and agree on the precise history of transactions, we batch transactions into blocks. This means dozens (or hundreds) of transactions are committed, agreed on, and synchronized all at once.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IfIIPvKz7pa4dW70OQoS_w.png" /></figure><p>● Ether: It is a type of cryptocurrency used in the Ethereum network just like a bitcoin is used in a blockchain network. It is a peer-to-peer currency, similar to Bitcoin. It tracks and promotes each transaction in the network.<br>● Gas: It is an internal currency of the Ethereum network. We need gas to run applications on the Ethereum network, much as we need gas to run a vehicle.<br>● Ethereum Accounts: There are two types of accounts. The first one is the externally owned account which is used to store transactions and the second one is the contract account which stores the details of the smart contract.<br>● Nounce: Has a different meaning based on the account type. For externally owned accounts, nonce means the number of transactions via this account. For a contract account, nonce means the number of contracts generated via this account.<br>● Storage Root: It is the main root node of a Merkle tree. Hash of all details of the account is stored here. The root of the Merkle tree is the verification of all transactions.<br>● Ethash: It is the POW algorithm used in Ethereum 1.0.</p><p><strong>Networks in Ethereum</strong><br>Networks are different Ethereum environments you can access for development, testing, or production use cases. Since Ethereum is a protocol, there can be multiple independent “networks” that conform to the protocol without interacting with each other. The different types of networks are:<br>● PUBLIC NETWORKS: are accessible to anyone in the world with an internet connection. Anyone can read or create transactions on a public blockchain and validate the transactions being executed. The consensus among peers decides on the inclusion of transactions and the state of the network.<br>● Ethereum Mainnet: Mainnet is the primary public Ethereum production blockchain, where actual-value transactions occur on the distributed ledger. Making a transaction on the mainnet requires an actual Ethereum and costs some amount.<br>● Ethereum Testnets: These are networks used by protocol developers or smart contract developers to test both protocol upgrades as well as potential smart contracts in a production-like environment before deployment to Mainnet. Think of this as an analog to production versus staging servers. ETH on testnets has no real value; therefore, there are no markets for testnet ETH. It is possible to get some ETH from <a href="https://faucet.rinkeby.io/">faucets</a>. Some of the testnets are:</p><p>○ Sepolia<br>○ Ropsten<br>○ Rinkeby<br>○ Kovan</p><p><strong>EVM’s</strong><br>Ethereum Virtual Machine (EVM) is a computation engine that acts like a decentralized computer that has millions of executable projects. It is considered to be the part of Ethereum that runs execution and smart contract deployment. EVM is a software framework that allows developers to construct Ethereum-based decentralized applications (DApps). All Ethereum accounts and smart contracts are stored on this virtual computer. Contracts are usually authored in high-level languages like Solidity and then compiled into EVM<br>bytecode. This implies that the machine code is separated from the host computer’s network, disc, and other operations. Every node in the Ethereum network runs an EVM instance, allowing them to agree on the same set of instructions to be executed.</p><p><strong>How does EVM work?</strong><br>The EVM’s goal is to figure out what Ethereum’s overall state will be for each block on the blockchain. Ethereum, like other blockchain-based networks, has its own native money (ETH) and employs a distributed ledger to keep track of transactions while imposing particular rules for how users can interact with the network. Ethereum, on the other hand, offers an additional layer of functionality thanks to its smart contract capabilities. The EVM is a critical component of the Ethereum Protocol and the Ethereum system’s consensus engine. It enables anybody to run code in a trustless ecosystem where the outcome of execution may be guaranteed and is entirely predictable (i.e., smart contract execution). A system that keeps track of execution costs assigns an associated cost in Gas units to each instruction implemented on the EVM.</p><p><strong>What language is used to write Smart Contract?<br></strong>Solidity is the most popular language used to build smart contracts. It is an object-oriented, high-level language for implementing smart contracts. Solidity is highly influenced by C++, Python, and JavaScript and has been designed to target the Ethereum Virtual Machine (EVM). It is statically typed and supports inheritance, libraries, and complex user-defined types among other features.</p><p>For quick with solidity programming, a popular IDE known as Remix IDE can be used. The online IDE is best for a quick start and to experiment with starting to write Solidity language, deployment of contracts on EVM, compatibility, and other related fields, but it might not come<br>in very handy when it comes to the actual development of smart contracts. For the actual development and writing of solidity code, I have been using Vscode with the Solidity extension.</p><p>There are different development environments of Ethereum. Some of the popular ones are Hardhat, Brownie, Embark, and truffle. I have initialized my project using all three of the environments but chose HardHat for development. These environments give you the ability to easily deploy smart contracts and test smart contracts. Setting up a HardHat environment is quite an easy and a straightforward process:</p><blockquote>Using Yarn as a package manager<br>Installation:<br>yarn add –dev hardhat // adding it as a dev dependency<br>Initialization<br>yarn hardhat &gt; create simple project</blockquote><p>This will give us a basic configuration script for deployment, sample contract, and required test folders. From there it is possible to write tasks that will be added to the list of available tasks. Writing scripts using hardhat is much easier and makes the development time much shorter.</p><p><strong>Testing in Smart Contract<br></strong>One of the most crucial steps for enhancing smart contract security is to test them. It is crucial to conduct thorough testing prior to releasing contracts on the Ethereum network because, unlike traditional software, smart contracts often cannot be modified after being launched. The term refers to the process of carefully examining and evaluating a smart contract to determine the<br>level of its source code during the development cycle. Testing a smart contract minimizes the likelihood of software faults that could result in expensive exploits and makes it simpler to find flaws and vulnerabilities. <a href="https://rekt.news/leaderboard/">Rekt</a> lists out the names of some defi protocols that have fallen victim to attack, exploit, or arbitrage. The list given shows how seriously testing has to be taken.</p><p>Testing smart contracts are really important as the code will be public to everyone and anyone could penetrate loose end-points if proper tests aren’t implemented. In hardhat, it is possible to perform testing using normal javascript testing libraries like Chai. We then can perform unit testing, integration testing, and system testing. For some scenarios testing the implementation might be a bit expensive and difficult so we can use mocking to mimic the actual behavior and make sure our scripts run the way they are supposed to.</p><p><strong>Implementation</strong></p><p>The DAPP will have 3 applications:</p><ul><li>Smart contract (Back-end)</li><li>Admin Panel (Front-end)</li><li>Mobile App</li></ul><h3>Back-end(smart contract)</h3><p>The <a href="https://github.com/jedisam/Refund-by-location-smart-contract">back-end</a> was developed using solidity which will enable admins of an organization to add and manage an employee and receive the coordinate of an employee at a random time. Test scripts were written using chai (a javascript testing framework) to make sure everything works correctly.</p><pre>//SPDX-License-Identifier: Unlicense</pre><pre>pragma solidity ^0.8.0;</pre><pre>import “hardhat/console.sol”;</pre><pre>contract Refund {</pre><pre>address owner;</pre><pre>struct EmployeeDetail {</pre><pre>string name;</pre><pre>uint256 lat;</pre><pre>uint256 lon;</pre><pre>uint256 allowedDistance;</pre><pre>}</pre><pre>struct conditionDetail {</pre><pre>string status;</pre><pre>bool condition;</pre><pre>}</pre><pre>mapping (address =&gt; EmployeeDetail) employeeDetail;</pre><pre>// mapping(address =&gt; bool) public employeeCondition;</pre><pre>mapping(address =&gt; conditionDetail) public employeeCondition;</pre><pre>address[] public employees;</pre><pre>constructor() {</pre><pre>owner = msg.sender;</pre><pre>console.log(“Deploying a Refund with Owner:”, owner);</pre><pre>}</pre><pre>function createEmployee(address empAddress, string memory name, uint256 lat, uint256 lon, uint256 allowedDistance) public {</pre><pre>// restrict employee creation to owner</pre><pre>require(msg.sender == owner);</pre><pre>// set User name using the employeeDetail mapping</pre><pre>employeeDetail[empAddress].name = name;</pre><pre>// set Employee lat using the userStructs mapping</pre><pre>employeeDetail[empAddress].lat = lat;</pre><pre>// set Employee lon using the employeeDetail mapping</pre><pre>employeeDetail[empAddress].lon = lon;</pre><pre>// set the Employee’s allowed distance using the employeeDetail mapping</pre><pre>employeeDetail[empAddress].allowedDistance = allowedDistance;</pre><pre>// Set default employee condition to not verified</pre><pre>employeeCondition[empAddress].status = “Not Verified”;</pre><pre>employeeCondition[empAddress].condition = false;</pre><pre>// push user address into userAddresses array</pre><pre>employees.push(empAddress);</pre><pre>}</pre><pre>function getEmployeeDetail(address empAddress) public view returns (string memory, uint256, uint256, uint256) {</pre><pre>return (employeeDetail[empAddress].name, employeeDetail[empAddress].lat, employeeDetail[empAddress].lon, employeeDetail[empAddress].allowedDistance);</pre><pre>}</pre><pre>function ingestCoordinate(address empAdderss, uint256 lat, uint256 lon, uint256 etimestamp) public {</pre><pre>require(etimestamp &gt;= 0 &amp;&amp; etimestamp &lt;= 12 || etimestamp &gt;= 18 &amp;&amp; etimestamp &lt;= 22);</pre><pre>uint256 distance = calculateDistance(lat, lon);</pre><pre>if (distance &gt; employeeDetail[empAdderss].allowedDistance) {</pre><pre>// employeeCondition[msg.sender] = false;</pre><pre>// Set default employee condition to not verified</pre><pre>employeeCondition[empAdderss].status = “Verified”;</pre><pre>employeeCondition[empAdderss].condition = false;</pre><pre>} else {</pre><pre>employeeCondition[empAdderss].status = “Verified”;</pre><pre>employeeCondition[empAdderss].condition = true;</pre><pre>}</pre><pre>}</pre><pre>function getEmployees() public view returns (address[] memory) {</pre><pre>return employees;</pre><pre>}</pre><pre>function payEmployee(address empAddress, uint256 amount) public payable{</pre><pre>require(msg.sender == owner);</pre><pre>require(amount &gt; 0);</pre><pre>require(employeeCondition[empAddress].condition);</pre><pre>// require(employeeCondition[empAddress].status == “Verified”);</pre><pre>payable(empAddress).transfer(amount);</pre><pre>}</pre><pre>// Find the square root of a number using the Babylonian method</pre><pre>function sqrt(uint x) public pure returns (uint y) {</pre><pre>uint z = (x + 1) / 2;</pre><pre>y = x;</pre><pre>while (z &lt; y) {</pre><pre>y = z;</pre><pre>z = (x / z + z) / 2;</pre><pre>}</pre><pre>return y;</pre><pre>}</pre><pre>function calculateDistance(uint256 lat2, uint256 lon2) public view returns (uint256 dist)</pre><pre>{</pre><pre>(,uint256 lat1, uint256 lon1,) = getEmployeeDetail(msg.sender);</pre><pre>uint256 distance = uint256(sqrt((lat2 — lat1) ** 2 + (lon2 — lon1) ** 2));</pre><pre>return uint256(distance);</pre><pre>}</pre><pre>}</pre><p>Finally, I deployed the smart contract using hardhat to a rinkeby testnet. I used free ethers from <a href="https://faucet.rinkeby.io/">rinkeby faucet</a> to make transactions on the blockchain. On the deployment of a smart contract, an address will be returned and recorded because the front-end will be using that address to communicate with the back-end(smart contract). It will also generate an Application Binary Interface(abi) in the project directory which is just a standard way to interact with contracts in the Ethereum ecosystem, both from outside the blockchain and for contract-to-contract interaction.</p><h3>Front-end</h3><p>Front-end to backend smart contract interaction mainly requires about three things which are:</p><ul><li>Application Binary Interface (abi)</li><li>Smart contract address</li><li>Client-side library (ethers…)</li></ul><p>The first two are generated above on smart contract deployment. For the client-side library, it’s possible to use ethers or any other library out there to make a call to the smart contract.</p><p><a href="https://github.com/jedisam/refund-smart-conract-mobile-app">The admin panel</a> was built using react(typescript), which will enable admins to manage employees by interacting with the blockchain.</p><p><a href="https://github.com/jedisam/refund-smart-conract-mobile-app">The mobile app</a> was developed using expo (a lighter version of react-native) which will track employees and send their coordinates along with the time stamp to the blockchain. The blockchain will then check if it’s the specified time range and then calculate their distance from the given distance by the employee. If their location is not in compliance with the agreement it will display that to the admin.</p><p>To be able to send the coordinates of an employee in the background I used a package called <a href="https://docs.expo.dev/versions/latest/sdk/background-fetch">background-fetch</a> from the expo which will be able to run in the background of the mobile application by being triggered at a random time.</p><h3>Conclusion</h3><p>It can be seen that by using smart contracts one can provide a reliable and transparent system that will make the management system much easier.</p><p><strong>Future works.<br></strong>In the future, I will work on the payment integration to the system so that employees would be paid in ethers.</p><p>Admin App: <a href="https://refund-by-location.netlify.app/">https://refund-by-location.netlify.app/</a></p><p>GitHub: <a href="https://github.com/jedisam/Refund-by-location-smart-contract">https://github.com/jedisam/Refund-by-location-smart-contract</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8f82a619ee75" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/refund-by-location-dapp-mobile-app-using-solidity-8f82a619ee75">Refund by location DAPP mobile app using Solidity</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Digital Certificate Distribution using Alogrand’s Blockchain with wallet integration]]></title>
            <link>https://medium.com/codex/digital-certificate-distribution-using-alogrand-blockchain-93d185430869?source=rss-6f96426a180a------2</link>
            <guid isPermaLink="false">https://medium.com/p/93d185430869</guid>
            <category><![CDATA[digital-certificates]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[dapps]]></category>
            <category><![CDATA[algorand]]></category>
            <dc:creator><![CDATA[Yididiya Samuel]]></dc:creator>
            <pubDate>Sat, 18 Jun 2022 20:13:53 GMT</pubDate>
            <atom:updated>2022-07-01T19:54:17.264Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2Se8uVq0FfcIwmAGwdm7UQ.png" /></figure><h3>Introduction</h3><p>The third generation of web technology is known as Web 3.0. It is a decentralized network, which implies that instead of customers accessing the internet through services mediated by large tech companies such as Google, Apple, or Facebook, individuals own and govern areas of the internet themselves.</p><p>In block-chains, there is a consensus among blocks which is an algorithm that makes the decentralized record-keeping more similar to a centralized database. It’s an automated process to ensure that there exists only one single valid copy of the record shared by all the nodes. There exist different types of consensus in a blockchain system, here I will present the two primary types of consensus in the blockchain system. In short, the consensus protocol ensures that every new block added to the Blockchain is the one and only version of the truth that all nodes in the Blockchain agree on.</p><ol><li>Proof-of-Work consensus(POW): The algorithms that run the distributed system in this sort of consensus reward miners who solve mathematical puzzles. New network transactions are sent from the software wallets that execute them to all of the network’s mining clients. Each mining client in Bitcoin, for example, has a memory pool that collects incoming unconfirmed transactions. The mining software verifies new transactions and groups them into blocks at a given interval(which might be different from blockchain to blockchain). Each mining client has a financial incentive to be the first to create a new block of transactions, which the other machines will all accept as the new network truth state and add to the decentralized copy of the Blockchain they keep on their peer node. The major disadvantage of POW consensus is that it uses very high computation power to produce crypto security which is wasteful and hazardous for the environment now and in the future when the blockchain system when most of the people in the world start using the system.</li><li>Proof-of-stake(POS): Instead, this consensus mechanism is based on network ownership. The originator of a new block in POS systems is chosen in a deterministic manner, based on its stake, or degree of commitment (wealth) in the network. POS systems, on the other hand, maybe overly complicated with voting layers and aren’t always more efficient than POW in terms of what may be termed unnecessary processing. Thus, PoS encourages validators through an incentive mechanism to reach an agreement.</li></ol><p>The NFT market’s increasing carbon footprint is another issue that needs to be addressed due to the high processing required for each transaction. According to a report by The New York Times, “the creation of an average NFT has a stunning environmental footprint of over 200 kilograms of planet-warming carbon, equivalent to driving 500 miles in a typical American gasoline-powered car.” The immense carbon footprint of NFT issuance comes from the consensus mechanism deployed by the leading blockchain for NFTs. Unfortunately, the majority of NFT mining and trading is taking place on a Proof of Work (PoW) chain that requires energy-intensive crypto mining every time an NFT is created or traded. Needless to say, this is not sustainable.</p><h3>Objective</h3><p>This project tries to enable clients to be able to solve the challenges ensuring that certificates are available to all trainees in a secure way, and (if possible) that certificate holders can benefit from smart contract actions now and in the future. At present, certificates are distributed as simple PDF files, without the ability to verify their authenticity nor can trainer undertake smart actions with the trainees/their contracts. To solve that problem, after starting to use the digital certificate, the training organization will publicly announce its crypto wallet address. So, if someone can prove that they have received an NFT token directly from the address given, they have completed the program.</p><h3>The chain we will be using</h3><p>10 Academy(the training organization) has partnered with Algorand to use the Algorand Blockchain as the foundational element of the NFT, and this must now be implemented. I will be building an end-to-end Web3 dapps on the Algorand Blockchain that will help 10 Academy generate and distribute Non-Fungible Tokens (NFTs) as 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>Algorand is a new-gen blockchain that is bridging the decentralized and centralized world of finance. Its native crypto is ALGO. Algorand Standard Assets run on the blockchain’s “Layer-1” and include fungible, non-fungible, restricted fungible, and restricted non-fungible assets. Algorand uses a POS consensus algorithm to obtain a blockchain agreement, which is ecologically friendly and eliminates high commuting power waste. Algorand’s system picks block validators randomly and secretly for every period. In this way, Algorand achieves full decentralization, as it gives all users equal chances to be selected by the system. This also ensures the highest possible degree of security, since no one knows who the next block validators are. There is no need for mining, which allows Algorand to achieve carbon neutrality, an important selling point for NFTs as they go mainstream. This is a significant step forward from the issues that different blockchain technologies have faced in the past. The Algorand chain also has cheaper transaction costs, which makes it ideal for the application we’ll be using.</p><h3>Technology stack used</h3><p><strong>Front-End</strong>: For the front-end development of the project, I used React.js and the bootstrap framework for CSS. The front-end code was used to handle all of the trainee logic as well as the admin management.</p><p>I have used the AlgoSigner chrome extension for a wallet integration which will enable the admin and the trainee to sign different transactions.</p><p>The admin section</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QPcpKX9lM2Vof4gl" /></figure><p>The admin of the program will have an option to:</p><ol><li>Add a trainee to the program</li><li>Mint the certificates of trainees that passed the program</li><li>View the list of trainees</li><li>View list of optins from trainees</li><li>Accept or decline an opt-in request from a trainee</li></ol><p>The Trainee Section</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NSlFGS6bDavMd6Lt" /></figure><p>The trainee of the system has the functionality that enables the trainee to:</p><ol><li>Opt-in for a certificate once he finishes the training (the transaction is signed using AlgoSigner as a wallet integration).</li><li>View his minted certificate when the asset is transferred from the admin</li></ol><p><strong>Back-end: </strong>For the back-end, I have used Node.JS with express as the framework and MongoDB as the database. The major functionalities that are in the back-end are:</p><ol><li>A route to view the list of trainees(Admin side).</li><li>A route to add a trainee to the program(Admin side).</li><li>An emailing system to email the asset id that has been minted by the admin. The asset-id the student or the trainee will mint will be emailed by the system once the trainee finishes his training program and the admin mints his certificate to the blockchain (Admin side).</li><li>Opt-in for a certificate(Trainee side)</li><li>View his asset(Trainee side)</li><li>Asset creation, asset transfer, and asset freezing functionalities by using the Algo SDK.</li></ol><p>The implementation of algorand’s block-chain is such that an asset can only be transferred to someone who has opted-in. This is because anyone could transfer a non-valuable asset and impose a charge on the receiver. To avoid this, Alogrand updated the implementation to require that any form of asset transfer be requested/opted-in for by the receiver. So, in our scenario, the trainee will opt-in for a certain asset using the asset-id that the admin has emailed to the trainee, and then the system admin can transfer that asset to the trainee.</p><h3><strong>Future Plans</strong></h3><p>Future plan for the current application is to implement all the functionality using a smart contract(Reach).</p><p><a href="https://tenx-dapp.netlify.app/">Live Link</a></p><p><a href="https://github.com/jedisam/certificate-distribution-smart-contract">Github</a></p><p>References:</p><p><a href="https://developer.algorand.org/docs/get-started/dapps/">https://developer.algorand.org/docs/get-started/dapps/</a></p><p><a href="https://developer.algorand.org/tutorials/creating-javascript-transaction-purestake-api/">https://developer.algorand.org/tutorials/creating-javascript-transaction-purestake-api/</a></p><p><a href="https://d.mba/blog/school-certificates-for-the-digital-age">https://d.mba/blog/school-certificates-for-the-digital-age</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=93d185430869" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/digital-certificate-distribution-using-alogrand-blockchain-93d185430869">Digital Certificate Distribution using Alogrand’s Blockchain with wallet integration</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Machine learning and deep learning approach to predict Pharmaceuticals Sales using python]]></title>
            <link>https://medium.com/@yidisam18/machine-learning-and-deep-learning-approach-to-predict-pharmaceuticals-sales-using-python-27d16450259c?source=rss-6f96426a180a------2</link>
            <guid isPermaLink="false">https://medium.com/p/27d16450259c</guid>
            <category><![CDATA[exploratory-data-analysis]]></category>
            <category><![CDATA[predictions]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Yididiya Samuel]]></dc:creator>
            <pubDate>Sat, 28 May 2022 20:34:15 GMT</pubDate>
            <atom:updated>2022-05-28T23:15:56.485Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yLQFkwhQjnS-iSHO" /></figure><h3>Table of Contents:</h3><ol><li>Introduction</li><li>Objectives</li><li>Exploratory Data Analysis</li><li>Modeling</li><li>Conclusion</li></ol><h3>Introduction</h3><p>Every organization can benefit from a sales forecast to help them make better decisions and accurate forecasting of sales is an important and inexpensive way to increase profits. Without effectively anticipating client demand and future product/service sales, no business can improve its financial performance. Business owners have traditionally forecasted revenues based on their years of experience, which has proven to be less accurate. These days, business owners don’t simply want to rely on their own judgment to anticipate sales; they want to use historical data to forecast sales accurately. The greatest way to forecast sales with considerably more accuracy is to use deep learning and machine learning. In this article, I will show how to apply machine learning to forecast future sales.</p><h3>Objectives</h3><p>The finance team wants to forecast sales in all their stores across several cities six weeks ahead of time. It has been identified factors such as promotions, competition, school and state holidays, seasonality, and locality as necessary for predicting the sales across the various stores. The main objective is to build and serve an end-to-end product that delivers this prediction to analysts in the finance team six weeks ahead of time.</p><h3>Dataset Description</h3><p>The data used for this project is from the Kaggle competition and it can be downloaded <a href="https://drive.google.com/file/d/1EgqYG4gN3GKtMhmPala81dEsFpFVm97j/view?usp=sharing">here</a>.</p><p>Data fields:</p><p><strong>Id</strong> — an Id that represents a (Store, Date) duple within the test set</p><p><strong>Store</strong> — a unique Id for each store</p><p><strong>Sales</strong> — the turnover for any given day (this is what you are predicting)</p><p><strong>Customers</strong> — the number of customers on a given day</p><p><strong>Open</strong> — an indicator for whether the store was open: 0 = closed, 1 = open</p><p><strong>StateHoliday</strong> — indicates a state holiday. Normally all stores, with few exceptions, are closed on state holidays. Note that all schools are closed on public holidays and weekends. a = public holiday, b = Easter holiday, c = Christmas, 0 = None</p><p><strong>SchoolHoliday</strong> — indicates if the (Store, Date) was affected by the closure of public schools</p><p><strong>StoreType</strong> — differentiates between 4 different store models: a, b, c, d</p><p><strong>Assortment</strong> — describes an assortment level: a = basic, b = extra, c = extended. Read more about assortment <a href="https://en.wikipedia.org/wiki/Retail_assortment_strategies">here</a>.</p><p><strong>CompetitionDistance</strong> — the distance in meters to the nearest competitor store.</p><p><strong>CompetitionOpenSince[Month/Year]</strong> — gives the approximate year and month of the time the nearest competitor was opened.</p><p><strong>Promo</strong> — indicates whether a store is running a promo on that day.</p><p><strong>Promo2</strong> — Promo2 is a continuing and consecutive promotion for some stores: 0 = store is not participating, 1 = store is participating.</p><p><strong>Promo2Since[Year/Week] </strong>— describes the year and calendar week when the store started participating in Promo2.</p><p><strong>PromoInterval</strong> — describes the consecutive intervals Promo2 is started, naming the months the promotion is started anew. E.g. “Feb, May, Aug, Nov” means each round starts in February, May, August, and November of any given year for that store.</p><p>There are two separate CSV files that will be used to train the model. These are:</p><ul><li>Train.csv</li><li>store.csv</li></ul><p>We will join these two tables based on the store ID on each data for the training.</p><h3>Exploratory Data Analysis of the Dataset</h3><pre>train_df = pd.read.csv(“train.csv”)<br>store_df = pd.read_csv(“store.csv”)</pre><h4>Data Overview</h4><pre>train_df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/731/0*rlrf5TudRobspqdA" /></figure><pre>store_df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jh_J06QiZeY7gKXC" /></figure><p>We can now merge the two tables based in the Store ID as follows:</p><pre>data = pd.merge(train_df, store_df, on=’Store’)</pre><p><strong>Total Sales of Stores:</strong></p><pre><strong>plt.figure(figsize=(12, 7))<br>sns.scatterplot(data=train_df, x=train_df[‘Store’], y=train_df[‘Sales’])</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/754/0*e57yTb7kMV1FIivu" /></figure><p>Most of the sales are within the range of 0–2,200 and there are multiple outliers that need to be handled.</p><p><strong>Sales Correlation with Customers for each Store Type:</strong></p><pre><strong>plt.figure(figsize=(12, 7))<br>sns.scatterplot(data=train_df[“Sales”, “Customers”], x=train_df[‘Customers’], y=train_df[‘Sales’])</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/754/0*lcomLY8OXYCiV__P" /></figure><p>The number of sales is positively correlated with the number of customers for each store type.</p><p>Sales correlation with competition Distance</p><pre><strong>plt.figure(figsize=(12, 7))<br>sns.scatterplot(data=train_df[“Sales”, “CompetitionDistance”], x=train_df[CompetitionDistance], y=train_df[‘Sales’])</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/754/0*bIAxNqmJZyX0Uqur" /></figure><p><strong>Interestingly, as the competition distance increases, the sales decreases. There are some sales for store type A as the competition distance is very high.</strong></p><p><strong>Sales on holidays</strong></p><pre><strong>plt.figure(figsize=(12, 7))<br>sns.barplot(data=holiday_df, x=’’StateHoliday’, y=’Sales’)</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/747/0*vMkWTUAwGPMMRqYV" /></figure><p><strong>There are fewer sales on holidays</strong></p><p><strong>Sales on each Month per store</strong></p><pre><strong>sns.relplot(x=”Month”, y=”Sales”, hue=”StoreType”, data=train_df);</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/409/0*2kKrChtvSkkatVTX" /></figure><p><strong>June has the highest amount of sales, January has the lowest</strong></p><p><strong>Sales on each Day</strong></p><pre><strong>sns.relplot(x=”DayOfWeek”, y=”Sales”, hue=”StoreType”, data=train_df);</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/409/0*ne1CZP4vHT9xWJjX" /></figure><p><strong>Store B is mostly open on Saturday and has a higher amount of Sales</strong></p><h3>Data Preprocessing</h3><ul><li>Filling missing values</li><li>Fill numerical features with their median</li></ul><pre>miss_1 = [‘Promo2SinceYear’, ‘Promo2SinceWeek’, ‘CompetitionOpenSinceMonth’, ‘CompetitionOpenSinceYear’, ‘CompetitionDistance’]</pre><pre>for col in miss_1:</pre><pre> df[col] = df[col].fillna(df[col].median()</pre><ul><li>Fill categorical features with mode</li></ul><pre>Categ_var = [‘PromoInterval’]<br>for col in Categ_var:</pre><pre>  df[col] = df[col].fillna(df[col].mode()[0])</pre><p>df[‘Open] = df[‘Open].fillna(0)</p><p>These should fill all missing values</p><ul><li>Handling outliers</li></ul><p>Most of the outliers are in the Sales and Customers column, I replaced outliers with IQR</p><pre>Columns = [‘Sales’, ‘Customers’]<br>for col in columns:</pre><pre>Q1, Q3 = df[col].quantile(</pre><pre>0.25), df[col].quantile(0.75)</pre><pre>IQR = Q3 — Q1</pre><pre>cut_off = IQR * 1.5</pre><pre>lower, upper = Q1 — cut_off, Q3 + cut_off</pre><pre>df[col] = np.where(</pre><pre>df[col] &gt; upper, upper, df[col])</pre><pre>df[col] = np.where(</pre><pre>df[col] &lt; lower, lower, df[col])</pre><ul><li>Label Encoding</li></ul><pre>from sklearn.preprocessing import LabelEncoder</pre><pre>categorical_columns = [‘PromoInterval’, ‘Assortment’, ‘StoreType’]<br># Label encoding</pre><pre>label_encoded_columns = preprocess.label_encode(train_df, categorical_columns)</pre><pre>label_encoded_columns = []</pre><pre># For loop for each columns</pre><pre>le = LabelEncoder()</pre><pre>for col in categorical_columns:</pre><pre> # We define new label encoder to each new column</pre><pre> # Encode our data and create new Dataframe of it,</pre><pre> column_dataframe = pd.DataFrame(</pre><pre> le.fit_transform(df[col]), columns=[col])</pre><pre> # and add new DataFrame to “label_encoded_columns” list</pre><pre> label_encoded_columns.append(column_dataframe)</pre><pre> # Merge all data frames<br>label_encoded_columns = pd.concat(label_encoded_columns, axis=1)</pre><pre>train_df.drop(categorical_columns, axis=1, inplace=True)</pre><pre># Merge DataFrames</pre><pre>train_df = pd.concat([train_df, label_encoded_columns], axis=1)</pre><h3>Modeling</h3><p>We can use machine learning models like Random Forest Regressor to predict sales as well as deep learning to have better accuracy for sales prediction.</p><p>Machine learning model (Random Forest Regressor)</p><p>It’s possible to use sklearn pipeline while building a machine learning model to compute all the data cleaning as well as modeling steps together. For the machine learning part, I used Random Forest Regressor to forecast sales.</p><pre>from sklearn.pipeline import Pipeline<br>from sklearn.impute import SimpleImputer<br>from sklearn.preprocessing import StandardScaler<br>from sklearn.ensemble import RandomForestRegressor<br></pre><pre>data_transformer = Pipeline(steps=[</pre><pre>(&#39;imputer&#39;, SimpleImputer(strategy=&#39;mean&#39;))</pre><pre>,(&#39;scaler&#39;, StandardScaler())</pre><pre>])</pre><pre>pipeline = Pipeline(steps = [</pre><pre>(&#39;preprocessor&#39;, data_transformer)</pre><pre>,(&#39;regressor&#39;,RandomForestRegressor(max_depth=57, random_state=0))</pre><pre>])</pre><p>Finally, fit and score the model</p><pre>model_rg = pipeline.fit(X_train, y_train)<br>model_rg.score(X_test, y_test)</pre><p>I got an accuracy of about 90%.</p><p>To save the model:</p><pre><em># Save model based on time st</em></pre><pre>model_rg = &#39;../models/&#39; + datetime.datetime.now().strftime(&quot;%Y-%m-%d-%H-%M-%S&quot;) + &#39;.pkl&#39;</pre><pre>pickle.dump(rf_model, open(rf_model_path, &#39;wb&#39;))</pre><p>Deep Learning approach</p><p>For deep learning, I used TensorFlow to train my model. When training data that is time series or changing overtime, the train-test split isn’t the same way as it is used to be done using train_test_split library from sklearn. This is because we want to train our data to predict the future based on the past unseen data. The best way to do this is to sort the data based on the Date index and split it using the manual way. Here is the code section I used to split the data:</p><pre>train_size = int(len(df2) * 0.70) <br>test_size = len(df2) - train_size <br>train, testt = df2.iloc[0:train_size], df2.iloc[train_size:len(df2)]<br>print(train.shape, testt.shape) #(591036, 2) (253302, 2)</pre><p>The same goes for the test Data:</p><pre>test_size = int(len(testt) * 0.50)<br>val_size = len(testt) - test_size<br>test, val = testt.iloc[0:test_size],testt.iloc[test_size:len(testt)]<br>print(val.shape, test.shape)</pre><p>We can then build an LSTM model to train the Data:</p><pre>model = Sequential()<br>model.add(LSTM(128, input_shape=(X_train.shape[1], train.shape[2])))<br>model.add(Dropout(rate=0.2))<br>model.add(RepeatVector(X_train.shape[1]))<br>model.add(LSTM(128, return_sequences=True))<br>model.add(Dropout(rate=0.2))<br>model.add(TimeDistributed(Dense(X_train.shape[2])))<br>model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=0.0001, epsilon=1e-08, decay=0.01), loss=&#39;mae&#39;)<br>model.summary()</pre><p>Finally, fit the data</p><pre>history = model.fit(X_train, y_train, epochs=10, batch_size=40, validation_data=(X_val, y_val), callbacks=[keras.callbacks.EarlyStopping(monitor=&#39;val_loss&#39;, patience=3, mode=&#39;min&#39;)], shuffle=False)</pre><h3>Conclusion</h3><p>Time series analysis is a very useful way to predict future trends based on ongoing practices. Current deep learning approaches have opened a great way to increase the accuracy and efficiency of the model, and more work can be done by using a fine-tuned implementation of deep learning given the required computational resource and time.</p><h3>References</h3><ul><li><a href="https://machinelearningmastery.com/time-series-forecasting-long-short-term-memory-network-python/">Time Series Forecasting with the Long Short-Term Memory Network in Python - Machine Learning Mastery</a></li><li><a href="https://machinelearningmastery.com/how-to-develop-deep-learning-models-for-univariate-time-series-forecasting/">Deep Learning Models for Univariate Time Series Forecasting - Machine Learning Mastery</a></li></ul><p><a href="https://medium.com/vickdata/a-simple-guide-to-scikit-learn-pipelines-4ac0d974bdcf">https://medium.com/vickdata/a-simple-guide-to-scikit-learn-pipelines-4ac0d974bdcf</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=27d16450259c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Applying machine learning for A/B hypothesis testing using]]></title>
            <link>https://medium.com/@yidisam18/applying-machine-learning-for-a-b-hypothesis-testing-using-ca7377d2ac59?source=rss-6f96426a180a------2</link>
            <guid isPermaLink="false">https://medium.com/p/ca7377d2ac59</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[a-b-testing]]></category>
            <category><![CDATA[dvc]]></category>
            <category><![CDATA[hypothesis-testing]]></category>
            <dc:creator><![CDATA[Yididiya Samuel]]></dc:creator>
            <pubDate>Sat, 21 May 2022 19:10:38 GMT</pubDate>
            <atom:updated>2022-05-21T19:12:03.982Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/275/0*M2lDwhXRgaSncdRN" /></figure><h3>Introduction</h3><p>These days, hardly one wants to hear other people’s viewpoints. To make corporate decisions, political moves, shift careers, and so on, everyone relies on the outcome and conclusion of data. The current activity takes a scientific approach and is data-driven. And when it comes to marketing or design decisions for websites, advertisements, or other digital efforts, A/B testing is the ideal approach to eliminate uncertainties and gut feelings.</p><p>A/B testing, commonly known as split testing, is a randomized experimentation method in which two or more copies of a variable (web page, page element, etc.) are given to various segments of website users at the same time to see which one has the most impact and drives business metrics.</p><p>It can also be viewed as an online experiment used to compare prospective enhancements to a control (or original) version of a website, mobile application, or ad. Simply said, statistical analysis allows you to see which variant (version) works best for your audience. The goal of this study is to find new product variants that will improve the existing product’s performance and make it more successful and optimal, resulting in a favorable therapeutic effect.</p><p>One example of AB testing is determining the importance of Brand Awareness. Different sorts of commercials are used by different advertiser companies to build brand awareness. They want to determine if their advertisement improves brand recognition or has no effect after each advertisement. There may be a rise in the number of favorable answers after viewing the commercial, but this could be due to a variety of factors rather than the advertisement itself. AB testing comes in handy in this situation. We can successfully evaluate the hypothesis of the brand impact optimizer using AB testing. It is possible to make significant changes in every part of today’s organization by employing this statistical framework.</p><h3>Why should you consider A/B testing?</h3><p>If B2B companies are dissatisfied with the number of unqualified leads they receive each month, eCommerce firms are dealing with a high percentage of cart abandonment. Meanwhile, low viewer engagement is a problem for media and publishing companies. Some typical issues, such as leaks in the conversion funnel, drop-offs on the checkout page, and so on, have an impact on these basic conversion KPIs. These are some of the reasons why A/B testing should be considered.</p><ul><li><strong>Low-risk business change</strong></li></ul><p>Businesses can make big adjustments to their products in stages. These will ensure that their organization improves consumer happiness while also lowering the risk of their present conversion rate. For instance, an online learning platform can gradually boost conversion rates by employing various calls to action that increase the response rates of students interested in enrolling in the course.</p><ul><li><strong>Get better Brand awareness</strong></li></ul><p>Advertising businesses can raise brand awareness by selecting the correct type of ads that improve customer positive reaction rates, like in the example given in the introductory section.</p><ul><li><strong>Boost future commercial gains</strong></li></ul><p>Businesses can change the color, typeface, or even the entire layout of their websites. When A/B testing, the choice to implement one version or the other should always be based on data. Do not stop testing until the design is complete. Test other web page elements once the new version goes live to verify that the most engaging version is served to visitors.</p><h3>Types of A/B testing</h3><ul><li><strong>Classical A/B Testing</strong></li></ul><p>It is a sort of testing in which the addition or removal of a certain element is examined to see if there is a difference in conversion rates between the control and experimental groups. The following are the steps to calculate A/B testing using the classical method:</p><p>The data’s P-value is determined first. P-value is a statistical measurement used to validate a hypothesis against observed data. It is the likelihood of generating outcomes as extreme as the observed results of a statistical hypothesis test, provided that the null hypothesis is correct. The area under the probability distribution curve for all values of statistics that are at least as far from the reference value as the observed value is, relative to the total area under the probability distribution curve, can be determined using integral calculus. It can be estimated using spreadsheets based on the statistics’ probability distribution. One can decide whether to accept the null hypothesis or not based on the determined P-value.</p><p>The classical AB testing first defines a baseline conversion rate which is the current conversion rate under the existing design and the minimum detectable effect which is the minimum improvement over the conversion rate of the existing asset one wants to detect.</p><p>The MDE can be calculated as desired conversion lift / BCR * 100</p><ul><li>It will then calculate the sample size required for the experiment and the results of the AB test will be calculated.</li><li>One can use the Z-test when the population variance is known and/or the sample size is bigger than 30. The Z test will be calculated as</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*sGzQ8-5CpM7QjGsb" /></figure><ul><li><strong>Sequential testing</strong></li></ul><p>Sequential testing is an updated/modified version of traditional A/B testing. It allows consumers to complete the experiment sooner while reducing the risk of misleading findings. When implementing sequential testing, the following strategy is used:</p><ul><li>Choosing sample size</li><li>Randomly assigning variations under test to the treatment and control, with 50% probability each.</li><li>Tracking the number of incoming successes for both variations. Let’s refer to the conversion rate of treatment variation as T and CR of control as C.</li><li>Finishing the test when T−C reaches √2N and declare the treatment variation to be the winner of your A/B test.</li><li>Finishing the test when T+C reaches N. In such a case, declare that the experiment had no winner.</li></ul><h4>Advantages of sequential A/B testing over classical A/B testing</h4><ul><li>The main advantage of sequential testing is that it enables the user to finish up the experiment much earlier than classical testing without compromising the false-positive results. The classical testing only allowed to get the test result at the end of the sample size for both variations is reached. In turn, the sequential testing allows multiple checks on every step, ensuring that the error level won’t exceed 5%.</li><li>optimize necessary observation (sample size).</li><li>Reduce the likelihood of error.</li></ul><h3>Machine Learning approach for A/B testing</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/545/0*9nxj3Ws2dSmSR4Ra" /></figure><p>Machine Learning methods, unlike statistical inference, allow us to model large systems that encompass all ongoing events, user attributes, and more. It enables us to extract system-related data, allowing the researcher to focus on important elements of the prediction. In this case, we’ll utilize machine learning to forecast whether a certain ad will increase client awareness of the product.</p><p>Utilizing data from the advertising agency, we’ll look for A/B testing using classical, sequential, and machine learning methods.</p><h4>Background Information</h4><p>Business objective</p><p>An advertising company is running an online ad for a client with the intention of increasing brand awareness. The advertiser company earns money by charging the client based on user engagements with the ad it designed and serves via different platforms. To increase its market competitiveness, the advertising company provides a further service that quantifies the increase in brand awareness as a result of the ads it shows to online users. The main objective of this project is to test if the ads that the advertising company runs resulted in a significant lift in brand awareness.</p><p><strong>Data</strong></p><p>The BIO data for this project is a “Yes” and “No” response of online users to the following question</p><p><strong><em>Q: Do you know the brand Lux?</em></strong></p><p>O Yes</p><p>O No</p><p>This is a test run and the main objective is to validate the hypothesis algorithm you built. SmartAd ran this campaign from 3–10 July 2020. The users that were presented with the questionnaire above were chosen according to the following rule:</p><p><strong><em>Control</em></strong>: users who have been shown a dummy ad</p><p><strong><em>Exposed:</em></strong> users who have been shown a creative (ad) that was designed by SmartAd for the client.</p><p>The data is available for download<a href="https://drive.google.com/file/d/1FVPOkNiQioJJ1A-NTy3YnoWYJZheCjPg/view?usp=sharing"> here</a>.</p><p>The data collected for this challenge has the following columns</p><ul><li><strong>auction_id: </strong>the unique id of the online user who has been presented the BIO. In standard terminologies this is called an impression id. The user may see the BIO questionnaire but choose not to respond. In that case both the <strong>yes</strong> and <strong>no</strong> columns are zero.</li><li><strong>experiment</strong>: which group the user belongs to — control or exposed.</li><li><strong>date</strong>: the date in YYYY-MM-DD format</li><li><strong>hour</strong>: the hour of the day in HH format.</li><li><strong>device_make</strong>: the name of the type of device the user has e.g. Samsung</li><li><strong>platform_os: </strong>the id of the OS the user has.</li><li><strong>browser</strong>: the name of the browser the user uses to see the BIO questionnaire.</li><li><strong>yes</strong>: 1 if the user chooses the “Yes” radio button for the BIO questionnaire.</li><li><strong>no</strong>: 1 if the user chooses the “No” radio button for the BIO questionnaire.</li></ul><p><strong>EDA of the dataset</strong></p><p>Data overview</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jrIafsy7yRKdWVno" /><figcaption>Data overview</figcaption></figure><p>Data distribution</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/486/0*slnxl-XqBsc7h5xO" /><figcaption>Data description</figcaption></figure><p>Time distribution of the data for people who did not participate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2EvdHx0_K393Sznn" /></figure><p>Time distribution for people who participated in the campaign.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4a4eQngXnozl8JUy" /></figure><p>The time distribution for users that participated is similar to those that did not participate in the campaign. It can be clearly seen that time distribution wasn’t the factor.</p><p>Treatment distribution for participating users</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/393/0*oXcuPOOyCeD_gklZ" /></figure><p>It can be seen that there is a little amount of data that participated in the campaign.</p><p>Date distribution for participated users.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_Gl4ey18e0zQ4m3p" /></figure><p>Browser distribution for those that participated in the campaign.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KQ9v8Z6z5Xz8FHCv" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*r_yEgV5PUwv9nJv9" /></figure><p>Some browsers are not present which might mean that the ad platform might not be working on some browsers.</p><p>Enough of EDA, now let’s go over the testing algorithms.</p><p><strong>Classical A/B Testing</strong></p><p>The data needs to be normalized for classical A/B testing.</p><p>&gt;&gt; Question: Does the Smart add (experiment = 1) show an improvement in user engagement (response rate)</p><p>Null Hypothesis:</p><p>H0: there is no difference in brand awareness between the exposed and control groups</p><p>Alt Hypothesis:</p><p>H1: there is a difference in brand awareness between the exposed and control groups</p><p>Method: Binomial test</p><p>Threshold or significance level: 0.05</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/733/0*7el2gt4sTwkqoaTo" /></figure><p>The distribution in blue is the probability of conversions for the control group while the distribution in orange is the probability of conversions for the exposed group. As we can see there is a difference between the mean of the two distributions.</p><p>Using the proprotions_ztest from statsmodels.stats.proportion, we can calculator the z-test, p-value as follows:</p><blockquote>#storing number of conversions for exposed and control groups as numpy arrays</blockquote><blockquote>count = np.array([exposed_converted.shape[0], control_converted.shape[0]])</blockquote><blockquote>#storing sample sizes of exposed and control group as numpy arrays</blockquote><blockquote>nobs = np.array([exposed.shape[0], control.shape[0]])</blockquote><blockquote>#storing results of z test in variables</blockquote><blockquote>stat, p_val = proportions_ztest(count, nobs, alternative = ‘larger’)</blockquote><p>The P-value result is 0.25 which is less than the significance level, thus we don’t have enough evidence to reject the null hypothesis.</p><p><strong>A/B testing formulation in Machine Learning context:</strong></p><p><strong>Training and Testing Sets</strong></p><p>For each version of the data, we split the data into 70% training, 20% validation, and 10% test sets. We will train the model using 5-fold validation. The steps in the machine learning model development are the following:</p><ol><li>Checking for missing values.</li><li>Checking for outliers.</li><li>Splitting the data.</li><li>Encoding categorical columns.</li><li>Get the day of the week from the date column as a new column</li><li>Using the cross_validate method from sklearn.mode_selection to train the data in 5-fold validation.</li></ol><p><strong>Result: </strong>Test Metrics</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/515/1*oJp1xj7juOUkmjkwqbZo5g.png" /><figcaption>Test metrics result</figcaption></figure><p>7. Feature importance</p><p><strong>Advantages of using MLFlow and DVC, K-Fold in ML experimentation</strong></p><p>I have used DVC in the machine learning process to version data and track it across each version change. MLFlow was used to track model development and accuracy metrics.</p><p>DVC has the advantage of reducing the amount of storage space necessary to handle your data sets while also assisting in tracking changes made while conducting various operations on the data. We will face numerous challenges without DVC, such as diagnosing a model fault caused by inconsistent model outputs.<br>The main advantages of including MLflow in ML experimentation are the transparency and standardization it brings to the table when it comes to training, tuning, and deploying ML models.</p><p>K-fold cross-validation is a preferable strategy for validating our model’s performance. It uses distinct chunks of the data set as the validation set to evaluate the model.<br>Our data collection is divided into K-folds. K represents the number of folds into which you want to split your data. If we use 5-folds, the data set divides into five sections. In different iterations, one part becomes the validation set.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*PM93y9CfuzaLIxYG" /></figure><p><strong>Limitations of the analysis</strong></p><p>The number of data for people that have reacted to the ad is very small. This has been a major bottleneck for the machine learning model.</p><p><strong>Conclusion</strong></p><p>Based on the analysis it can be concluded that the new ad did not have an impact on brand awareness. We did not have enough data for the machine learning model but it can be seen that date and the browser have more importance for the model so the ad company can focus more on those attributes to test more on customers’.</p><p>You can find the code on my GitHub <a href="https://github.com/jedisam/abtest-mlops">here</a>.</p><p>References:</p><p><a href="https://www.austinrochford.com/posts/2014-01-01-intro-to-sequential-testing.html">https://www.austinrochford.com/posts/2014-01-01-intro-to-sequential-testing.html</a></p><p><a href="https://www.business-science.io/business/2019/03/11/ab-testing-machine-learning.html">https://www.business-science.io/business/2019/03/11/ab-testing-machine-learning.html</a></p><p><a href="http://sl8r000.github.io/ab_testing_statistics/">http://sl8r000.github.io/ab_testing_statistics/</a></p><p><a href="https://github.com/mdcramer/SPRT">https://github.com/mdcramer/SPRT</a></p><p><a href="https://hbr.org/2017/06/a-refresher-on-ab-testing">https://hbr.org/2017/06/a-refresher-on-ab-testing</a></p><p><a href="https://www.kaggle.com/jgroff/unit-3-hypothesis-testing">https://www.kaggle.com/jgroff/unit-3-hypothesis-testing</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ca7377d2ac59" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>