<?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 Natnael Melese on Medium]]></title>
        <description><![CDATA[Stories by Natnael Melese on Medium]]></description>
        <link>https://medium.com/@natnaelmelese?source=rss-d8b62df65657------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*EcMY6IA6nNhlfqPa.</url>
            <title>Stories by Natnael Melese on Medium</title>
            <link>https://medium.com/@natnaelmelese?source=rss-d8b62df65657------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 13:27:28 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@natnaelmelese/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[Creating a Private Network in Ethereum]]></title>
            <link>https://medium.com/@natnaelmelese/creating-a-private-network-in-ethereum-1cd741201b7c?source=rss-d8b62df65657------2</link>
            <guid isPermaLink="false">https://medium.com/p/1cd741201b7c</guid>
            <category><![CDATA[geth]]></category>
            <category><![CDATA[web3]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[ethereum]]></category>
            <dc:creator><![CDATA[Natnael Melese]]></dc:creator>
            <pubDate>Sat, 12 Nov 2022 22:54:01 GMT</pubDate>
            <atom:updated>2022-11-12T22:54:01.177Z</atom:updated>
            <content:encoded><![CDATA[<p>Create your first private network in Ethereum</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BVn936_Qt3azWFH-J7HI9Q.jpeg" /></figure><h4>Part 1 of this article:</h4><p><a href="https://medium.com/@natnaelmelese/etherium-refund-by-location-smart-contract-ecc031ee5f7c">Etherium: Refund by Location Smart Contract</a></p><h3>What is Ethereum Private Network?</h3><p>A blockchain that is entirely private and separate from the main Ethereum network is known as an Ethereum Private Network. Organizations mostly use the Ethereum Private Network to limit Blockchain read access. The only nodes allowed to access this Blockchain will be those with the appropriate permissions. The nodes in this network are not linked to the nodes in the main network, and they can only communicate with other nodes in this private Blockchain.</p><h3>Installing Ethereum on Ubuntu</h3><p>To create an Ethereum Private Network, we first need to have Ethereum installed in our system. In this section of the Ethereum Private Network Tutorial, you will learn how to install Ethereum on Ubuntu.</p><pre>$ sudo apt-get install software-properties-common<br>$ sudo add-apt-repository -y ppa:ethereum/ethereum<br>$ sudo apt-get update<br>$ sudo apt-get install ethereum</pre><h3>Creating Accounts For Ethereum Private Network</h3><p>Before creating new accounts, let us create a new directory. By using the below commands:</p><pre>$ mkdir eth-private<br>$ cd eth-private</pre><p>Let’s create two accounts:</p><pre>$ mkdir node0 node1<br>$ geth --datadir ./node0 account new<br>$ geth --datadir ./node0 account new</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9n9V3HqO71d77iRa_LU3xw.png" /></figure><p><strong><em>Do not forget both passphrases! </em></strong>Save these addresses somewhere because we will be using these further.</p><h4>Creating Genesis File</h4><p>The attributes that characterize the Blockchain are contained in a Genesis file. As the starting point of the Blockchain, a Genesis file must be created in order to construct a Blockchain. Let’s build the Genesis file right away.</p><p>We will be using <a href="https://github.com/puppeth">Puppeth</a>.</p><p>Puppeth lets you create a new Ethereum network down to the genesis block, bootnodes, miners, and ethstats servers without the hassle that it would normally entail.</p><pre>┌──(n㉿kali)-[~/Documents/10_Academy/GethPoA/eth-private]<br>└─$ puppeth<br>+-----------------------------------------------------------+<br>| Welcome to puppeth, your Ethereum private network manager |<br>|                                                           |<br>| This tool lets you create a new Ethereum network down to  |<br>| the genesis block, bootnodes, miners and ethstats servers |<br>| without the hassle that it would normally entail.         |<br>|                                                           |<br>| Puppeth uses SSH to dial in to remote servers, and builds |<br>| its network components out of Docker containers using the |<br>| docker-compose toolset.                                   |<br>+-----------------------------------------------------------+<br><br>Please specify a network name to administer (no spaces, hyphens or capital letters please)<br>&gt; testnetwork<br><br>Sweet, you can set this via --network=testnetwork next time!<br><br>INFO [11-12|17:17:29.433] Administering Ethereum network           name=testnetwork<br>WARN [11-12|17:17:29.470] No previous configurations found         path=/home/n/.puppeth/testnetwork<br><br>What would you like to do? (default = stats)<br> 1. Show network stats<br> 2. Configure new genesis<br> 3. Track new remote server<br> 4. Deploy network components<br>&gt; </pre><p>By selecting option 2 we configure can create new genesis file</p><pre>What would you like to do? (default = stats)<br> 1. Show network stats<br> 2. Configure new genesis<br> 3. Track new remote server<br> 4. Deploy network components<br>&gt; 2<br><br>What would you like to do? (default = create)<br> 1. Create new genesis from scratch<br> 2. Import already existing genesis<br>&gt; 1<br><br>Which consensus engine to use? (default = clique)<br> 1. Ethash - proof-of-work<br> 2. Clique - proof-of-authority<br>&gt; 2<br><br>How many seconds should blocks take? (default = 15)<br>&gt; 15<br><br>Which accounts are allowed to seal? (mandatory at least one)<br>&gt; 0x</pre><p>Now we use the previous account addresses.</p><pre>Which accounts are allowed to seal? (mandatory at least one)<br>&gt; 0x2Bd22E105E6Bf66e3748a3be2d94099572E1bd35<br>&gt; 0x2E0A40623aE4671cD934744784B63a948f450d83<br>&gt; 0x<br><br>Which accounts should be pre-funded? (advisable at least one)<br>&gt; 0x2E0A40623aE4671cD934744784B63a948f450d83<br>&gt; 0x2Bd22E105E6Bf66e3748a3be2d94099572E1bd35<br>&gt; 0x</pre><pre>Should the precompile-addresses (0x1 .. 0xff) be pre-funded with 1 wei? (advisable yes)<br>&gt; y<br><br>Specify your chain/network ID if you want an explicit one (default = random)<br>&gt; 202111</pre><p>Save the genesis file.</p><pre>What would you like to do? (default = stats)<br> 1. Show network stats<br> 2. Manage existing genesis<br> 3. Track new remote server<br> 4. Deploy network components<br>&gt; 2<br><br> 1. Modify existing configurations<br> 2. Export genesis configurations<br> 3. Remove genesis configuration<br>&gt; 2<br><br>Which folder to save the genesis spec into? (default = current)<br>  Will create testnetwork.json<br>&gt; <br>INFO [11-12|17:25:14.267] Saved native genesis chain spec          path=testnetwork.json</pre><p><strong><em>testnetwork.json</em></strong> has been created inside the eth-private directory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/301/1*9s9lkpmp9Epa9vv41D--Ow.png" /></figure><h4>Instantiating Data Directory</h4><p>Before starting the Blockchain, we have to instantiate the data directory. The Data Directory is the directory where the data related to the Blockchain is stored. To instantiate the data directory, run the following command:</p><pre>┌──(n㉿kali)-[~/Documents/10_Academy/GethPoA/eth-private]<br>└─$ geth --datadir ./node0 init ./testnetwork.json <br>INFO [11-12|17:29:41.814] Maximum peer count                       ETH=50 LES=0 total=50<br>INFO [11-12|17:29:41.816] Smartcard socket not found, disabling    err=&quot;stat /run/pcscd/pcscd.comm: no such file or directory&quot;<br>INFO [11-12|17:29:41.833] Set global gas cap                       cap=50,000,000<br>INFO [11-12|17:29:41.835] Allocated cache and file handles         database=/home/n/Documents/10_Academy/GethPoA/eth-private/node0/geth/chaindata cache=16.00MiB handles=16<br>INFO [11-12|17:29:44.212] Opened ancient database                  database=/home/n/Documents/10_Academy/GethPoA/eth-private/node0/geth/chaindata/ancient/chain readonly=false<br>INFO [11-12|17:29:44.212] Writing custom genesis block <br>INFO [11-12|17:29:44.283] Persisted trie from memory database      nodes=357 size=50.72KiB time=5.343584ms gcnodes=0 gcsize=0.00B gctime=0s livenodes=1 livesize=0.00B<br>INFO [11-12|17:29:44.286] Successfully wrote genesis state         database=chaindata hash=afbf4f..643643<br>INFO [11-12|17:29:44.286] Allocated cache and file handles         database=/home/n/Documents/10_Academy/GethPoA/eth-private/node0/geth/lightchaindata cache=16.00MiB handles=16<br>INFO [11-12|17:29:45.014] Opened ancient database                  database=/home/n/Documents/10_Academy/GethPoA/eth-private/node0/geth/lightchaindata/ancient/chain readonly=false<br>INFO [11-12|17:29:45.014] Writing custom genesis block <br>INFO [11-12|17:29:45.050] Persisted trie from memory database      nodes=357 size=50.72KiB time=1.430879ms gcnodes=0 gcsize=0.00B gctime=0s livenodes=1 livesize=0.00B<br>INFO [11-12|17:29:45.051] Successfully wrote genesis state         database=lightchaindata hash=afbf4f..643643<br>                                                                                                                    <br>┌──(n㉿kali)-[~/Documents/10_Academy/GethPoA/eth-private]<br>└─$ geth --datadir ./node1 init ./testnetwork.json<br>INFO [11-12|17:29:56.570] Maximum peer count                       ETH=50 LES=0 total=50<br>INFO [11-12|17:29:56.573] Smartcard socket not found, disabling    err=&quot;stat /run/pcscd/pcscd.comm: no such file or directory&quot;<br>INFO [11-12|17:29:56.578] Set global gas cap                       cap=50,000,000<br>INFO [11-12|17:29:56.582] Allocated cache and file handles         database=/home/n/Documents/10_Academy/GethPoA/eth-private/node1/geth/chaindata cache=16.00MiB handles=16<br>INFO [11-12|17:29:58.454] Opened ancient database                  database=/home/n/Documents/10_Academy/GethPoA/eth-private/node1/geth/chaindata/ancient/chain readonly=false<br>INFO [11-12|17:29:58.454] Writing custom genesis block <br>INFO [11-12|17:29:58.490] Persisted trie from memory database      nodes=357 size=50.72KiB time=5.732143ms gcnodes=0 gcsize=0.00B gctime=0s livenodes=1 livesize=0.00B<br>INFO [11-12|17:29:58.493] Successfully wrote genesis state         database=chaindata hash=afbf4f..643643<br>INFO [11-12|17:29:58.493] Allocated cache and file handles         database=/home/n/Documents/10_Academy/GethPoA/eth-private/node1/geth/lightchaindata cache=16.00MiB handles=16<br>INFO [11-12|17:29:59.035] Opened ancient database                  database=/home/n/Documents/10_Academy/GethPoA/eth-private/node1/geth/lightchaindata/ancient/chain readonly=false<br>INFO [11-12|17:29:59.035] Writing custom genesis block <br>INFO [11-12|17:29:59.068] Persisted trie from memory database      nodes=357 size=50.72KiB time=4.890809ms gcnodes=0 gcsize=0.00B gctime=0s livenodes=1 livesize=0.00B<br>INFO [11-12|17:29:59.071] Successfully wrote genesis state         database=lightchaindata hash=afbf4f..643643</pre><h4>Create a boot node</h4><p>A boot node is a node that serves just as the first connection point through which an Ethereum node connects to other nodes. It’s basically a relayer of information helping nodes connect.</p><p>Creation and running of a boot node is done as follows:</p><pre>$ bootnode --genkey=boot.key</pre><p>Now a boot.key file will be created inside eth-private directory</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/340/1*1I9L7wg4HXcbktdAsjP7Ew.png" /></figure><pre>┌──(n㉿kali)-[~/Documents/10_Academy/GethPoA/eth-private]<br>└─$ bootnode --nodekey=boot.key<br>enode://ae4d706f1d2141ac7de0622f87b4c23d988c272c6a31ff058e38ed8deb1930a9a4d19c5396a731476c81c4abfc3c8c1537f8b8b5448cb55d41ff0758daa5660d@127.0.0.1:0?discport=30301<br>Note: you&#39;re using cmd/bootnode, a developer tool.<br>We recommend using a regular node as bootstrap node for production deployments.<br>INFO [11-12|17:36:19.255] New local node record                    seq=1,668,292,579,254 id=618e42e8fa53b953 ip=&lt;nil&gt; udp=0 tcp=0</pre><p>Remember using cmd/bootnode is for development purpose only.</p><h4>Start individula nodes</h4><pre>┌──(n㉿kali)-[~/Documents/10_Academy/GethPoA/eth-private]<br>└─$ geth --datadir ./node1 --port 30302 --http --http.addr &#39;localhost&#39; --http.port 8545 --http.api &#39;personal,db,eth,net,web3,txpool,miner&#39; --bootnodes &#39; &#39; --networkid 202111 --allow-insecure-unlock --password 123456 --mine console<br>INFO [11-12|17:40:00.485] Maximum peer count                       ETH=50 LES=0 total=50<br>INFO [11-12|17:40:00.486] Smartcard socket not found, disabling    err=&quot;stat /run/pcscd/pcscd.comm: no such file or directory&quot;<br>INFO [11-12|17:40:00.489] Set global gas cap                       cap=50,000,000<br>INFO [11-12|17:40:00.491] Allocated trie memory caches             clean=154.00MiB dirty=256.00MiB<br>INFO [11-12|17:40:00.500] Allocated cache and file handles         database=/home/n/Documents/10_Academy/GethPoA/eth-private/node1/geth/chaindata cache=512.00MiB handles=524,288<br>INFO [11-12|17:40:00.884] Opened ancient database                  database=/home/n/Documents/10_Academy/GethPoA/eth-private/node1/geth/chaindata/ancient/chain readonly=false<br>INFO [11-12|17:40:00.914]  <br>INFO [11-12|17:40:00.914] --------------------------------------------------------------------------------------------------------------------------------------------------------- <br>INFO [11-12|17:40:00.914] Chain ID:  202111 (unknown) <br>INFO [11-12|17:40:00.914] Consensus: Clique (proof-of-authority) <br>INFO [11-12|17:40:00.915]  <br>INFO [11-12|17:40:00.915] Pre-Merge hard forks: <br>INFO [11-12|17:40:00.915]  - Homestead:                   0        (https://github.com/ethereum/execution-specs/blob/master/network-upgrades/mainnet-upgrades/homestead.md) <br>INFO [11-12|17:40:00.915]  - Tangerine Whistle (EIP 150): 0        (https://github.com/ethereum/execution-specs/blob/master/network-upgrades/mainnet-upgrades/tangerine-whistle.md) <br>INFO [11-12|17:40:00.915]  - Spurious Dragon/1 (EIP 155): 0        (https://github.com/ethereum/execution-specs/blob/master/network-upgrades/mainnet-upgrades/spurious-dragon.md) <br>INFO [11-12|17:40:00.915]  - Spurious Dragon/2 (EIP 158): 0        (https://github.com/ethereum/execution-specs/blob/master/network-upgrades/mainnet-upgrades/spurious-dragon.md) <br>INFO [11-12|17:40:00.915]  - Byzantium:                   0        (https://github.com/ethereum/execution-specs/blob/master/network-upgrades/mainnet-upgrades/byzantium.md) <br>INFO [11-12|17:40:00.915]  - Constantinople:              0        (https://github.com/ethereum/execution-specs/blob/master/network-upgrades/mainnet-upgrades/constantinople.md) <br>INFO [11-12|17:40:00.915]  - Petersburg:                  0        (https://github.com/ethereum/execution-specs/blob/master/network-upgrades/mainnet-upgrades/petersburg.md) <br>INFO [11-12|17:40:00.915]  - Istanbul:                    0        (https://github.com/ethereum/execution-specs/blob/master/network-upgrades/mainnet-upgrades/istanbul.md) <br>INFO [11-12|17:40:00.915]  - Berlin:                      &lt;nil&gt; (https://github.com/ethereum/execution-specs/blob/master/network-upgrades/mainnet-upgrades/berlin.md) <br>INFO [11-12|17:40:00.915]  - London:                      &lt;nil&gt; (https://github.com/ethereum/execution-specs/blob/master/network-upgrades/mainnet-upgrades/london.md) <br>INFO [11-12|17:40:00.916]  <br>INFO [11-12|17:40:00.916] The Merge is not yet available for this network! <br>INFO [11-12|17:40:00.916]  - Hard-fork specification: https://github.com/ethereum/execution-specs/blob/master/network-upgrades/mainnet-upgrades/paris.md <br>INFO [11-12|17:40:00.916] --------------------------------------------------------------------------------------------------------------------------------------------------------- <br>INFO [11-12|17:40:00.916]  <br>INFO [11-12|17:40:00.917] Initialising Ethereum protocol           network=202,111 dbversion=&lt;nil&gt;<br>INFO [11-12|17:40:00.920] Loaded most recent local header          number=0 hash=afbf4f..643643 td=1 age=20m44s<br>INFO [11-12|17:40:00.920] Loaded most recent local full block      number=0 hash=afbf4f..643643 td=1 age=20m44s<br>INFO [11-12|17:40:00.920] Loaded most recent local fast block      number=0 hash=afbf4f..643643 td=1 age=20m44s<br>WARN [11-12|17:40:00.921] Failed to load snapshot, regenerating    err=&quot;missing or corrupted snapshot&quot;<br>INFO [11-12|17:40:00.922] Rebuilding state snapshot <br>INFO [11-12|17:40:00.924] Resuming state snapshot generation       root=d61525..8ca6b4 accounts=0 slots=0 storage=0.00B dangling=0 elapsed=1.295ms<br>INFO [11-12|17:40:00.924] Regenerated local transaction journal    transactions=0 accounts=0<br>INFO [11-12|17:40:00.925] Stored checkpoint snapshot to disk       number=0 hash=afbf4f..643643<br>INFO [11-12|17:40:00.936] Generated state snapshot                 accounts=258 slots=0 storage=9.64KiB dangling=0 elapsed=13.505ms<br>INFO [11-12|17:40:00.958] Gasprice oracle is ignoring threshold set threshold=2<br>WARN [11-12|17:40:00.958] Error reading unclean shutdown markers   error=&quot;leveldb: not found&quot;<br>WARN [11-12|17:40:00.958] Engine API enabled                       protocol=eth<br>WARN [11-12|17:40:00.958] Engine API started but chain not configured for merge yet <br>INFO [11-12|17:40:00.958] Starting peer-to-peer node               instance=Geth/v1.10.26-stable-e5eb32ac/linux-amd64/go1.18.5<br>INFO [11-12|17:40:01.143] New local node record                    seq=1,668,292,801,140 id=5468bc8adfe4f5ed ip=127.0.0.1 udp=30302 tcp=30302<br>INFO [11-12|17:40:01.143] Started P2P networking                   self=enode://8af8b4856ebed204ef2ab9b0d78ca585df64d5d5de264b941a874fb27f2f8eac897bb46aeff6eab16e3eefdd57f696d65b8d62b5faf75c03caa171593737eed1@127.0.0.1:30302<br>INFO [11-12|17:40:01.198] IPC endpoint opened                      url=/home/n/Documents/10_Academy/GethPoA/eth-private/node1/geth.ipc<br>ERROR[11-12|17:40:01.198] Unavailable modules in HTTP API list     unavailable=[db] available=&quot;[admin debug web3 eth txpool personal clique miner net]&quot;<br>INFO [11-12|17:40:01.199] Generated JWT secret                     path=/home/n/Documents/10_Academy/GethPoA/eth-private/node1/geth/jwtsecret<br>INFO [11-12|17:40:01.274] HTTP server started                      endpoint=127.0.0.1:8545 auth=false prefix= cors= vhosts=localhost<br>INFO [11-12|17:40:01.274] WebSocket enabled                        url=ws://127.0.0.1:8551<br>INFO [11-12|17:40:01.274] HTTP server started                      endpoint=127.0.0.1:8551 auth=true  prefix= cors=localhost vhosts=localhost<br>INFO [11-12|17:40:01.274] Transaction pool price threshold updated price=0<br>INFO [11-12|17:40:01.274] Updated mining threads                   threads=0<br>INFO [11-12|17:40:01.274] Transaction pool price threshold updated price=1,000,000,000<br>INFO [11-12|17:40:01.274] Etherbase automatically configured       address=0x2E0A40623aE4671cD934744784B63a948f450d83<br>INFO [11-12|17:40:01.274] Commit new sealing work                  number=1 sealhash=1cdcaf..ddb826 uncles=0 txs=0 gas=0 fees=0 elapsed=&quot;192.008µs&quot;<br>WARN [11-12|17:40:01.274] Block sealing failed                     err=&quot;authentication needed: password or unlock&quot;<br>INFO [11-12|17:40:01.274] Commit new sealing work                  number=1 sealhash=1cdcaf..ddb826 uncles=0 txs=0 gas=0 fees=0 elapsed=&quot;434.581µs&quot;<br>Welcome to the Geth JavaScript console!<br><br>instance: Geth/v1.10.26-stable-e5eb32ac/linux-amd64/go1.18.5<br>coinbase: 0x2e0a40623ae4671cd934744784b63a948f450d83<br>at block: 0 (Sat Nov 12 2022 17:19:16 GMT-0500 (EST))<br> datadir: /home/n/Documents/10_Academy/GethPoA/eth-private/node1<br> modules: admin:1.0 clique:1.0 debug:1.0 engine:1.0 eth:1.0 miner:1.0 net:1.0 personal:1.0 rpc:1.0 txpool:1.0 web3:1.0<br><br>To exit, press ctrl-d or type exit<br>&gt;net.peerCount<br>0<br>&gt; eth.accounts<br>[&quot;0x2e0a40623ae4671cd934744784b63a948f450d83&quot;]<br>&gt; </pre><p>Now you can access all the Ethereum API which hase set functions to invoke operations ,access data, and store data.</p><ul><li>admin.nodeInfo.enode</li><li>net.listening</li><li>net.peerCount</li><li>admin.peers</li><li>eth.coinbase</li><li>eth.getBalance(eth.coinbase)</li><li>personal</li><li>eth.accounts</li><li>miner.setEtherbase(web3.eth.accounts[0])</li><li>miner.setEtherbase(“0x2Bd22E105E6Bf66e3748a3be2d94099572E1bd35”)</li><li>miner.start()</li><li>miner.stop()</li><li>miner.hashrate</li><li>eth.getBlock(0)</li><li>eth.getBlock(“latest”)</li><li>eth.blockNumber</li><li>web3.eth.getBlock(BLOCK_NUMBER).hash</li><li>eth.syncing</li><li>debug.verbosity(6) // highest logging level, 3 is default</li></ul><p>More API functions</p><ul><li><a href="https://ethereum.org/en/developers/docs/apis/json-rpc/">JSON-RPC API | ethereum.org</a></li><li><a href="https://geth.ethereum.org/docs/rpc/ns-admin">admin Namespace</a></li></ul><h3>References</h3><ol><li><a href="https://www.sitepoint.com/puppeth-introduction/">https://www.sitepoint.com/puppeth-introduction/</a></li><li><a href="https://github.com/ethereum/wiki/wiki/JSON-RPC">https://github.com/ethereum/wiki/wiki/JSON-RPC</a></li><li><a href="https://geth.ethereum.org/docs/rpc/ns-admin">https://geth.ethereum.org/docs/rpc/ns-admin</a></li><li><a href="https://github.com/puppeth">https://github.com/puppeth</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1cd741201b7c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Computer Vision for Creative Optimisation]]></title>
            <link>https://medium.com/@natnaelmelese/computer-vision-for-creative-optimisation-6deaa9b0088e?source=rss-d8b62df65657------2</link>
            <guid isPermaLink="false">https://medium.com/p/6deaa9b0088e</guid>
            <category><![CDATA[lstm]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[computer-vision]]></category>
            <dc:creator><![CDATA[Natnael Melese]]></dc:creator>
            <pubDate>Thu, 10 Nov 2022 20:01:36 GMT</pubDate>
            <atom:updated>2022-11-10T20:01:36.964Z</atom:updated>
            <content:encoded><![CDATA[<p>Computer Vision for Creative Optimisation: KPI maximization through image analysis</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*pZutBaFhZHcI8g-5bSi0Ig.jpeg" /></figure><p><a href="https://github.com/natyrix/creative_optimization">GitHub - natyrix/creative_optimization: Computer Vision for Creative Optimisation: KPI maximisation through image analysis</a></p><p>AdkaDevelop a deep learning-based computer vision algorithm that segments<br>objects from creative assets and relate them to the KPI parameters of the<br>corresponding campaigns.</p><h3>Overview and Objective</h3><blockquote>Computer vision is a field of artificial intelligence that trains computers to<br>interpret and understand the visual world. Using digital images from cameras and videos and deep learning models, machines can accurately identify and classify objects and then react to what they “see.”</blockquote><p>Dynamic creative is a method of programmatic advertising in which ad<br>components such as headlines, descriptions, images, CTAs, etc. are changed in real time according to parameters predefined by the advertiser. Common parameters include the time of day, weather, location, etc.</p><p>Dynamic creative optimization (DCO) is a form of dynamic creative that uses machine learning technology to produce personalized experiences for<br>viewers. This automated process leverages the available customer data and<br>other connected data sources plus real-time testing and analytics to select<br>the most effective combination of creative elements for each viewer.</p><p>Your client this week is Adka — an online mobile ad business. Adka<br>provides the following service to its clients.</p><p>Adka has been running a vast number of advertisements and each<br>advertisement has its own Creative. These creatives were made based on the experience of designers and company needs. As a result, there is no way of evaluating creatives during production and knowing how well they might perform when they are served.</p><p>Adka plans to change this predicament by developing an algorithm that<br>helps it optimize its creatives based on campaign performance data.<br>Develop a deep learning-based computer vision algorithm that segments<br>objects from creative assets and relate them to the KPI parameters of the<br>corresponding campaigns.</p><h3>Image segmentation</h3><p>Image segmentation is used in computer vision to separate a digital image<br>into multiple parts. In an image classification task, the network assigns a label (or class) to each input image. However, suppose you want to know the shape of that object, which pixel belongs to which object, etc. In this case, you need to assign a class to each pixel of the image, this task is known as segmentation. A segmentation model returns much more detailed information about the image. In an era where cameras and other devices increasingly need to see and interpret the world around them, image segmentation has become an indispensable technique for teaching devices how to understand the world around them.</p><h4>Approaches in Image Segmentation</h4><ul><li><strong>Similarity approach</strong>: This approach is based on detecting similarity<br>between image pixels to form a segment, based on a threshold. ML<br>algorithms like clustering are based on this type of approach to<br>segment an image.</li><li><strong>Discontinuity approach:</strong> This approach relies on the discontinuity of<br>pixel intensity values of the image. Line, Point, and Edge Detection<br>techniques use this type of approach for obtaining intermediate<br>segmentation results which can be later processed to obtain the final<br>segmented image.</li></ul><h4>Types of Image Segmentation</h4><ul><li><strong>Semantic segmentation</strong></li></ul><p>It involves arranging the pixels in an image based on semantic classes. In this model, every pixel belongs to a specific class, and the segmentation model does not refer to any other context or information. An instance could be a semantic segmentation performed on an image with multiple trees and vehicles. This will provide a mask that categorizes all types of trees into one class (tree) and all types of vehicles, whether they are buses, cars, or bicycles, into one class (vehicles). However, this approach results in the problem statement being often poorly defined, especially if there are several instances grouped in the same class. For example, an image of a crowded street might segment the entire area of the crowd as the “people” class.</p><ul><li><strong>Instance segmentation</strong></li></ul><p>Instance segmentation involves classifying pixels based on the instances of<br>an object (as opposed to object classes). Instance segmentation algorithms<br>do not know which class each region belongs to; rather, they separate similar or overlapping regions based on the boundaries of objects. An example of an instance segmentation model would be when someone processes an image of a crowded street. It should ideally locate individual objects within the crowd, identifying the number of instances in the image. However, it cannot predict the region or object (a person) for each instance.</p><ul><li><strong>Panoptic segmentation</strong></li></ul><p>This type of segmentation is a newer type of segmentation, often expressed<br>as a combination of semantic and instance segmentation. It predicts the<br>identity of each object, segregating every instance of each object in the<br>image. It is useful for many products that require vast amounts of information to perform their tasks. For example, self-driving cars must be able to capture and understand their surroundings quickly and accurately. They can achieve this by feeding a live stream of images to a panoptic segmentation algorithm.</p><h4>Modern Image segmentation algorithms</h4><p>These methods make predictions on a coarser resolution than the input<br>image in order to limit computational complexity. By spending a large part of its computation budget (oversampling) on non-ambiguous regions of an<br>image, like a dog’s torso or the background, such techniques undersample<br>more challenging parts of an object, missing fine-grained details like a dog’s paw or object edges more generally.</p><ul><li><strong>PointRend</strong></li></ul><p>A new efficient and high-resolution image segmentation approach called<br>PointRend, is inspired by the classical adaptive sampling technique used in computer graphics rendering. It produces sharper and more accurate<br>segmentation of objects and scenes, compared with previous state-of-the-art methods. The PointRend module performs point-based segmentation<br>predictions at adaptively selected locations, which is inspired by the classical technique of adaptive subdivision used for rendering in computer graphics. As a result, the model efficiently produces significantly more detailed segmentation with pixel-level precision that was not possible using previous best segmentation approaches, such as Mask R-CNN or Semantic FPN.</p><p>PointRend yields significant gains on two major benchmarks, for both instance and semantic segmentation tasks. Mask R-CNN enhanced by the PointRend segmentation head produces masks that are 8x more detailed than the standard Mask R-CNN model output, increasing average precision up to 2.8 percent.</p><p>The PointRend approach builds on top of existing image segmentation<br>approaches, such as Mask R-CNN, Semantic FPN, and Deeplab, which<br>efficiently produce a coarse prediction. Starting from coarse global prediction, PointRend gradually upscales and refines the prediction, reaching the resolution of the input image in just a few steps.</p><p>At each step, PointRend selects a subset of locations on the upscaled<br>prediction that require refinement. For each of these locations, the new model updates its prediction independently, using features from the intermediate representation of the underlying convolutional neural network. You can see an example of the process in the animation above.</p><p>Overall, the technique allows researchers to obtain a high-resolution<br>segmentation while making an actual prediction for just a small fraction of the overall pixels in the input image. PointRend avoids using excessive<br>computation on the areas that can be flawlessly predicted by a coarse<br>prediction. At the same time, it refines its prediction for pixels that lie in the challenging regions of an object or a scene. Such adaptivity leads to an<br>efficient inference that can be modified based on the computational resources at hand and without the need to retrain the model.</p><h3>Image features relevant for dynamic creative optimization</h3><p>A dynamic creative optimization is a form of dynamic creative that uses<br>machine learning technology to produce personalized experiences for<br>viewers would be more effective if relevant information about the users of<br>ads are carefully extracted. Moreover, with the new kind of communication by images, image features relevant for dynamic creative optimization can also be extracted to better understand the customers and design personalized ads for them.</p><h4>Features that can be extracted and used to understand human interaction:</h4><ul><li>Openness to experience (O),</li><li>Conscientiousness ©,</li><li>Extraversion (E),</li><li>Agreeableness (A) and</li><li>Neuroticism (N).</li></ul><p>After experimenting on the PsychoFlickr corpus the dataset that provides 200 “favored” images from 300 Flickr users for a total of 60 000 images they<br>demonstrated the viability of using a recent, powerful methodology like<br>convolutional neural networks, in tackling these new types of images<br>understanding applications. The experimental results were promising and<br>crucial for building reliable predictors. Their end product software could also be used as a marketing evaluation tool to help predict the impact of a set of images on a hypothetical audience of customers.</p><h3>How image features are related to campaign KPIs</h3><p>Online advertisements are ubiquitous in nowadays life, creating considerable revenue for many companies. As a common medium of advertisements, advertising creatives, can deliver rich product information quickly to users in a visual manner.</p><p>Appealing creatives improve visual experience and may lead to an increase in click-through rate (CTR). For merchants and e-commerce companies, the increase in CTR can be considered an indicator of an increase in revenue.</p><p>With the rapid development of the Internet, recommendation systems<br>have been proposed to solve the problem of information overload, such as<br>online advertising, point of interest recommendations]and so on. Creatives<br>are ubiquitous in online advertisements. Some works have paid attention to<br>CTR prediction on ad creatives via extracting expressive visual features to<br>increase the CTR.</p><p>Some success of automated machine learning (AutoML) has been achieved in recommendation systems. Different from regular tasks for AutoML, such as classification in computer vision, search space becomes diverse rather than the neural architectures.</p><p>Another attention is that the search for high-order features helps improve the CTR prediction. Furthermore, the search for interaction functions for<br>collaborative filtering reveals the improvements caused by searching<br>operation functions between different user embeddings and item<br>embeddings</p><h3>Implementation of the project</h3><h4>Extracted Features</h4><p>Implementation will be found in the below notebook</p><p><a href="https://github.com/natyrix/creative_optimization/tree/main/notebooks">creative_optimization/notebooks at main · natyrix/creative_optimization</a></p><ol><li>Logo and logo positions.</li><li>Emotions for the human faces.</li><li>The transition time between click &amp; engagement screen.</li><li>Audio Extraction.</li><li>Text transcription from extracted audio.</li><li>Sentiment analysis on the extracted texts.</li><li>Word count (from transcribed text)</li><li>Dominant colors.</li><li>The CTA button (Apply Now button in the figure above),</li><li>Transcribed text from audio.</li></ol><h4>Applying machine learning model to predict KPI (<strong>Engagement Ration(ER) and Click Through Ratio(CTR)</strong>)</h4><h4>Random Forest (Engagement Rate)</h4><p>Implementation will be found in the below notebook</p><p><a href="https://github.com/natyrix/creative_optimization/blob/main/notebooks/all_features_random_forest.ipynb">creative_optimization/all_features_random_forest.ipynb at main · natyrix/creative_optimization</a></p><ul><li>Feature Importance</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jIWjW4RuaAB4K3H2F093nQ.png" /><figcaption>all_features_RF_feature_importanceER</figcaption></figure><ul><li>Prediction vs Real Value</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j_funB86TDMFDlOFA2p5IQ.png" /><figcaption>all_features_RF_predictionsER</figcaption></figure><h4>Random Forest (Click Through Rate)</h4><ul><li>Feature Importance</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q2Gln3PKynGNothjnCPxJQ.png" /><figcaption>all_features_RF_feature_importanceCTR</figcaption></figure><ul><li>Prediction vs Real Value</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VUbLPGDDRCrOxJgNiJRaag.png" /><figcaption>all_features_RF_predictionsCTR</figcaption></figure><h4>Deep Learning (Engagement Rate)</h4><p>Implementation will be found in the below notebook</p><p><a href="https://github.com/natyrix/creative_optimization/blob/main/notebooks/all_features_modeling.ipynb">creative_optimization/all_features_modeling.ipynb at main · natyrix/creative_optimization</a></p><ul><li>Validation Loss</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/565/1*hUNjhc8WVURwiEFOhNQlEg.png" /></figure><ul><li>LOSS</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QlgTTZI5Rt8h5HF1nfYgeQ.png" /></figure><ul><li>Mean Absolute Error</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-hgNW8UO9ThhCfCazvGMYQ.png" /></figure><ul><li>Mean Standard Error</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NyYas6xTFNX59QQKhsMD6Q.png" /></figure><h4>Deep Learning (Click Through Rate)</h4><ul><li>Validation Loss</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/582/1*uEpiv3b3Tz9fi3C3AIrO0Q.png" /></figure><ul><li>LOSS</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zBeKDwDSxSU5hxYebaLNaQ.png" /></figure><ul><li>Mean Standard Error</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u0rEsOaB06k0wSjLMzEZ6A.png" /></figure><h3>Challenge Faced</h3><ul><li>Most of the features were resource intensive and complex to extract.</li><li>Time was our biggest constraint while implementing this project.</li><li>Extracting logo position from each creative was a big issue mostly because not all the assets had logo files.</li></ul><h3>Future Plan</h3><ul><li>In the future we plan to improve users dashboard.</li><li>To improve models accuracy.</li><li>To collect sufficient amount of data.</li><li>To extract even more features.</li><li>At the time of writing we only implemented 1 Machine Learning Model and 1 Deep Learning Model. For the future we plan to implement more models(Both ML, and Deep Learning)</li></ul><h3>References</h3><ol><li><a href="https://datagen.tech/guides/image-annotation/image-segmentation/">https://datagen.tech/guides/image-annotation/image-segmentation/</a></li><li><a href="https://www.fritz.ai/image-segmentation/">https://www.fritz.ai/image-segmentation/</a></li><li><a href="https://www.tandfonline.com/doi/full/10.1080/08839514.2022.2032924">https://www.tandfonline.com/doi/full/10.1080/08839514.2022.2032924</a></li><li><a href="https://medium.com/@nils_reimers/openai-gpt-3-text-embeddings-really-a-new-state-of-the-art-in-dense-text-embeddings-6571fe3ec9d9">https://medium.com/@nils_reimers/openai-gpt-3-text-embeddings-really-a-new-state-of-the-art-in-dense-text-embeddings-6571fe3ec9d9</a></li><li><a href="https://docs.dagger.io/1200/local-dev/">https://docs.dagger.io/1200/local-dev/</a></li><li><a href="https://www.cs.ccu.edu.tw/~wtchu/papers/2016ICS-chu.pdf">https://www.cs.ccu.edu.tw/~wtchu/papers/2016ICS-chu.pdf</a></li><li><a href="https://celtra.com/">https://celtra.com/</a></li><li><a href="https://gradio.app/">https://gradio.app/</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6deaa9b0088e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Etherium: Refund by Location Smart Contract]]></title>
            <link>https://medium.com/@natnaelmelese/etherium-refund-by-location-smart-contract-ecc031ee5f7c?source=rss-d8b62df65657------2</link>
            <guid isPermaLink="false">https://medium.com/p/ecc031ee5f7c</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[web3]]></category>
            <category><![CDATA[blockchain]]></category>
            <dc:creator><![CDATA[Natnael Melese]]></dc:creator>
            <pubDate>Sat, 29 Oct 2022 19:34:39 GMT</pubDate>
            <atom:updated>2022-11-12T22:56:31.791Z</atom:updated>
            <content:encoded><![CDATA[<p>Building Refund Mobile and Web Dapps by Location Smart Contract</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*Cv5T_EI_B0qtdJyx6CetLw.jpeg" /></figure><p><a href="https://github.com/natyrix/Refund-by-Location">GitHub - natyrix/Refund-by-Location: The refund by location smart contract 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.</a></p><p>The refund by location smart contract 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.</p><p>Part 2 of this article is about “<a href="https://medium.com/@natnaelmelese/creating-a-private-network-in-ethereum-1cd741201b7c"><strong><em>Creating a Private Network in Ethereum</em></strong></a>”</p><p><a href="https://medium.com/@natnaelmelese/creating-a-private-network-in-ethereum-1cd741201b7c">Creating a Private Network in Ethereum</a></p><h3>Overview and Objective</h3><blockquote>Ethereum is a decentralized, open-source blockchain with smart contract<br>functionality. Ether is the native cryptocurrency of the platform. Among<br>cryptocurrencies, ether is second only to bitcoin in market capitalization.</blockquote><p>The refund by location smart contract is aimed to be used when one party, for example, an employer, agrees to pay another party, for example, an<br>employee, for being present in a certain geographic area for a certain<br>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.</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.</p><p>Produce an Ethereum based dApp that has both the smart contract tested<br>and deployed in a testnet and a front end that will allow monitoring of the<br>status.</p><h3>Understanding of the Ethereum Blockchain</h3><p>The Ethereum blockchain is essentially a transaction-based state machine. In computer science, a state machine refers to something that will read a series of inputs and, based on those inputs, will transition to a new state.</p><p>With Ethereum’s state machine, we begin with a “genesis state.” This is<br>analogous to a blank slate before any transactions have happened on the<br>network. When transactions are executed, this genesis state transitions into some final state. At any point in time, this final state represents the current state of Ethereum.</p><h4>Gas and payment</h4><ul><li>One very important concept in Ethereum is the concept of fees.<br>Every computation that occurs as a result of a transaction on the<br>Ethereum network incurs a fee — there’s no free lunch! This fee is<br>paid in a denomination called “gas.”</li><li>Gas is the unit used to measure the fees required for a particular<br>computation. Gas price is the amount of Ether you are willing to<br>spend on every unit of gas, and is measured in “gwei.” “Wei” is the<br>smallest unit of Ether, where 1018 Wei represents 1 Ether. One gwei<br>is 1,000,000,000 Wei.</li><li>With every transaction, a sender sets a gas limit and gas price.<br>The product of gas price and gas limit represents the maximum<br>amount of Wei that the sender is willing to pay for executing a<br>transaction.</li></ul><h4>Transaction and messages</h4><ul><li>We noted earlier that Ethereum is a transaction-based state<br>machine. In other words, transactions occurring between different<br>accounts are what move the global state of Ethereum from one<br>state to the next.</li><li>In the most basic sense, a transaction is a cryptographically<br>signed piece of instruction that is generated by an externally<br>owned account, serialized, and then submitted to the blockchain.</li><li>There are two types of transactions: message calls and contract<br>creations (i.e. transactions that create new Ethereum contracts).</li></ul><h4>Blocks</h4><ul><li>All transactions are grouped together into “blocks.” A blockchain<br>contains a series of such blocks that are chained together.</li></ul><p>In Ethereum, a block consists of:</p><ul><li>The block header</li><li>Information about the set of transactions included in that<br>block</li><li>A set of other block headers for the current block’s ommers(Ommer blocks are created in the Ethereum blockchain when two blocks are created and submitted to the ledger at roughly the same time).</li></ul><h4>Ethereum networks</h4><p>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.</p><h4><strong>Ethereum Mainnet</strong></h4><ul><li>Mainnet is the primary public Ethereum production blockchain, where<br>actual-value transactions occur on the distributed ledger.</li><li>When people and exchanges discuss ETH prices, they’re talking about<br>Mainnet ETH.</li></ul><h4><strong>Ethereum Testnets</strong></h4><ul><li>In addition to Mainnet, there are public testnets. These are networks<br>used by protocol developers or smart contract developers to test both<br>protocol upgrades as well as potential smart contracts in a<br>production-like environment before deployment to Mainnet. Think of<br>this is an analog to production versus staging servers.</li><li><strong>Goerli: </strong>Goerli is a proof-of-stake testnet. It is expected to be maintained<br>long-term as a stable testnet for application developers. Before its<br>testnet merge, Goerli was a proof-of-authority testnet.</li><li><strong>Sepolia: </strong>Sepolia is a proof-of-stake testnet. Although Sepolia is still<br>running, it is not currently planned to be maintained long-term.<br>Before undergoing The Merge in June 2022, Sepolia was a<br>proof-of-work testnet.</li></ul><h4>Consortium networks</h4><ul><li>The consensus process is controlled by a pre-defined set of nodes that<br>are trusted. For example, a private network of known academic<br>institutions that each govern a single node, and blocks are validated by<br>a threshold of signatories within the network.</li><li>If a public Ethereum network is like the public internet, a consortium<br>network is like a private intranet.</li></ul><h4>How smart contracts are designed</h4><p>Smart contracts are self-executing digital contracts that define the terms of a blockchain transaction using code. This code makes it possible to, among<br>other things, exchange massive amounts of money within set input<br>parameters. Smart contracts are written with a variety of coding languages,<br>and the most popular one is Solidity.</p><h4>Smart contract design patterns</h4><p>Smart contract design patterns are reusable, repeatable solutions in writing code. They can serve a wide range of purposes but can be seen as offering four main functions:</p><ul><li><strong>Security patterns</strong> — To protect your contract against breaches.</li><li><strong>Efficiency patterns</strong> — To reduce the cost of executing your contract.</li><li><strong>Access control patterns</strong> — To manage who can execute the functions of<br>your contract.</li><li><strong>Contract management patterns</strong> — To organize your contracts and how<br>they interact.</li></ul><p>While these categories capture the main functions of all smart contract<br>patterns, it’s important to note that patterns are used across all blockchains, on and off-chain, in domain-based chains, and in data management.</p><p>For example, say you want to build a smart contract that will have a few<br>evolutions during its life cycle. You might use something called a state machine pattern, which falls under the multi-domain feature pattern. A state machine pattern allows you to manage smart contract transitions through different “state” transitions over time. This pattern is used in many scenarios, including your basic smart contract implementation, so we highlight it here.</p><p>Just keep in mind that we’re focusing here on the functions of various smart contract design patterns in the wider blockchain ecosystem.</p><h3>Ethereum Virtual Machine(EVM)</h3><p>The part of the protocol that actually handles processing the transactions is<br>Ethereum’s own virtual machine, known as the Ethereum Virtual Machine<br>(EVM).</p><p>The EVM is a Turing complete virtual machine, as defined earlier. The only<br>limitation the EVM has that a typical Turing complete machine does not is that the EVM is intrinsically bound by gas. Thus, the total amount of computation that can be done is intrinsically limited by the amount of gas provided.</p><p>Moreover, the EVM has a stack-based architecture. A stack machine is a<br>computer that uses a last-in, first-out stack to hold temporary values.</p><p>The size of each stack item in the EVM is 256-bit, and the stack has a<br>maximum size of 1024.</p><p>The EVM has memory, where items are stored as word-addressed byte arrays. Memory is volatile, meaning it is not permanent.</p><p>The EVM also has storage. Unlike memory, storage is non-volatile and is<br>maintained as part of the system state. The EVM stores program code<br>separately, in a virtual ROM that can only be accessed via special instructions.</p><p>In this way, the EVM differs from the typical von Neumann architecture, in<br>which program code is stored in memory or storage.</p><h3>Smart contract security</h3><p>Security is one of the most important considerations when writing smart<br>contracts. In the field of smart contract programming, mistakes are costly and easily exploited.</p><p>As with other programs, a smart contract will execute exactly what is written, which is not always what the programmer intended. Furthermore, all smart contracts are public, and any user can interact with them simply by creating a transaction. Any vulnerability can be exploited, and losses are almost always impossible to recover. It is therefore critical to follow best practices and use well-tested design patterns.</p><p>Security patterns are designed to maximize the level of security of a smart<br>contract against any risk. They are used to ward off reentrancy attacks,<br>overflow attacks, or the flawed behavior of the actual smart contracts.</p><p>These patterns might have a built-in panic button, such as the emergency<br>stop pattern, which gives the option to disable contract functionality if<br>necessary. Or a pattern might use rate limiters to control how often a task can be executed within a specified period. The check effect interaction pattern minimizes potential attack surfaces to reduce the risk of malicious contracts taking over.</p><p>Other examples of security design patterns are:</p><ol><li>Balance limit pattern</li><li>Pull-over push payments</li><li>Secure ether transfer</li><li>Balance limit pattern</li><li>Pull-over push payments</li><li>Secure ether transfer</li><li>Fork check</li><li>Termination</li><li>Math pattern</li><li>Time constraint</li><li>Mutex pattern</li><li>Auto deprecation design pattern</li><li>Withdrawal pattern</li></ol><h3>Tools used in the project</h3><h4>React JS for the web dApp</h4><p>React is a library for building composable user interfaces. It encourages the creation of reusable UI components, which present data that changes over time. Lots of people use React as the V in MVC.<br>React abstracts away the DOM from you, offering a simpler programming model and better performance</p><h4>Flutter for the mobile dApp</h4><p>Flutter is an open-source UI software development kit created by Google. It is used to develop cross-platform applications for Android, iOS, Linux, macOS, Windows, Google Fuchsia, and the web from a single codebase. First described in 2015, Flutter was released in May 2017.</p><h4>Solidity for Contract’s programing language</h4><p>Solidity is an object-oriented programming language for implementing smart contracts on various blockchain platforms, most notably, Ethereum.</p><h4>Web3.js for interacting with the contracts from UI</h4><p>web3.js is a collection of libraries that allow you to interact with a local or remote Ethereum node using HTTP, IPC, or WebSocket.</p><h4>Truffle to deploy, test, and compile our contracts</h4><p>The Truffle Suite is an ecosystem for Web3 development that consists of three different tools: Truffle, Ganache, and Drizzle. Truffle is a development environment, asset pipeline, and testing framework for developing smart contracts.</p><h4>Metamask for linking accounts to perform transactions</h4><p>MetaMask is a software cryptocurrency wallet used to interact with the Ethereum blockchain. It allows users to access their Ethereum wallet through a browser extension or mobile app, which can then be used to interact with decentralized applications.</p><h4>Ganache for creating Ethereum blockchain on the local machine</h4><p>Ganache is a pioneer in the Ethereum development space, aiding DApp developers and enthusiasts to build, test, and explore blockchain since 2016.</p><h3>Setup and Installation</h3><ul><li><a href="https://trufflesuite.com/boxes/react/">React Truffle Box - Truffle Suite</a></li><li><a href="https://flutter.dev/">Flutter - Build apps for any screen</a></li><li><a href="https://trufflesuite.com/ganache/">Ganache</a></li><li><a href="https://metamask.io/">The Ultimate Crypto Wallet for DeFi, Web3 Apps, and NFTs | MetaMask</a></li></ul><h3>Project Implementation</h3><h4>Writing the Smart Contract</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/149e277f569ef18dcbab6b32418f06a5/href">https://medium.com/media/149e277f569ef18dcbab6b32418f06a5/href</a></iframe><ul><li>We will start by creating the Employee <em>init_employee</em> and the Employer <em>init_employer</em>.</li></ul><pre>function init_employee(string memory _name, address a)</pre><pre>function init_employer(string memory _name, address a)</pre><ul><li>We will then create the contract <em>create_contract</em>.</li></ul><pre>function create_contract(address _employer_address, address _employee_address, uint[2] memory lat, uint[2] memory lng, uint radius)</pre><ul><li>We will then store records of the employee’s location <em>create_employee_location_info</em></li></ul><pre>function create_employee_location_info(uint contract_id, address _employee_address, uint[2] memory _lat, uint[2] memory _lng, string memory _timestamp, bool _status, uint _distance)</pre><ul><li>truffle-config.js</li></ul><pre>//<a href="https://github.com/natyrix/Refund-by-Location/blob/main/refund_contract/truffle-config.js">truffle-config.js</a><br>require(&#39;dotenv&#39;).config();<br>const HDWalletProvider = require(&#39;<a href="http://twitter.com/truffle/hdwallet-provider">@truffle/hdwallet-provider</a>&#39;);<br>const { INFURA_API_KEY, MNEMONIC } = process.env;</pre><pre>module.exports = {<br>  networks: {<br>    development: {<br>      host: &quot;127.0.0.1&quot;,<br>      port: 7545,<br>      network_id: &quot;*&quot;<br>    },<br>    goerli: {<br>      provider: () =&gt; new HDWalletProvider(MNEMONIC, INFURA_API_KEY),<br>      network_id: &#39;5&#39;,<br>      gas: 4465030<br>    }<br>  }<br>};</pre><ul><li>Deploy the contract to ganache</li></ul><pre>$ truffle deploy --network development</pre><h4>Creating the Employer’s page</h4><p><a href="https://github.com/natyrix/Refund-By-Location-Frontend">GitHub - natyrix/Refund-By-Location-Frontend: Front end for https://github.com/natyrix/Refund-by-Location</a></p><ul><li>Create a Provider React component that allows consuming components to subscribe to context changes.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0126451b1decfdbe9f3eb00d54aaf2c7/href">https://medium.com/media/0126451b1decfdbe9f3eb00d54aaf2c7/href</a></iframe><ul><li>Create employee using</li></ul><pre>//<a href="https://github.com/natyrix/Refund-By-Location-Frontend/blob/main/src/components/AddEmployee.jsx">AddEmployee.js</a></pre><pre>const { state: { contract, accounts } } = useEth();</pre><pre>contract.methods.init_employee(employeeName, employeeAddress).send({ from: accounts[0] });</pre><ul><li>Create contract using</li></ul><pre><br>const { state: { contract, accounts } } = useEth();</pre><pre>contract.methods.create_contract(accounts[0], employeeAddress, [l,latindex], [lg, lngindex], radius).send({ from: accounts[0] })</pre><p><strong>More functionalities are found in the below link</strong></p><p><a href="https://github.com/natyrix/Refund-By-Location-Frontend">GitHub - natyrix/Refund-By-Location-Frontend: Front end for https://github.com/natyrix/Refund-by-Location</a></p><h4>Creating the Employee page using flutter</h4><ul><li>Connect to the contract and fetch all needed functions.</li></ul><pre>Future&lt;void&gt; getDeployedContract() async {<br>    // Telling Web3dart where our contract is declared.<br>    _contract = DeployedContract(<br>        ContractAbi.fromJson(_abi!, &quot;RefundByLocation&quot;), _contractAddress!);</pre><pre>// Extracting the functions, declared in contract.<br>    _writeName = _contract!.function(&quot;employercount&quot;);<br>    _getEmployeeCount = _contract!.function(&quot;employercount&quot;);<br>    _getContractCount = _contract!.function(&quot;contract_info_count&quot;);<br>    _getContract = _contract!.function(&quot;contract_infos&quot;);<br>    _getEmployeeLocationCount =<br>        _contract!.function(&quot;employee_location_infos_count&quot;);<br>    _getEmployeeLocation = _contract!.function(&quot;employee_location_infos&quot;);<br>    _sendEmployeeLocation =<br>        _contract!.function(&quot;create_employee_location_info&quot;);</pre><pre>// getValue();<br>    print(&quot;############GETTING CONTRACT###########&quot;);<br>    print(_contractAddress);<br>    print(&quot;############GETTING CONTRACT###########&quot;);<br>  }</pre><ul><li>Full source code for connecting to contract and calling smart contract functions.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/210a5cb0c358af7d455d92a205c078b4/href">https://medium.com/media/210a5cb0c358af7d455d92a205c078b4/href</a></iframe><ul><li>Link to full flutter app.</li></ul><p><a href="https://github.com/natyrix/Refund-by-Location-Flutter">GitHub - natyrix/Refund-by-Location-Flutter: Flutter app for https://github.com/natyrix/Refund-by-Location</a></p><p>Part 2: About Creating a Private Network in Ethereum</p><p><a href="https://medium.com/@natnaelmelese/creating-a-private-network-in-ethereum-1cd741201b7c">Creating a Private Network in Ethereum</a></p><h3>Lessons</h3><ul><li>Create dApp using react.</li><li>Create dApp using flutter.</li><li>Write smart contracts using Solidity.</li><li>Test and debug smart contracts</li></ul><h3>Future Plans</h3><ul><li>I plan to deploy this project to Ethereum main net.</li><li>Implement fund transfers.</li><li>Implement full connection using metamask on the flutter side.</li></ul><h3>References</h3><ol><li><a href="https://medium.com/ethereum-developers/the-ultimate-end-to-end-tutorial-to-create-and-deploy-a-fully-descentralized-dapp-in-ethereum-18f0cf6d7e0e">https://medium.com/ethereum-developers/the-ultimate-end-to-end-tutorial-to-create-and-deploy-a-fully-descentralized-dapp-in-ethereum-18f0cf6d7e0e</a></li><li><a href="https://dev.to/yakult/a-tutorial-build-dapp-with-hardhat-react-and-ethersjs-1gmi">https://dev.to/yakult/a-tutorial-build-dapp-with-hardhat-react-and-ethersjs-1gmi</a></li><li><a href="https://www.appypie.com/app-builder/web3-app-maker">https://www.appypie.com/app-builder/web3-app-maker</a></li><li><a href="https://preethikasireddy.medium.com/how-does-ethereum-work-anyway-22d1df506369">https://preethikasireddy.medium.com/how-does-ethereum-work-anyway-22d1df506369</a></li><li><a href="https://blog.logrocket.com/top-5-decentralized-app-development-frameworks/">https://blog.logrocket.com/top-5-decentralized-app-development-frameworks/</a></li><li><a href="https://github.com/ManoVikram/Lottery-DApp">https://github.com/ManoVikram/Lottery-DApp</a></li><li><a href="https://moralis.io/create-mobile-ethereum-dapp-with-react-native-template/">https://moralis.io/create-mobile-ethereum-dapp-with-react-native-template/</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ecc031ee5f7c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Causal Inference]]></title>
            <link>https://medium.com/@natnaelmelese/causal-inference-d545262755de?source=rss-d8b62df65657------2</link>
            <guid isPermaLink="false">https://medium.com/p/d545262755de</guid>
            <category><![CDATA[causal-inference]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[causality]]></category>
            <dc:creator><![CDATA[Natnael Melese]]></dc:creator>
            <pubDate>Sun, 23 Oct 2022 19:41:20 GMT</pubDate>
            <atom:updated>2022-11-28T14:22:25.433Z</atom:updated>
            <content:encoded><![CDATA[<p>Logistic optimization: Delivery drivers location optimization with Causal Inference</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b5NWhUHyj0AVcwQRHonp7w.png" /></figure><p><a href="https://github.com/natyrix/Causal-Inference">GitHub - natyrix/Causal-Inference: Logistic optimization: Delivery drivers location optimization with Causal Inference</a></p><p>The client for this week’s challenge is ZDelivery, work on its data to help it<br>understand the primary causes of unfulfilled requests and develop solutions that recommend drivers&#39; locations that increase the fraction of complete orders. Since drivers are paid based on the number of requests they accept, your solution will help ZDelivery business grow in client satisfaction and increase business.</p><h3>Overview and Objective</h3><blockquote>Causal inference is the process of determining the independent, actual effect of a particular phenomenon that is a component of a larger system. The main difference between causal inference and inference of association is that causal inference analyzes the response of an effect variable when the cause of the effect variable is changed. The science of why things occur is called etiology. Causal inference is said to provide evidence of causality theorized by causal reasoning.</blockquote><p>Causality is often difficult to pin down because of our expectations of physical systems. If you drop a tennis ball from a window, you know that it will fall. Similarly, if you hit a billiard ball with a cue, you know which direction it will go. We constantly see causation in the physical world; it’s tempting to generalize this to larger, more complex systems, such as meteorology, online social networks, and global finance.</p><p>However, causality breaks down relatively rapidly even in simple physical<br>systems. Let us return to the billiard table. We hit Ball 1, which hits Ball 2,<br>which hits Ball 3, and so on. Knowing the exact trajectory of Ball 1 would allow us to calculate the exact trajectories of all subsequent balls. However, given an ever-so-slight deviation of Ball 1’s actual trajectory from the trajectory we use in our calculation, our prediction for Ball 2 will be slightly off, our prediction for Ball 3 will be further off, and our prediction for Ball 5 could be totally off. Given the small amount of noise in the system, which always occurs, we can’t say anything about the trajectory of Ball 5: we have no idea of the causal link between how we hit Ball 1 and the trajectory of Ball 5.</p><h3>About the Data</h3><p>There are two datasets available for this project.</p><p><strong>The first one contains information about the Trips</strong></p><ul><li><strong>Trip ID:</strong> This represents the unique identification number of the<br>current trip.</li><li><strong>Trip Origin:</strong> Combination of latitude and longitude in (LAT, LNG)<br>format, which holds GPS coordinates for the trip origin.</li><li><strong>Trip Destination:</strong> Combination of latitude and longitude in (LAT,<br>LNG) format, which holds GPS coordinates for the trip destination.</li><li><strong>Trip Start Time:</strong> This represents the timestamp of the trip’s start<br>time.</li><li><strong>Trip End Time:</strong> This represents the timestamp of the trip’s end<br>time.</li></ul><p><strong>The second one contains delivery requests by clients </strong>(fulfilled and<br>unfulfilled). Each trip in the first table is broadcasted to drivers, only one<br>driver can accept a trip, which means all the other drivers’ actions will<br>be considered as a rejection.</p><ul><li><strong>ID</strong>: Unique identification number for each row in the dataset.</li><li><strong>order_id</strong>: Identification number for the broadcasted trips.</li><li><strong>driver_id</strong>: Identification number for the drivers.</li><li><strong>driver_action</strong>: This represents drivers’ action whether ‘accept’ or<br>‘reject’.</li><li><strong>lat</strong>: Latitude of the driver while the trip was broadcasted.</li><li><strong>lng</strong>: Longitude of the driver while the trip was broadcasted.</li></ul><h3>Exploratory Data Analysis</h3><h4>Some Feature Extractions</h4><ul><li>Weekday/Weekend</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7fe799c622bf2f69d4a9bab0ec641588/href">https://medium.com/media/7fe799c622bf2f69d4a9bab0ec641588/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/301/1*kAy5XiYDrDEs1A7HK4AZRA.png" /><figcaption>is_weekend count</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f5dImVkpRfWGRZjf6jDEtQ.png" /></figure><ul><li>Holiday</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d4bcd6eed3ea0d287bbecd0b89208555/href">https://medium.com/media/d4bcd6eed3ea0d287bbecd0b89208555/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/321/1*PmI4NNT4MzWauvaOikpBwg.png" /><figcaption>is_holiday</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v7Z-ouav_tynyCzm7x3DhQ.png" /></figure><ul><li>Distance between trip origin and trip destination</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/307f922f113bb21631ef7cfc67592b88/href">https://medium.com/media/307f922f113bb21631ef7cfc67592b88/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/318/1*0OWAsCCgShsQ0Fe09Txvzw.png" /><figcaption>Descriptive statistics</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iTrZY13aiJXMkaLkSZfuqg.png" /></figure><ul><li>Speed (Km/h)</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/872980eb3b74df141889ac81d40bcc3a/href">https://medium.com/media/872980eb3b74df141889ac81d40bcc3a/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/310/1*mfHLHKEcwO5JuOCEOXYQnQ.png" /><figcaption>Descriptive statistics</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WRGvyxCy9RnKqD7NwLr5LA.png" /></figure><h3>Causal Learning</h3><p><a href="https://causalnex.readthedocs.io/en/latest/03_tutorial/01_first_tutorial.html">A first CausalNex tutorial - causalnex 0.12.1 documentation</a></p><h4>Merging the two datasets based on the trip ID</h4><ul><li><strong>Get the driver&#39;s latitude and longitude.</strong></li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/95f91345e3a9b5f34d1d31e5973e7b42/href">https://medium.com/media/95f91345e3a9b5f34d1d31e5973e7b42/href</a></iframe><pre>preprocessed_trip_df[&#39;driver_lat&#39;] <strong>=</strong> driver_lat<br>preprocessed_trip_df[&#39;driver_lng&#39;] <strong>=</strong> driver_lng<br></pre><ul><li><strong>Calculate the distance between the trip origin and the coordinates of the driver</strong></li></ul><pre>driver_lat_coordinates <strong>=</strong> preprocessed_trip_df[&#39;driver_lat&#39;]<strong>.</strong>tolist()<br>driver_lng_coordinates <strong>=</strong> preprocessed_trip_df[&#39;driver_lng&#39;]<strong>.</strong>tolist()<br>ending_coordinates <strong>=</strong> []<br><strong>for</strong> i <strong>in</strong> range(len(driver_lat_coordinates)):<br>    ending_coordinates<strong>.</strong>append(f&#39;{driver_lat_coordinates[i]},{driver_lng_coordinates[i]}&#39;)</pre><pre>start_coordinates <strong>=</strong> preprocessed_trip_df[&#39;Trip Origin&#39;]<strong>.</strong>tolist()</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/307f922f113bb21631ef7cfc67592b88/href">https://medium.com/media/307f922f113bb21631ef7cfc67592b88/href</a></iframe><ul><li><strong>Compute unfulfilled orders</strong></li></ul><pre>preprocessed_trip_df_with_drivers[&#39;is_fulfilled&#39;] <strong>=</strong> preprocessed_trip_df_with_drivers[&#39;driver_distance&#39;]<strong>.</strong>apply(<br>    <strong>lambda</strong> x: 1 <strong>if</strong> x <strong>!=-</strong>2 <strong>else</strong> 0)</pre><pre>preprocessed_trip_df_with_drivers[preprocessed_trip_df_with_drivers[&#39;is_fulfilled&#39;]<strong>==</strong>0]<strong>.</strong>shape<br>(609, 14)</pre><p>Final dataframe structure after dropping some unwanted cols.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/387/1*NWHQK4I-hyqNKlTLipuBHw.png" /></figure><ul><li><strong>Scale and normalize numerical data</strong></li></ul><pre><strong>from</strong> sklearn <strong>import</strong> preprocessing<br><strong>from</strong> causalnex.structure.notears <strong>import</strong> from_pandas</pre><pre>x <strong>=</strong> struct_data<strong>.</strong>values <em>#returns a numpy array</em><br>min_max_scaler <strong>=</strong> preprocessing<strong>.</strong>MinMaxScaler()<br>x_scaled <strong>=</strong> min_max_scaler<strong>.</strong>fit_transform(x)<br>df <strong>=</strong> pd<strong>.</strong>DataFrame(x_scaled)<br><br>sm <strong>=</strong> from_pandas(df)</pre><pre>{&#39;is_weekend&#39;: 0, &#39;is_holiday&#39;: 1, &#39;distance&#39;: 2, &#39;speed&#39;: 3, &#39;driver_distance&#39;: 4, &#39;is_fulfilled&#39;: 5}</pre><ul><li><strong>Visualize</strong></li></ul><pre>viz <strong>=</strong> plot_structure(<br>    sm,<br>    graph_attributes<strong>=</strong>{&quot;scale&quot;: &quot;0.5&quot;},<br>    all_node_attributes<strong>=</strong>NODE_STYLE<strong>.</strong>WEAK,<br>    all_edge_attributes<strong>=</strong>EDGE_STYLE<strong>.</strong>WEAK,<br>)<br>Image(viz<strong>.</strong>draw(format<strong>=</strong>&#39;png&#39;))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/935/1*qGAqEA4UxB-cQaM5MMnGyA.png" /></figure><ul><li><strong>Remove edges below threshold</strong></li></ul><pre>sm<strong>.</strong>remove_edges_below_threshold(0.8)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/811/1*W64frRD_q9xM4glZ4Bla3A.png" /></figure><ul><li><strong>Correct relationships</strong></li></ul><p>distance ---&gt; is_fulfilled<br>distance ---&gt; is_fulfilled<br>driver_distance ---&gt; is_fulfilled</p><ul><li><strong>Incorrect relationships</strong></li></ul><p>distance ---&gt; is_weekend<br>driver_distance ---&gt; is_weekend</p><p>Let&#39;s re-run structure learning with additional constraints to avoid incorrect relationships</p><ul><li><strong>Rename columns</strong></li></ul><pre>df <strong>=</strong> df<strong>.</strong>rename(columns<strong>=</strong>{0: &quot;is_weekend&quot;, 1: &quot;is_holiday&quot;, 2: &quot;distance&quot;, 3: &quot;speed&quot;,4: &quot;driver_distance&quot;, 5: &quot;is_fulfilled&quot;}, errors<strong>=</strong>&quot;raise&quot;)</pre><pre>sm <strong>=</strong> from_pandas(df, tabu_edges<strong>=</strong>[(&quot;driver_distance&quot;, &quot;is_weekend&quot;),(&quot;distance&quot;, &quot;is_weekend&quot;)], w_threshold<strong>=</strong>0.8)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/747/1*stQexU13NV6xS58Ggx3YNw.png" /></figure><pre>sm<strong>.</strong>add_edge(&quot;is_weekend&quot;, &quot;is_fulfilled&quot;)<br>sm<strong>.</strong>add_edge(&quot;is_holiday&quot;, &quot;is_fulfilled&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/791/1*TFfg_H_8xAYEKJJMrS0P5w.png" /></figure><h3>Fitting the Conditional Distribution of the Bayesian Network</h3><pre><strong>from</strong> causalnex.network <strong>import</strong> BayesianNetwork<br><br>bn <strong>=</strong> BayesianNetwork(sm)</pre><h4>Preparing the Discretised Data</h4><ul><li><strong>Cardinality of Categorical Features</strong></li></ul><pre>df_c <strong>=</strong> preprocessed_trip_df_with_drivers<strong>.</strong>copy()<br>df_c[&#39;is_weekend&#39;] <strong>=</strong> df_c[&#39;is_weekend&#39;]<strong>.</strong>apply(<strong>lambda</strong> x: &#39;weekday&#39; <strong>if</strong> x <strong>==</strong> 0 <strong>else</strong> &quot;weekend&quot;)<br>df_c[&#39;is_holiday&#39;] <strong>=</strong> df_c[&#39;is_holiday&#39;]<strong>.</strong>apply(<strong>lambda</strong> x: &#39;holiday&#39; <strong>if</strong> x <strong>!=</strong>0 <strong>else</strong> &quot;no-holiday&quot;)<br>df_c[&#39;is_fulfilled&#39;] <strong>=</strong> df_c[&#39;is_fulfilled&#39;]<strong>.</strong>apply(<strong>lambda</strong> x: &#39;fulfilled&#39; <strong>if</strong> x <strong>!=</strong>0 <strong>else</strong> &quot;unfulfilled&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/581/1*aqh4lsErUHx1LW8vqemMRg.png" /></figure><ul><li><strong>Discretizing Numeric Features</strong></li></ul><pre>from causalnex.discretiser import Discretiser<br>discretised_data = df_c.copy()</pre><pre>discretised_data[&quot;distance&quot;] = Discretiser(method=&quot;fixed&quot;,<br>        numeric_split_points=[1,100]).transform(discretised_data[&quot;distance&quot;].values)<br>discretised_data[&quot;distance&quot;].value_counts()</pre><pre># output<br>1    26039<br>0      390<br>2        7</pre><pre>discretised_data[&quot;driver_distance&quot;] <strong>=</strong> Discretiser(method<strong>=</strong>&quot;fixed&quot;,<br>        numeric_split_points<strong>=</strong>[1,100])<strong>.</strong>transform(discretised_data[&quot;driver_distance&quot;]<strong>.</strong>values)<br>discretised_data[&quot;driver_distance&quot;]<strong>.</strong>value_counts()</pre><pre>#output<br>1    17361<br>0     9073<br>2        2</pre><pre>discretised_data[&quot;speed&quot;] <strong>=</strong> Discretiser(method<strong>=</strong>&quot;fixed&quot;,<br>        numeric_split_points<strong>=</strong>[1,100])<strong>.</strong>transform(discretised_data[&quot;speed&quot;]<strong>.</strong>values)<br>discretised_data[&quot;speed&quot;]<strong>.</strong>value_counts()</pre><pre>#output<br>1    24515<br>2     1681<br>0      240</pre><ul><li><strong>Create Labels for Numeric Features</strong></li></ul><pre>distance_map <strong>=</strong> {<br>    0: &quot;short-distance&quot;,<br>    1: &quot;medium-distance&quot;,<br>    2: &quot;long-distance&quot;<br>}<br>speed_map <strong>=</strong> {<br>    0: &quot;slow-speed&quot;,<br>    1: &quot;medium-speed&quot;,<br>    2: &quot;fast-speed&quot;<br>}<br>discretised_data[&quot;distance&quot;] <strong>=</strong> discretised_data[&quot;distance&quot;]<strong>.</strong>map(distance_map)<br>discretised_data[&quot;driver_distance&quot;] <strong>=</strong> discretised_data[&quot;driver_distance&quot;]<strong>.</strong>map(distance_map)<br>discretised_data[&quot;speed&quot;] <strong>=</strong> discretised_data[&quot;speed&quot;]<strong>.</strong>map(speed_map)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/625/1*ms9BPfk1GNlwBIatweZ7Cg.png" /></figure><h4>Train / Test Split</h4><p>Like many other machine learning models, we will use a train and test split to help us validate our findings.</p><pre><strong>from</strong> sklearn.model_selection <strong>import</strong> train_test_split<br><br>train, test <strong>=</strong> train_test_split(discretised_data, train_size<strong>=</strong>0.9, test_size<strong>=</strong>0.1, random_state<strong>=</strong>7)</pre><h4>Model Probability</h4><p>With the learned structure model from earlier and the discretized data, we can now fit the probability distribution of the Bayesian Network. The first step in this is specifying all of the states that each node can take. This can be done either from data or by providing a dictionary of node values. We use the full dataset here to avoid cases where states in our test set do not exist in the training set. For real-world applications, these states may need to be provided using the dictionary method.</p><pre>bn <strong>=</strong> bn<strong>.</strong>fit_cpds(train, method<strong>=</strong>&quot;BayesianEstimator&quot;, bayes_prior<strong>=</strong>&quot;K2&quot;)<br>bn<strong>.</strong>cpds[&quot;is_fulfilled&quot;]</pre><ul><li><strong>Predict the State given the Input Data</strong></li></ul><p>The prediction method of BayesianNetwork allows us to make predictions based on the data using the learned Bayesian Network. For example, we want to predict if a trip is fulfilled or not based on the input data. Imagine we have trip data that looks like this:</p><pre>discretised_data<strong>.</strong>loc[57, discretised_data<strong>.</strong>columns <strong>!=</strong> &#39;is_fulfilled&#39;]</pre><pre>#output<br>is_weekend                 weekday<br>is_holiday              no-holiday<br>distance           medium-distance<br>speed                 medium-speed<br>driver_distance    medium-distance</pre><pre>predictions <strong>=</strong> bn<strong>.</strong>predict(discretised_data, &quot;is_fulfilled&quot;)<br>print(f&quot;The prediction is &#39;{predictions<strong>.</strong>loc[57, &#39;is_fulfilled_prediction&#39;]}&#39;&quot;)</pre><pre>#output<br>The prediction is &#39;fulfilled&#39;</pre><h3>Modeling</h3><p>In this <a href="https://github.com/natyrix/Causal-Inference/blob/main/notebooks/causal_learning.ipynb">notebook</a> I have implemented 4 machine learning models, below I will try to share the results.</p><h4>Random Forest</h4><p><strong>Normalize</strong></p><pre>norm_df <strong>=</strong> preprocessed_trip_df_with_drivers<strong>.</strong>copy()<br>x <strong>=</strong> norm_df<strong>.</strong>values <em>#returns a numpy array</em><br>min_max_scaler <strong>=</strong> preprocessing<strong>.</strong>MinMaxScaler()<br>x_scaled <strong>=</strong> min_max_scaler<strong>.</strong>fit_transform(x)<br>df <strong>=</strong> pd<strong>.</strong>DataFrame(x_scaled)</pre><p><strong>Fit</strong></p><pre><strong>from</strong> sklearn.pipeline <strong>import</strong> Pipeline<br><strong>from</strong> sklearn.ensemble <strong>import</strong> RandomForestRegressor</pre><pre>X <strong>=</strong> df<strong>.</strong>drop(columns<strong>=</strong>[&#39;is_fulfilled&#39;], axis<strong>=</strong>1)<br>y <strong>=</strong> df[&#39;is_fulfilled&#39;]<br>X_train, X_test, y_train, y_test <strong>=</strong> train_test_split(<br>    X, y, test_size<strong>=</strong>0.2, random_state<strong>=</strong>123)<br>pipeline = Pipeline(steps=[<br>    (&#39;regressor&#39;, RandomForestRegressor(n_estimators=12, random_state=42))<br>])<br>model = pipeline.fit(X_train, y_train)</pre><p><strong>Validate</strong></p><pre>val_accuracy <strong>=</strong> model<strong>.</strong>score(X_test, y_test)<br>val_accuracy</pre><pre>#output<br>1.0</pre><ul><li>We can see that the validation accuracy is 1.0 which means that the model is overfitting.</li></ul><h3>LogisticRegression</h3><p><strong>Fit</strong></p><pre>from sklearn.linear_model import LogisticRegression<br>model = LogisticRegression()<br>results = cross_validate(estimator=model,<br>    X=X,<br>    y=y,<br>    cv=5,<br>    scoring=scoring,<br>    return_train_score=True, return_estimator=True)</pre><p><strong>Model result</strong></p><pre>{&#39;Training Accuracy scores&#39;: array([0.97697182, 0.97692562, 0.97697291, 0.97697291, 0.97697291]),<br> &#39;Mean Training Accuracy&#39;: 97.69632320376157,<br> &#39;Training Precision scores&#39;: array([0.97697182, 0.97692562, 0.97697291, 0.97697291, 0.97697291]),<br> &#39;Mean Training Precision&#39;: 0.9769632320376156,<br> &#39;Training Recall scores&#39;: array([1., 1., 1., 1., 1.]),<br> &#39;Mean Training Recall&#39;: 1.0,<br> &#39;Training F1 scores&#39;: array([0.98835179, 0.98832815, 0.98835235, 0.98835235, 0.98835235]),<br> &#39;Mean Training F1 Score&#39;: 0.9883473967699015,<br> &#39;Validation Accuracy scores&#39;: array([0.9769289 , 0.97711368, 0.97692453, 0.97692453, 0.97692453]),<br> &#39;Mean Validation Accuracy&#39;: 97.696323325532,<br> &#39;Validation Precision scores&#39;: array([0.9769289 , 0.97711368, 0.97692453, 0.97692453, 0.97692453]),<br> &#39;Mean Validation Precision&#39;: 0.9769632332553201,<br> &#39;Validation Recall scores&#39;: array([1., 1., 1., 1., 1.]),<br> &#39;Mean Validation Recall&#39;: 1.0,<br> &#39;Validation F1 scores&#39;: array([0.98832983, 0.98842438, 0.98832759, 0.98832759, 0.98832759]),<br> &#39;Mean Validation F1 Score&#39;: 0.9883473960193727,<br> &#39;Coefficients&#39;: []}</pre><blockquote>LogisticRegression is not overfitting but we still can not be sure due to the unfulfilled trips covering a very small portion of the dataset. We don’t have comparable samples for the unfulfilled orders which constitute only 0.023% of the sample.</blockquote><p>The results of the remaining models will be found in the notebook.</p><p><a href="https://github.com/natyrix/Causal-Inference/blob/main/notebooks/causal_learning.ipynb">Causal-Inference/causal_learning.ipynb at main · natyrix/Causal-Inference</a></p><h3>Logistic optimization</h3><p><a href="https://mattdelventhal.com/post/technician_route/">Optimal Routing with Mixed Integer Programming | Matt Delventhal</a></p><h4>Time and Space</h4><ul><li>Suppose that the day starts at <strong><em>time 0</em></strong> and ends after <strong><em>T hours</em></strong>. For specific times <strong><em>T</em></strong> there will be a broadcast for trip <strong><em>t</em></strong> at T where drives are located on location <strong><em>Ld</em></strong>.</li></ul><h4>Trips</h4><ul><li>There are T trips to be completed. Each trip t = { 1, 2,...., T} has a priority level 𝝅t (if priority is applied if not priority level will be 1) and requires pt minutes to be completed.</li><li>Each trip t should be fully completed by the time ct.</li><li>Let the distance between each trip&#39;s origin and destination be tod</li><li>Let the location of each trip be given by Lt = {1, 2,..., N}.</li></ul><h4>Drivers</h4><ul><li>There are K drivers available for work. Each driver is located at Ok = {1, 2,...,N} for k = {1,2,...,K}.</li><li>Each driver is located d distance away from the broadcasted order</li><li>Every driver can only accept 1 order on a single trip t</li></ul><h4>Broadcasted Orders</h4><ul><li>There are b broadcasted orders b = {1, 2,....,B} for every trip where B is the total number of available nearby drivers</li></ul><h4>Company’s Problem</h4><ul><li>The destination of the trip defines where the driver will travel, from the trip origin to the trip destination,</li><li>To increase the number of fulfilled orders, plenty of drivers have to be placed in areas where most trips originated.</li><li>So for every driver’s location Ld, Ld has to be near the next predicted trip origin,</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*mqthWMwzpYiplNsFxbJegg.png" /></figure><h4>Constraints</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/1*zOYFVYLvNRKVjJu0PEFOaA.png" /></figure><h3>Lessons learned and Conclusion</h3><ul><li>Creating causal graphs.</li><li>Infer the causal graph from observational data and then validate the graph</li><li>Building model pipelines and orchestration</li><li>As you can observe all the 3 models except LogisticRegression, have an accuracy of 1 which is a sign of overfitting.</li><li>Even in the case of the LogisticRegression model, we can not be 100% sure to conclude the model was accurate because we don’t have comparable samples for the unfulfilled orders which constitute only 0.023% of the sample.</li><li>We can however conclude that ML models are overfitted with a higher proportion.</li><li>Logistic optimization</li></ul><h3>Future plans</h3><ul><li>Applying valid interventions and visualizing results.</li><li>Create a day in the life of ZDelivery driver visualizations.</li><li>Improving Logistic optimization</li><li>Collect more business expert thoughts in order to create a more detailed causal graph.</li></ul><h3>References</h3><ol><li><a href="https://arxiv.org/pdf/2107.00793.pdf">https://arxiv.org/pdf/2107.00793.pdf</a></li><li><a href="https://en.wikipedia.org/wiki/Causal_graph">https://en.wikipedia.org/wiki/Causal_graph</a></li><li><a href="https://en.wikipedia.org/wiki/Rubin_causal_model">https://en.wikipedia.org/wiki/Rubin_causal_model</a></li><li><a href="https://arxiv.org/pdf/1803.01422.pdf">https://arxiv.org/pdf/1803.01422.pdf</a></li><li><a href="https://causalnex.readthedocs.io/en/latest/04_user_guide/04_user_guide.html">https://causalnex.readthedocs.io/en/latest/04_user_guide/04_user_guide.html</a></li><li><a href="https://causalnex.readthedocs.io/en/latest/03_tutorial/03_tutorial.html">https://causalnex.readthedocs.io/en/latest/03_tutorial/03_tutorial.html</a></li><li><a href="http://web.math.ku.dk/~peters/jonas_files/scriptChapter1-4.pdf">http://web.math.ku.dk/~peters/jonas_files/scriptChapter1-4.pdf</a></li><li><a href="http://bayes.cs.ucla.edu/WHY/why-ch1.pdf">http://bayes.cs.ucla.edu/WHY/why-ch1.pdf</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d545262755de" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Crypto Trading Engineering]]></title>
            <link>https://medium.com/trading-data-analysis/crypto-trading-engineering-c717f647e749?source=rss-d8b62df65657------2</link>
            <guid isPermaLink="false">https://medium.com/p/c717f647e749</guid>
            <category><![CDATA[finance]]></category>
            <category><![CDATA[trading]]></category>
            <category><![CDATA[crypto]]></category>
            <category><![CDATA[backtesting]]></category>
            <dc:creator><![CDATA[Natnael Melese]]></dc:creator>
            <pubDate>Sat, 15 Oct 2022 18:55:10 GMT</pubDate>
            <atom:updated>2022-10-19T12:47:53.479Z</atom:updated>
            <content:encoded><![CDATA[<p>Crypto Trading Engineering: Scalable Backtesting Infrastructure</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*b9OiuJYrBWXHsn7H_xAKSw.png" /></figure><p><a href="https://github.com/10AcademyB6Week7/Scalable-Backtesting-Infrastructure">GitHub - 10AcademyB6Week7/Scalable-Backtesting-Infrastructure: Crypto Trading Engineering: Scalable Backtesting Infrastructure</a></p><p>Mela is your client this week. A startup called Mela wants to make it simple for everyone to enter the world of cryptocurrencies. It also wants to give investors a reliable source of investment while lowering the risk associated with trading cryptocurrencies.<br>Design a robust data pipeline that can run various backtests and store various useful artifacts in a robust data warehouse system.</p><h3>Overview and Objective</h3><p>Backtesting is the general method for seeing how well a strategy or model<br>would have done ex-post. Backtesting assesses the viability of a trading<br>strategy by discovering how it would play out using historical data. If backtesting works, traders and analysts may be confident to employ it going forward.</p><p>Backtesting involves applying a strategy or predictive model to historical data to determine its accuracy. It can be used to test and compare the viability of trading strategies so traders can employ and tweak successful strategies.</p><p>Analysts use backtesting to test and compare various trading<br>techniques without risking money. The theory is that if their strategy<br>performed poorly in the past, it is unlikely to perform well in the future (and vice versa). The two main components looked at during testing are the overall profitability and the risk level taken.</p><p>However, a backtest will look at the performance of a strategy relative to<br>many different factors. A successful backtest will show traders a strategy<br>that’s proven to deliver positive results historically. While the market never<br>moves the same, backtesting relies on the assumption that stocks move in<br>similar patterns as they did historically.</p><h3>About the Data</h3><p>The data used for backtesting is fetched from:</p><ul><li><a href="https://finance.yahoo.com/">Yahoo Finance - Stock Market Live, Quotes, Business &amp; Finance News</a></li><li><a href="https://www.binance.com/en/landing/data">Buy/Sell Bitcoin, Ether and Altcoins | Cryptocurrency Exchange | Binance</a></li></ul><h4>Exploratory Data Analysis</h4><p>The data analyzed is bitcoin’s historical data — BTC-USD downloaded from yahoo finance. From this result, we can see that it has 1797 rows which in our case is the data recorded for each day. It has 7 columns which are descriptions for the date, open, close, high, low, Adj close, and volume price for each day.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/658/1*Kr-yIGk90M9UERHHoWqPyQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/423/1*-M-sHSODhdOn2LM9GByq9g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/952/1*9JRfbdrW-CIoRaxGSUZXxg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/946/1*n6KnjB0R9yqX2u7o4qCtHg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/949/1*fZaQR5r0Yxic5IxR5sKAXg.png" /></figure><p>The visual description of opening and closing prices for each year</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/642/1*jUWaJODQzF8UdHuLvZ-_1g.png" /><figcaption>Opening Price</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/665/1*TBXwyA5qj7NoeNREaUxnhg.png" /><figcaption>Closing Price</figcaption></figure><p><strong>Correlation plot for dataset</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/591/1*hzPw6zh3ODhNZZBRKvAA0A.png" /></figure><h3>Technologies and tools used to build the project</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U7yLm7i8DubE3FrX0raZzw.png" /><figcaption>Workflow diagram</figcaption></figure><h4>Frontend</h4><p>React is a library for building composable user interfaces. It encourages the creation of reusable UI components, which present data that changes over time. Lots of people use React as the V in MVC.<br>React abstracts away the DOM from you, offering a simpler programming model and better performance</p><p><strong>Principal Benefits of React:</strong></p><ul><li><strong>Reusable Components: </strong>One of the most considerable advantages of React.js for application development is the option to reuse development components as you go. This perk allows starting the development cycle with tiny pieces and slowly progressing to larger ones, eventually getting component-based app fundamentals. Because it’s possible to reuse these components, the development team can save time and money by focusing on other tasks. Consequently, you get a more optimized application by saving resources and getting the most out of the framework capacity.</li><li><strong>Mobile-Friendliness: </strong>Knowing that the technology you choose is community-driven is a calming thought for any business endeavor. One of the benefits of using React.js is its exceptional community support over time. Although Meta maintains the framework, React has a massive community of developers worldwide. Business-wise, the availability of a significant number of competent React.js developers across the globe is one of the core advantages you should use in your project.</li><li><strong>Community Support:</strong> It’s no doubt that mobile-friendliness is one of many benefits of using React.js for your project development. At its core, using this framework means that you can develop and release cross-platform applications without significant restrictions. In the long run, this perk translates to having a more extensive reach for your web application, which is a massive advantage for a well-rounded business project.</li></ul><h4>Kafka</h4><ul><li>Kafka is a new kind of data infrastructure Instead of treating data like<br>things, Kafka treats data like events, It does not just store these events<br>as long as necessary it also handles stream processes dynamically<br>which means it can scale to handle any number of applications.</li><li>As the number of audio recorders (the producers) grew or shrinks as the case may be, Kafka will dynamically meet up with the demand.</li><li>During the consumption of a topic, you can also configure a group with<br>multiple consumers. Each of the consumers in a specific group will<br>access messages from a particular subset of partitions within the topics<br>they subscribe to. This will assure that every message is delivered to<br>one consumer in the group, and all of the messages that carry the same<br>key make it to the same consumer.</li></ul><p><strong>Principal Benefits of Kafka</strong></p><ul><li><strong>Scalability</strong>: Kafka is a distributed system, which is able to be scaled<br>quickly and easily without incurring any downtime. Apache Kafka is able to handle many terabytes of data without incurring much at all in the way of overhead.</li><li><strong>Durability</strong>: Kafka persists the messages on the disks, which provides<br>intra-cluster replication. This makes for a highly durable messaging<br>system.</li><li><strong>Reliability</strong>: Kafka replicates data and is able to support multiple<br>subscribers. Additionally, it automatically balances consumers in the<br>event of failure. That means that it’s more reliable than similar<br>messaging services available.</li><li><strong>High Performance</strong>: Kafka delivers high throughput for both publishings<br>and subscribing, utilizing disk structures that are capable of offering<br>constant levels of performance, even when dealing with many<br>terabytes of stored messages.</li></ul><h4>Airflow</h4><ul><li>Airflow is one of the platforms that is used for workflow management in<br>the data engineering pipeline. It can be used as a data orchestration<br>tool to programmatically author, schedule, and monitor workflows.</li><li>It streamlines increasingly complex enterprise procedures and is based<br>on the idea of “Configuration as a code.”</li><li>Directed acyclic graphs (DAG) are used by Airflow to control workflow<br>orchestration. It enables data engineers to put together and control<br>workflows made up of many data sources.</li></ul><p><strong>Principal Benefits of Airflow</strong></p><ul><li><strong>Task Dependency management</strong>: It is extremely good at<br>managing different sorts of dependencies, be it task completion,<br>dag runs status, file, or partition presence through the specific<br>sensor. Airflow also handles task dependency concepts such as<br>branching.</li><li><strong>DAGs</strong>: are a way to set up workflows, they can set up a sequence<br>of operations that can be individually retried on failure and<br>restarted where the operation failed. Dags provides a nice<br>abstraction to a series of operations.</li></ul><h4><strong>Backend</strong></h4><ul><li>The /get_backtest_scene endpoint will be used to fetch backtest scenes containing parameters for our backtest. The /get_backtest_scene endpoint will be used to fetch backtest scenes containing parameters for our backtest.</li><li>After we have fetched the backtest scenes we stream the data to our Kafka cluster.</li><li>Once we’ve streamed our backtest scene into our cluster our backtest checker module will consume the scene and check to see if there is a previous backtest result stored in our database with the same backtest parameters</li><li>The /backtest_results endpoint will consume the backtest results returned from either our database or our backtest engine and return the results to our front end.</li></ul><h4>Database</h4><ul><li>The user information table will store the user’s first and last name, email, and password</li><li>The backtest scene table will be used to store backtest parameters such as the name of the coin, start and end date for historical data to be used, the indicators they would like to use, starting cash and commission</li><li>The backtest results table will be used to store backtest results with the following fields’ return, the number of traders, Winning traders, losing traders, max drawdown, and Sharpe ratio.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b9f80b5cdcc5944409cedd4abb3d5950/href">https://medium.com/media/b9f80b5cdcc5944409cedd4abb3d5950/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/911/1*1N-7chknJpetDGTMg6HNrg.png" /></figure><h3><strong>Backtest engine implementation</strong></h3><p>Vectorbt excels at processing large amounts of data. By representing strategy data as numpy arrays, it takes advantage of the fast computation speeds numpy offers for vectorized operations. This allows for testing hundreds of variations of strategies relatively quickly.</p><pre>#<a href="https://github.com/10AcademyB6Week7/Scalable-Backtesting-Infrastructure/blob/main/scripts/vectorbt_pipeline.py">vectorbt_pipeline.py</a></pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c8f476a07db255768ba2fcbece2e74b5/href">https://medium.com/media/c8f476a07db255768ba2fcbece2e74b5/href</a></iframe><p><strong>Running indicators</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/759775801e90b3b1ed09a540b3b922f3/href">https://medium.com/media/759775801e90b3b1ed09a540b3b922f3/href</a></iframe><p><strong>Indicator SMA</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bd9257f05b877509adb3db5ee77643f4/href">https://medium.com/media/bd9257f05b877509adb3db5ee77643f4/href</a></iframe><p><strong>Indicator bbands</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9efed2f9aa20fa6059a1fd0ece07068f/href">https://medium.com/media/9efed2f9aa20fa6059a1fd0ece07068f/href</a></iframe><p><strong>Return backtest result</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2f7e85f9b7ac62731442b334b29b1131/href">https://medium.com/media/2f7e85f9b7ac62731442b334b29b1131/href</a></iframe><pre>Vecotorbt Result<br>Start: 2021-10-11 04:00:00+00:00<br>End: 2022-10-10 04:00:00+00:00<br>Period: 252<br>Start Value: 1000.0<br>End Value: 1016.0349950853556<br>Total Return [%]: 1.6034995085355603<br>Benchmark Return [%]: -29.96950592414962<br>Max Gross Exposure [%]: 100.0<br>Total Fees Paid: 0.0<br>Max Drawdown [%]: 14.677441759336915<br>Max Drawdown Duration: 83.0<br>Total Trades: 2<br>Total Closed Trades: 2<br>Total Open Trades: 0<br>Open Trade PnL: 0.0<br>Win Rate [%]: 50.0<br>Best Trade [%]: 8.789075701732942<br>Worst Trade [%]: -6.605053078029709<br>Avg Winning Trade [%]: 8.789075701732942<br>Avg Losing Trade [%]: -6.605053078029709<br>Avg Winning Trade Duration: 44.0<br>Avg Losing Trade Duration: 20.0<br>Profit Factor: 1.2427686030062737<br>Expectancy: 8.017497542677802</pre><p><strong>Save the result and publish to a topic</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/601f5ad80a02f66e5e95c896c79cbdbf/href">https://medium.com/media/601f5ad80a02f66e5e95c896c79cbdbf/href</a></iframe><p><strong>Plot fast and slow SMA</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1dbdd91f682aa4e53c465ed2c75bb801/href">https://medium.com/media/1dbdd91f682aa4e53c465ed2c75bb801/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*B01jQuO7mOy_ExpPHcwYKA.png" /></figure><p><strong>Run Backtest</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d541a116a99938f883c76b376ccacd3e/href">https://medium.com/media/d541a116a99938f883c76b376ccacd3e/href</a></iframe><h3>Lessons learned</h3><ul><li>Understand the difference between fundamental and technical analysis.</li><li>Creating a dynamic scene using an ini file.</li><li>Running multiple backtests using different technical indicators and assets.</li><li>CML integration to run various backtests on algorithmic changes.</li><li>Backtest automation using airflow.</li><li>Designing and creating Machine Learning and Data Engineering pipeline.</li><li>Creating and end-to-end crypto trading platform.</li></ul><h3>Future plans</h3><ul><li>To incorporate more backtesting indicators other than the classic ones.</li><li>To add functionality that will allow users to run one backtest using multiple indicators since most traders usually confirm a profitable backtested indicator with another indicator.</li><li>To utilize more airflow’s extensive functionalities.</li><li>To build a trading bot that can be configured to run multiple and complex backtests then choose the best-performing strategy (or a stipulated metric threshold) and trade with real money</li><li>To try out a database with a normalized star-schema design where the fact table contains an id and other measurable primary data to be analyzed, and each indicator (and their params) will serve as a dimension table.</li><li>To return a plot of users&#39; portfolios after running a backtest alongside the necessary metrics.</li></ul><h3>References</h3><ol><li><a href="https://vectorbt.dev/">https://vectorbt.dev/</a></li><li><a href="https://support.coinex.com/hc/en-us/articles/8747125554329-Introduction-to-K-line">https://support.coinex.com/hc/en-us/articles/8747125554329-Introduction-to-K-line</a></li><li><a href="https://www.investopedia.com/articles/trading/05/030205.asp">https://www.investopedia.com/articles/trading/05/030205.asp</a></li><li><a href="https://www.investopedia.com/terms/t/technicalanalysis.asp">https://www.investopedia.com/terms/t/technicalanalysis.asp</a></li><li><a href="https://www.investopedia.com/terms/m/movingaverage.asp">https://www.investopedia.com/terms/m/movingaverage.asp</a></li><li><a href="https://www.investopedia.com/articles/active-trading/052014/how-use-moving-average-buy-stocks.asp">https://www.investopedia.com/articles/active-trading/052014/how-use-moving-average-buy-stocks.asp</a></li><li><a href="https://towardsdatascience.com/why-apache-airflow-is-a-great-choice-for-managing-data-pipelines-48effcce3e41">https://towardsdatascience.com/why-apache-airflow-is-a-great-choice-for-managing-data-pipelines-48effcce3e41</a></li><li><a href="https://github.com/confluentinc/kafka-rest">https://github.com/confluentinc/kafka-rest</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c717f647e749" width="1" height="1" alt=""><hr><p><a href="https://medium.com/trading-data-analysis/crypto-trading-engineering-c717f647e749">Crypto Trading Engineering</a> was originally published in <a href="https://medium.com/trading-data-analysis">Trading Data Analysis</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Text-to-speech Data Collection]]></title>
            <link>https://medium.com/@natnaelmelese/text-to-speech-data-collection-899d15f403ba?source=rss-d8b62df65657------2</link>
            <guid isPermaLink="false">https://medium.com/p/899d15f403ba</guid>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Natnael Melese]]></dc:creator>
            <pubDate>Sat, 08 Oct 2022 19:45:00 GMT</pubDate>
            <atom:updated>2022-10-08T21:25:03.227Z</atom:updated>
            <content:encoded><![CDATA[<p>Data Engineering: text-to-speech data collection with Kafka, Airflow, and Spark</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l2GF8mPOUfcVymEXquFzDw.png" /></figure><p><a href="https://github.com/natyrix/text-to-speech-data-collection">GitHub - natyrix/text-to-speech-data-collection: Data Engineering: text-to-speech data collection with Kafka, Airflow, and Spark</a></p><p>Produce a tool that can be deployed to process posting and receiving text and audio files from and into a data lake, apply transformation in a distributed manner, and load it into a warehouse in a suitable format to train a speech-to-text model.</p><h3>Overview and Objective</h3><p>The process of acquiring and measuring audio data is known as voice or speech data collection. Virtual assistants and other AI systems have become more user-friendly thanks to the utilization of this data, which may be gleaned from various sources and is used by machines to comprehend and process audio input.</p><p>AI, which recognizes speech, is a cognitive service that attempts to imitate human action. Speech recognition technology gives machines a similar ability to how humans can hear speech, retain what is said, and respond appropriately.</p><p>For crucial use cases like transcription and voice analysis, speech recognition uses AI to translate spoken language into text.</p><p>There are many text corpora for Amharic and Swahili languages, build a data engineering pipeline that allows recording millions of Amharic and Swahili speakers reading digital texts in-app and on web platforms.</p><p>This platform will act as a data source for clients’ speech-to-text ML engines by providing accurate audios of a text corpus in a suitable format for training a speech-to text-model.</p><h3>Technologies and tools used to build the data capture pipeline</h3><h4>Kafka</h4><ul><li>Kafka is a new kind of data infrastructure Instead of treating data like<br>things, Kafka treats data like events, It does not just store these events<br>as long as necessary it also handles stream processes dynamically<br>which means it can scale to handle any number of applications.</li><li>As the number of audio recorders (the producers) grew or shrinks as the case may be, Kafka will dynamically meet up with the demand.</li><li>During the consumption of a topic, you can also configure a group with<br>multiple consumers. Each of the consumers in a specific group will<br>access messages from a particular subset of partitions within the topics<br>they subscribe to. This will assure that every message is delivered to<br>one consumer in the group, and all of the messages that carry the same<br>key make it to the same consumer.</li></ul><p><strong>Principal Benefits of Kafka</strong></p><ul><li><strong>Scalability</strong>: Kafka is a distributed system, which is able to be scaled<br>quickly and easily without incurring any downtime. Apache Kafka is able to handle many terabytes of data without incurring much at all in the way of overhead.</li><li><strong>Durability</strong>: Kafka persists the messages on the disks, which provides<br>intra-cluster replication. This makes for a highly durable messaging<br>system.</li><li><strong>Reliability</strong>: Kafka replicates data and is able to support multiple<br>subscribers. Additionally, it automatically balances consumers in the<br>event of failure. That means that it’s more reliable than similar<br>messaging services available.</li><li><strong>High Performance</strong>: Kafka delivers high throughput for both publishings<br>and subscribing, utilizing disk structures that are capable of offering<br>constant levels of performance, even when dealing with many<br>terabytes of stored messages.</li></ul><h4><strong>Airflow</strong></h4><ul><li>Airflow is one of the platforms that is used for workflow management in<br>the data engineering pipeline. It can be used as a data orchestration<br>tool to programmatically author, schedule, and monitor workflows.</li><li>It streamlines increasingly complex enterprise procedures and is based<br>on the idea of “Configuration as a code.”</li><li>Directed acyclic graphs (DAG) are used by Airflow to control workflow<br>orchestration. It enables data engineers to put together and control<br>workflows made up of many data sources.</li></ul><p><strong>Principal Benefits of Airflow</strong></p><ul><li><strong>Task Dependency management</strong>: It is extremely good at<br>managing different sorts of dependencies, be it task completion,<br>dag runs status, file, or partition presence through the specific<br>sensor. Airflow also handles task dependency concepts such as<br>branching.</li><li><strong>DAGs</strong>: are a way to set up workflows, they can set up a sequence<br>of operations that can be individually retried on failure and<br>restarted where the operation failed. Dags provides a nice<br>abstraction to a series of operations.</li></ul><h4>Spark</h4><ul><li>Provides a unified environment that accepts data from many different<br>forms and allows all the tools to work together on the same data,<br>passing a data set from one step to the next.</li><li>It provides this service in a single or clustered environment. We will be<br>using spark to perform data transformations on the text corpus.</li></ul><p><strong>Principal Benefits of Spark</strong></p><ul><li>Spark can be deployed in a variety of ways, and provides native<br>bindings for Java, Scala, Python, and R programming<br>languages, and supports SQL, streaming data, machine learning,<br>and graph processing. Apache Spark is an essential tool for a<br>large-scale data pipeline project such as ours, it allows us to<br>allow us to perform processing tasks on a large dataset.</li></ul><h3>Exploratory Data Analysis and Insights</h3><h4>About the data</h4><p>There are a number of large text corpora we will use, but for the purpose of testing the backend development, we used the recently released Amharic news text classification dataset with a baseline performance dataset</p><p><a href="https://github.com/IsraelAbebe/An-Amharic-News-Text-classification-Dataset">GitHub - IsraelAbebe/An-Amharic-News-Text-classification-Dataset: An Amharic News Text classification Dataset</a></p><p>The data has the following columns.</p><ul><li><strong>headline</strong></li><li><strong>category</strong></li><li><strong>date</strong></li><li><strong>views</strong></li><li><strong>article</strong></li><li><strong>link</strong></li></ul><pre>df<strong>.</strong>category<strong>.</strong>unique()</pre><pre>array([&#39;ስፖርት&#39;, &#39;መዝናኛ&#39;, &#39;ሀገር አቀፍ ዜና&#39;, &#39;ቢዝነስ&#39;, &#39;ዓለም አቀፍ ዜና&#39;, &#39;ፖለቲካ&#39;, nan],<br>      dtype=object)</pre><p><strong>Word Length</strong></p><pre>df[&#39;word_len&#39;] <strong>=</strong> df[&#39;article&#39;]<strong>.</strong>str<strong>.</strong>split()<strong>.</strong>str<strong>.</strong>len()<br>df<strong>.</strong>head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5E79Nx3VQSFSTukYSnL2Eg.png" /><figcaption>Word length</figcaption></figure><pre>df<strong>.</strong>info()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/324/1*GK9eoyDftdbyuwhkzqfhqQ.png" /><figcaption>df.info()</figcaption></figure><pre>df<strong>.</strong>word_len<strong>.</strong>mean()<br>248.9586853912942</pre><h3>Implementations of the Project</h3><ul><li>We will divide our topics among our data categories.</li></ul><pre>topic_names = {<br>   &quot;ሀገር አቀፍ ዜና&quot;: &quot;g2-national_news&quot;,<br>   &quot;መዝናኛ&quot;: &quot;g2-entertainment&quot;,<br>   &quot;ቢዝነስ&quot;: &quot;g2-business&quot;,<br>   &quot;ዓለም አቀፍ ዜና&quot;: &quot;g2-international_news&quot;,<br>   &quot;ፖለቲካ&quot;:&quot;g2-politics&quot;,<br>   &quot;ስፖርት&quot;:&quot;g2-sport&quot;<br>}</pre><ul><li>We will have an API endpoint that is connected to a producer that takes<br>the audio recording and passes it to the Kafka cluster.</li></ul><pre>#<a href="https://github.com/10AcademyB6Week7/text-to-speech-data-collection/blob/main/backend/api.py">api.py</a></pre><pre>producer = KafkaProducer(bootstrap_servers=[&#39;b-   1.batch6w7.6qsgnf.c19.kafka.us-east-1.amazonaws.com:9092&#39;,&#39;b-  2.batch6w7.6qsgnf.c19.kafka.us-east-1.amazonaws.com:9092&#39;],<br>client_id=&#39;g2-text-producer&#39;,value_serializer=lambda x:   dumps(x).encode(&#39;utf-8&#39;))</pre><pre>headline = request.form.get(&quot;headline&quot;)<br>article = request.form.get(&quot;article&quot;)<br>json_id = request.form.get(&quot;json_id&quot;)<br>audio_file = request.files[&quot;file&quot;]<br>if audio_file.filename != &#39;&#39;:<br>   filename = secure_filename(audio_file.filename)<br>   file_path = app.config[&quot;UPLOAD_FOLDER&quot;] + filename + f&quot;{datetime.now()}&quot;<br>   audio_file.save(file_path)<br>   print(file_path)<br>   producer.send(&quot;g2-audio-output&quot;, {&quot;headline&quot;:headline,&quot;article&quot;:article,&quot;json_id&quot;:json_id,&quot;file_path&quot;:file_path}).get(timeout=30)<br> <br>return jsonify({&quot;status&quot;: &quot;success&quot;,&quot;file_path&quot;:file_path})</pre><pre><br># <a href="https://github.com/10AcademyB6Week7/text-to-speech-front-end/blob/cbe0d8b027ddc10026caeef7d416db434eb4be49/src/components/record/Record.jsx">Record.jsx</a></pre><pre>async function handleAudioUpload(file) {<br>        // console.log(file);<br>        let formData = new FormData();<br>        formData.append(&#39;file&#39;, file)<br>        formData.append(&#39;json_id&#39;,454)<br>        formData.append(&#39;headline&#39;, text[&#39;headline&#39;])<br>        formData.append(&#39;article&#39;, text[&#39;article&#39;]) <br>        try{<br>          setIsLoading(true)<br>          let res = await axios.post(`${BASE_URL}/get_audio`, formData);<br>          console.log(res)<br>          let data = res.data;<br>          if(data!==undefined){<br>            if(data.status === &quot;success&quot;){<br>              alert(&quot;Recording submitted&quot;)<br>            }else{<br>                alert(data.message)<br>            }<br>          }<br>          else{<br>              alert(&quot;Something went wrong&quot;)<br>          }<br>        }catch(e){<br>                console.log(e)<br>                alert(e.message)<br>            }finally{<br>              setIsLoading(false)<br>            }<br>    }</pre><pre>&lt;Recorder <br>  record={true} <br>  title={&quot;New recording&quot;}<br>  audioURL={audioDetails.url}<br>  showUIAudio<br>  handleAudioStop={(data) =&gt; handleAudioStop(data)}<br>  handleOnChange={(value) =&gt; handleOnChange(value, &quot;firstname&quot;)}<br>  handleAudioUpload={(data) =&gt; handleAudioUpload(data)} <br>  handleReset={handleRest}<br>  mimeTypeToUseWhenRecording={`audio/webm`} <br>/&gt;</pre><ul><li>We will have an API endpoint that is connected to a Kafka consumer<br>who is subscribed to the data stream coming from our Amharic news<br>data.</li></ul><pre>#<a href="https://github.com/10AcademyB6Week7/text-to-speech-data-collection/blob/main/backend/api.py">api.py</a></pre><pre><a href="http://twitter.com/app">@app</a>.route(&#39;/return_processed_audio&#39;, methods=[&#39;POST&#39;])<br>def return_processed_audio():<br>    try:<br>        if request.method == &quot;POST&quot;:<br>            conn = sqlite3.connect(&#39;processed_audio.db&#39;)<br>            json_id = request.get_json()[&quot;json_id&quot;]<br>            cursor = conn.execute(&quot;SELECT json_id, headline, article, file_path from Audio)<br>            for row in cursor:<br>                json_id = row[0]<br>                headline = row[1]<br>                article = row[2]<br>                file_path = row[3]<br>                audio_file = open(&quot;{}&quot;.format(file_path), &quot;rb&quot;).read()<br>                return jsonify({&quot;status&quot;: &quot;success&quot;,&quot;json_id&quot;:json_id,&quot;headline&quot;:headline,&quot;article&quot;:article,&quot;audio_file&quot;:audio_file})<br>        else:<br>            return{<br>                &quot;status&quot;: &quot;error&quot;,<br>                &quot;message&quot;: f&quot;{request.method} is not allowed&quot;<br>            }<br>    except Exception as e:<br>        return{<br>            &quot;status&quot;: &quot;error&quot;,<br>            &quot;message&quot;: str(e)<br>        }</pre><ul><li>We will use random partitions to balance data across our partitions<br>when writing topics.</li><li>We will configure your producer to wait for acknowledgments; to make<br>sure the message has actually made it to the partition on the broker.</li><li>We will tune our consumer socket buffers for high bandwidth ingestion.</li><li>Will use pyspark to ensure there aren’t any blank audio files being sent<br>to the cluster.</li><li>We will have a consumer who will be connected to our S3 bucket which<br>is subscribed to the audio data stream coming from our Kafka cluster.</li><li>We will have a producer connected to our S3 bucket that sends a<br>datastream of Amharic news data to its subscribers.</li></ul><h3>Lessons learned</h3><ul><li>Creating and setting up kafka cluster.</li><li>How to use dags to Orchestrate storage of events collected to a database.</li><li>How to create an S3 bucket data lake.</li><li>Media recording API for both vanilla js and ReactJS implementations.</li><li>How to transform and load data to and from the data lake.</li></ul><h3>Future plans</h3><ul><li>Implementing more effective models to preprocess the uploaded audio.</li><li>Providing a way for users to download data(audio + text corpus).</li><li>Improving the data’s structure so that it may be immediately applied to an ML model.</li><li>Completing the streaming pipeline.</li></ul><h3>References</h3><ol><li><a href="https://dev.to/florimondmanca/breaking-news-everything-is-an-event-streams-kafka-and-you-2n9j">https://dev.to/florimondmanca/breaking-news-everything-is-an-event-streams-kafka-and-you-2n9j</a></li><li><a href="https://spark.apache.org/docs/latest/structured-streaming-kafka-integration.html">https://spark.apache.org/docs/latest/structured-streaming-kafka-integration.html</a></li><li><a href="https://towardsdatascience.com/why-apache-airflow-is-a-great-choice-for-managing-data-pipelines-48effcce3e41">https://towardsdatascience.com/why-apache-airflow-is-a-great-choice-for-managing-data-pipelines-48effcce3e41</a></li><li><a href="https://github.com/confluentinc/kafka-rest">https://github.com/confluentinc/kafka-rest</a></li><li><a href="https://www.confluent.io/blog/event-sourcing-using-apache-kafka/">https://www.confluent.io/blog/event-sourcing-using-apache-kafka/</a></li><li><a href="https://www.kai-waehner.de/blog/2020/08/07/apache-kafka-handling-large-messages-and-files-for-image-video-audio-processing/">https://www.kai-waehner.de/blog/2020/08/07/apache-kafka-handling-large-messages-and-files-for-image-video-audio-processing/</a></li><li><a href="https://docs.databricks.com/getting-started/try-databricks.html">https://docs.databricks.com/getting-started/try-databricks.html</a></li><li><a href="https://www.w3schools.com/js/js_whereto.asp">https://www.w3schools.com/js/js_whereto.asp</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=899d15f403ba" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Algorand End-to-End Web3 dApps]]></title>
            <link>https://medium.com/@natnaelmelese/algorand-end-to-end-web3-dapps-9facb6f95434?source=rss-d8b62df65657------2</link>
            <guid isPermaLink="false">https://medium.com/p/9facb6f95434</guid>
            <category><![CDATA[web3]]></category>
            <category><![CDATA[algorand]]></category>
            <category><![CDATA[nft]]></category>
            <dc:creator><![CDATA[Natnael Melese]]></dc:creator>
            <pubDate>Sat, 01 Oct 2022 18:43:44 GMT</pubDate>
            <atom:updated>2022-10-02T02:10:58.431Z</atom:updated>
            <content:encoded><![CDATA[<p>Certificate generation, distribution, and value transfer with Algorand NFTs and smart contracts</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zr2N4eM3t5glsO6VURU22w.png" /></figure><p><a href="https://github.com/natyrix/algorand">GitHub - natyrix/algorand: End-to-End Web3 dApps: certificate generation, distribution, and value transfer with Algorand NFTs and smart contracts</a></p><p>Build 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><h3>Overview and Objective</h3><p>The user-controlled internet is at the core of Web3 technology. A rising<br>number of decentralized technologies, including blockchains, smart<br>contracts, oracles, cryptocurrency wallets, storage networks, and others, are helping to achieve this.</p><p>The World Wide Web’s dependable, resilient infrastructure was made<br>possible by centralization, which also assisted in bringing billions of people online. At the same time, a small group of centralized organizations control a sizable portion of the World Wide Web and make unilateral decisions over what should and shouldn’t be permitted.</p><p>Web3 is the answer to this dilemma. Instead of a Web monopolized by large<br>technology companies, Web3 embraces decentralization and is being built,<br>operated, and owned by its users. Web3 puts the power in the hands of<br>individuals rather than corporations.</p><p>In this project, the client is 10 Academy; the client would like to solve the challenge of 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 10 Academy undertake smart actions with the trainees/their contracts.</p><h3>The Algorand Blockchain</h3><p>Algorand (ALGO) was developed by MIT professor Silvio Micali and launched in 2019 as an open-source decentralized network designed to eliminate the need for hard forks while increasing scaling and transaction speed.</p><p>Algorand is a green blockchain introduced to provide a vast array of<br>technologies primarily to support decentralized finance. This<br>carbon-negative chain combines an energy-friendly consensus with<br>sound policies to ensure the earth remains green. It has a native coin<br>called ALGO, which helps in enhancing its agenda.</p><p>Algorand uses a unique variation of Proof of Stake called Pure Proof of<br>Stake (PPoS). PPoS is a highly democratized PoS consensus mechanism<br>with a low minimum staking requirement for participating in and<br>securing the network only one ALGO coin is needed to participate.</p><p>Algorand has a unique two-tiered blockchain structure. The base layer supports smart contracts, asset creation, and atomic swaps between assets. All of these processes take place on Layer 1 of the Algorand blockchain, which helps ensure security and compatibility. It has an API available for developers to access the Algorand blockchain, which makes it easy to build web3 apps.</p><h4>Several Algorand statistics as of publication</h4><ul><li>The market rank of Algorand is 31 based on a market capitalization of $2.5B</li><li>Algorand has a circulating supply of 6,931,152,987 ALGO. The highest recorded Algorand price is 3.15 EUR. And the lowest recorded ALGO price is 0.09 EUR.</li><li>Price: $0.3574 for 1 ALGO</li><li>Fees are calculated based on the size of the transaction and a user can choose to augment a fee to help prioritize acceptance into a block when network traffic is high and blocks are consistently full. There is no concept of gas fees on Algorand.</li><li>The minimum fee for a transaction is only 1,000 microAlgos or 0.001 Algos.</li><li>Circulating supply of 6,931,152,987 ALGO.</li></ul><h3>Technologies and Tools used for Project</h3><h4>Frontend (Reactjs)</h4><ul><li>Used for building interactive user interfaces and web applications quickly and efficiently with significantly less code than you would with vanilla JavaScript.</li><li>An open-source, component-based library that is responsible only for the view layer of the application.</li></ul><h4>Backend (Django)</h4><ul><li>A high-level Python web framework that encourages rapid development and clean, pragmatic design.</li><li>Built by experienced developers, Django takes care of much of the hassle of web development, so you can focus on writing your app without needing to reinvent the wheel.</li></ul><h3>Implementations of the Project</h3><p>In order to design a user interface for trainees and staff members, I chose ReactJs for this project. The trainees have a page where they can opt-in to the NFT asset and request certificates. A page for certificate requesters and mint NFT for trainees is available to staff members. I connected to the Algorand test net environment using this tool to obtain wallet addresses, generate NFTs, handle user authentication and profile management, and provide the API for each functionality. And finally, use AlgoSign to sign every transaction securely.</p><h4>Steps Followed:</h4><ol><li>Trainees/Admins will choose their wallet address.</li><li>If they are registered they will be directed to their respective pages.</li><li>Trainees will request the NFT using a button provided.</li><li>To claim the NFT, the trainee must opt-in their asset. They’ll have access to their NFT.</li><li>A staff member reviews certificate requests, and if the applicant met all the requirements, an NFT will be issued with the applicant’s name and address.</li><li>The uploaded file will be stored in the project’s IPFS-based distributed storage infrastructure. Secondly, send Algorand the link so they can create an asset with the file link.</li></ol><h4>Save the file to a distributed system.</h4><pre>#Save the file to a distributed system.</pre><pre>async function upload_to_web3_2(asset_id){<br>        let formData = new FormData();<br>        formData.append(&#39;file&#39;, file)<br>        formData.append(&#39;pinataOptions&#39;, &#39;{&quot;cidVersion&quot;: 1}&#39;);<br>        formData.append(&#39;pinataMetadata&#39;, &#39;{&quot;name&quot;: &quot;MyFile&quot;, &quot;keyvalues&quot;: {&quot;company&quot;: &quot;10Academy&quot;}}&#39;);</pre><pre>let config = {<br>            method: &#39;post&#39;,<br>            url: &#39;<a href="https://api.pinata.cloud/pinning/pinFileToIPFS&#39;">https://api.pinata.cloud/pinning/pinFileToIPFS&#39;</a>,<br>            headers: { <br>              &#39;Authorization&#39;: &#39;Bearer {API_TOKEN}&#39;, <br>            //   ...formData.getHeaders()<br>            },<br>            data : formData<br>          };</pre><pre>const res = await axios(config);<br>        console.log(res.data);<br>        let img_url = `<a href="https://gateway.pinata.cloud/ipfs/$%7Bres.data.IpfsHash%7D%60">https://gateway.pinata.cloud/ipfs/${res.data.IpfsHash}`</a><br>        await mint(asset_id,img_url)<br>    }</pre><h4>Create an Asset</h4><pre>#Create an Asset</pre><pre>async function mint(created_id, url){<br>    if(recieverAddress.length !==0 &amp;&amp; assetName.length !==0  &amp;&amp; unitName.length !==0  &amp;&amp; note.length !==0 &amp;&amp; file!==null){<br>    try{<br>       setIsLoading(true)<br>       const server = &#39;<a href="https://testnet-algorand.api.purestake.io/ps2&#39;">https://testnet-algorand.api.purestake.io/ps2&#39;</a><br>       const token = { &#39;X-API-Key&#39;: &#39;{TOKEN}&#39; }<br>       const port = &#39;&#39;;</pre><pre>       let algodClient = new Algodv2(token, server, port);<br>       let health = await algodClient.healthCheck().do()<br>                <br>       let txParamsJS = await algodClient.getTransactionParams().do()<br>       console.log(txParamsJS)</pre><pre>       const txn = makeAssetCreateTxnWithSuggestedParamsFromObject({<br>          from: address,<br>          assetName: assetName,<br>          unitName: unitName,<br>          total: 1,<br>          decimals: 0,<br>          assetURL: url,<br>          note: AlgoSigner.encoding.stringToByteArray(note),<br>          suggestedParams: {...txParamsJS}<br>    })<br>       console.log(&quot;CREATED&quot;)</pre><pre>       const txn_b64 = AlgoSigner.encoding.msgpackToBase64(txn.toByte());<br>       console.log(&quot;ENCODED&quot;)</pre><pre>// const myAlgoConnect = new MyAlgoConnect();</pre><pre>       let signedTxs = await AlgoSigner.signTxn([{txn: txn_b64}])</pre><pre>// const signedTxs = await myAlgoConnect.signBytes(txn_b64, address);</pre><pre>        console.log(&quot;SIGNED TXS&quot;)<br>        console.log(signedTxs)</pre><pre>        let tx = await AlgoSigner.send({<br>             ledger: &#39;TestNet&#39;,<br>             tx: signedTxs[0].blob<br>         })</pre><pre>        console.log(&quot;SEND:&quot;)<br>        console.log(tx)<br>                  <br>        let d = await AlgoSigner.algod({<br>            ledger: &#39;TestNet&#39;,<br>            path: &#39;/v2/transactions/pending/&#39; + tx.txId<br>         })<br>                <br>        console.log(&quot;D&quot;)<br>        console.log(d)<br>        let txInfo = await waitForConfirmation( algodClient,tx.txId)<br>        console.log(&quot;TX INFO&quot;)<br>        console.log(txInfo)</pre><pre>        if(txInfo[&#39;asset-index&#39;]!==undefined){<br>            await update_asset_index(created_id, txInfo[&#39;asset-index&#39;], url, assetName)<br>        }</pre><pre>   }catch(e){<br>        console.log(e)<br>        alert(e.message)<br>   }finally{<br>        setIsLoading(false)<br>   }<br> }else{<br>    alert(&quot;All Fields are required&quot;)<br> }<br>}</pre><h4>Asset Opt-in</h4><pre>#Asset Opt-in</pre><pre>async function optin(){<br>    try{<br>      if(note.length!==0 &amp;&amp; selectedAssetID !== null &amp;&amp; selectedAssetIndex !== null){<br>        setOpen(o =&gt; !o)<br>        setIsLoading(true)<br>        const algodServer = &#39;<a href="https://testnet-algorand.api.purestake.io/ps2&#39;">https://testnet-algorand.api.purestake.io/ps2&#39;</a><br>        const indexerServer = &#39;<a href="https://testnet-algorand.api.purestake.io/idx2&#39;">https://testnet-algorand.api.purestake.io/idx2&#39;</a><br>        const token = { &#39;X-API-Key&#39;: &#39;{Token}&#39; }</pre><pre>        const port = &#39;&#39;;</pre><pre>        let algodClient = new Algodv2(token, algodServer, port);<br>        // let indexerClient = new Indexer(token, indexerServer,                        port);</pre><pre>        algodClient.healthCheck().do()</pre><pre>        let txParamsJS = await    algodClient.getTransactionParams().do()<br>        console.log(txParamsJS)</pre><pre>// let result = await AlgoSigner.indexer({<br>        //   ledger: &#39;TestNet&#39;,<br>        //   path: `/v2/assets?name=${asset_name}&amp;limit=5`,<br>        // })</pre><pre>// let assets<br>        console.log(address)<br>        console.log(+selectedAssetIndex)<br>        // console.log(address)</pre><pre>        const txn = makeAssetTransferTxnWithSuggestedParamsFromObject({<br>          from: address,<br>          to: address,<br>          assetIndex: +selectedAssetIndex,<br>          note:AlgoSigner.encoding.stringToByteArray(note),<br>          amount:0,<br>          suggestedParams: {...txParamsJS}<br>        })<br>        console.log(&quot;CREATED&quot;)</pre><pre>        const txn_b64 = await AlgoSigner.encoding.msgpackToBase64(txn.toByte());<br>        console.log(&quot;ENCODED&quot;)<br>        console.log(txn_b64)</pre><pre>        let signedTxs = await AlgoSigner.signTxn([{txn: txn_b64}]) <br>        console.log(&quot;SIGNED TXS&quot;)<br>        console.log(signedTxs)</pre><pre>        let tx = await AlgoSigner.send({<br>          ledger: &#39;TestNet&#39;,<br>          tx: signedTxs[0].blob<br>        })</pre><pre>        console.log(&quot;SEND:&quot;)<br>        console.log(tx)</pre><pre>        let d = await AlgoSigner.algod({<br>          ledger: &#39;TestNet&#39;,<br>          path: &#39;/v2/transactions/pending/&#39; + tx.txId<br>        })<br>      <br>        console.log(&quot;D&quot;)<br>        console.log(d)</pre><pre>        let txInfo = await waitForConfirmation( algodClient, tx.txId)<br>        console.log(&quot;TX INFO&quot;)<br>        console.log(txInfo)</pre><pre>        await update_asset_status()<br>      }<br>      else{<br>        alert(&quot;All fields are required.&quot;)<br>      }</pre><pre>    }<br>    catch(e){<br>      console.log(e)<br>      alert(e.message)<br>    }<br>    finally{<br>        setIsLoading(false)<br>    }<br>  }</pre><h3>What I have learned</h3><p><strong>Concepts closely related to this project:</strong></p><ul><li>Algorand’s standard asset(ASA) feature enables the minting of NFTs.</li><li>Algorand is a really fast and scalable blockchain platform that uses a proof-of-stake protocol to finalize transactions immediately.</li><li>Storing and distributing data with IPFS saves bandwidth by retrieving data from multiple peers at once.</li><li>A user requests content based on its unique CID, IPFS retrieves that data based on the CID from multiple nodes at once, and it is then delivered to the user in the quickest, most efficient way possible.</li></ul><p><strong>General concepts about decentralized apps.</strong></p><ul><li>For a public blockchain, the decision to add a transaction to the chain is made by consensus. This means that the majority of “nodes” (or computers in the network) must agree that the transaction is valid. The people who own the computers in the network are incentivized to verify transactions through rewards.</li><li>Wallets in a blockchain are made possible (and secure) using security and encryption methods like a secure hashing algorithm, private key, and public key pair.</li><li>Blockchain is a shared, immutable ledger that facilitates the process of recording transactions and tracking assets in a business network.</li><li>Everything on the blockchain is a transaction.</li><li>A blockchain platform allows users and developers to create novel uses on top of an existing blockchain infrastructure.</li></ul><h3>Future Plans</h3><ul><li>The dapp lies on Algorand’s test net, for the future, I am planning to deploy it into the main net.</li><li>Apply robust and reusable smart contracts to make this project 100% decentralized.</li><li>Test and prevent</li></ul><h3>References</h3><ol><li><a href="https://www.coinbase.com/blog/understanding-web-3-a-user-controlled-internet">https://www.coinbase.com/blog/understanding-web-3-a-user-controlled-internet</a></li><li><a href="https://indepth.dev/posts/1506/an-introduction-to-blockchain">https://indepth.dev/posts/1506/an-introduction-to-blockchain</a></li><li><a href="https://explorer.dappflow.org/">https://explorer.dappflow.org/</a></li><li><a href="https://www.pinata.cloud/">https://www.pinata.cloud/</a></li><li><a href="https://developer.algorand.org/solutions/assets-and-custom-transfer-logic/">https://developer.algorand.org/solutions/assets-and-custom-transfer-logic/</a></li><li><a href="https://developer.purestake.io/login">https://developer.purestake.io/login</a></li><li><a href="https://developer.algorand.org/docs/get-details/parameter_tables/?from_query=opt%20#minimum-balance">https://developer.algorand.org/docs/get-details/parameter_tables/?from_query=opt%20#minimum-balance</a></li><li><a href="https://developer.algorand.org/articles/linking-algorand-stateful-and-stateless-smart-contracts/">https://developer.algorand.org/articles/linking-algorand-stateful-and-stateless-smart-contracts/</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9facb6f95434" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Engineering]]></title>
            <link>https://medium.com/@natnaelmelese/data-engineering-c67056816f29?source=rss-d8b62df65657------2</link>
            <guid isPermaLink="false">https://medium.com/p/c67056816f29</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[etl-pipeline]]></category>
            <category><![CDATA[airflow]]></category>
            <dc:creator><![CDATA[Natnael Melese]]></dc:creator>
            <pubDate>Sat, 24 Sep 2022 14:37:30 GMT</pubDate>
            <atom:updated>2022-09-25T02:39:41.957Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Data warehouse tech stack with PostgreSQL, DBT, Airflow, and Redash</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/851/1*ufK6KyTG84-fCEbe-fcPYg.jpeg" /></figure><ul><li><a href="https://github.com/natyrix/traffic-data-warehouse">GitHub - natyrix/traffic-data-warehouse: Data Engineering: Data warehouse tech stack with MySQL, DBT, Airflow</a></li><li><a href="https://open-traffic.epfl.ch/index.php/downloads/#1599047632450-ebe509c8-1330">Downloads</a></li></ul><p>A city traffic department wants to collect traffic data using swarm UAVs<br>(drones) from a number of locations in the city and use the data collected for improving traffic flow in the city and for a number of other undisclosed<br>projects. Your startup is responsible for creating a scalable data warehouse<br>that will host the vehicle trajectory data extracted by analyzing footage taken by swarm drones and static roadside cameras.</p><h4>Overview and Objective</h4><p>With data driving critical business decisions, testing the data warehouse data integration process is essential. Data comes from numerous sources. The data source affects data quality, so data profiling and data cleaning must be ongoing. Source data history, business rules, or audit information may no longer be available.</p><p>Additionally, in the ETL process, data flows through a pipeline before reaching the data warehouse. You must test the entire ETL pipeline to ensure each data type is transformed or copied as expected. Most importantly, the data warehouse is a strategic enterprise resource. Testing is required.</p><p>This project aims to provide a data pipeline and warehouse for traffic data gathered from various places throughout a city. We’ll integrate our DBT (data build tool) into the Extract Load Transform (ELT) architecture.</p><p>The data warehouse should take into account future needs, and organize data such that a number of downstream projects query the data efficiently. You should use the Extract Load Transform (ELT) framework using DBT. Unlike the Extract, Transform, Load (ETL), the ELT framework helps analytic engineers in the city traffic department set up transformation workflows on a need basis.</p><h4>About the data</h4><p>You can obtain the data we’ll be using for this project from pNEUMA data. A half million automobiles’ naturalistic trajectories from the congested downtown of Athens, Greece, are collected in the open large-scale dataset known as pNEUMA. A swarm of drones was utilized in the ground-breaking experiment to gather the data.</p><h4>Methodologies/Tools</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/977/1*1kWyIDnxocoaIN3tLplgxg.png" /><figcaption>Techstack diagram</figcaption></figure><h4><strong>SQLAlchemy</strong></h4><p>SQLAlchemy is a library that facilitates the communication between Python programs and databases. Most of the time, this library is used as an Object Relational Mapper (ORM) tool that translates Python classes to tables on relational databases and automatically converts function calls to SQL statements.</p><h4><strong>Apache Airflow</strong></h4><p>Apache Airflow is used for the scheduling and orchestration of data pipelines or workflows. Orchestration of data pipelines refers to the sequencing, coordination, scheduling, and managing of complex data pipelines from diverse sources.</p><h4>dbt(Data Build Tool)</h4><p>dbt (Data Build Tool) is an open-source Python application that uses modular SQL queries to allow data engineers and analysts to transform data in their warehouses. It takes care of the ‘T’ in ETL procedures and handles the data engineering that comes before analytics.</p><h4>Data Warehouse (PostgreSQL)</h4><p>PostgreSQL is used as the primary data store or data warehouse for many<br>web, mobile, geospatial, and analytics applications.</p><ul><li>Enterprise-class open source relational database.</li><li>Supports both SQL (relational) and JSON (non-relational) querying.</li><li>Offers a wider variety of data types than MySQL.</li><li>Supports triggers on a wide variety of commands, except for those that<br>have a global effect</li></ul><h4>Redash</h4><p>Redash is designed to enable anyone, regardless of the level of technical<br>sophistication, to harness the power of data big and small. SQL users leverage Redash to explore, query, visualize, and share data from any data source.</p><h4>Save raw data and transform on Apache Airflow using DAGs</h4><p><strong>Save raw data</strong></p><pre>def load_raw_data(path, table_name):<br>    print(&quot;WRITING DATA&quot;)<br>    engine = create_engine(&quot;######&quot;)<br>    df = pd.read_csv(path, sep=&quot;[,;:]&quot;, index_col=False)</pre><pre>df.to_sql(table_name, con=engine, if_exists=&#39;replace&#39;,index_label=&#39;id&#39;)<br>    print(&quot;DATA SAVED&quot;)</pre><pre>with DAG(<br>    dag_id=&#39;save_to_db&#39;,<br>    default_args=default_args,<br>    description=&#39;this dag loads raw data to ware house&#39;,<br>    start_date=airflow.utils.dates.days_ago(1),<br>    schedule_interval=&#39;<a href="http://twitter.com/once">@once</a>&#39;<br>)as dag:<br>    task1 = PythonOperator(<br>        task_id=&#39;migrate&#39;,<br>        python_callable=load_raw_data,<br>        op_kwargs={<br>            &quot;path&quot;: &quot;./data/sample.csv&quot;,<br>            &quot;table_name&quot;:&quot;trafficinfo&quot;<br>        }<br>    )<br>    task1</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Br2Lx_tOhYDxL2YQsiegvw.png" /></figure><p><strong>Transform and save</strong></p><p>Simple transformation</p><pre>def modify_data(location):<br>    print(&quot;TRANSFORMING&quot;)<br>    with open(location, &#39;r&#39;, encoding=&#39;ISO-8859-1&#39;) as f:<br>        lines = f.readlines()<br>        updated_lines=&quot;&quot;<br>        for index , line in enumerate(lines):<br>            each_line = line.split(&#39;;&#39;)<br>            if index != 0:<br>                new_lines = [l.strip() for l in each_line]<br>                updated_lines += &quot;;&quot;.join(new_lines[0:10]) + &quot;;&quot; + &quot;_&quot;.join(new_lines[10:])+&quot;\n&quot;<br>            else:<br>                new_lines = [l.strip() for l in each_line]<br>                updated_lines += &quot;;&quot;.join(new_lines[:len(new_lines)-1]) + &quot;;&quot; + &quot;time&quot; + &quot;;&quot; + &quot;other_data&quot; + &quot;\n&quot; <br>    with open(&#39;./data/transformed_dataset.csv&#39;, &quot;w&quot;) as f:<br>        f.writelines(updated_lines)<br>    print(&quot;TRANSFORMED&quot;)</pre><pre>def save_data(table_name):<br>    print(&quot;SAVING TO DB&quot;)<br>    engine = create_engine(&quot;postgresql://postgres:nvskFr7xOO8bndqdqh9W@containers-us-west-30.railway.app:7828/railway&quot;)<br>    df = pd.read_csv(&quot;./data/transformed_dataset.csv&quot;, sep=&quot;;&quot;, index_col=False)<br>    df.to_sql(table_name, con=engine, if_exists=&#39;replace&#39;,index_label=&#39;id&#39;)<br>    print(&quot;SAVED&quot;)</pre><pre>with DAG(<br>    dag_id=&#39;transform_and_save_to_db&#39;,<br>    default_args=default_args,<br>    description=&#39;this dag transforms and saves&#39;,<br>    start_date=airflow.utils.dates.days_ago(1),<br>    schedule_interval=&#39;<a href="http://twitter.com/once">@once</a>&#39;<br>)as dag:<br>    task1 = PythonOperator(<br>        task_id=&#39;modify_and_add&#39;,<br>        python_callable=modify_data,<br>        op_kwargs={<br>            &quot;location&quot;: &quot;./data/raw_dataset.csv&quot;<br>        }<br>    )<br>    task2 = PythonOperator(<br>        task_id=&#39;save_modified&#39;,<br>        python_callable=save_data,<br>        op_kwargs={<br>            &quot;table_name&quot;: &quot;transformed_data&quot;<br>        }<br>    )<br>    task1 &gt;&gt; task2Generate sample time series data</pre><pre>def transform_data():<br>    cols = [&#39;track_id&#39;, &#39;type&#39;, &#39;lat&#39;, &#39;lng&#39;, &#39;speed&#39;, &#39;lon_acc&#39;, &#39;lat_acc&#39;, &#39;time&#39;]</pre><pre>with open(&quot;./data/sample.csv&quot;, &#39;r&#39;, encoding=&#39;ISO-8859-1&#39;) as f:<br>        lines = f.readlines()<br>        updated_lines=&quot;&quot;<br>        for index , line in enumerate(lines):<br>            # if index == 2:<br>            #     break<br>            each_line = line.split(&#39;;&#39;)<br>            if index != 0:<br>                new_lines = [l.strip() for l in each_line]<br>                other_data = new_lines[4:]<br>                i=0<br>                while i &lt; len(other_data):<br>                    vals = other_data[i:i+6]<br>                    i+=84<br>                    # if i &lt; 1000:<br>                    if len(vals) != 0:<br>                        x = [new_lines[0], new_lines[1]]<br>                        for v in vals:<br>                            x.append(v)<br>                        if len(x)==8:<br>                            updated_lines += &quot;;&quot;.join(x) +&quot;\n&quot;<br>                    else:<br>                        break<br>            else:<br>                new_lines = [l.strip() for l in each_line]<br>                updated_lines += &quot;;&quot;.join(cols) + &quot;\n&quot;</pre><pre>with open(&#39;./data/time_series_transformed_dataset.csv&#39;, &quot;w&quot;) as f:<br>        f.writelines(updated_lines)</pre><pre>def load_data_to_db(path, table_name):<br>    print(&quot;WRITING DATA&quot;)<br>    engine = create_engine(&quot;######&quot;)<br>    df = pd.read_csv(path, sep=&quot;;&quot;, index_col=False)</pre><pre>df.to_sql(table_name, con=engine, if_exists=&#39;replace&#39;,index_label=&#39;id&#39;)<br>    print(&quot;DATA SAVED&quot;)</pre><pre>with DAG(<br>    dag_id=&#39;save_time_series_to_db&#39;,<br>    default_args=default_args,<br>    description=&#39;this dag sample time series data to db&#39;,<br>    start_date=airflow.utils.dates.days_ago(1),<br>    schedule_interval=&#39;<a href="http://twitter.com/once">@once</a>&#39;<br>)as dag:<br>    task1 = PythonOperator(<br>        task_id=&#39;transform_time_series&#39;,<br>        python_callable=transform_data<br>    )<br>    task2 = PythonOperator(<br>        task_id=&#39;save_time_series&#39;,<br>        python_callable=transform_data,<br>        op_kwargs={<br>            &quot;path&quot;: &quot;./data/time_series_transformed_dataset.csv&quot;,<br>            &quot;table_name&quot;:&quot;sample_time_series&quot;<br>        }<br>    )<br>    task1 &gt;&gt; task2</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Hpc3fNw-2gnDz3itJJuz8A.png" /></figure><h4>dbt(Data Build Tool)</h4><pre>#<a href="https://github.com/natyrix/traffic-data-warehouse/blob/main/traffic_dbt/models/traffic_model/schema.yml">schema.yml</a><br>version: 2</pre><pre>models:<br>  - name: transformed_data_final<br>    description: &quot;traffic data&quot;<br>    columns:<br>      - name: id<br>        description: &quot;unique id&quot;<br>      - name: track_id<br>        description: &quot;track id&quot;<br>      - name: type<br>        description: &quot;type&quot;<br>      - name: traveled_d<br>        description: &quot;traveled_d&quot;<br>      - name: avg_speed<br>        description: &quot;avg_speed&quot;<br>      - name: lat<br>        description: &quot;lat&quot;<br>      - name: lon<br>        description: &quot;lon&quot;<br>      - name: speed<br>        description: &quot;speed&quot;<br>      - name: lon_acc<br>        description: &quot;lon_acc&quot;<br>      - name: lat_acc<br>        description: &quot;lat_acc&quot;<br>      - name: time<br>        description: &quot;time&quot;</pre><p>Selecting avg distance, and average speed based on type.</p><pre>#<a href="https://github.com/natyrix/traffic-data-warehouse/blob/main/traffic_dbt/models/traffic_model/avg_distance_by_type.sql">avg_distance_by_type.sql</a><br>select &quot;type&quot; , AVG(&quot;traveled_d&quot;) as dist_avg<br>from {{ ref(&#39;traffic_model&#39;) }}<br>Group by &quot;type&quot;</pre><pre>#<a href="https://github.com/natyrix/traffic-data-warehouse/blob/main/traffic_dbt/models/traffic_model/avg_speed_by_type.sql">avg_speed_by_type.sql</a><br>select &quot;type&quot; , AVG(&quot;avg_speed&quot;) as speed_avg<br>from {{ ref(&#39;traffic_model&#39;) }}<br>Group by &quot;type&quot;</pre><pre>#<a href="https://github.com/natyrix/traffic-data-warehouse/blob/main/traffic_dbt/models/traffic_model/type.sql">type.sql</a><br>select &quot;type&quot; , COUNT(id) as type_valfrom {{ ref(&#39;traffic_model&#39;) }}Group by &quot;type&quot;</pre><pre>#<a href="https://github.com/natyrix/traffic-data-warehouse/blob/main/traffic_dbt/models/traffic_model/traffic_model.sql">traffic_model.sql</a><br>{{ config(materialized=&#39;view&#39;) }} <br>with traffic_model as (select * from transformed_data_final ) <br>select *from traffic_model</pre><pre>#<a href="https://github.com/natyrix/traffic-data-warehouse/blob/main/traffic_dbt/models/traffic_model/speed_and_distance.sql">speed_and_distance.sql</a><br>select d_avg.dist_avg, s_avg.speed_avg, t_val.type_valfrom {{ ref(&#39;avg_distance_by_type&#39;) }} as d_avg, {{ ref(&#39;avg_speed_by_type&#39;) }} as s_avg, {{ ref(&#39;type&#39;) }} as t_val</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y0MIv75bkKvhJHk5tQjdQg.png" /></figure><h4>Visualization using Redash</h4><p><strong>Main Dashboard</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sNDLHCNMVv29gpPLW5doQA.png" /><figcaption>Main Dashboard</figcaption></figure><p><strong>Vehicle types</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/682/1*FuttwfYGfSw3aOsAqQOfGw.png" /><figcaption>Vehicle types</figcaption></figure><p><strong>Location changes through time</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/1*BUoILLVOcHplrO7tKB_Wpw.png" /><figcaption>Location changes through time</figcaption></figure><p><strong>Speed changes through time</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/682/1*r0AU_ZSX56JSLPehs09kLA.png" /><figcaption>Speed changes through time</figcaption></figure><p><strong>Speed comparison through time</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/682/1*27wgbDt7thLqpjIAO7H32A.png" /><figcaption>Speed comparison through time</figcaption></figure><h3>Conclusion</h3><ul><li>I have learned a lot while doing this project, it was an extensive area of the subject, but it was a great learning experience.</li><li>The above tools can make data management seamless and effective.</li></ul><h3>Limitations and Future Plans</h3><ul><li>The downloaded data was large and which results in loading time being quite long, and also CPU intensive.</li><li>Hosting the redash dashboard online.</li><li>Adding more transformation on the DBT to grasp a few more pieces of information.</li></ul><h3>References</h3><ol><li><a href="https://redash.io/help/open-source/setup"><strong>https://redash.io/help/open-source/setup</strong></a></li><li><a href="https://www.astronomer.io/guides/airflow-dbt/"><strong>https://www.astronomer.io/guides/airflow-dbt/</strong></a></li><li><a href="https://docs.getdbt.com/reference/commands/cmd-docs"><strong>https://docs.getdbt.com/reference/commands/cmd-docs</strong></a></li><li><a href="https://towardsdatascience.com/how-to-build-a-data-extraction-pipeline-with-apache-airflow-fa83cb8dbcdf"><strong>https://towardsdatascience.com/how-to-build-a-data-extraction-pipeline-with-apache-airflow-fa83cb8dbcdf</strong></a></li><li><a href="https://redash.io/help/open-source/admin-guide/env-vars-settings"><strong>https://redash.io/help/open-source/admin-guide/env-vars-settings</strong></a></li><li><a href="https://fitdevops.in/how-to-setup-redash-dashboard-on-ubuntu/"><strong>https://fitdevops.in/how-to-setup-redash-dashboard-on-ubuntu/</strong></a></li><li><a href="https://medium.com/@Cartelis/setting-up-an-open-source-modern-data-stack-6dd41094cd2f"><strong>https://medium.com/@Cartelis/setting-up-an-open-source-modern-data-stack-6dd41094cd2f</strong></a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c67056816f29" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Prompt Engineering]]></title>
            <link>https://medium.com/@natnaelmelese/prompt-engineering-3654c322f9a3?source=rss-d8b62df65657------2</link>
            <guid isPermaLink="false">https://medium.com/p/3654c322f9a3</guid>
            <category><![CDATA[prompt-engineering]]></category>
            <category><![CDATA[mlops]]></category>
            <dc:creator><![CDATA[Natnael Melese]]></dc:creator>
            <pubDate>Sat, 17 Sep 2022 19:35:03 GMT</pubDate>
            <atom:updated>2022-09-18T00:54:28.543Z</atom:updated>
            <content:encoded><![CDATA[<p><strong><em>In-context learning with GPT-3 and other Large Language Models</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/811/1*vZW5ExkkPDvMbin7LmVSLA.png" /></figure><p><a href="https://github.com/natyrix/Prompt-Engineering">GitHub - natyrix/Prompt-Engineering: Prompt Engineering: In-context learning with GPT-3 and other Large Language Models</a></p><h3>What is Prompt Engineering</h3><p>Prompt engineering is a natural language processing (NLP) concept that involves discovering inputs that yield desirable or useful results. Prompting is the equivalent of telling the Genius in the magic lamp what to do.</p><p>Prompting was not a developed feature by AI experts. It was an emergent feature. In short, by developing these huge machine learning models, prompting became the way to have the machine execute the inputs.</p><p>This article contains the following.</p><ol><li>Word Embedding, Fine-tuning, and In-context Learning.</li><li>Few-shot, One-shot, and Zero-shot Learning.</li><li>Prompt Design Principles.</li><li>How to apply the above concepts to our dataset(Job Description dataset).</li></ol><h4>Overview and Objective</h4><p>Large Language Models combined with several AI capabilities can produce images and text and perform on par with or better than humans in various activities. This method is contributing to the global revolution that is taking place in critical fields such as science, medicine, and art (DALL-E, MidJourney, Imagine, etc.).</p><p>The team behind the GPT-3 LLM popularized in-context learning, which sparked a new revolution in the application of LLMs to a variety of activities for which they were not initially trained. This contrasts with the customary fine-tuning necessary to provide AI models with the tools they needed to perform better in activities they were not prepared for.</p><p>Systematically explore strategies that help generate prompts for LLMs to extract relevant entities from job descriptions and also to classify web pages given only a few examples of human scores. You will be also required to compare responses and accuracies of multiple LLM models for given prompts.</p><h4>About the data</h4><p>This project contains two data sets</p><ol><li>News artifacts from web pages.</li><li>Job descriptions ( together named entities)</li></ol><h4>News artifacts from web pages.</h4><p>A client has a system that collects news artifacts from web pages, tweets, Facebook posts, etc. The client is interested in scoring a given new artifact against a topic. The client has hired experts to score a few of these news items in the range from 0 to 10; a score of 0 means the news item is totally NOT relevant while a score of 10 means the news item is very relevant. The range of results between 0 and 10 signifies the degree of relevance of the news item to the topic.</p><p>The client wants to explore how useful existing LLMs such as GPT-3 are for this task. You are hired as a consultant to explore the efficiency of GPT3-like LLMs for this task. If your recommendation is positive, you must demonstrate that your strategies to design prompts are reproducible and produce a consistent result.</p><h4>Job descriptions ( together named entities)</h4><p>The data are job descriptions ( together named entities) and relationships between entities in JSON format.</p><p><a href="https://towardsdatascience.com/how-to-train-a-joint-entities-and-relation-extraction-classifier-using-bert-transformer-with-spacy-49eb08d91b5c">How to Train a Joint Entities and Relation Extraction Classifier using BERT Transformer with spaCy…</a></p><p><strong>Training Data</strong></p><p><a href="https://github.com/walidamamou/relation_extraction_transformer/blob/main/relations_training.txt">relation_extraction_transformer/relations_training.txt at main · walidamamou/relation_extraction_transformer</a></p><p><strong>Test Data</strong></p><p><a href="https://github.com/walidamamou/relation_extraction_transformer/blob/main/relations_test.txt">relation_extraction_transformer/relations_test.txt at main · walidamamou/relation_extraction_transformer</a></p><p>Given a job description text, return the list of entities (and their relationship if possible) extracted from the job description by the LLM model.</p><h3>Methodologies/Tools</h3><p><strong>MLFlow</strong>: is an open-source platform for <strong>managing the end-to-end machine learning lifecycle</strong>. It has the following primary components: Tracking: Allows you to track experiments to record and compare parameters and results.</p><ul><li>It is easy to set up a model tracking mechanism in MLflow.</li><li>It offers very intuitive APIs for serving.</li><li>It provides data collection, data preparation, model training, and taking the model to production.</li></ul><p><strong>Data Version Control(DVC)</strong>: Open-source Version Control System for Machine Learning Projects. It is an open-source Version Control System for data science and machine learning projects.</p><ul><li>Along with data versioning, DVC also allows model and pipeline tracking.</li><li>With DVC, you don’t need to rebuild previous models or data modeling techniques to achieve the same past state of results.</li><li>Along with data versioning, DVC also allows model and pipeline tracking.</li></ul><p><strong>Cohere: is </strong>A platform enabling developers to generate or analyze text to do things like write copy, moderate content, classify data, and extract information, all at a massive scale.</p><ul><li>Use the Cohere platform to build natural language understanding and generation into your product with a few lines of code.</li><li>Cohere’s large language models can solve a broad spectrum of natural language use cases, including classification, semantic search, paraphrasing, summarization, and content generation.</li><li>Through finetuning, users can create massive models customized to their use case and trained on their data.</li></ul><h3>Word Embedding, Fine-tuning, and In-context Learning.</h3><h4>Word Embedding</h4><p>A word embedding is a learned representation for text where words that have the same meaning have a similar representation.</p><p>It is this approach to representing words and documents that may be considered one of the key breakthroughs of deep learning on challenging natural language processing problems.</p><p>Word embeddings are in fact a class of techniques where individual words are represented as real-valued vectors in a predefined vector space. Each word is mapped to one vector and the vector values are learned in a way that resembles a neural network, and hence the technique is often lumped into the field of deep learning.</p><p>The techniques include:</p><ul><li>Embedding Layer</li><li>Word2Vec</li><li>GloVe</li></ul><h4>Fine-tuning</h4><ul><li>Is the process in which parameters of a model must be adjusted very precisely in order to fit with certain observations.</li><li>During the fine-tuning process, we add a task-specific layer to the PLMs(Pre Trained Language Models) and carry out the usual backpropagation method using a suitable loss function.</li><li>Although task-specific fine-tuning is a relatively cheap task (few dollars) for models like BERT with a few hundred million parameters, it becomes quite expensive for large GPT-like models which have several billion parameters.</li></ul><h4>In-context Learning</h4><ul><li>In-context learning allows users to quickly build models for a new use case without worrying about fine-tuning and storing new parameters for each task. It typically requires very few training examples to get a prototype working, and the natural language interface is intuitive even for non-experts.</li><li>Was popularized in the original GPT-3 paper as a way to use language models to learn tasks given only a few examples.</li><li>During in-context learning, we give the LM a prompt that consists of a list of input-output pairs that demonstrate a task.</li><li>At the end of the prompt, we append a test input and allow the LM to make a prediction just by conditioning the prompt and predicting the next tokens.</li><li>Is unlike conventional machine learning in that there’s no optimization of any parameters.</li></ul><h3>Few-shot, One-shot, and Zero-shot Learning.</h3><h4>Few-shot learning</h4><ul><li>Few-shot learning (FSL), also referred to as low-shot learning (LSL) in a few sources, is a type of machine learning method where the training dataset contains limited information.</li><li>Important because it helps companies reduce cost, time, computation, data management, and analysis.</li><li>Few-shot learning is a test base where computers are expected to learn from few examples like humans.</li><li>By using few-shot learning, machines can learn rare cases. For example, when classifying images of animals, a machine learning model trained with few-shot learning techniques can classify an image of a rare species correctly after being exposed to a small amount of prior information.</li></ul><h4>One-shot learning</h4><ul><li>One-shot learning performs classification tasks using past data.</li><li>One-shot learning is the task of learning information about object categories from a single training example. Found mostly in computer vision.</li><li>One-shot learning has been using the Siamese network approach.</li><li>Eventually, Siamese networks were compared to comparative loss functions, after which the triplet loss function was proven to be better and the FaceNet system began using them.</li><li>Contrastive loss and triplet loss functions are now used for high-quality face embeddings, which have become the foundation for modern facial recognition.</li></ul><h4>Zero-shot learning</h4><ul><li>Zero-shot learning involves little human intervention, and the models depend on previously trained concepts and additional existing data.</li><li>Zero-shot learning is the challenge of learning modeling without using data labeling.</li><li>Reduces the time and effort that data labeling takes.</li><li>Instead of giving training examples, zero-shot learning gives a high-level description of new categories so that the machine can relate them to existing categories that the machine has learned about.</li><li>Can be used in computer vision, natural language processing, and machine perception.</li></ul><h3>Prompt Design Principles</h3><p>The design of the prompt to produce a particular type of model, the output is typically referred to as prompt programming.</p><p>Humans approach all linguistic tasks with unconscious expectations and<br>assumptions not only about the content but also about form.</p><p>A number of strategies have been developed to design prompts so that they are more likely to produce the desired outcome. The most common strategies can be categorized as few-shot and zero-shot promoting strategies.</p><p>So what are the best ways to design an effective prompt?</p><ul><li>The best way to design an effective prompt is by trial and error.</li><li>Find the right combination of prompt templates and answers. Prompt-based learning is highly dependent on both the prompt templates (e.g., “It is”) and the given answers (e.g., “beautiful”). To this end, it remains challenging to search for an optimal combination of both template and answer and requires a lot of trial and error</li></ul><h4>Applying Prompt Engineering on Job Description Dataset</h4><p>We won’t cover data cleaning applied to the data set since it is out of the scope of this article, but feel free to check out the github repo.</p><p><strong>Applying few-shot learning</strong></p><pre>Output<br>{&#39;EXPERIENCE&#39;: &#39; 10+ years,5+ years&#39;,<br> &#39;SKILLS&#39;: &#39; software engineering,technical management,release engineering,tools engineering,DevOps&#39;,<br> &#39;DIPLOMA&#39;: &#39; BS/MS&#39;,<br> &#39;DIPLOMA_MAJOR&#39;: &#39; Computer Science&#39;}</pre><pre>Test Entities<br>{&#39;EXPERIENCE&#39;: &#39;10+ years,5+ years&#39;,<br> &#39;SKILLS&#39;: &#39;software engineering,technical management,release engineering,tools engineering,DevOps&#39;,<br> &#39;DIPLOMA&#39;: &#39;BS/MS&#39;,<br> &#39;DIPLOMA_MAJOR&#39;: &#39;Computer Science&#39;}</pre><p>Checking Similarity</p><pre><strong>from</strong> difflib <strong>import</strong> SequenceMatcher<br>prediction_similarity <strong>=</strong> {}<br><strong>for</strong> k,v <strong>in</strong> tokens<strong>.</strong>items():<br>    <strong>if</strong> k <strong>in</strong> response_dict<strong>.</strong>keys():<br>        prediction_similarity[k] <strong>=</strong> SequenceMatcher(<strong>None</strong>, v, response_dict[k])<strong>.</strong>ratio()<br>    <strong>else</strong>:<br>        prediction_similarity[k] <strong>=</strong> 0.0<br>prediction_similarity</pre><p>Plotting Similarity Plot</p><pre>plt.bar(range(len(result)), list(result.values()), plt.xticks(range(len(result)), <br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/372/1*r4z1c1t441t5Dd1lwkZDaw.png" /><figcaption>Similarity Plot</figcaption></figure><p><strong>Applying zero-shot learning on fine-tuned model</strong></p><pre>prompt <strong>=</strong> f&quot;Job Description: {test_data[2][&#39;document&#39;]<strong>.</strong>strip()} --&quot;<br>prompt<br>&#39;Job Description: BA/BS\n5+ years of program or project management experience\n2+ years of technical project/program management experience\nTrack record of operating independently\nExperience understanding user needs, gathering requirements, and defining scope\nCommunication experience interacting with a variety of audiences from engineers, to vendors, to research leaders\nTrack record of building cross-functional relationships\n\nPREFERRED \nExperience working with UX Research and/or UX Design --&#39;</pre><p>Send a request and print the response</p><pre>response <strong>=</strong> co<strong>.</strong>generate( <br>model<strong>=</strong>&#39;e1819ef5-937f-4a18-902d-680daee4e0fa-ft&#39;, <br>prompt<strong>=</strong>prompt,<br>max_tokens<strong>=</strong>400, <br>temperature<strong>=</strong>0.5, <br>k<strong>=</strong>0, <br>p<strong>=</strong>1, <br>frequency_penalty<strong>=</strong>0, <br>presence_penalty<strong>=</strong>0, <br>stop_sequences<strong>=</strong>[&quot;--&quot;], <br>return_likelihoods<strong>=</strong>&#39;NONE&#39;) <br>print(&#39;Prediction: {}&#39;<strong>.</strong>format(response<strong>.</strong>generations[0]<strong>.</strong>text))</pre><pre>Prediction:  especially in a consumer-facing product<br>Experience managing a team of UX Researchers and/or UX Designers<br>Experience managing a team of engineers<br>Experience managing a team of product managers<br>Experience working in a startup environment<br>Experience with Agile methodologies<br>Experience with user research tools and techniques<br><br>DIPLOMA <br>5+ years of program or project management experience<br>2+ years of technical project/program management experience<br>Track record of operating independently<br>Experience understanding user needs, gathering requirements, and defining scope<br>Communication experience interacting with a variety of audiences from engineers, to vendors, to research leaders<br>Track record of building cross-functional relationships<br><br>PREFERRED <br>Experience working with UX Research and/or UX Design --</pre><p><em>Due to a lack of sufficient sample data on both datasets, we weren’t able to make experiments as much as we wished, but feel free to fork the repository and experiment.</em></p><h4>Conclusion</h4><ul><li>Fine-tuned models perform better in a zero-shot entity extraction.</li><li>If we design a dynamic efficient prompt then cohere’s LLM will effectively generate the entities we are looking for.</li></ul><h4>Limitations and Future Plans</h4><ul><li>Often API requests to cohere end up in a timeout, especially while using tools like postman to hit our endpoints, this issue arises since the API call to cohere is initiated from our end and while our endpoint function is waiting for cohere’s response postman will throw a timeout exception and abort the request.</li><li>The sample size was too small, for both data sets.</li><li>In the future after collecting enough amount of data implementing news artifact scoring will be successful, for now since we have only 10 rows of data, and most of the scores are 0, means even if we trained our model on that data, almost all of its predictions will be 0.0.</li></ul><h4>References</h4><ol><li><a href="https://os.cohere.ai/">https://os.cohere.ai/</a></li><li><a href="https://docs.cohere.ai/api-reference/">https://docs.cohere.ai/api-reference/</a></li><li><a href="https://docs.cohere.ai/finetuning-wiki/">https://docs.cohere.ai/finetuning-wiki/</a></li><li><a href="https://arxiv.org/pdf/1909.08593.pdf%5D">https://arxiv.org/pdf/1909.08593.pdf%5D</a></li><li><a href="https://www.analyticsvidhya.com/blog/2020/06/nlp-project-information-extraction/">https://www.analyticsvidhya.com/blog/2020/06/nlp-project-information-extraction/</a></li><li><a href="https://towardsdatascience.com/how-i-used-natural-language-processing-to-extract-context-from-news-headlines-df2cf5181ca6">https://towardsdatascience.com/how-i-used-natural-language-processing-to-extract-context-from-news-headlines-df2cf5181ca6</a></li><li><a href="https://fourweekmba.com/prompt-engineering/">https://fourweekmba.com/prompt-engineering/</a></li><li><a href="https://www.xcubelabs.com/blog/faqs-few-shot-learning-everything-you-need-to-know/">https://www.xcubelabs.com/blog/faqs-few-shot-learning-everything-you-need-to-know/</a></li><li><a href="https://machinelearningmastery.com/what-are-word-embeddings/">https://machinelearningmastery.com/what-are-word-embeddings/</a></li><li><a href="https://analyticsindiamag.com/how-to-train-your-llm-efficiently/">https://analyticsindiamag.com/how-to-train-your-llm-efficiently/</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3654c322f9a3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pharmaceutical Sales Prediction]]></title>
            <link>https://medium.com/@natnaelmelese/pharmaceutical-sales-prediction-1285502cd66?source=rss-d8b62df65657------2</link>
            <guid isPermaLink="false">https://medium.com/p/1285502cd66</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[sales-prediction]]></category>
            <dc:creator><![CDATA[Natnael Melese]]></dc:creator>
            <pubDate>Sat, 10 Sep 2022 18:31:49 GMT</pubDate>
            <atom:updated>2022-09-14T18:51:28.610Z</atom:updated>
            <content:encoded><![CDATA[<p>Predicting sales using deep learning</p><ul><li><a href="https://github.com/natyrix/Pharmaceutical-Sales-Prediction-across-multiple-stores">GitHub - natyrix/Pharmaceutical-Sales-Prediction-across-multiple-stores: Time-series forecasting of sales using machine learning</a></li><li><a href="https://www.kaggle.com/competitions/rossmann-store-sales/data">Rossmann Store Sales</a></li></ul><p>This project is based on Rossmann Pharmaceuticals data analysis posted on Kaggle and also included in 10Academy challenge week3. It is a machine learning project that includes data preprocessing, exploration, regressions, and deep learning concepts. If you are interested continue reading</p><h4><strong>Why Sales Prediction?</strong></h4><p>In today’s competitive world where sales are highly important for companies, accurate sales forecasting plays a key role in every successful retail business. It can be helpful in inventory management by avoiding overproduction and reducing overstock.</p><p>In addition, it can be a great tool for increasing the profitability of a company by cost prediction.</p><h4><strong>Overview and Objective</strong></h4><p>Rossmann Pharmaceutical’s finance team wants to forecast sales in all their stores across several cities six weeks ahead of time. Managers in individual stores rely on their years of experience as well as their personal judgment to forecast sales.</p><p>The data team identified factors such as promotions, competition, school and state holidays, seasonality, and locality as necessary for predicting sales across the various stores. The task is to build and serve an end-to-end product that delivers this prediction to analysts in the finance team.</p><h4><strong>About the data</strong></h4><p>The following are descriptions for those that aren’t self-explanatory.</p><ul><li><strong>Id</strong> — an Id that represents a (Store, Date) duple within the test set.</li><li><strong>Store</strong> — a unique Id for each store</li><li><strong>Sales</strong> — the turnover for any given day (this is what you are predicting)</li><li><strong>Customers</strong> — the number of customers on a given day</li><li><strong>Open</strong> — an indicator for whether the store was open: 0 = closed, 1 = open</li><li><strong>StateHoliday</strong> — indicates a state holiday. Normally all stores, with few exceptions, are closed on state holidays. Note that all schools are closed on public holidays and weekends. a = public holiday, b = Easter holiday, c = Christmas, 0 = None</li><li><strong>SchoolHoliday</strong> — indicates if the (Store, Date) was affected by the closure of public schools</li><li><strong>StoreType</strong> — differentiates between 4 different store models: a, b, c, d</li><li><strong>Assortment</strong> — describes an assortment level: a = basic, b = extra, c = extended. Read more about assortment <a href="https://en.wikipedia.org/wiki/Retail_assortment_strategies">here</a></li><li><strong>CompetitionDistance</strong> — the distance in meters to the nearest competitor store</li><li><strong>CompetitionOpenSince[Month/Year]</strong> — gives the approximate year and month of the time the nearest competitor was opened</li><li><strong>Promo</strong> — indicates whether a store is running a promo on that day</li><li><strong>Promo2</strong> — Promo2 is a continuing and consecutive promotion for some stores: 0 = store is not participating, 1 = store is participating</li><li><strong>Promo2Since[Year/Week] </strong>— describes the year and calendar week when the store started participating in Promo2</li><li><strong>PromoInterval</strong> — describes the consecutive intervals Promo2 is started, naming the months the promotion is started anew. E.g. “Feb, May, Aug, Nov” means each round starts in February, May, August, or November of any given year for that store</li></ul><h4>Methodologies/Tools</h4><p><strong>MLFlow</strong>: is an open-source platform for <strong>managing the end-to-end machine learning lifecycle</strong>. It has the following primary components: Tracking: Allows you to track experiments to record and compare parameters and results.</p><ul><li>It is easy to set up a model tracking mechanism in MLflow.</li><li>It offers very intuitive APIs for serving.</li><li>It provides data collection, data preparation, model training, and taking the model to production.</li></ul><p><strong>Data Version Control(DVC)</strong>: Open-source Version Control System for Machine Learning Projects. It is an open-source Version Control System for data science and machine learning projects.</p><ul><li>Along with data versioning, DVC also allows model and pipeline tracking.</li><li>With DVC, you don’t need to rebuild previous models or data modeling techniques to achieve the same past state of results.</li><li>Along with data versioning, DVC also allows model and pipeline tracking.</li></ul><p><strong>Continuous Machine Learning(CML):</strong> is CI/CD for Machine Learning Projects · GitFlow for data science · Auto reports for ML experiments.</p><h3>Explanatory Data Analysis</h3><h4>Comparison of sales during StateHolidays and ordinary days</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*POlGNNfnJnznEEa8qXTSkw.png" /><figcaption>Comparison of sales during StateHolidays and ordinary days</figcaption></figure><h4>Sales and Customers across different store types</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*BbWnX-CheLCQXNbnavPUzA.png" /><figcaption>Sales and Customers across different StoreTypes</figcaption></figure><h4>Distribution of promotion in the training and test datasets</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/743/1*A2OqCwEN6QS0EKWCGtOTkQ.png" /><figcaption>Distribution of promotion in the training and test datasets</figcaption></figure><h4>Christmas Sales 2013/2014</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/817/1*XdSdP49ThajjWMNX_kzUUg.png" /><figcaption>Christmas Sales 2013/2014</figcaption></figure><h4>Sales and Customers across different assortment types</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/897/1*pHfBe_TSP_Qk09GUG-hJMw.png" /><figcaption>Sales and Customers across different assortment types</figcaption></figure><h4>Sales and Customers across different days of the week</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/897/1*M2dvvGLTds9bOCH9c365NQ.png" /><figcaption>Sales and Customers across different days of the week</figcaption></figure><h4>Top 10 features with the highest correlation with sales</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/664/1*tdXFpqCoXw4TdVOmJNPmSg.png" /><figcaption>Top 10 features with the highest correlation with sales</figcaption></figure><h4>Explanatory Data Analysis Summary</h4><p>This summary includes some of our findings in the EDA(Explanatory Data Analysis) stage.</p><ul><li>The most selling and crowded store type is b.</li><li>The most selling and crowded assortment is b.</li><li>Sales are highly correlated to customers.</li><li>For all stores, promotion leads to an increase in Sales and Customers. But promotions have a low impact on store type b and assortment b when compared to the other store types and assortments. So promotions should be applied more in the other store types and assortments.</li><li>Store type b is the most opened store type on all weekdays and has its<br>highest sales on Sundays than the other days.</li></ul><h3>Sales Prediction Using Random Forest Regression</h3><p>Random forest, as its name implies, consists of a large number of individual decision trees that operate as an ensemble. Each individual tree in the random forest spits out a class prediction and the class with the most votes becomes our model’s prediction.</p><h4>True Lable vs Predicted Label</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/1*_Ca7JTGkQp_NJkBj6i6ENw.png" /><figcaption>True Lable vs Predicted Label</figcaption></figure><h4>Feature Importance</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*rLWbPABEuoRVsWaKILaIag.png" /><figcaption>Feature Importance</figcaption></figure><pre>{&#39;Accuracy&#39;: 83.99 %., &#39;RMSE Score&#39;: 1508.46, &#39;R2_Squared&#39;: 0.85, &#39;MAE Score&#39;: 857.57}</pre><h3>Sales Prediction with Deep Learning</h3><p>Good sales forecasts play a crucial role in assisting enterprises to improve. With the development of Artificial Intelligence, increasing methods have been adopted to solve the forecasting problem.</p><p>For this project, we will use LSTM(Long Short Term Memory) algorithm. It is a variety of recurrent neural networks (RNNs) that are capable of learning long-term dependencies, especially in sequence prediction problems.</p><h4>Important steps to follow while predicting sales using LSTM</h4><ol><li>Preprocessing data, including Cleaning, Scaling, and Normalizing.</li><li>Visualizing data.</li><li>Separating dataset into training and validation.</li><li>Setting format to use feed into LSTM.</li><li>Defining and Estimating training loss and validation loss.</li><li>Forecasting on the validation set and access accuracy.</li></ol><h3>Visualizations</h3><h4><strong>Time Series Plots with and without Scaled data</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VflWY--k0JxC6dVn20kZSg.png" /><figcaption>Time Series Plots with and without Scaled data</figcaption></figure><h4>Sales Data with and without Scaled Data</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_xAdT69EVZOhh44l4dExJg.png" /><figcaption>Sales Data with and without Scaled Data</figcaption></figure><h3>Autocorrelation and Partial Autocorrelation</h3><p>Autocorrelation and partial autocorrelation are measures of association between current and past series values and indicate which past series values are most useful in predicting future values. With this knowledge, you can determine the order of processes in an ARIMA(autoregressive integrated moving average) model. More specifically,</p><ul><li><strong>Autocorrelation function (ACF):</strong> At lag <em>k</em>, this is the correlation between series values that are <em>k</em> intervals apart.</li><li><strong>Partial autocorrelation function (PACF):</strong> At lag <em>k</em>, this is the correlation between series values that are <em>k</em> intervals apart, accounting for the values of the intervals between.</li></ul><h4>Autocorrelation Plot</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cm_vD7B8oCX405G6G27PNg.png" /><figcaption>Autocorrelation Plot</figcaption></figure><h4>Partial Autocorrelations Plot</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BmDG9kCRAMu35mIEOjSYTw.png" /><figcaption>Partial Autocorrelations Plot</figcaption></figure><h4>Defining and Estimating training loss and validation loss.</h4><ul><li><strong>Training Loss: </strong>The training loss indicates how well the model is fitting the training data.</li><li><strong>Validation Loss:</strong> The validation loss indicates how well the model fits new data.</li></ul><pre>model <strong>=</strong> Sequential()<br>model<strong>.</strong>add(LSTM(8, input_shape<strong>=</strong>[<strong>None</strong>, 1], return_sequences<strong>=True</strong>))<br>model<strong>.</strong>add(LSTM(4, input_shape<strong>=</strong>[<strong>None</strong>, 1]))<br>model<strong>.</strong>add(Dense(1))<br>model<strong>.</strong>compile(loss<strong>=</strong>&quot;mse&quot;, optimizer<strong>=</strong>&#39;adam&#39;)<br>history <strong>=</strong> model<strong>.</strong>fit(DatasetTrain, epochs<strong>=</strong>EPOCHS,<br>                    validation_data<strong>=</strong>DatasetVal, verbose<strong>=</strong>0)<br>fig <strong>=</strong> plt<strong>.</strong>figure()<br>plt<strong>.</strong>plot(history<strong>.</strong>history[&#39;loss&#39;], label<strong>=</strong>&quot;loss&quot;)<br>plt<strong>.</strong>plot(history<strong>.</strong>history[&#39;val_loss&#39;], label<strong>=</strong>&quot;val_loss&quot;)<br>plt<strong>.</strong>legend()<br>plt<strong>.</strong>show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/378/1*pPrb6sPDws6e1HW7h0Yr5Q.png" /><figcaption>Training Loss and Validation Loss</figcaption></figure><h4><strong>Initialize LSTM Model</strong></h4><pre>m <strong>=</strong> Sequential()<br>m<strong>.</strong>add(LSTM(units<strong>=</strong>50, return_sequences<strong>=True</strong>, input_shape<strong>=</strong>(xin<strong>.</strong>shape[1], 1)))<br>m<strong>.</strong>add(Dropout(0.2))<br>m<strong>.</strong>add(LSTM(units<strong>=</strong>50))<br>m<strong>.</strong>add(Dropout(0.2))<br>m<strong>.</strong>add(Dense(units<strong>=</strong>1))<br>m<strong>.</strong>compile(optimizer<strong>=</strong>&#39;adam&#39;, loss<strong>=</strong>&#39;mean_squared_error&#39;, metrics<strong>=</strong>[&#39;mse&#39;, &#39;mae&#39;])</pre><h4>Fit LSTM Model</h4><pre>history <strong>=</strong> m<strong>.</strong>fit(xin, next_X, epochs<strong>=</strong>700, batch_size<strong>=</strong>50, verbose<strong>=</strong>0)</pre><h4>Plotting Training Loss</h4><pre>plt<strong>.</strong>figure(figsize<strong>=</strong>(20, 10))<br>plt<strong>.</strong>grid()<br>plt<strong>.</strong>title(&#39;LSTM MODEL TRAINING LOSS - EPOCH DIAGRAM&#39;)<br>plt<strong>.</strong>ylabel(&#39;Loss&#39;)<br>plt<strong>.</strong>xlabel(&#39;Epoch&#39;)<br>plt<strong>.</strong>semilogy(history<strong>.</strong>history[&#39;loss&#39;])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tRIIBew1NPZDbjseVqtW5Q.png" /><figcaption>LSTM MODEL TRAINING LOSS</figcaption></figure><h4>Predicting 1 step ahead</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jX3LIksSwgH4mbTBNIBvtg.png" /><figcaption>Predicting 1 step ahead</figcaption></figure><h4>Predicting the next step using predicted values</h4><pre>X_pred <strong>=</strong> Xtest<strong>.</strong>copy()<br><strong>for</strong> i <strong>in</strong> range(window, len(X_pred)):<br>    xin <strong>=</strong> X_pred[i<strong>-</strong>window:i]<strong>.</strong>to_numpy()<strong>.</strong>reshape((1, window, 1))<br>    X_pred[i] <strong>=</strong> m<strong>.</strong>predict(xin)</pre><h4>Plot prediction vs actual for test data</h4><pre>plt<strong>.</strong>figure(figsize<strong>=</strong>(40,10))<br>plt<strong>.</strong>title(&#39;LSTM MODEL PREDICTION VS ACTUAL TEST DATA&#39;)<br>plt<strong>.</strong>xticks(rotation<strong>=</strong>90)<br>plt<strong>.</strong>grid()<br>plt<strong>.</strong>plot(X_pred[window:], &#39;:&#39;, label<strong>=</strong>&#39;LSTM&#39;)<br>plt<strong>.</strong>plot(next_X1, &#39;--&#39;, label<strong>=</strong>&#39;Actual&#39;)<br>plt<strong>.</strong>legend()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NsnVqp-hTRVkNI7fq3G8SA.png" /><figcaption>prediction vs actual for test data</figcaption></figure><h4>Mean Absolute Error</h4><p>Refers to the magnitude of difference between the prediction of observation and the true value of that observation.</p><pre>plt<strong>.</strong>figure(figsize<strong>=</strong>(15, 10))<br>plt<strong>.</strong>grid()<br>plt<strong>.</strong>title(&#39;MEAN ABSOLUTE ERROR OF LSTM&#39;)<br>plt<strong>.</strong>ylabel(&#39;Mean Absolute Error&#39;)<br>plt<strong>.</strong>xlabel(&#39;Epoch&#39;)<br>plt<strong>.</strong>semilogy(history<strong>.</strong>history[&#39;mae&#39;])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/913/1*wBACBaCUTbNbj6QiRl9Y7A.png" /><figcaption>Mean Absolute Error</figcaption></figure><h3>Conclusion</h3><ul><li><strong>Mean Absolute Error(MAE):</strong> The value of the mean absolute error(MAE) for our model is <strong>0.05563876032829285</strong>. It is a good result since MAE shows the magnitude of difference between the prediction of observation and the true value.</li><li><strong>Mean Squared Error(MSE): </strong>The value of the mean squared error(MSE) for our model is <strong>0.05563876032829285. </strong>It is a good result since MSE is defined as the Mean or Average of the square of the difference between actual and estimated values.</li></ul><p>Based on the above results we can conclude that our model performed efficiently.</p><p>Limitations and Future Plans</p><ul><li>The lack of sufficient infrastructure to train the models was one of the biggest limitations I faced while working on this project.</li><li>In the future, I am planing to apply pruning to the models in order to increase efficiency and effectiveness.</li></ul><h3>References</h3><ol><li><a href="https://ieeexplore.ieee.org/document/9389930">https://ieeexplore.ieee.org/document/9389930</a></li><li><a href="https://machinelearningmastery.com/how-to-develop-deep-learning-models-for-univariate-time-series-forecasting/">https://machinelearningmastery.com/how-to-develop-deep-learning-models-for-univariate-time-series-forecasting/</a></li><li><a href="https://machinelearningmastery.com/gentle-introduction-autocorrelation-partial-autocorrelation/">https://machinelearningmastery.com/gentle-introduction-autocorrelation-partial-autocorrelation/</a></li><li><a href="https://www.kaggle.com/c/rossmann-store-sales/notebooks">https://www.kaggle.com/c/rossmann-store-sales/notebooks</a></li><li><a href="https://medium.com/@D33B/the-unreasonable-effectiveness-of-random-forests-f33c3ce28883">https://medium.com/@D33B/the-unreasonable-effectiveness-of-random-forests-f33c3ce28883</a></li><li><a href="https://www.kaggle.com/emehdad/time-series-linear-models-tslm">https://www.kaggle.com/emehdad/time-series-linear-models-tslm</a></li><li><a href="https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i-hello-world">https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i-hello-world</a></li><li><a href="https://heartbeat.fritz.ai/5-regression-loss-functions-all-machine-learners-should-know-4fb140e9d4b0">https://heartbeat.fritz.ai/5-regression-loss-functions-all-machine-learners-should-know-4fb140e9d4b0</a></li><li><a href="https://stackoverflow.com/questions/53645882/pandas-merging-101">https://stackoverflow.com/questions/53645882/pandas-merging-101</a></li><li><a href="https://machinelearningmastery.com/time-series-forecasting-long-short-term-memory-network-python/">https://machinelearningmastery.com/time-series-forecasting-long-short-term-memory-network-python/</a></li><li><a href="https://opendatascience.com/what-is-pruning-in-machine-learning/">https://opendatascience.com/what-is-pruning-in-machine-learning/</a></li><li><a href="https://towardsdatascience.com/understanding-random-forest-58381e0602d2">https://towardsdatascience.com/understanding-random-forest-58381e0602d2</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1285502cd66" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>