<?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 ARSLANOV on Medium]]></title>
        <description><![CDATA[Stories by ARSLANOV on Medium]]></description>
        <link>https://medium.com/@arslan-bobir?source=rss-c8518b32c75e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Stories by ARSLANOV on Medium</title>
            <link>https://medium.com/@arslan-bobir?source=rss-c8518b32c75e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 08:36:22 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@arslan-bobir/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[Resolve Cannot drop server ‘SERVERNAME’ because it is used as a Publisher in replication.]]></title>
            <link>https://arslan-bobir.medium.com/resolve-cannot-drop-server-servername-because-it-is-used-as-a-publisher-in-replication-b62dc4982d01?source=rss-c8518b32c75e------2</link>
            <guid isPermaLink="false">https://medium.com/p/b62dc4982d01</guid>
            <dc:creator><![CDATA[ARSLANOV]]></dc:creator>
            <pubDate>Sun, 22 Feb 2026 06:09:31 GMT</pubDate>
            <atom:updated>2026-02-22T06:12:16.250Z</atom:updated>
            <content:encoded><![CDATA[<p>You are trying to delete linked server in SQL Server but failing with something like below error:</p><pre>Msg 20582, Level 16, State 1, Procedure sp_MSrepl_check_server, Line 31 [Batch Start Line 8]<br>Cannot drop server &#39;SERVERNAME&#39; because it is used as a Publisher in replication.</pre><p>The above error happens because this linked server was configured as publisher in distributor.</p><p>Steps to resolve:</p><ol><li>First try below:</li></ol><pre>EXEC sp_dropserver <br>     N&#39;SERVERNAME&#39;, <br>     @droplogins =  &#39;droplogins&#39;;</pre><p>2. If the above does not resolve, try below:</p><pre>SELECT * FROM msdb.dbo.MSdistpublishers<br>DELETE FROM msdb.dbo.MSdistpublishers where name = &#39;SERVERNAME&#39;<br><br>EXEC sp_dropserver <br>     N&#39;SERVERNAME&#39;, <br>     @droplogins =  &#39;droplogins&#39;;</pre><h4>Subscribe below to learn more about SQL Server:<br><a href="https://youtube.com/@arslanov1886?si=egLQZpCvUbk2LZGf"><strong>ARSLANOV YOUTUBE CHANNEL</strong></a></h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b62dc4982d01" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Resolving “Not clustered or the cluster service is up and online” in SQL Server patching]]></title>
            <link>https://arslan-bobir.medium.com/resolving-not-clustered-or-the-cluster-service-is-up-and-online-in-sql-server-patching-9d921f7848f9?source=rss-c8518b32c75e------2</link>
            <guid isPermaLink="false">https://medium.com/p/9d921f7848f9</guid>
            <category><![CDATA[sql-server]]></category>
            <category><![CDATA[wmi]]></category>
            <dc:creator><![CDATA[ARSLANOV]]></dc:creator>
            <pubDate>Thu, 16 Nov 2023 06:18:17 GMT</pubDate>
            <atom:updated>2023-11-16T06:18:17.590Z</atom:updated>
            <content:encoded><![CDATA[<p>I faced one issue with a customer I want to share.</p><p>Customer had SQL Server 2016. While installing the security patch, they faced below error and installation failed:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cEyHkG6VhLGu3oifwmeKwA.png" /></figure><p>After checking the Setup bootstrap Detail logs, I found the below logs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/962/1*zDt4DlDJV3jCS737OKNcDw.png" /></figure><p>The above logs are showing that the call to WMI class is being cancelled after 20 mins wait. We are not being able to access the class. This issue is related to WMI.</p><p>To resolve the issue, we started WBEMTEST and run WMI query “select * from win32_service”. However, the process has stuck at process called “Eaphost”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/558/1*jLpr7DKyGwly3gKQoqXh6Q.png" /></figure><p>To resolve the issue, we just stopped Eaphost process which belonged to Elastic Agent and the query succeeded afterwards:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/561/1*LJ3MZDu0iifsNVkvNs6ZhQ.png" /></figure><p>After retrying the installation, we successfully installed the patch.</p><p>That is all :)</p><p>To learn more about SQL Server: <a href="https://www.youtube.com/channel/UCrf9xG9beltktYoQ_fq1KLQ">ARSLANOV — YouTube</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9d921f7848f9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Indexing in SQL Server]]></title>
            <link>https://arslan-bobir.medium.com/indexing-in-sql-server-203ec4100247?source=rss-c8518b32c75e------2</link>
            <guid isPermaLink="false">https://medium.com/p/203ec4100247</guid>
            <category><![CDATA[sql-server]]></category>
            <category><![CDATA[non-clustered-index]]></category>
            <category><![CDATA[clustered-index]]></category>
            <dc:creator><![CDATA[ARSLANOV]]></dc:creator>
            <pubDate>Sun, 04 Jun 2023 16:48:27 GMT</pubDate>
            <atom:updated>2023-06-04T16:48:27.987Z</atom:updated>
            <content:encoded><![CDATA[<p>YouTube: <a href="https://www.youtube.com/watch?v=aJNSy94tsxM&amp;ab_channel=SimpleSQLServer">Internals of indexing in SQL Server: All you need to know!!! — YouTube</a></p><p>Hello everyone. Welcome to my blog.<br>In this blog, I am going to talk about indexing in SQL Server. To be more specific, I will share what is index and why we need them with specific examples.<br>Afterwards, I will talk about index types in sql server including clustered and non-clustered index.<br>Finally, I will end this video by talking about covering and include indexes. <br>If you find this video useful, please do not forget to subscribe to follow my future blog series.<br>Let us get started.</p><p><strong>First of all, what is index?</strong><br>- An index is a “a feature that improves the performance of searches” and in this way the performance of the queries in SQL Server. That is it.<br>- We can say this is similar to the index of a book where page numbers are mapped to the key words. A book index helps you to quickly go to the page containing the word you are searching for.<br>If there is no index, you may have to rely on your memory, intuition or you may have to search the word by going through the each page in the book. This is very time consuming.<br>- The same applies to the tables and indexing in SQL Server. Indexes allow SQL Server to quickly search for data in a table.</p><p>Without indexes, SQL Server has to search through all the data, which can be very time-consuming process. Let us see how it happens by looking at internal behavior of SQL Server when there is no index.</p><p>Consider the following ‘Employees’ table as an example where there is no index.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/642/1*vRKX-OHjdiS-_3NtDUzrbg.png" /></figure><p>Let us run SELECT query to fine an employee with First name “James”.</p><pre>SELECT * FROM [Person].[Person] WHERE FirstName = ‘James’</pre><p>SQL Server does not know where this data is located. Therefore, SQL Server has to search for the data by going through each row in the table.</p><p>For example, let us illustrate this process.</p><p>SQL Server searches a data with first name until row 25. Found one value matching the query. Then the search will continue until row 42. Then, again with the same process until the end of the table. This process happens with every table without an index and it is very time consuming.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/663/1*kAyMbZAtB4hU678iR2FyBg.png" /></figure><p>Let us see what happens if we do have an index.</p><p>If we have an index for the FirstName column, SQL Server does not need to search for the whole table but directly find the records.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/705/1*OJs6C6yVjiJ4bR7EX7i4bw.png" /></figure><p>This is very efficient, right?</p><p><strong>Internal architecture of the databases</strong></p><p>Ok, we understood the importance of the indexing in SQL Server queries.<br>Now, let us deep dive and understand how indexes are built by looking at internal structures of the index.<br>But beforehand, to understand indexing, it is important to understand the internal structure of the database. Therefore, Let’s start by understanding the internal structure of the database before moving to indexes.<br>Each database in SQL Server contains at least one data file and transaction log file. Each datafile contains 8KB sized data pages.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/690/1*CRb8LRYwxHhBb8SEn-DLKQ.png" /></figure><p>SQL Server extracts data from disk at page level. Each page contains the actual data and the group of pages are located in heap. In other words, heap is a group of unclustered pages. <br>I want to also mention that a collection of 8 pages is called an extent. When data is added, one extent is allocated, subsequently added data is stored on eight consecutive pages. <br>This ensures that the data for the same object is stored on eight consecutive pages. Storing data of the same object helps to improve reading and searching performance.</p><p><strong>Internal structure of the index: non-clustered index</strong></p><p>Now, we understand the structure of database. Let us switch to the structure of indexes.<br>There are two types of indexes in SQL Server: clustered and non-clustered index. I will start with non-clustered index.<br>First, index structure is architecture is based on the tree structure. <br>First level is called root node and contains one root page.<br>After root node, here comes middle nodes. Middle node may consist of several levels based on the data. In our case it consists of only one level since we have a small data.<br>After middle node, lastly comes leaf node where index architecture ends.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/889/1*E0kwMA6Vq7d1luHKbsEtnQ.png" /></figure><p>As you can see, in each level data is sorted based on the first column which first name. The next column is lower page ids in root node and middle nodes. <br>In the leaf node however, it becomes ROW id: first number is file id, second one is heap page id and third one is row number in page.</p><p>Let us see how the flow of our query in this architecture.</p><p>We run this query.</p><pre>SELECT *<br>FROM [Person].[Person] <br>WHERE FirstName = ‘James&#39;</pre><p>First, the flow starts with root page and SQL Server defines JACK and Murphy rows there. SQL Server understands that James is between these rows. Therefore, it selects page number 33 and then it goes to page number 33.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/793/1*LE9N6QL7Kj5D3yX8qe3r2Q.png" /></figure><p>There, SQL Server finds Jack and Laren. It understands that James should be in 169 since next row is already starting with letter “L”. As a result, page number 169 is selected, and James&#39;s row is found there.</p><p>Here we find that James is located in File numbered 1, Page numbered 402 and in the first row of heap or heap table we can say. Then the result is returned.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/911/1*TxwUpuyF5NiLahINwArBhQ.png" /></figure><p>These all the operations we just saw is called non-clustered index seek with row id lookup in SQL Server.</p><p><strong>Cluster existence non-working cases</strong></p><p>Sometimes, even if you create non-clustered index, you might notice that this index is not being used. Instead, Table scan is being used.</p><p>When you face this issue:</p><ol><li>When indexed column is not used in query’s WHERE clause. You should always use indexed column in WHERE clause if you want SQL Server to implement indexes in the query.</li><li>When SQL server finds that Table scan or non-clustered index scan is faster than non-clustered index seek with RID lookup. We already know what table scan is. Table scan is searching for the record by going through all the records in the table while non-clustered index scan is scanning the whole leaf node.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/516/1*2qyvXFkPjmnVii8omhhOsQ.png" /></figure><p>Indexes are most effective when retrieving one to a few hundred data items from a large amount of data. If there is a large amount of relevant data, the RID Lookup might be costly, and less efficient than a table scan.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/532/1*gwruKQwegodelpsVAp_BLw.png" /></figure><p><strong>Clustered index</strong></p><p>OK, so far, we have discussed ‘non-clustered indexes’, and now we will discuss another type of index, clustered indexes.</p><p>The difference between a non-clustered index and a clustered index is that in a non-clustered index, as you might remember, a pointer to the actual data (row identifier: RID) is stored at leaf level.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/671/1*QnBpuJiR_FQwz9ki_-at4w.png" /></figure><p>But in clustered index the actual data itself is stored. For example, we created a clustered index based on the FirstName column. As you can see, the leaf node includes the actual data pages which is sorted based on the column “FirstName”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*h3g6LoCqvf5Jkw68q8g9zw.png" /></figure><p>This shows there are some important points regarding clustered index. Firstly, we cannot create more than one clustered index for one table. Furthermore, when we create clustered index, the actual data is sorted in pages in leaf node. Therefore, creating clustered index takes more time than non-clustered index. Moreover, When sorting is happening, we should store sorting data temporarily in temp table. Therefore, we should have enough storage for creating clustered index.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/653/1*gEuqWCYv4rlvxO_ljsXhhA.png" /></figure><p>OK, so far, we discussed about heap, clustered index and non-clustered index.</p><p>In the case of heap table structure, we have table scan only. In the case of indexing, we have clustered index scan and non-clustered index scan where the whole leaf node is scanned. The most efficient way we found is clustered index seek and non-clustered index seek where only required part of the table is scanned.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/537/1*R2db73qBIma2Hv0766tDjQ.png" /></figure><p><strong>Automatic creation of the indexes</strong></p><p>Until here we came by creating indexes manually. However, clustered index can also be created automatically. When?</p><ol><li>When table is created with primary key</li><li>When Table is created with Unique column</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/672/1*Eq7IDynlm4Yj2e4Bd_NXbg.png" /></figure><p>As you can see, I created tables with primary and unique keys and tables have been created with clustered indexes.</p><p><strong>Non-clustered + clustered index case structure</strong></p><p>Ok. Let us discuss about a case where we have both clustered and non-clustered indexes created. We will end up with the following flow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/660/1*pTczLJVjw7zVUDunaxFx5g.png" /></figure><p>In this case, as you can see, in the leaf node of the non-clustered index, BusinessEntityId has been set instead of Row ids.</p><p>Thank you for your time!!!!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=203ec4100247" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SQL Server Troubleshooting: Resolving “The login is from an untrusted domain and cannot be used…]]></title>
            <link>https://arslan-bobir.medium.com/sql-server-troubleshooting-resolving-the-login-is-from-an-untrusted-domain-and-cannot-be-used-7a1a6c715817?source=rss-c8518b32c75e------2</link>
            <guid isPermaLink="false">https://medium.com/p/7a1a6c715817</guid>
            <category><![CDATA[windows-authentication]]></category>
            <category><![CDATA[ntlm]]></category>
            <category><![CDATA[sms]]></category>
            <category><![CDATA[sql-server]]></category>
            <category><![CDATA[kerberos]]></category>
            <dc:creator><![CDATA[ARSLANOV]]></dc:creator>
            <pubDate>Wed, 20 Jul 2022 06:32:35 GMT</pubDate>
            <atom:updated>2023-05-06T15:03:56.185Z</atom:updated>
            <content:encoded><![CDATA[<h3>SQL Server Troubleshooting: Resolving “<em>The login is from an untrusted domain and cannot be used with Windows authentication</em>”</h3><p><strong>Subscribe for learning SQL Server:</strong> <a href="https://www.youtube.com/channel/UCrf9xG9beltktYoQ_fq1KLQ">Simple SQL Server — YouTube</a></p><h3>Issue background</h3><p>You have created a domain (e.g., test.mydom.com) as in <strong>Figure 1</strong> below where there is a domain controller, an application server where SSMS is installed and finally, a database server where SQL server is running. You have also verified that Application server and database server are in the same domain and TCP/IP is enabled in SQL Native client configuration in “db” server. Furthermore, you have also created inbound firewall rule in “db” which allows the connection to PORT number 1433 that is being used by SQL server.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/978/1*6W8QGebjNL3ScLzpKu_4rQ.png" /><figcaption>Figure 1</figcaption></figure><p>You have a domain user called TEST\login which is added as login user in SQL server.</p><p>When you login as a user “TEST\login” to the “app” and try to login SQL server in “db” with Windows Authentication in SSMS, you face following error:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wics_nzyNQ38TJ-0-zIMLA.png" /><figcaption>Figure 2</figcaption></figure><p>In addition, you find following logs in ERRORLOG showing</p><pre>Login failed. The login is from an untrusted domain and cannot be used with Windows authentication. [CLIENT: 10.0.0.6]<br><br>Logon SSPI handshake failed with error code 0x8009030c, state 14 while establishing a connection with integrated security; the connection has been closed. </pre><p>In this article, I will try to summarize the possible root causes of the above error and respective solutions.</p><h3><strong>Briefly about Windows Authentication process</strong></h3><p>When an application (e.g., SSMS) opens a connection and uses Windows Authentication, by default SQL server uses NTLM for local connection and Kerberos authentication for remote connection. If Kerberos cannot be used in remote connection, then Windows will fall back to NTLM authentication.</p><p>The detailed Kerberos authentication steps can be summarized as below:</p><ol><li>An application (e.g., SSMS) opens a connection with Windows Authentication, and passes an SPN which is constructed based on the service name, FQDN, port number and database SQL server instance name:<em> MSSQLSvc/&lt;FQDN&gt;:[&lt;port&gt; | &lt;instancename&gt;]</em>. For example, in our case, “app” server must be passing the SPN in the form of “MSSQLSvc/db.test.mydom.com”. I am omitting port number since it is default (1433) and instance name since I am using default instance, not named instance. For further details, please refer to documentation (<a href="https://docs.microsoft.com/en-us/sql/database-engine/configure-windows/register-a-service-principal-name-for-kerberos-connections?view=sql-server-ver16#Formats">https://docs.microsoft.com/en-us/sql/database-engine/configure-windows/register-a-service-principal-name-for-kerberos-connections?view=sql-server-ver16#Formats</a>).</li><li>The generated SPN will be submitted to Domain Controller (dc). If a valid SPN exists in dc, the token will be provided by dc and this token will be submitted to SQL Server by app server for authentication purpose.</li><li>app server logon/access db server and passes the token to the SQL server running inside for validation</li><li>If token is valid, Windows Authentication succeeds.</li></ol><p>If any step above fails, Kerberos authentication fails and NTLM authentication is used instead by default. If NTLM authentication cannot also be used, you will face an error message in Figure 2.</p><p>Therefore, in order to find the root cause of the error message in Figure 2, we should investigate why both Kerberos and NTLM authentications are not working.</p><h3><strong>Possible causes of why NTLM is not working</strong></h3><ol><li>Please login to db server and go to <em>Computer Configuration &gt; Windows Settings&gt; Security Settings &gt; Local Policies &gt; Security Options </em>and check NTLM settings is restricted in your server.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YfiwCw2t6dy5ipmSoB223g.png" /></figure><p>Also check the same settings in your other servers including app and dc.</p><p>2. Login to db server and go to <em>Computer Configuration &gt; Windows Settings&gt; Security Settings &gt; Local Policies &gt; User Rights Assignment </em>and check the Windows account you are using to login is included in the highlighted policies below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WZgExuC-M0KK3d7ouoAPyw.png" /></figure><p>If the account is not included in the policies, please add them and run <em>gpupdate/force</em> in cmd to ensure that the policy update has been applied immediately.</p><blockquote>FURTHERMORE, PLEASE NOTE THAT THE ABOVE SETTINGS ALSO PREVENTS KERBEROS AUTHENTICATION ALONG WITH NTLM.</blockquote><h3>Possible causes of why Kerberos is not working</h3><p>The failure of in-advance SPN registration in domain controller is one of the main causes of Kerberos authentication failure. The SPN is registered in advance by default when SQL server starts with a log-on account which has enough permissions to register SPN. Suppose the account starting SQL Server doesn’t have permission to register an SPN in Active Directory Domain Services. In that case, this call fails, and a warning message as below is logged in the Application event log as well as the SQL Server error log:</p><p><em>&lt;The SQL Server Network Interface library could not register the Service Principal Name (SPN)&gt;</em></p><p>Consequently, when a client submits SPN to DC to verify, DC cannot verify SPN, and the error in Figure 2 pops out (if NTLM is also not allowed):</p><p><em>&lt;Login failed. The login is from an untrusted domain and cannot be used with Windows authentication&gt;</em></p><p>To register the SPN, the Database Engine must be running under a built-in account, such as Local System (not recommended), or NETWORK SERVICE(<em>NT SERVICE\MSSQLSERVER</em>), or an account that has permission to register an SPN. You can register an SPN using a domain administrator account, but this is not recommended in a production environment. When SQL Server runs on the Windows 7 or Windows Server 2008 R2 or later versions of operating system, you can run SQL Server using a virtual account or a managed service account (MSA). Both virtual accounts and MSA’s can register an SPN. If SQL Server isn’t running under one of these accounts, the SPN isn’t registered at startup, and the domain administrator must register the SPN manually.</p><p>In short, please check SPN is registered successfully. You should see the logs as below in ERRORLOG:</p><pre>The SQL Server Network Interface library successfully registered the Service Principal Name (SPN)</pre><p>If there is a failure, you will see the below log:</p><pre>The SQL Server Network Interface library could not register the Service Principal Name (SPN)</pre><p>If you see the above failure log, please change your SQL server logon account to NETWORK SERVICE(<em>NT SERVICE\MSSQLSERVER</em>) or manually register the SPNs in DC. For further details, please refer to <a href="https://docs.microsoft.com/en-us/sql/database-engine/configure-windows/register-a-service-principal-name-for-kerberos-connections?view=sql-server-ver16#Permissions">Register a Service Principal Name for Kerberos Connections — SQL Server | Microsoft Docs</a>.</p><h3>Summary</h3><p>To summarize, the error in Figure 1 mostly occurs because of the following:</p><ol><li>NTLM is restricted in one of the involved servers</li><li>The client server is not allowed to access the db server</li><li>SPN registration has failed</li></ol><p>If you do not see the issues with the above settings, please contact Microsoft support for further investigations. We are always happy to help you:).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7a1a6c715817" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Best-practices in using Python Classes in Programming]]></title>
            <link>https://arslan-bobir.medium.com/best-practices-in-using-python-classes-in-programming-fe8fefd120eb?source=rss-c8518b32c75e------2</link>
            <guid isPermaLink="false">https://medium.com/p/fe8fefd120eb</guid>
            <dc:creator><![CDATA[ARSLANOV]]></dc:creator>
            <pubDate>Sun, 28 Mar 2021 13:22:11 GMT</pubDate>
            <atom:updated>2021-03-28T13:22:11.556Z</atom:updated>
            <content:encoded><![CDATA[<h3>Foreword</h3><p>Python is an object oriented programming language and almost everything in Python is an object. Python Classes are object constructors and widely used in Python-programming world. In this article, I am going to present you some best-practices in using Python Classes in programming. In particular, you will get to know:</p><ol><li><strong>The merits of using Classes instead of dictionary</strong>: sometimes it is better to use Classes instead of dictionaries in Python programming. You will get to know about these cases</li><li><strong>Decreasing the redundancy of your Classes with “dataclasses” module</strong></li><li><strong>Using @property instead of instance variables in Classes</strong></li></ol><h3>A case where using a Class is better than using dictionaries in Python</h3><p>Sometimes you may feel that creating Classes is time-consuming as well as complex and therefore, you opt for just creating individual methods and using dictionaries as follows:</p><pre>from datetime import date<br>import json</pre><pre>def get_fullname(user):<br>  fullname = f&#39;{user[&#39;name&#39;]} {user[&#39;surname&#39;]}&#39;<br>  return fullname</pre><pre>def get_user_age(user):<br>  date_born = user[&#39;birthday&#39;]<br>  age = date.today().year - date_born.year<br>  return age</pre><pre>def load_user():<br>  with open(&#39;./user.json&#39;, encoding=&#39;utf-8&#39;) as file:<br>     return json.load(file)</pre><p>The above-mentioned example uses “user” dictionary and several methods to get user properties. Is this a proper way? You need to take the user, convert it to the dictionary and take the properties by using individual methods. Can we refactor it and use more Pythonic way? The answer is ‘yes’. Look at the following best-practice:</p><pre>from datetime import date<br>import json<br>from dataclasses import dataclass</pre><pre>@dataclass<br>class User:<br>  name: str<br>  surname: str<br>  birthday: date</pre><pre>  @property<br>  def get_fullname(self):<br>    fullname = f&#39;{self.name} {self.surname}&#39;<br>    return fullname</pre><pre>  @property<br>  def get_user_age(self):<br>    date_born = self.birthday<br>    age = date.today().year - date_born.year<br>    return age</pre><pre>def load_user():<br>  with open(&#39;./user.json&#39;, encoding=&#39;utf-8&#39;) as file:<br>     return User(**json.load(file))</pre><h3>Using “dataclasses”</h3><p>Sometimes it is overwhelming to use Class because of the need to define many instance variables as follows:</p><pre>class User:<br>  def __init__(self, name, surname, birthday, citizenship, address, workplace, job):<br>    self.name = name<br>    self.surname = surname<br>    self.birthday = birthday<br>    self.citizenship = citizenship<br>    self.address = address<br>    self.workplace = workplace<br>    self.job = job</pre><p>There is not a problem with the above example but redundancy.</p><p>We can deal with the above-mentioned redundancy by using “dataclasses”:</p><pre>from dataclasses import dataclass<br>from datetime import datetime</pre><pre>@dataclass<br>class User:<br>  name: str<br>  surname: surname<br>  birthday: birthday<br>  citizenship: citizenship<br>  address: address<br>  workplace: workplace<br>  job: job</pre><pre>  @property<br>  def get_fullname(self):<br>    fullname = f&#39;{self.name} {self.surname}&#39;<br>    return fullname</pre><h3><strong>Using @property instead of instance variables</strong></h3><p>While creating Classes, sometimes, you define instance variables just to use in the methods as below:</p><pre>form datetime import date</pre><pre>@dataclass<br>class User:<br>  name: str<br>  surname: surname<br>  birthday: date<br>  age: None</pre><pre>  def calc_user_age(self):<br>    date_born = self.birthday<br>    self.age = date.today().year - date_born.year</pre><pre>  def age_display(self):<br>    return f&quot;I am {self.age} years old.&quot;</pre><p>The main problem with the above example is that if you run “age_display” method before “calc_user_age”, you will get “None”. In other words, you should always remember to run “calc_user_age” before “age_display”.</p><p>You can refactor the above written code as follows with @property:</p><pre>form datetime import date</pre><pre>@dataclass<br>class User:<br>  name: str<br>  surname: surname<br>  birthday: date</pre><pre>  @property<br>  def age(self):<br>    date_born = self.birthday<br>    age = date.today().year - date_born.year<br>    return age</pre><pre>def age_display(self):<br>    return f&quot;I am {self.age} years old.&quot;</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fe8fefd120eb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Connecting to Servers through Bastion Host in GCP by using SSH tunnels (in Mac)]]></title>
            <link>https://arslan-bobir.medium.com/connecting-to-servers-through-bastion-host-in-gcp-by-using-ssh-tunnels-in-mac-3536ee54062d?source=rss-c8518b32c75e------2</link>
            <guid isPermaLink="false">https://medium.com/p/3536ee54062d</guid>
            <dc:creator><![CDATA[ARSLANOV]]></dc:creator>
            <pubDate>Mon, 08 Mar 2021 16:46:05 GMT</pubDate>
            <atom:updated>2021-03-08T16:46:05.044Z</atom:updated>
            <content:encoded><![CDATA[<h3>Overview</h3><p>In order to keep security of servers, data engineers often use bastion host as a “door” to the server and connect to the server through this bastion by using SSH. In this article, we will create this kind of environment in GCP (in Figure 1 below) with the help of deployment manager and do SSH connection to the Server through Bastion. Note that if you have an environment in GCP and all services (including Bastion) are running, you can skip “<strong>Creating the environment in GC</strong>P” section below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/854/1*MzHFRPE4Db_asK48RWHUnA.png" /><figcaption>Figure 1. SSH connection to Server in Private Subnet through Bastion</figcaption></figure><h3>Creating the environment in GCP</h3><h4>Requirements</h4><p>You need to have an account and a project in GCP in order to move the next stages. Furthermore, please, <a href="https://cloud.google.com/sdk/docs/install">install gcloud command</a> in order to run deployment manager commands below.</p><h4>Creating</h4><p>Please, pull the code from <a href="https://github.com/Bobirmirzo/gcp-vpc-with-deployment-manager">Github</a> which will be used to create the environment in Figure 1 above. After pulling, run the following codes to create the environment:</p><pre># Setting a default project<br>gcloud config set project {project.id}</pre><pre># Run the deployment manager and create the environment<br>./deployments_create.sh my-infra infra.yaml</pre><h3>Connecting to Bastion with SSH tunnels</h3><p>Run the following code and check whether you have .ssh folder:</p><pre>ls ~/.ssh</pre><p>If there is not such directory, create the one:</p><pre>mkdir ~/.ssh<br>chmod 700 ~/.ssh</pre><p>After the code above, generate the ssh-keys by running <em>ssh-keygen</em>. You are asked a series of questions. Accept all the defaults by pressing Enter. Enter a passphrase for your SSH key if you want.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/826/1*CvAiD1Yl80_2v8j_wh53bA.png" /><figcaption>Figure 2. Generating ssh keys</figcaption></figure><p>After the code above, run the following:</p><pre>cd ~/.ssh<br>chmod 600 *</pre><p>After generating the keys, copy “.pub” version of the secrets you generated above to the “Metadata” of the “Compute Engine” in GCP:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*JRFRkyy3LUifwy1O-l_6Jg.png" /><figcaption>Figure 3. Metadata section of Compute Engines in GCP</figcaption></figure><p>and most importantly, currently, firewall Ingress rule source ranges are 0.0.0.0/0, meaning you can enter to bastion from any IP. In order to increase security, delete this 0.0.0.0/0 and insert your IP there:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/566/1*TtvqzliUoCak-0aOCkOe7Q.png" /><figcaption>Figure 4. Firewall for bastion host</figcaption></figure><p><strong>DO NOT FORGET TO INCLUDE YOUR IP IN BASTION FIREWALL</strong> so that you can connect with your IP to the servers.</p><p>Finally, connect to the server through Bastion by using SSH tunnels by using following codes:</p><pre>ssh -i ~/.ssh/id_rsa {metadata_username}@{bastion_public_ip} -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -f -N -L 10610:{server_private_ip}:22</pre><pre>ssh localhost -p 10610</pre><p>metada_username: your “username” in Metadata of Compute Engine in GCP</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/607/1*vvywKZxqKZj6X-qyjHuhoA.png" /><figcaption>Figure 5. Username in Metada</figcaption></figure><p>THAT’S IT !!!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3536ee54062d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automating Terraform in Github Actions with self-host runner in AWS]]></title>
            <link>https://medium.com/jdsc-tech-blog/automating-terraform-in-github-actions-with-self-host-runner-in-aws-a21359a80f9c?source=rss-c8518b32c75e------2</link>
            <guid isPermaLink="false">https://medium.com/p/a21359a80f9c</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[terraform]]></category>
            <dc:creator><![CDATA[ARSLANOV]]></dc:creator>
            <pubDate>Fri, 05 Mar 2021 01:51:12 GMT</pubDate>
            <atom:updated>2021-03-05T01:51:12.062Z</atom:updated>
            <content:encoded><![CDATA[<h3>Automating Terraform in GitHub Actions with self-host runner in AWS</h3><h3>Background</h3><p>Recently, we have built a prototype environment in AWS for our application. The application is in the process of development and we are going to add additional features to it. There we faced an issue: for each additional feature, we had to add or change some of the AWS services. For example, adding Fargate services, container definitions or creating new Cloud Front with S3 buckets for the front of the new application feature. The main problem was that we had to manually add, remove or change services and it was costly in terms of time. Due to this reason, we automated our infrastructure-build by building Infra-CI-CD pipeline with <strong>Terraform</strong> and <strong>GitHub Actions</strong> which allow us to quickly respond to any demand for a change in infrastructure in AWS. In this article, I am going to build and present this CI-CD pipeline so that you can also easily build CI-CD for your infrastructure in AWS.</p><h3>Introduction</h3><p>Figure 1 below represents Diagram of Infra-CI-CD we are going to build in this article. The diagram consists of following features:</p><p><strong><em>Main application environment</em></strong><em>: </em>this is the environment where our application runs. For simplicity, I only included some services including RDS and EC2 instance in Private Subnets. This infrastructure will be built with Terraform and will be target of our CI-CD pipeline: we are going to build CI-CD to change the services in this environment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UV8DTYApkEfB3lXidl8A6g.png" /><figcaption>Figure 1</figcaption></figure><p><strong><em>Self-host runner environment</em></strong>: this is the environment where our self-host runners for GitHub actions run and make changes to the application environment. Note that instead of self-host runners, you can also run default runners of GitHub Actions. However, in this case security problem arises: you should give this runner a very strong “AWS Admin role” in order to change services. Furthermore, in order to access AWS, this default runner should get AWS Secret Access Keys and IDs. I found that submitting these secrets and role to GitHub Actions and Runner is dangerous and decided to use self-host runners in AWS ECS with Admin Role which is located safely in private subnet under my control and get any secrets (e.g. github tokens) from Secrets Manager. <em>If you want, you can reduce permissions for the runner. For example, if it is required to change ECS, you can give the runner only ECS Admin.</em></p><p>This environment for self-host runners is also built with Terraform which I am going to show later.</p><p><strong><em>GitHub Actions</em></strong>: When a code is committed to GitHub and Pull request is created, GitHub Actions are run with self-host runner and CI is started. There are following steps in CI:</p><ol><li>Lint check</li><li>Terraform code format check</li><li>Security check: checks if there is any security issue in the changed application Terraform file</li><li>Terraform code validation check</li><li>Terraform plan: to see what changes will occur</li><li>Create notification to GitHub Comment about changes in AWS services in application environment</li></ol><p>If you merge the code to the main branch, CD starts in self-host runners. CD includes following steps:</p><ol><li>Terraform apply: apply the code and make changes to the infrastructure environment</li><li>Send notification to Slack channel about changes in services after terraform apply finished so that your team can see what services have been added, removed or changed</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hM9OHAG-fw1xqSsBhF3t_w.png" /><figcaption>Figure 2. Workflow in GitHub during Infra-CI-CD</figcaption></figure><p><em>S3 bucket</em>: in order to keep terraform state file, S3 bucket is used. Self-host runner accesses to this bucket and understands the current state of the application environment and conducts CI-CD.</p><h3><em>Starting to Build Infra-CI-CD</em></h3><p>Source Code is in <a href="https://github.com/Bobirmirzo/infra-ci-cd"><strong>GitHub</strong></a>.</p><blockquote><strong><em>Setting environment variables</em></strong></blockquote><p>Firstly, in order to enable Terraform access AWS account and to create self-host runner, we should set environment variables as follows:</p><pre>export PAT={YOUR_GITHUB_PERSONAL_TOKEN_HERE}<br>export ORG={YOUR_GITHUB_ORG_HERE}<br>export REPO={YOUR_GITHUB_REPO_NAME_HERE}<br>export AWS_DEFAULT_REGION={YOUR_AWS_DEFAULT_REGION_HERE}<br>export AWS_SECRET_ACCESS_KEY={YOUR_AWS_SECRET_ACCESS_KEY_HERE}<br>export AWS_ACCESS_KEY_ID={YOUR_AWS_ACCESS_KEY_ID_HERE}<br>export AWS_ACCOUNT_ID={YOUR_AWS_ACCOUNT_ID_HERE}</pre><p>Terraform automatically checks above variables.</p><blockquote><strong><em>Setting backends for Terraform state files</em></strong></blockquote><p>In this stage, we should create two S3 buckets as backend: one for “Terraform state-file used to create Application environment” and another for “Terraform state-file used to create self-host-runner environment”. The settings of the backends have already been done in backend files in GitHub:</p><ol><li><a href="https://github.com/Bobirmirzo/infra-ci-cd/blob/main/backend.tf">Application environment Terraform backend</a> file</li><li><a href="https://github.com/Bobirmirzo/infra-ci-cd/blob/main/self-host-runner-ECS/backend.tf">Self-host runner environment Terraform backend file</a></li></ol><p>You should create buckets manually with the names “self-host-runner-bucket” and “app-infra-state-bucket” as defined in the files. <strong>If your default region is different from “ap-northeast-1”, do not forget to change default region in the files to your region.</strong></p><blockquote><strong><em>Creating application environment</em></strong></blockquote><p>Let us create application environment. Pull the source code from the <a href="https://github.com/Bobirmirzo/infra-ci-cd"><strong>GitHub</strong></a><strong> </strong>and run following codes:</p><pre># Initiate terraform<br>terraform init</pre><pre># Check which resources will be created<br>terraform plan</pre><pre># Create environment<br>terraform apply</pre><blockquote><strong><em>Creating self-host runner</em></strong></blockquote><p>After creating application environment above, we switch to creating self-host runner and its running environment in the same AWS account. The code to create the runner and its running environment have already been written in “self-host-runner-ECS” folder in the same GitHub repository above. Enter the folder and run following codes:</p><pre># Initiate terraform<br>terraform init</pre><pre># Create environment<br>./tf_apply.sh</pre><p>The above code creates an environment for self-host runner to run and ECR repository for us to push runner’s container. Now, we should create container and push it to ECR as follows:</p><pre># Login to registry <br>aws ecr get-login-password | docker login --username AWS --password-stdin $AWS_ACCOUNT_ID.dkr.ecr.ap-northeast-1.amazonaws.com</pre><pre># Create a container<br>docker build -f Dockerfile -q -t ecs-runner .</pre><pre>docker tag ecs-runner $AWS_ACCOUNT_ID.dkr.ecr.ap-northeast-1.amazonaws.com/ecs-runner</pre><pre># Push the container to ECR<br>docker push $AWS_ACCOUNT_ID.dkr.ecr.ap-northeast-1.amazonaws.com/ecs-runner</pre><pre># Start the runner<br>aws ecs update-service --cluster ecs-runner-cluster --service <a href="https://ap-northeast-1.console.aws.amazon.com/ecs/home?region=ap-northeast-1#/clusters/ecs-runner-cluster/services/ecs-runner-ecs-service/details">ecs-runner-ecs-service</a> --force-new-deployment</pre><p>After running the code above, the self-host runners in AWS for GitHub Actions start in the form of Fargate instances (autoscaling: max=2 and min=1) and you should see it running in GitHub:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/692/1*xF0cfAX6MWff3BMa8_RV6g.png" /><figcaption>Figure 3. Self-host runner in GitHub</figcaption></figure><blockquote>Setting GitHub Actions</blockquote><p>Before creating workflow files, save the secrets below to your Repository’s GitHub Secrets:</p><pre>1. SLACK_TOKEN<br>2. SLACK_CHANNEL_ID<br>3. SLACK_BOT_NAME<br>4. AWS_ACCOUNT_ID<br>5. GITHUB_TOKEN</pre><p>Furthermore, enter to “.tfnotify” folder and fill in points below in “github.yml” file:</p><pre>.......<br>owner: &quot;{your org}&quot;</pre><pre>name: &quot;{your repo name}&quot;<br>........</pre><p>In order GitHub Actions to run, you need workflow files. I have created workflow files for both CI and CD in “.github” folder. There you can see all of the jobs done in CI-CD pipeline. Just include these files as they are along with above run terraform files and push to your repository.</p><p>When you open pull request to main branch, CI runs as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/701/1*HtmXf6DpHj-6KpupcCp6Ow.png" /><figcaption>Figure 4. Pull request</figcaption></figure><p>After CI finishes, you can see the terraform plan outcome in the GitHub Comments as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/711/1*D-gWIYM6a46Z14Va91C2aw.png" /><figcaption>Figure 5. Notification of Terraform Plan to GitHub Comments</figcaption></figure><p>If you merge the above PR request to Main branch, CD starts and terraform apply runs. After terraform apply finishes and services have been changed, deleted or added, you can see the notification about it in your Slack channel which you defined above.</p><p>YOUR PIPELINE IS READY. THAT IS IT!!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a21359a80f9c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/jdsc-tech-blog/automating-terraform-in-github-actions-with-self-host-runner-in-aws-a21359a80f9c">Automating Terraform in Github Actions with self-host runner in AWS</a> was originally published in <a href="https://medium.com/jdsc-tech-blog">JDSC Tech Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tips to pass the Google Cloud Professional Data Engineer Certification exam]]></title>
            <link>https://medium.com/jdsc-tech-blog/tips-to-pass-the-google-cloud-professional-data-engineer-certification-exam-8de65ae20a84?source=rss-c8518b32c75e------2</link>
            <guid isPermaLink="false">https://medium.com/p/8de65ae20a84</guid>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[gcp-certification]]></category>
            <category><![CDATA[gcp]]></category>
            <category><![CDATA[データエンジニア]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[ARSLANOV]]></dc:creator>
            <pubDate>Fri, 30 Oct 2020 02:02:29 GMT</pubDate>
            <atom:updated>2020-10-30T02:02:29.990Z</atom:updated>
            <content:encoded><![CDATA[<p>As most machine learning projects and big data analysis are switching to the cloud, the need for professionals who can effectively build data solutions in the cloud is significantly increasing. With GCP Professional Data Engineer Certificate, you can demonstrate that you have adequate skills and knowledge to design and build data processing systems and create machine learning models on Google Cloud Platform.</p><p>Recently, I passed this certification exam with nearly three months of studying: I do not have 3+ years of experience as recommended by Google to pass this exam, and it has been only 6 months since I have started working on the cloud at my company. I think the key to my success was just studying right for this exam.</p><p>In this short article, I want to share some tips on how to prepare for this exam and pass it successfully. I cannot guarantee that you will definitely pass the exam if you follow these tips, but I strongly believe that these tips will surely increase the probability of your success.</p><h4><strong>Tip 1/Step 1: Complete the specialization at Coursera “Data Engineering with Google Cloud Professional Certificate”</strong></h4><p>In the beginning, you should get familiar with Google Cloud by taking the “Data Engineering with Google Cloud Professional Certificate in Coursera. I think this is a perfect starting point for the preparation for the test.</p><p>I <strong>highly recommend</strong> that you do not rush to complete the course. While taking each lesson, also study the documentation related to the topic. For example, if you take a lesson about “Dataproc”, study the relevant Google documentation about this service. You do not need to study and understand all the service’s documentation at this stage (which is impossible, I think 😅) but try to understand about 30–40% of the documentation, especially the “Concepts” part. And lastly, and most importantly, do practical exercises: create and run the service in GCP and see how it works. Do not just do it once, but at least twice or three times. Coursera has excellent Qwiklabs for this, and you can easily leverage it.</p><h4><a href="https://www.amazon.co.jp/Official-Certified-Professional-Engineer-English-ebook/dp/B086Q6V6G6/ref=sr_1_4?dchild=1&amp;keywords=data+engineer&amp;qid=1602422559&amp;sr=8-4"><strong>Tip 2/Step 2: Read an excellent book “Professional Data Engineer Study Guide”</strong></a></h4><p>I can say that this book contains nearly all the necessary information required to pass the exam, and found it the best source of learning. It has well-organized chapters about GCP services and provides many key points you should remember while solving the test. At the end of each section, there are tests on what you have learnt. I found these tests very close to the actual test, and it helped me a lot to prepare for the test. To tell the truth, after reading this book, I have been able to improve my knowledge by about 40–50%, and my results in the mock test significantly improved.</p><p>Furthermore, at this stage, I highly recommend that you do not just finish the book but also study Google documentation related to each chapter and topic at the same time. At this stage, try to understand about 50–60% of documentation, especially the “Concepts” and “Best practices” part.</p><h4>Tip 3/Step 3: Read <a href="https://www.amazon.co.jp/Google-Cloud-Platform-Action-Geewax/dp/1617293520/ref=sr_1_1?__mk_ja_JP=%E3%82%AB%E3%82%BF%E3%82%AB%E3%83%8A&amp;dchild=1&amp;keywords=google+in+action&amp;qid=1602423710&amp;sr=8-1">“Google Cloud Platform in Action”</a></h4><p>You may find this book is old, but it is very useful and informative. This book can teach you the ways to deploy scalable and reliable applications on GCP, which is an important topic in the exam. Furthermore, this book has practical guidelines with the help of which you can also exercise and run the GCP services and deepen your knowledge. Lastly and most importantly, this book shows how to maximize storage services and manage containers in Kubernetes, which is very useful for the exam. Try this book!!</p><p>And again, (😅) at this stage also, do not forget to deepen your knowledge by reading Google documentation. Try to revise what you have learnt until now in the documentation and try to increase your understanding in the documentation to 70–80%.</p><h4><strong>Tip 4/Step 4: Take the Udemy course “Complete Google Data Engineer and Cloud Architect Guide”</strong></h4><p>After completing the previous steps, you can take this course to revise what you have learnt until now and deepen your knowledge in each GCP service. This course is very informative, and I found it very useful. I have been able to understand many key points in GCP services in this course. Most importantly, this course provides very good lessons on Hadoop Ecosystem. Study this section very carefully because this can greatly help you understand the questions in the exam..</p><h4><strong>Tip 5/Step 5: P</strong>ractice the tests<strong> in the book “Google Cloud Professional Data Engineer Practice Tests”</strong></h4><p>At this stage, start practicing the actual tests by reading the book, “Google Cloud Professional Data Engineer Practice Tests”. This book does not only provide you with questions but also answers with explanations. Do not just solve and move to the next question but try to understand each question and read related documentation if you cannot solve the question, and most importantly, remember the questions with answers. You may face the same or very close questions in the exam 😉.</p><h4>Tip 6/Step 6: Practice tests in <a href="https://www.examtopics.com/exams/google/professional-data-engineer/view/1/">“ExamTopics”</a></h4><p>This site is an excellent source for practicing tests since it provides many actual exam questions. To tell the truth, although I found many answers to the questions wrong (since it has been solved by “their experts” 😉), I have been able to familiarize myself with many questions, exercised a lot and reviewed many topics and documentation if I could not find answers to the questions while using this site.</p><h4>AND REVISE THE DOCUMENTATION ONCE MORE AND TAKE THE EXAM!!!</h4><h4>Further notes by the author</h4><p>I have spent a lot of time preparing for the exam and tried very hard learning many materials by following the above-mentioned steps. However, it is worth mentioning that my surrounding environment has also helped me a lot in passing this exam for a short period of time. I am fortunate to work at Japan Data Science Consortium (JDSC), the company which actively utilizes Google Cloud Platform for building machine learning models and doing big data analysis. By working at this company every day, I have actively engaged in data science analysis on GCP and improved my knowledge on this platform.Furthermore, I am surrounded by several experts in the data science field and proud owners of the certification (e.g. <a href="https://www.credential.net/385dd18d-98c7-4e90-8f45-c50cbb84261e">Keisuke Hashimoto</a>, <a href="https://www.credential.net/dc0aa829-1338-4260-b08c-a01b710404bb?key=2f430bc709fb6dc203447664bcc4a4061fb7cf3e3e6e831e4307f7e57daca95c">Shimpei Ohsugi</a>, <a href="https://googlecloudcertified.credential.net/profile/c2b4d41772e6b37514d41ad5ad9f6e2e03e8b585">Momota Sasaki</a>, <a href="https://www.credential.net/7f8b6288-c051-4fa2-9a10-2a056ba4012e?key=71f33b713e4f37ada03b7b6c8a3029d5493918c0995610b80cf59c139f7207e7">Takuto Sugisaki</a>). While working and consulting with them constantly on building scalable, maintainable, and reliable applications on Google Cloud Platform, I have significantly improved my data engineering skills. This has also helped me a lot in passing this prestigious exam. It is very pleasant to work at this company and with all these people.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bsznjCXvyzdSoIHtddaIdw.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8de65ae20a84" width="1" height="1" alt=""><hr><p><a href="https://medium.com/jdsc-tech-blog/tips-to-pass-the-google-cloud-professional-data-engineer-certification-exam-8de65ae20a84">Tips to pass the Google Cloud Professional Data Engineer Certification exam</a> was originally published in <a href="https://medium.com/jdsc-tech-blog">JDSC Tech Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kubernetes: A way to reliable and scalable data-intensive application]]></title>
            <link>https://medium.com/jdsc-tech-blog/kubernetes-a-way-to-reliable-and-scalable-data-intensive-application-15b6edf08bd1?source=rss-c8518b32c75e------2</link>
            <guid isPermaLink="false">https://medium.com/p/15b6edf08bd1</guid>
            <category><![CDATA[trials]]></category>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[ARSLANOV]]></dc:creator>
            <pubDate>Tue, 18 Aug 2020 04:41:35 GMT</pubDate>
            <atom:updated>2020-08-18T04:41:35.572Z</atom:updated>
            <content:encoded><![CDATA[<p>By effectively using the technological developments, <em>Data-intensive applications </em>are pushing the boundaries of what can be done. An application becomes <em>data-intensive</em> if data is its primary challenge. Nowadays, many applications are <em>data-intensive</em>. Such applications have to:</p><ul><li>Store data in the database for the later use</li><li>Cache data so that they can decrease the cost of expensive operations and increase the speed of reads</li><li>Have a search functionality so that users can easily filter a large amount of data by keyword</li><li>Periodically process and give insights from a large amount of data in database (batch processing)</li></ul><p>Due to these minimum requirements and wide-ranging functionalities, building<em> data -intensive applications</em> is becoming a complicated task. There are many database systems, for example, with different characteristics designed to meet the demand of wide range of application requirements. Moreover, to meet all above mentioned requirements, you can not design your application with a single tool or component. You should break down the work into tasks, write an application code to assign each task to a single tool.</p><p>For instance as depicted in Figure 1 below, if you have an application-managed caching or full-text search server, your responsibility with the codes for the application becomes to keep caches and indexes in sync with the main database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O861dVYS1GTWRn0l-6sQtA.png" /><figcaption>Figure 1. Example of data-intensive application design with several components</figcaption></figure><p>By combining these types of several components with distinct responsibilities, you create a <em>data-intensive </em>application that provides a service, and the interface of your service (API) hides these details from your end-users.</p><p>While designing data-intensive applications, you should always consider about the following questions:</p><ul><li>If some parts of your application go wrong (e.g. hardware failure which is considered a usual phenomenon in software engineering), does your application keep the data correctly and handle this failure without impacting the API performance ?</li><li>If parts of the application become outdated, how can you update them by constantly keeping good service performance to the clients?</li><li>If a significant increase in load is observed, how can the application handle this ?</li></ul><p>In other words, your application should be <strong>reliable</strong>: its data system should constantly work in stable and correct conditions, do not lose or expose data outside even in the face of adversity such as hardware and software failures. Furthermore, you should have reasonable ways to deal with future data, traffic and complexity volume growth, namely <strong>scalability</strong>.</p><blockquote>How can we achieve this scalable and reliable application? Is there any way out?</blockquote><blockquote>Yes, <strong>Kubernetes.</strong></blockquote><p>The purpose of this article is to introduce Kubernetes and show how it can be used to achieve scalable, reliable and maintainable application.</p><h3><strong>About Kubernetes</strong></h3><p>Kubernetes is an open-source platform for deployment containerised applications and managing them (№3 in Figure 3 below). It automates many of the manual processes including deploying, managing, and scaling containerised applications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jjlNS03kmKYe8bgWzM-OKQ.png" /><figcaption>Figure 1. Different application deployment techniques</figcaption></figure><blockquote><strong>Kubernetes Architecture</strong></blockquote><p>The main building block of Kubernetes is a cluster of computers where a master node and worker nodes connect to each other and work as a single unit (Figure 2).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Uyob2yLBvqQlkghqk6WAzA.png" /><figcaption>Figure 2. The architecture of Kubernetes with two nodes (VMs) where two applications are placed in each.</figcaption></figure><p>A cluster consists of a master node and worker node. A master is responsible for coordinating all activities including scheduling applications, maintaining desired state of applications, scaling applications, and rolling out new updates.</p><p>A worker node is a virtual machine. Each node has a Kubelet, which is an agent for managing the node and communicating with the Kubernetes master. A container consists of an application and is located in a pod. When an application is deployed, the master starts the application containers and schedules them to run on nodes.</p><blockquote><strong>Creating and running a cluster on Kubernetes</strong></blockquote><p>Kubernetes cluster can be created with both on cloud (e.g. <a href="https://cloud.google.com/kubernetes-engine">GKE</a>) and on local computer (e.g. Minikube). Minikube is a lightweight Kubernetes implementation where you can create a simple cluster with one worker node. In this article I have created a sample recorder application (<a href="https://github.com/Bobirmirzo/Scalable-app-on-Kubernetes/tree/master/api">github</a>) and deployed it on Minikube by the following steps.</p><p><strong>Step 1</strong></p><p>Containerising an app in Docker with following Dockerfile:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/703/1*PPzbd708p5-5Oujo_T7pMA.png" /><figcaption>Figure 3. Dockerfile</figcaption></figure><pre># You build your docker and push it to docker hub. Therefore, you    # should first open account at docker hub and insert account name    # (in my case &quot;arslanov&quot;) below:</pre><pre>$ docker build -t arslanov/scalable_app_for_kubernetes:scalable_api .<br>$ docker push .</pre><p>You can run the containerised app at <a href="http://0.0.0.0:8080/">http://0.0.0.0:8080</a> after running:</p><pre>$ docker run -p 8080:8080 arslanov/scalable_app_for_kubernetes:scalable_api</pre><p><strong>Step 2</strong></p><p>Install Minikube and kubectl</p><p><strong>Step 3</strong></p><p>Start the cluster:</p><pre># Creating cluster<br>$ minikube start</pre><p>You can check created cluster with “kubectl cluster-info” and created node with “get nodes”</p><p><strong>Step 4</strong></p><p>We deploy the app with following deployment.yaml:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/689/1*dFRhXHLNZoww2-7Q57Z5TQ.png" /><figcaption>Figure 4. deployment.yaml</figcaption></figure><pre># Creating deployment<br>$ kubectl create -f api_deployment.yaml</pre><p>Pods that are running inside Kubernetes are running on a private and isolated network. By default, they are visible from other pods and services within the same Kubernetes cluster, but not outside the network. Therefore, we create a service which allows us access to pods and our application in the container:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/541/1*iUAg1p6J3lCgmugP93ZHRA.png" /><figcaption>Figure 5. api_service.yaml</figcaption></figure><pre># Creating a service<br>$ kubectl create -f api_service.yaml</pre><pre># Launching a service: Now you can access an app from browser!<br>$ minikube service recorder-app</pre><p>We have created a cluster and run our application in it. Now, we will explore how Kubernetes can give us reliable, scalable and maintainable application.</p><h3>Reliability with Kubernetes</h3><p>According to Klepmann (2017), reliability is defined as “continuing to work correctly, even when things go wrong”. These things can be referred as faults and your application should be fault-tolerant or resilient. However, we cannot decrease the probability of faults to zero (<strong>it is impossible</strong>) but we can prevent some serious faults from causing a system to completely stop serving (aka failures) to customers.</p><p><strong><em>Hardware faults</em></strong></p><p>Hardware faults (e.g. Hard Disk or CPU crash, faulty RAMs etc.)are referred as the main cause of system failures. In recent years, there is a significant move with different responses to create systems which can tolerate such hardware faults. One of the possible responses can be to create and keep redundant components “<em>in stock</em>”. When one of the working components dies, this redundant component quickly takes its place and application keeps running uninterrupted. But <em>how can we create this redundant component and replace them with dead one when needed? Is there any technique? </em>Yes, Kubernetes can be one of the techniques.</p><p>Kubernetes has ReplicaSet service which creates and maintains replica pods running at any given time. This service guarantees the availability of a redundant pod with an application container. If any pod dies inside the node, these replica pods have been replaced with dead ones immediately and your application continues to serve without failure.</p><p>You can easily create replicas of pods with containers by changing “replicas” section of “deployment.yaml” in Figure 4 as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h2foK6qUkKKfYeUGwMIW7g.png" /><figcaption>Figure 6. Creating pod replicas in Kubernetes</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LA-WSPfO-ziVpAEGq200Cw.png" /><figcaption>Figure 7. Kubernetes with 3 replicas</figcaption></figure><p><strong><em>Software faults</em></strong></p><p>While running an application, we often face systematic software errors with the data system. As Klepmann (2017) stated, these type of faults lie dormant for a particularly long period of time until some unusual event triggers them. In these circumstances, some kind of assumptions might have been built, and software can be following these assumptions. Eventually, this assumption stops being true for some reason, and software failure occurs.There is no quick solution to the problem of systematic faults. One solution to these types of faults can be carefully thinking about assumptions and isolating the process and environment where these assumptions have been built from other environments. Kubernetes can also help here.</p><p>In Kubernetes, since applications are running in containers, each application’s running environment is predictable and isolated from other applications’ environments. Containers include software dependencies needed by the application, such as specific versions of programming language runtimes and other software libraries. In short, each application has its own consistent environment to run and does not affect other environment and libraries. This can often help in preventing software faults in Kubernetes.</p><p>Furthermore, replication feature of Kubernetes described above can also react to any faults that occurred in pods because of software failures and replace the faulty pods with healthy replicated ones in around 5seconds.</p><p><strong><em>Human errors</em></strong></p><p>Engineers and data scientists who build data-intensive applications can be another source of system faults. As Klepmann (2017) claimed, even though humans have the best intentions, humans are known to be unreliable.</p><p>If so, with unreliable humans, is there a way to make application reliable? Although human errors are beyond the scope of this article, I can suggest some ways such as:</p><ul><li>Designing a system with programming techniques such as object oriented programming with well-designed abstractions where one can easily detect bugs;</li><li>Develop whole-system integration tests and manual tests;</li><li>Set up logging and clear monitoring the running process;</li><li>Most importantly, by rolling out code in a step-by-step process, we should minimise the impact of failure and allow fast recovery. In this case, only a subset of users may be impacted by the failure.</li></ul><p>In the case of <em>human errors, </em>Kubernetes can help engineers by providing logs at container, node and cluster levels so that they can debug much easily. Refer to <a href="https://kubernetes.io/docs/concepts/cluster-administration/logging/">Logging Architecture in Kubernetes</a>.</p><p>Example of Container level logging:</p><pre># Add &quot;args&quot; to api_deployment.yaml as follows and run:</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/578/1*QDZ_2wvmZDySA55BqoysCA.png" /></figure><pre>$ kubectl apply -f example.yaml<br>$ kubectl log &lt;container-name&gt;</pre><p>The output becomes smth like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/412/1*wjHYyG4ALMrWhm7AtDEB1Q.png" /></figure><h3>Deeper dive in scalability</h3><p>Imagine your data-intensive application is working with 1000 customers and processing their data today. However, after one year, the system has grown from from 1000 to 10000 concurrent users. Can your application handle this sudden increase in load? In other words, does your application system have scalability?</p><p>Scalability can be achieved in three ways:</p><ul><li>Traditional scaling: switching to more a powerful machine with, for example, higher CPU and bigger RAM/SSD which can handle increased load:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ej7_1-Kwug0NGj8yRW1kEA.png" /></figure><ul><li>Creating virtual machines (VMs) and running the application by distributing its load across VMs. When the load reaches the limit, manually/automatically increases VMs and distributes the increased load:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gnh9vFl8iJesCDAFNU3GUQ.png" /></figure><ul><li>Each Virtual Machine has its own instance of an operating system, and you can run applications on it with access to memory, file systems, networking interfaces, and the other attributes. But flexibility comes with a cost. In this environment, the smallest unit of computing is a Virtual Machine. The guest OS may be large, even gigabytes in size. It can take minutes to boot up. Suppose your application is a big success. As demand for it increases, you have to scale out in units of an entire Virtual Machine with a guest operating system for each. That can mean your resource consumption grows faster than you like.<strong> Instead of getting a blank Virtual Machine, you should get access to a family of services that an application needs.</strong> Here come <strong>Containers with Kubernetes. </strong>You just<strong> </strong><a href="https://docs.docker.com/get-started/overview/">Containerise applications </a>and its dependencies with limited access to its own partition of the file system and hardware,<a href="https://docs.docker.com/get-started/overview/"> </a>and locate them on a VM and run in Kubernetes. There is only one operating system for all VMs and containers. If load increases, containers automatically(can also be manually) scales up and small VMs (suitable for the size of the containers) with the guest OS are created very fast and you just use only required resources:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hMMhJSJxSWSU3WAH1I32Bw.png" /></figure><p>Because of lower cost, much flexibility, and speed, the containerised deployment is often preferred. With the help of Kubernetes, we can orchestrate the running of containers and achieve scalability.</p><p>Example:</p><pre># Manually scaling your deployment<br>$ kubectl scale deployments/recorder-app --replicas=4</pre><pre>#Launching autoscale<br>$ kubectl autoscale deployment recorder-app --cpu-percent=50 --min=1 --max=10</pre><p><a href="https://jdsc.ai/recruit/">JDSC RECRUIT｜採用情報｜</a></p><p>本稿は「『隔週で丸1日 研究開発・勉強Day』の仕組みを利用してData ScientistがKubernetesを試してみた」の記事になります。</p><p><a href="https://jdsc.ai/recruit/benefit/">JDSC RECRUIT｜採用情報｜日本データサイエンス研究所</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=15b6edf08bd1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/jdsc-tech-blog/kubernetes-a-way-to-reliable-and-scalable-data-intensive-application-15b6edf08bd1">Kubernetes: A way to reliable and scalable data-intensive application</a> was originally published in <a href="https://medium.com/jdsc-tech-blog">JDSC Tech Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Multioutput CNN in PyTorch]]></title>
            <link>https://medium.com/jdsc-tech-blog/multioutput-cnn-in-pytorch-c5f702d4915f?source=rss-c8518b32c75e------2</link>
            <guid isPermaLink="false">https://medium.com/p/c5f702d4915f</guid>
            <category><![CDATA[pytorch]]></category>
            <dc:creator><![CDATA[ARSLANOV]]></dc:creator>
            <pubDate>Wed, 25 Mar 2020 07:14:13 GMT</pubDate>
            <atom:updated>2020-03-25T07:14:13.374Z</atom:updated>
            <content:encoded><![CDATA[<p>PyTorch is an open source deep learning research platform/package which utilises tensor operations like NumPy and uses the power of GPU. It was developed by Facebook’s AI research group and is now widely used for machine learning. In this article, I want to concentrate on Multioutput CNN (Convolutional Neural Network) analysis in PyTorch. There are many guidelines on how to use PyTorch for deep learning analysis. However, as far as I know, Multioutput CNN in PyTorch is one of the less mentioned topics and I want to fill this gap with this article.</p><p>This article has been published for non-commercial knowledge-sharing purposes and the content of this article belongs to the author only; they do not necessarily reflect the views of JDSC (Japan Data Science Consortium). The aligned and cropped images have been obtained from <a href="https://susanqq.github.io/UTKFace/">UTKFace</a>. The copyright belongs to the original owners. If any of the images belongs to you, please let the author know and the images will be removed from the article immediately.</p><p><strong>Note</strong>: this guide is primarily for data-scientists/data-engineers who have sufficient knowledge in PyTorch. If you do not have enough knowledge, you can learn PyTorch from <a href="https://pytorch.org/tutorials/">PyTorch.org</a> tutorials. Furthermore, I can recommend an excellent course in Coursera called “<a href="https://www.coursera.org/specializations/deep-learning?utm_source=gg&amp;utm_medium=sem&amp;utm_content=17-DeepLearning-ROW&amp;campaignid=6465471773&amp;adgroupid=76541762319&amp;device=c&amp;keyword=python%20neural%20network&amp;matchtype=b&amp;network=g&amp;devicemodel=&amp;adpostion=&amp;creativeid=379493352694&amp;hide_mobile_promo&amp;gclid=CjwKCAjwvOHzBRBoEiwA48i6AsPFIYJg0go_DV9eto9whtneI30LK5roeM3GCrYhdP8tEX94QjbBnhoCe4gQAvD_BwE">Deep Neural Networks in PyTorch</a>”.</p><h3><strong>Task description and Dataset overview</strong></h3><p>As for the dataset for the preceding analysis in PyTorch, imagine you have 2000 images of people (you can download these images from <a href="https://susanqq.github.io/UTKFace/">UTKFace</a>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/297/1*afwIlJR3pvfcKDBY4eCerw.png" /><figcaption>Figure 1. UTKFace dataset</figcaption></figure><p>In order to save space, these images have been digitalized and transferred to parquet file in the following form:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/451/1*19myLZDoCNGY-TxVN1rkcg.png" /><figcaption>Table 1. The first four samples from UTKFace dataset called ‘train_image.parquet’</figcaption></figure><p>Your task is to classify these images by finding gender, ethnicity and age of the people. In other words, your model should take one input (image) and produce multiple outputs (age, gender and ethnicity). Furthermore, for your model training, you have been given ‘train.csv’ which provides you with age, ethnicity and gender data for each image you have:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/692/1*5Gtd2zu6NidP2UpL-HP7RA.png" /><figcaption>Table 2. The first four samples for model training</figcaption></figure><p>where 1=male and 0=female in gender column. As for ethnicity, there are four groups: 1=European, 2=African, 3=Asian and 4=Other. You should merge these two datasets, train_image.parquet and train.csv, and conduct CNN analysis.</p><h3><strong>CNN analysis</strong></h3><h4>Importing libraries</h4><pre># General libraries<br>import pandas as pd  #For working with dataframes<br>import numpy as np   #For working with image arrays<br>import cv2          #For transforming image<br>import matplotlib.pyplot as plt  #For representation</pre><pre>#For model building<br>import torch<br>from torch import nn, optim<br>import torchvision<br>from torchvision import transforms, datasets, models, utils<br>from torch.utils.data import Dataset, DataLoader <br>from PIL import Image<br>from sklearn.model_selection import train_test_split<br>from torch.nn import functional as F<br>from skimage import io, transform<br>from torch.optim import lr_scheduler<br>from skimage.transform import AffineTransform, warp</pre><p>torch library is the main library for the PyTorch analysis. With the help of “<em>nn</em>”, we can build custom models and “optim” enables us to use Gradient Descent functions like <strong>Adam </strong>and <strong>SGD. </strong>With regards to the remaining libraries such as torchvision, PIL and skimage, we will use them for data transformations and building data loading pipelines.</p><h4><strong><em>Loading data using Dataset and DataLoader</em></strong></h4><p>torch.utils.data.Dataset and torch.utils.data.DataLoader enables you to import, transform your data and send this data to your model. In other words, you can build an excellent data pipeline with these two classes.</p><p>First, we start with creating Dataset class:</p><pre>class MyData(Dataset):<br>    def __init__(self, train=True, transform=None):<br>        #Loading train.csv<br>        train_df=pd.read_csv(&#39;train.csv&#39;)<br>        #Loading image data and merging with train.csv<br>        df=pd.merge(pd.read_parquet(&#39;image_train_data.parquet&#39;),\<br>        train_df, on=&#39;image_id&#39;).drop([&#39;image_id&#39;], axis=1)<br>        #Leaving only image related  columns<br>        feature=df.drop([&#39;age&#39;, &#39;gender&#39;, &#39;race&#39;], axis=1)<br>        #Setting labels<br>        label_age=df[&#39;age&#39;]<br>        label_gender=df[&#39;gender&#39;]<br>        label_race=df[&#39;race&#39;]<br>        #Splitting the data into train and validation set<br>        X_train, X_test, y_age_train, y_age_test, y_gender_train, y_gender_test, y_race_train,\<br>        y_race_test = train_test_split(feature, label_age, label_gender, label_race, test_size=0.2)<br>        <br>        if train==True:<br>            self.x=X_train<br>            self.age_y=y_age_train<br>            self.gender_y=y_gender_train<br>            self.race_y=y_race_train<br>        else:<br>            self.x=X_test<br>            self.age_y=y_age_test<br>            self.gender_y=y_gender_test<br>            self.race_y=y_race_test            <br>        <br>        #Applying transformation<br>        self.transform=transform<br>        <br>    def __len__(self):<br>        return len(self.x)<br>    <br>    def __getitem__(self, idx):<br>        image=np.array(self.x.iloc[idx, 0:]).astype(float).reshape(137, 236)<br>        label1=np.array([self.age_y.iloc[idx]]).astype(&#39;float&#39;)<br>        label2=np.array([self.gender_y.iloc[idx]]).astype(&#39;float&#39;)<br>        label3=np.array([self.race_y.iloc[idx]]).astype(&#39;float&#39;)<br>        <br>        sample={&#39;image&#39;: np.uint8(image), &#39;label_age&#39;: label1,\<br>                &#39;label_gender&#39;: label2,\<br>                &#39;label_race&#39;: label3}<br>        <br>        #Applying transformation<br>        if self.transform:<br>            sample=self.transform(sample)<br>            <br>        return sample</pre><p>In <strong>__init__ </strong>function of the class, firstly, you download and merge the datasets. Afterwards, you define labels and features of the dataset. For evaluating your model, you can also split into train and test (also called validation) data. Then, you switch to <strong>__len__ </strong>which returns the size of the dataset. Finally, you should develop <strong>__getitem__ </strong>function so that the function returns indexed data from dataset. These three functions are important part for Dataset class and you should never forget these functions!!!</p><p>Before switching to DataLoader, you should decide whether to use data transformation or not. Transforming data helps you decrease bias, increase accuracy as well as the data size and improve model performance. If you want to use data transformation, you can easily use the following classes:</p><ol><li><strong>Crop class:</strong></li></ol><pre>class crop(object):<br>    def __init__(self, resize_size):<br>        self.resize_size = resize_size<br>    def __call__(self, sample):<br>        image, label1, label2, label3 = sample[&#39;image&#39;],\<br>        sample[&#39;label_age&#39;], sample[&#39;label_gender&#39;], sample[&#39;label_race&#39;]<br>        _, thresh=cv2.threshold(image, 30, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)<br>        contours, _ = cv2.findContours(thresh,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)[-2:]<br>        <br>        idx=0<br>        ls_xmin=[]<br>        ls_ymin=[]<br>        ls_xmax=[]<br>        ls_ymax=[]<br>        <br>        for cnt in contours:<br>            idx+=1<br>            x,y,w,h = cv2.boundingRect(cnt)<br>            ls_xmin.append(x)<br>            ls_ymin.append(y)<br>            ls_xmax.append(x + w)<br>            ls_ymax.append(y + h)<br>        xmin = min(ls_xmin)<br>        ymin = min(ls_ymin)<br>        xmax = max(ls_xmax)<br>        ymax = max(ls_ymax)<br>        roi = image[ymin:ymax,xmin:xmax]    <br>        resized_image = cv2.resize(roi, (self.resize_size, self.resize_size),\<br>                                                             interpolation=cv2.INTER_AREA)<br>        sample={&#39;image&#39;: resized_image, &#39;label_age&#39;: label1, &#39;label_gender&#39;: label2,\<br>                &#39;label_race&#39;: label3}<br>        return sample</pre><p>With the help of above given “crop” class, you can transform you image by cropping it in the following way:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k0mWo0o1KcoJLZwzKKJ5mQ.png" /><figcaption>FIgure 2. Cropping image example</figcaption></figure><p>Cropping images helps your model concentrate more on important parts of the image and brings higher accuracy.</p><p><strong>2. Rotate image class:</strong></p><p>Second class rotates image and brings different types of data to your model. As a result, your model can see different types of images and this can also lead to higher accuracy.</p><pre>class rotate_image(object):<br>    def __call__(self, sample):<br>        image, label1, label2, label3 = sample[&#39;image&#39;],\<br>        sample[&#39;label_age&#39;], sample[&#39;label_gender&#39;], sample[&#39;label_race&#39;]<br>        min_scale = 0.8<br>        max_scale = 1.2<br>        sx = np.random.uniform(min_scale, max_scale)<br>        sy = np.random.uniform(min_scale, max_scale)<br>        # --- rotation ---<br>        max_rot_angle = 7<br>        rot_angle = np.random.uniform(-max_rot_angle, max_rot_angle) * np.pi / 180.<br>        # --- shear ---<br>        max_shear_angle = 10<br>        shear_angle = np.random.uniform(-max_shear_angle, max_shear_angle) * np.pi / 180.<br>        # --- translation ---<br>        max_translation = 4<br>        tx = np.random.randint(-max_translation, max_translation)<br>        ty = np.random.randint(-max_translation, max_translation)<br>        tform = AffineTransform(scale=(sx, sy), rotation=rot_angle, shear=shear_angle,<br>                            translation=(tx, ty))<br>        transformed_image = warp(image, tform)<br>        assert transformed_image.ndim == 2<br>        sample={&#39;image&#39;: resized_image, &#39;label_age&#39;: label1, &#39;label_gender&#39;: label2,\<br>                &#39;label_race&#39;: label3}<br>        return sample</pre><p><strong>3. Change to tensor class</strong></p><p>Tensors are building blocks of neural networks in PyTorch. For the neural network, the input <em>x</em> should be a tensor, the output <em>y </em>is a tensor, the network will be comprised of a set of parameters which are also tensors. Therefore, we should change all features and labels to tensor. We can achieve this by using following class:</p><pre>class RGB_ToTensor(object):<br>    def __call__(self, sample):<br>        image, label1, label2, label3 = sample[&#39;image&#39;],\<br>        sample[&#39;label_age&#39;], sample[&#39;label_gender&#39;], sample[&#39;label_race&#39;]<br>        <br>        image=torch.from_numpy(image).unsqueeze_(0).repeat(3, 1, 1)<br>        label1=torch.from_numpy(label1)<br>        label2=torch.from_numpy(label2)<br>        label3=torch.from_numpy(label3)<br>        <br>        return {&#39;image&#39;: image,<br>                &#39;label_age&#39;: label1,<br>                &#39;label_gender&#39;: label2,<br>                &#39;label_race&#39;: label3}</pre><p><strong>Note: although you do need to use other transformations, you have to use ‘RGB_ToTensor’ class since models in PyTorch can only be developed with tensors.</strong></p><p><strong>4. Normalization class</strong></p><pre>class Normalization(object):<br>    def __init__(self, mean, std):<br>        self.mean = mean.view(-1, 1, 1)<br>        self.std = std.view(-1, 1, 1)<br>    def __call__(self, sample):<br>        image, label1, label2, label3 = sample[&#39;image&#39;],\<br>        sample[&#39;label_age&#39;], sample[&#39;label_gender&#39;], sample[&#39;label_race&#39;]<br>        <br>        return {&#39;image&#39;: image,<br>                &#39;label_age&#39;: label1,<br>                &#39;label_gender&#39;: label2,<br>                &#39;label_race&#39;: label3}</pre><p>In PyTorch, transfer learning is widely used and this can significantly improve training time and accuracy. PyTorch has a page dedicated <a href="https://pytorch.org/docs/stable/torchvision/models.html">page</a> to transfer learning. We will learn how to develop model with transfer learning in later sections. For now, you should know that in order to use transfer learning and also to increase the speed of your model training, you should use above given Normalisation class.</p><p>After creating your transform functions, you can now easily use DataLoader to deliver your loaded, transformed data to your model:</p><pre>cnn_normalization_mean = torch.tensor([0.485, 0.456, 0.406])<br>cnn_normalization_std = torch.tensor([0.229, 0.224, 0.225])</pre><pre>transformed_train_data = MyData(train=True, transform=transforms.Compose([crop(256),\<br>                                            rotate_image(), RGB_ToTensor(),<br>                                            Normalization(cnn_normalization_mean,\<br>                                            cnn_normalization_std)]))</pre><pre>transformed_test_data = MyData(train=False, transform=transforms.Compose([crop(256),\<br>                                            RGB_ToTensor(),<br>                                            Normalization(cnn_normalization_mean,\<br>                                            cnn_normalization_std)]))</pre><pre>train_dataloader = DataLoader(transformed_train_data, batch_size=50, shuffle=True, num_workers=4)<br>test_dataloader = DataLoader(transformed_test_data, batch_size=50, shuffle=True, num_workers=4)</pre><p>Note that with the help of <a href="https://pytorch.org/docs/stable/torchvision/transforms.html">transforms.Compose</a>, we can easily compose our created functions. Furthermore, normalization numbers for mean and std have been chosen based on the <a href="https://pytorch.org/docs/stable/torchvision/models.html">guides</a> from PyTorch organization.</p><p><strong>Creating a Multioutput CNN model</strong></p><p>While building a model in PyTorch, you have two ways. First way is building your own custom model by using nn.Module or nn.Sequential. Second way is using nn.Module with pretrained models by just changing last layers of the pretrained model. The second option is mostly preferred in PyTorch community and therefore, I want to show the second option.</p><p>Before creating a model, we should import pretrainedmodels library:</p><pre>import pretrainedmodels</pre><p>Now, we create a multioutput CNN model by using resnet pretrained model:</p><pre>import pretrainedmodels<br>class CNN1(nn.Module):<br>    def __init__(self, pretrained):<br>        super(CNN1, self).__init__()<br>        if pretrained is True:<br>            self.model = pretrainedmodels.__dict__[&quot;resnet34&quot;](pretrained=&quot;imagenet&quot;)<br>        else:<br>            self.model = pretrainedmodels.__dict__[&quot;resnet34&quot;](pretrained=None)<br>        self.fc1 = nn.Linear(512, 100)  #For age class<br>        self.fc2 = nn.Linear(512, 2)    #For gender class<br>        self.fc3 = nn.Linear(512, 4)    #For race class<br>        <br>    def forward(self, x):<br>        bs, _, _, _ = x.shape<br>        x = self.model.features(x)<br>        x = F.adaptive_avg_pool2d(x, 1).reshape(bs, -1)<br>        label1 = self.fc1(x)<br>        label2= torch.sigmoid(self.fc2(x))  <br>        label3= self.fc3(x)<br>        return {&#39;label1&#39;: label1, &#39;label2&#39;: label2, &#39;label3&#39;: label3}</pre><p><strong>Using CUDA</strong></p><p>torch.cuda is used to set up and run CUDA operations. In other words, you can easily transfer your model and data to CUDA and increase the speed of training your model. This is one of the advantages of using PyTorch!! In order to use CUDA, you can easily type following code:</p><pre>device = torch.device(&quot;cuda:0&quot; if torch.cuda.is_available() else &quot;cpu&quot;)</pre><p>By using above code, you can define your device as the first visible CUDA device if you have CUDA available and load your model, data to this device. If you do not have access to GPU, the device will be automatically switched to CPU.</p><p><strong>Setting model and hyper-parameters</strong></p><p>After building model, we will set the model and move it to device we defined earlier. In this case, if GPU is available, the model will be moved to GPU, if not, the model stays at CPU.<br> We also set hyper-parameters. Note that we have defined two types of criterion: one for binary output (in the case of gender) and one for multilabel outputs.</p><pre>#Setting model and moving to device<br>model_CNN = CNN1(True).to(device)</pre><pre>#For binary output:gender<br>criterion_binary= nn.BCELoss()</pre><pre>#For multilabel output: race and age<br>criterion_multioutput = nn.CrossEntropyLoss()<br>optimizer = optim.SGD(model.parameters(), lr=0.001, momentum=0.9)</pre><p><strong>Creating training model function</strong></p><p>The last function is to training function. In building training function, you should be careful in setting criterion for each output.</p><pre>def train_model(model, criterion1, criterion2, optimizer, n_epochs=25):<br>    &quot;&quot;&quot;returns trained model&quot;&quot;&quot;<br>    # initialize tracker for minimum validation loss<br>    valid_loss_min = np.Inf<br>    for epoch in range(1, n_epochs):<br>        train_loss = 0.0<br>        valid_loss = 0.0<br>        # train the model #<br>        model.train()<br>        for batch_idx, sample_batched in enumerate(train_dataloader):<br>            # importing data and moving to GPU<br>            image, label1, label2, label3 = sample_batched[&#39;image&#39;].to(device),\<br>                                             sample_batched[&#39;label_age&#39;].to(device),\<br>                                              sample_batched[&#39;label_gender&#39;].to(device),\<br>                                               sample_batched[&#39;label_race&#39;].to(device)  <br>            # zero the parameter gradients<br>            optimizer.zero_grad()<br>            output=model(image)<br>            label1_hat=output[&#39;label1&#39;]<br>            label2_hat=output[&#39;label2&#39;]<br>            label3_hat=output[&#39;label3&#39;]         <br>            # calculate loss<br>            loss1=criterion1(label1_hat, label1.squeeze().type(torch.LongTensor))<br>            loss2=criterion2(label2_hat, label2.squeeze().type(torch.LongTensor))<br>            loss3=criterion1(label3_hat, label3.squeeze().type(torch.LongTensor))     <br>            loss=loss1+loss2+loss3<br>            # back prop<br>            loss.backward()<br>            # grad<br>            optimizer.step()<br>            train_loss = train_loss + ((1 / (batch_idx + 1)) * (loss.data - train_loss))<br>            if batch_idx % 50 == 0:<br>                print(&#39;Epoch %d, Batch %d loss: %.6f&#39; %<br>                  (epoch, batch_idx + 1, train_loss))<br>        # validate the model #<br>        model.eval()<br>        for batch_idx, sample_batched in enumerate(test_dataloader):<br>            image, label1, label2, label3 = sample_batched[&#39;image&#39;].to(device),\<br>                                             sample_batched[&#39;label_age&#39;].to(device),\<br>                                              sample_batched[&#39;label_gender&#39;].to(device),\<br>                                               sample_batched[&#39;label_race&#39;].to(device)  <br>            output = model(image)<br>            output=model(image)<br>            label1_hat=output[&#39;label1&#39;]<br>            label2_hat=output[&#39;label2&#39;]<br>            label3_hat=output[&#39;label3&#39;]               <br>            # calculate loss<br>            loss1=criterion1(label1_hat, label1.squeeze().type(torch.LongTensor))<br>            loss2=criterion2(label2_hat, label2.squeeze().type(torch.LongTensor))<br>            loss3=criterion1(label3_hat, label3.squeeze().type(torch.LongTensor))  <br>            loss=loss1+loss2+loss3<br>            valid_loss = valid_loss + ((1 / (batch_idx + 1)) * (loss.data - valid_loss))<br>        <br>        # print training/validation statistics <br>        print(&#39;Epoch: {} \tTraining Loss: {:.6f} \tValidation Loss: {:.6f}&#39;.format(<br>            epoch, train_loss, valid_loss))<br>        <br>        ## TODO: save the model if validation loss has decreased<br>        if valid_loss &lt; valid_loss_min:<br>            torch.save(model, &#39;model.pt&#39;)<br>            print(&#39;Validation loss decreased ({:.6f} --&gt; {:.6f}).  Saving model ...&#39;.format(<br>            valid_loss_min,<br>            valid_loss))<br>            valid_loss_min = valid_loss<br>    # return trained model<br>    return model</pre><h4>Training</h4><p>Finally, we train the model by using following code:</p><pre>model_conv=train_model(model_CNN, criterion_multioutput, criterion_binary, optimizer)</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c5f702d4915f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/jdsc-tech-blog/multioutput-cnn-in-pytorch-c5f702d4915f">Multioutput CNN in PyTorch</a> was originally published in <a href="https://medium.com/jdsc-tech-blog">JDSC Tech Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>