<?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 Ravi Teja Kandimalla on Medium]]></title>
        <description><![CDATA[Stories by Ravi Teja Kandimalla on Medium]]></description>
        <link>https://medium.com/@Ravitejakandimalla?source=rss-1b42a797764b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ebJ5UxtpX1UscB6FDdRrgg.jpeg</url>
            <title>Stories by Ravi Teja Kandimalla on Medium</title>
            <link>https://medium.com/@Ravitejakandimalla?source=rss-1b42a797764b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 20:10:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@Ravitejakandimalla/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[Left and Right Ventricle Segmentation from Cardiac MRI and Exploring Ejection Fraction]]></title>
            <link>https://medium.com/@Ravitejakandimalla/left-and-right-ventricle-segmentation-from-cardiac-mri-and-exploring-ejection-fraction-62deb6a7eaeb?source=rss-1b42a797764b------2</link>
            <guid isPermaLink="false">https://medium.com/p/62deb6a7eaeb</guid>
            <dc:creator><![CDATA[Ravi Teja Kandimalla]]></dc:creator>
            <pubDate>Mon, 01 May 2023 10:49:09 GMT</pubDate>
            <atom:updated>2023-05-01T10:56:10.699Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*UWIceDjt2TijMNYupGmIfw.png" /></figure><p>This article describes a<strong> Master’s program</strong> project aimed at developing a reliable method for segmenting the left and right ventricles in cardiac MRI images, with a focus on exploring the relationship between ventricular segmentation and ejection fraction. The project’s methodology and results are discussed, emphasizing the potential clinical applications of accurate ventricular segmentation and ejection fraction measurements for diagnosing and treating cardiovascular diseases.</p><h4>Abstract:-</h4><blockquote>This work focuses on segmenting the Left and Right ventricles in Magnetic Resonance Imaging (MRI) data and calculating Ejection Fraction (EF). A modified UNet model is used on publicly available datasets (ACDC, SCD, DSB) with data augmentation. Various techniques are used for EF calculation including ROI, Otsu’s method, Euclidean distance, and Simpson&#39;s method. Results show improved ventricle segmentation and EF calculation.</blockquote><h4><strong>Datasets:-</strong></h4><blockquote>ACDC: Automatic Cardiac Diagnosis Challenge. <a href="https://medium.com/@Ravitejakandimalla/cardiac-mri-publicly-available-datasets-70dde5621c87">Link</a></blockquote><blockquote>SCD: Sunnybrook Cardiac Data.<a href="https://medium.com/@Ravitejakandimalla/cardiac-mri-publicly-available-datasets-70dde5621c87">Link</a></blockquote><blockquote>DSB: Second Annual Data Science Bowl. <a href="https://medium.com/@Ravitejakandimalla/cardiac-mri-publicly-available-datasets-70dde5621c87">Link</a></blockquote><p>To start with Left Ventricle Segmentation, I have used customized U-Net architecture. And also a customized dataset that is a combination of both ACDC and SCB datasets.</p><h3>Left Ventricle Segmentation</h3><h4>Pre-Processing:-</h4><p>Preprocessing techniques used for training an image segmentation model. These include conversion of DICOM and NIfTI images and masks to .npy format, resizing to 250x200, identifying a threshold for LV, increasing model depth, applying regularization techniques such as batch normalization and dropout, increasing dataset size through data augmentation (horizontal and vertical flips, and rotations of 90°, 180°, and 270°). These techniques are aimed at improving the accuracy and generalization of the model.</p><h4>Pipeline for the Left Ventricle Segmentation:-</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*ne56chaZqoP8lDUEoxk2BA.png" /><figcaption>LV Segmentation</figcaption></figure><p>In general, the modifications to the U-Net architecture will depend on the specific characteristics of our data, such as the size and complexity of the images, the number of classes, and the level of detail required for accurate segmentation. It is often a trial-and-error process to find the optimal architecture for a given task, and the performance of the network can be evaluated using metrics such as accuracy, precision, and recall. So, I modified it accordingly.</p><pre>class UNet(nn.Module):<br>    def __init__(self, in_channels=1, out_channels=1, features=[64, 128, 256, 512]):<br>        super(UNet, self).__init__()<br>        self.ups = nn.ModuleList()<br>        self.downs = nn.ModuleList()<br>        self.pool = nn.MaxPool2d(kernel_size=2, stride=2)<br><br>        # down part of the network<br>        for feature in features:<br>            self.downs.append(DoubleConv(in_channels, feature))<br>            in_channels = feature<br>        <br>        # up part of the network<br>        for feature in reversed(features):<br>            self.ups.append(nn.ConvTranspose2d(feature*2, feature, kernel_size=2, stride=2)) # 1st one is a transposed conv<br>            self.ups.append(DoubleConv(feature*2, feature))                                  # 2nd one is a double conv<br>    <br>        self.bottleneck = DoubleConv(features[-1], features[-1]*2) # the bottommost layer<br>        self.final_conv = nn.Conv2d(features[0], out_channels, kernel_size=1) # last conv<br>    <br>    def forward(self, x):<br>        skip_connections = []<br>        downsample = []<br>        upsample = []<br>        up_skip_conv = []<br><br>        for down in self.downs:<br>            x = down(x)                # double conv<br>            skip_connections.append(x) # get skip connections from every step in the U<br><br>            x = self.pool(x)           # pooling layer to increase receptive field<br>            downsample.append(x)       # collecting feature maps for later &#39;down&#39;<br><br>        x = self.bottleneck(x) # bottommost conv<br>        skip_connections = skip_connections[::-1] # reversing the skip connections<br><br>        for index in range(0, len(self.ups), 2): # index step = 2<br>            x = self.ups[index](x)                                  # doing the upsampling<br>            upsample.append(x)                                      # collecting feature maps for later &#39;up&#39;<br><br>            skip_connection = skip_connections[index//2]            # gettng corressponding high res features<br><br>            if x.shape != skip_connection.shape:<br>                x = TF.resize(x, size=skip_connection.shape[2:])    # reshape for concat instead of crop<br><br>            concat_skip = torch.cat((skip_connection, x), dim=1)    # concat both high res and low res<br><br>            x = self.ups[index+1](concat_skip)                      # doing the double conv<br>            up_skip_conv.append(x)                                  # collecting feature maps for later &#39;up_skip&#39;<br>    <br>        x = self.final_conv(x)                                      # doing the final conv<br>        return {<br>            &#39;x&#39; : x,<br>            &#39;down&#39; : downsample,<br>            &#39;up&#39; : upsample,<br>            &#39;up_skip&#39; : up_skip_conv<br>            }</pre><h4>Results for LV Segmentation:-</h4><p>After preprocessing the data and training with the modified U-Net architecture, we got promising results with a dice loss of <strong>0.86. A</strong> sample of the left ventricle segmentation is shown below. LV segmentation trained with <strong>Activation Function</strong>: ReLU <strong>No.Of. Epochs: </strong>60 <strong>Batch Size</strong>: 32, model weights access link <strong>LVModel.pt</strong>. Left Ventricle Segmentation <strong>code</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CSgyhQmlf5RNn7HFQuHyPQ.jpeg" /><figcaption>Left Ventricle Segmentation Test Results</figcaption></figure><p>We also test the model with a third dataset that we have mentioned before i.e DSB dataset, and the results are shown below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*AYp2iyOl6FwM9AQUBz6iBQ.png" /><figcaption>Left Ventricle Segmentation for the DSB dataset</figcaption></figure><h3>Right Ventricle Segmentation</h3><p>For this task, we have used a different dataset that is DSB,</p><h4>Pre-Processing:-</h4><p>Preprocessing techniques used for training an image segmentation model. These include conversion of DICOM images and masks to .npy format, resizing to 250x200, identifying a threshold for LV, increasing model depth, applying regularization techniques such as batch normalization and dropout, increasing dataset size through data augmentation (horizontal and vertical flips, and rotations of 90°, 180°, and 270°).</p><pre>import os<br>import numpy as np<br><br>input_path = &#39;Input Path&#39;<br>save_path = &#39;Saving Path&#39;<br><br>def flip_horizontal(img):<br>    return np.fliplr(img)<br><br>def flip_vertical(img):<br>    return np.flipud(img)<br><br>def rotate(img, angle):<br>    return np.rot90(img, angle // 90)<br><br>transformations = {<br>    &#39;flip_horizontal&#39;: flip_horizontal,<br>    &#39;flip_vertical&#39;: flip_vertical,<br>    &#39;rotate_90&#39;: lambda img: rotate(img, 90),<br>    &#39;rotate_180&#39;: lambda img: rotate(img, 180),<br>    &#39;rotate_270&#39;: lambda img: rotate(img, 270) }<br><br>for filename in sorted(os.listdir(input_path)):<br>    img = np.load(os.path.join(input_path, filename))<br>    for transform_name, transform_func in transformations.items():<br>        transformed_img = transform_func(img)<br>        output_filename = f&#39;a_{os.path.splitext(filename)[0]}.npy&#39;<br>        np.save(os.path.join(save_path, output_filename), transformed_img)</pre><p>These techniques are aimed at improving the accuracy and generalization of the model. You can access the code here(Preprocessing).</p><h4>Pipeline for the Right Ventricle Segmentation:-</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*gcZKWKyt8XgtXOFLPnIObA.png" /><figcaption>Pipeline for the Right Ventricle Segmentation</figcaption></figure><h4>Results for RV Segmentation:-</h4><p>After preprocessing the data and training with the modified U-Net architecture, we got promising results with a dice loss of <strong>0.91. A</strong> sample of the left ventricle segmentation is shown below. <strong>Activation Function</strong>: ReLU <strong>No.Of. Epochs: 120</strong> <strong>Batch Size</strong>: 32.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RfHR5cLwOCUR_-Fib6xtmw.jpeg" /><figcaption>Right Ventricle Segmentation Test Results</figcaption></figure><h3><strong>Left Ventricle Ejection Fraction(LVEF)</strong></h3><p>This is the main part of my project, i.e. finding the Left Ventricle Ejection Fraction of a cardiac MRI. Each case in the dataset has an associated directory of DICOM files, which contain medical images of the heart. This dataset contains 500 cases of patients with various cardiac conditions, each case includes a set of DICOM-format, this dataset also provides the EDV and ESV labels for each case. And these labels are being used as ground truth for calculating Ejection Fraction. The structure of this dataset is shown below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*tK7JRbsSZMiET2WidQudYg.png" /><figcaption>Structure of the DSB dataset</figcaption></figure><p>LVEF is calculated by dividing the volume of blood pumped out of the left ventricle during systole (the phase of the heartbeat when the heart contracts) by the total volume of blood in the left ventricle at the end of diastole (the phase of the heartbeat when the heart is relaxed). The resulting number is multiplied by 100 to express the value as a percentage. The most common method to measure LVEF is echocardiography, which uses ultrasound waves to create images of the heart and measure the volumes of blood in the ventricles. Other methods include cardiac MRI and radionuclide imaging.</p><p>A normal LVEF is typically between 55% and 70%, meaning that the heart is able to pump out more than half of the blood it contains with each contraction. A reduced LVEF, which can be caused by various heart conditions, can lead to symptoms such as shortness of breath, fatigue, and fluid buildup in the lungs and other tissues.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/685/1*GKkC0XsBYcv3dRrEZSstMQ.png" /><figcaption>Calculation of Ejection Fraction</figcaption></figure><h4>DICOM METADATA</h4><p>DICOM (Digital Imaging and Communications in Medicine) is the standard file format used in medical imaging to store and transmit medical images and associated metadata between different systems. The header contains metadata fields, such as patient information. These fields are identified by tags, which are 16-bit numbers that uniquely identify each field (e.g., slice thickness, repetition time, and echo time). In our case, the DICOM header associated with an MR (magnetic resonance) image of the heart, was acquired using a <strong>Siemens Aera scanner</strong>. A sample of DICOM metadata is shown below.</p><pre>Dataset.file_meta -------------------------------<br>(0002, 0000) File Meta Information Group Length  UL: 216<br>(0002, 0001) File Meta Information Version       OB: b&#39;\x00\x01&#39;<br>(0002, 0002) Media Storage SOP Class UID         UI: MR Image Storage<br>(0002, 0003) Media Storage SOP Instance UID      UI: 1.3.6.1.4.1.9590.100.1.2.231756554710568080224097754881739649795<br>(0002, 0010) Transfer Syntax UID                 UI: Explicit VR Little Endian<br>(0002, 0012) Implementation Class UID            UI: 1.2.276.0.7230010.3.0.3.6.0<br>(0002, 0013) Implementation Version Name         SH: &#39;OFFIS_DCMTK_360&#39;<br>(0002, 0016) Source Application Entity Title     AE: &#39;&#39;<br>-------------------------------------------------<br>(0008, 0005) Specific Character Set              CS: &#39;ISO_IR 100&#39;<br>(0008, 0008) Image Type                          CS: [&#39;ORIGINAL&#39;, &#39;PRIMARY&#39;, &#39;M&#39;, &#39;RETRO&#39;, &#39;NORM&#39;, &#39;DIS2D&#39;]<br>(0008, 0013) Instance Creation Time              TM: &#39;155319.703000&#39;<br>(0008, 0016) SOP Class UID                       UI: MR Image Storage<br>(0008, 0018) SOP Instance UID                    UI: 1.3.6.1.4.1.9590.100.1.2.231756554710568080224097754881739649795<br>(0008, 0030) Study Time                          TM: &#39;154024.812000&#39;<br>(0008, 0031) Series Time                         TM: &#39;155319&#39;<br>(0008, 0032) Acquisition Time                    TM: &#39;155312.072500&#39;<br>(0008, 0060) Modality                            CS: &#39;MR&#39;<br>(0008, 0070) Manufacturer                        LO: &#39;SIEMENS&#39;<br>(0008, 103e) Series Description                  LO: &#39;sax&#39;<br>(0008, 1090) Manufacturer&#39;s Model Name           LO: &#39;Aera&#39;<br>(0008, 1140)  Referenced Image Sequence  3 item(s) ---- <br>   (0008, 1150) Referenced SOP Class UID            UI: MR Image Storage<br>   ---------<br>   (0008, 1150) Referenced SOP Class UID            UI: MR Image Storage<br>   ---------<br>   (0008, 1150) Referenced SOP Class UID            UI: MR Image Storage<br>   ---------<br>(0010, 0010) Patient&#39;s Name                      PN: &#39;NDSB_2&#39;<br>(0010, 0020) Patient ID                          LO: &#39;2&#39;<br>(0010, 0030) Patient&#39;s Birth Date                DA: &#39;19000101&#39;<br>(0010, 0040) Patient&#39;s Sex                       CS: &#39;M&#39;<br>(0010, 1010) Patient&#39;s Age                       AS: &#39;059Y&#39;<br>(0010, 1040) Patient&#39;s Address                   LO: &#39;&#39;<br>(0010, 2154) Patient&#39;s Telephone Numbers         SH: &#39;&#39;<br>(0018, 0015) Body Part Examined                  CS: &#39;HEART&#39;<br>(0018, 0020) Scanning Sequence                   CS: &#39;GR&#39;<br>(0018, 0021) Sequence Variant                    CS: [&#39;SK&#39;, &#39;SS&#39;]</pre><p>DICOM attributes are written row by row, and their metadata structure is similar to a dictionary, with each attribute having a unique tag for accessing it. The DICOM standard defines a unique tag for each attribute, which is a 32-bit value that is used to identify the attribute in the DICOM file.</p><h4>PYDICOM</h4><p>With PyDicom, you can easily read and write DICOM files, extract and manipulate metadata, and perform a range of other tasks related to medical imaging. Pydicom is a widely used open-source Python library for working with DICOM files. DICOM is a standard for storing, transmitting, and retrieving medical images and related information. Pydicom allows users to read, modify and write DICOM files in Python. With Pydicom, we can extract various metadata elements from DICOM files, such as the patient’s name, age, gender, imaging modality, acquisition parameters, and image pixel data. We can also modify or add metadata elements to the DICOM files.</p><p>In summary, DICOM is a standard for managing medical images and related data, with DICOM files containing both image data and metadata describing the image. DICOM attributes are accessed using unique tags, and PyDicom is a popular Python library used for working with DICOM files.</p><h4>ROI(Region Of Interest)</h4><p>In the context of cardiac MRI segmentation, ROI (Region of Interest) can be used to crop the image around the left ventricle, which is the area of interest. By focusing on this specific region of the image, it becomes easier to segment and identify the left ventricle, which is important for diagnosing and treating heart diseases. And we are using this concept to identify the left ventricle for a given cardiac MRI slice and the sample shown below.</p><pre>def crop_roi(img, dim_y, dim_x, cy, cx):<br>    cy, cx = int(round(cy)), int(round(cx))<br>    h, w = img.shape<br>    if dim_x &gt; w or dim_y &gt; h: raise ValueError(&#39;Crop dimensions larger than image dimension!&#39;)<br>    new_img = np.zeros((dim_y, dim_x))<br>    dx, dy = int(dim_x / 2), int(dim_y / 2)<br>    dx_odd, dy_odd = int(dim_x % 2 == 1), int(dim_y % 2 == 1)<br><br>    # Find boundaries for cropping [original img]<br>    dx_left = max(0, cx - dx)<br>    dx_right = min(w, cx + dx + dx_odd)<br>    dy_up = max(0, cy - dy)<br>    dy_down = min(h, cy + dy + dy_odd)<br><br>    # Find how many pixels to fill out in new image<br>    range_x = dx_right - dx_left<br>    range_y = dy_down - dy_up<br><br>    # Fill out new image from top left corner<br>    # Leave pixels outside range as 0&#39;s (black)<br>    new_img[0:range_y, 0:range_x] = img[dy_up:dy_down, dx_left:dx_right]<br>    return new_img</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/496/1*XSB72jHClhT5aBV2WT9e0g.png" /><figcaption>ROI Of Left Ventricle of Cardiac MRI slice</figcaption></figure><h4><strong>Otsu’s Thresholding</strong></h4><p>Otsu’s thresholding is an image thresholding technique used to automatically determine the optimal threshold value for image segmentation, separating foreground pixels from background pixels in an image. It assumes that the image contains only two classes of pixels — foreground and background — and works by computing a histogram of pixel intensities in the input image and then computing the variance between the two classes of pixels for every possible threshold value. The threshold that maximizes the between-class variance is then selected as the optimal threshold. Otsu’s thresholding is particularly useful in cases where the histogram of pixel intensities in an image is bimodal, and it can be implemented in various programming languages, including Python. thanks to <a href="https://medium.com/u/9bd50b3399d2">HBY coding academic</a> for providing such a beautiful article on Otsu’s method here you get the link to access the article(<a href="https://hbyacademic.medium.com/otsu-thresholding-4337710dc519">link</a>).</p><p>Steps to follow in Otsu’s method</p><blockquote>Process the input image.</blockquote><blockquote>Obtain image histogram (distribution of pixels).</blockquote><blockquote>Compute the threshold value, T.</blockquote><blockquote>Replace image pixels into the foreground (&gt;T white) and into the background (&lt;T black).</blockquote><p>code snippet of Otsu’s thresholding</p><pre>def thresh_segmentation(patient_img):<br>    thresh = threshold_otsu(patient_img)<br>    binary = patient_img &gt; thresh<br>    return binary</pre><h4>DATA FLOW</h4><p>First, we will take the patient’s 4D medical images as input and apply a series of preprocessing steps to prepare the images for further analysis. First, the images are rescaled to a standard size. Then, we go with histogram normalization performed in order to normalize the intensity values of the images to enhance contrast. Next, we crop the heart region from the rest of the body based on a specified heart pixel size. The images are then rotated to a standard orientation, and then we will find the left ventricle from the images and obtain labels for further analysis. Finally, segment the left ventricle 4D images for further analysis. This is the complete data flow in this process of calculating the EF.</p><pre>def preprocess_pipeline(patient, heart_pixel_size=150):<br>    rescaled_imgs = rescale_patient_4d_imgs(patient)<br>    normalized_imgs = histogram_normalize_4d(rescaled_imgs)<br>    cropped_imgs = crop_heart(normalized_imgs, heart_pixel_size=heart_pixel_size)<br>    rotated_images = rotate_images_210_deg(cropped_imgs, patient.orientation)<br>    segmented_left_ventricle_4d, labels = find_left_ventricle(rotated_images)<br>    return segmented_left_ventricle_4d</pre><h3>Volume calculation</h3><p>MRI scan images of a patient’s heart are loaded and processed. The images are rescaled, normalized, and cropped to focus on the heart area. If required, the images are also rotated to a common orientation. The left ventricle is then segmented in each image to create a 4D image volume of the left ventricle over time. The volume of the left ventricle in each time frame is calculated by summing the number of pixels that belong to the left ventricle and multiplying by the area of each pixel. The volumes of all slices are then summed up to obtain the total volume of the left ventricle at that time step. The minimum and maximum volumes are considered the end-systolic and end-diastolic volumes, respectively.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*NRoA4CECGkRCqXx5jzuiYQ.png" /><figcaption>Left Ventricle Volume Calculation</figcaption></figure><pre>def volume_for_patient(patient_images, slice_dist):<br>    num_slices, time, height, width = patient_images.shape<br>    volume = np.zeros((time))<br>    <br>    if slice_dist == 0:<br>        slice_dist = 10<br>    <br>    for i in range(time):<br>        time_volume = 0<br>        for j in range(num_slices):<br>            xy_size = np.sum(patient_images[j,i])<br>            time_volume = time_volume + xy_size * slice_dist<br>            <br>        # Volume in ml instead of mm^3<br>        volume[i] = time_volume/1000<br>    return volume </pre><h4>Results</h4><p>Simpson’s method to calculate the ejection fraction. This method uses the formula <strong>EF = ((LVEDV — LVESV) / LVEDV) x 100%</strong> to find the volumes of all the sax folders of each patient, now we consider the minimum and maximum volumes as ESV and EDV in each patient. The predicted EDV and ESV compared with ground truth and the relationship between the original and predicted volumes are shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zi75x8xrW-O7kZOl9Hg9eQ.png" /><figcaption>Calculated Volume vs original Volumes of End Diastole</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hHc4qs3J4EFre4FLKojKtQ.png" /><figcaption>Calculated Volume vs original Volumes of End Systole</figcaption></figure><p>We can see that clearly there is a Linear relation between the predicted and original volumes of both EDV and ESV, now we can find the Ejection Fraction of a left ventricle using these volumes. We finally send these two parameters EDV and ESV to a linear model to predict the ejection fraction and these results are shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SrxodbVAdzS6WoUNQNY0NQ.png" /><figcaption>Sample of 50 patients with <strong>R-squared</strong>:- 0.8972345712374354</figcaption></figure><p>This is how we can calculate the ejection fraction of a given cardiac MRI using a mathematical approach and deep learning models. If we look at all the 500 patients.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/609/1*gGn9Jmk-cRSmvO5YS0XeuA.png" /><figcaption>Ejection Fraction Predicted vs Original</figcaption></figure><p>It’s time to test the model with unseen data</p><pre>import pandas as pd<br>from sklearn.linear_model import LinearRegression<br>from sklearn.metrics import mean_squared_error, r2_score<br><br>data = &quot;Load the data&quot;<br><br># Split the data into training and testing sets<br>X_train = data[[&#39;Systole&#39;, &#39;Diastole&#39;]]<br>y_train = data[&#39;EF&#39;]<br><br>model = LinearRegression()<br><br>model.fit(X_train, y_train)<br><br># Predict the EF for new data<br>X_new = [[120.0, 80.0], [140.0, 90.0], [118.466460, 284.517899]]<br>y_pred = model.predict(X_new)<br><br># Calculate mean squared error<br>mse = mean_squared_error(y_train, model.predict(X_train))<br><br># Calculate R squared<br>r2 = r2_score(y_train, model.predict(X_train))<br><br># Print the predicted EF values, MSE, and R squared<br>print(&quot;Actual EDV and ESV values: &quot;, X_new)<br>print(&quot;Predicted EF values: &quot;, y_pred)<br>print(&quot;Mean squared error: &quot;, mse)<br>print(&quot;R squared: &quot;, r2)</pre><p>The output of this code snippet in my case is</p><pre>Actual EDV and ESV values:  [[120.0, 80.0], [140.0, 90.0], [118.46646, 284.517899]]<br>Predicted EF values:  [23.12595642 16.64664529 60.54729254]<br>Mean squared error:  21.698113219076127<br>R squared:  0.8172345712374354</pre><h3>Pipeline to calculate the Ejection Fraction</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*x7ZgU6g4pgzSRF-kTCZX-A.png" /><figcaption>Ejection Fraction Calculation</figcaption></figure><h4>Conclusion</h4><p>This project aimed to segment the left and right ventricles of cardiac MRI images and explore the ejection fraction using modified Unet architecture and data augmentations. The results showed promising accuracy in both ventricle segmentation and ejection fraction calculation, demonstrating the potential of deep learning and image analysis techniques in medical diagnosis.</p><h4>File Links</h4><p>Left Ventricle Segmentation — <a href="https://www.kaggle.com/code/ravitejakandimalla/left-ventricle-volume-of-cardiac-mri">link</a></p><p>Right Ventricle Segmentation — <a href="https://www.kaggle.com/code/ravitejakandimalla/cardiac-mri-right-ventricle-segmentation">link</a></p><p>Ejection Fraction Calculation — <a href="https://www.kaggle.com/code/ravitejakandimalla/ravi-teja-kandimalla">link</a></p><p>Preprocessing Files — link</p><p>Project Dissertation — <a href="https://docs.google.com/document/d/16t_700BZBbd5nw6bY7pwiseVrvO2Wu4FBRRKX_LDAPo/edit?usp=sharing">link</a></p><p>Project Slide-share — <a href="https://docs.google.com/presentation/d/1oZ2UvVGx6w6tPC6Xt10gfYzKhBmb3acW987_-YNhZU8/edit?usp=sharing">link</a></p><h3><strong>Acknowledgments</strong></h3><p>Firstly, I offer my gratitude to the one, who selected me for this project and shows the path to move forward. To him, I offer myself and this work at his lotus feet.</p><p>I would like to express my gratitude to <strong>Sri Bhaskaran sir</strong>, Department of Mathematics and Computer Science, Sri Sathya Sai Institute of Higher Learning, and <strong>Sri Krishnan Sir</strong>, CEO, Empathic Designs, LLC | Fremont, CA 94538 USA and Clinical Research Fellow (Volunteer), Department of Cardiology, SSSIHMS Whitefield for their confidence in me and for being such supportive supervisors.</p><p>I thank my friends <a href="https://medium.com/u/cc666ef5c031">Parth Maheshwari</a> <a href="https://medium.com/u/23a1a2a94bfd">Jammikunal</a> <a href="https://medium.com/u/60d9e55666d7">Mrinal Kanti Saha</a> <a href="https://medium.com/u/24c8d452e4c7">Akashbairagi</a> <a href="https://medium.com/u/7933b27118dc">Balu Niranjan</a> <a href="https://medium.com/u/9398bf167a39">Deepm-Rai</a> <a href="https://medium.com/u/a6a7aaa9fc6c">Saikrishna Balaji</a> <a href="https://medium.com/u/38dbcc69b4ff">Sai Nithish</a> @Narendrakumar Reddy @srihari <a href="https://medium.com/u/bb4c13fbdf87">Sainath</a> for being with me and supporting me throughout the project period</p><p>I thank Brother Vigneshwaran and Brother Sameer for providing valuable input and motivation.</p><h3><strong>References:-</strong></h3><p><strong>[1]</strong> O. Bernard et al., “Deep Learning Techniques for Automatic MRI Cardiac Multi-Structures Segmentation and Diagnosis: Is the Problem Solved?,” in IEEE Transactions on Medical Imaging, vol. 37, no. 11, pp. 2514–2525, Nov. 2018, doi: 10.1109/TMI.2018.2837502.</p><p><strong>[2]</strong> Banerjee, Tirthankar. “Automatic Segmentation of MRI Images — Tirthankar Banerjee.”<em>Medium</em>,21Feb.2019,https://medium.com/@tirthankar.banerjee/automatic-segmentation-of-MRI-images-2629eaf94071.</p><p><strong>[3]</strong>Yee,Chuck-Hou.<em>CardiacMRISegmentation</em>.https://chuckyee.github.io/cardiac-segmentaon/. Accessed 18 Apr. 2023.</p><p><strong>[4]</strong> “NPTEL :: Computer Science and Engineering.” <em>NOC: Deep Learning for Computer Vision</em>, <a href="https://archive.nptel.ac.in/courses/106/106/106106224/">https://archive.nptel.ac.in/courses/106/106/106106224/.</a> Accessed 18 Apr. 2023.</p><p><strong>[5]</strong> “Cardiac Segmentation With Strong Anatomical Guarantees.” <em>IEEE Xplore</em>, <a href="https://ieeexplore.ieee.org/abstract/document/9119450.">https://ieeexplore.ieee.org/abstract/document/9119450.</a> Accessed 18 Apr. 2023.</p><p><strong>[6]</strong> “Deep Learning Techniques for Automatic MRI Cardiac Multi-Structures Segmentation and Diagnosis: Is the Problem Solved?” <em>IEEE Xplore</em>, <a href="https://ieeexplore.ieee.org/document/8360453.">https://ieeexplore.ieee.org/document/8360453.</a> Accessed 18 Apr. 2023.</p><p><strong>[7]</strong> Alkousa, Omar. “Introducing PyDicom, Its Classes, Methods, and Attributes.” <em>Towards DataScience</em>,4Jan.2023,https://towardsdatascience.com/introducing-pydicom-its-classes-methods-and-attributes-518c1d71162.</p><p><strong>[8] </strong>Morsy, Yusif. “Read DICOM in Python — Yusif Morsy.” <em>Medium</em>, 14 Oct. 2020, <a href="https://yusifmorsy.medium.com/read-dicom-in-python-99a1a2220418.">https://yusifmorsy.medium.com/read-dicom-in-python-99a1a2220418.</a></p><p><strong>[9]</strong>“Second-Annual-Data-Science-Bowl.”<em>Kaggle</em>,https://www.kaggle.com/c/second-annual-data-science-bowl. Accessed 18 Apr. 2023.</p><p><strong>[10]</strong><em>Sunnybrook-Cardiac-Data–Cardiac_Atlas_Project</em>.https://www.cardiacatlas.org/sunnybrook-cardiac-data/. Accessed 18 Apr. 2023.</p><p><strong>[11]</strong> academic, HBY coding. “Otsu Thresholding — Image Binarization — HBY Coding Academic.”<em>Medium</em>,8May2021,https://hbyacademic.medium.com/otsu-thresholding-4337710dc519.</p><p><strong>[12] </strong>Shaaf, Zakarya Farea, et al. “Automatic Left Ventricle Segmentation from Short-Axis Cardiac MRI Images Based on Fully Convolutional Neural Network.” Diagnostics, vol. 12, no. 2, Feb. 2022, doi:10.3390/diagnostics12020414.</p><p><strong>[13] </strong><em>GitHub</em>, <a href="https://github.com/albumentations-team/albumentations.">https://github.com/albumentations-team/albumentations.</a> Accessed 18 Apr. 2023.</p><p><strong>[14]</strong> Zhang, Jeremy. “UNet — Line by Line Explanation.” <em>Towards Data Science</em>, 18 Oct. 2019, <a href="https://towardsdatascience.com/unet-line-by-line-explanation-9b191c76baf5.">https://towardsdatascience.com/unet-line-by-line-explanation-9b191c76baf5.</a></p><p><strong>[15] </strong>Du, Shuchen. “Understanding Dice Loss for Crisp Boundary Detection.” AI Salon, 30July2022,<a href="https://medium.com/ai-salon/understanding-dice-loss-for-crisp-boundary-detection-bb30c2e5f62b">https://medium.com/ai-salon/understanding-dice-loss-for-crisp-boundary-detection-bb30c2e5f62b</a>.</p><p><strong>[16]</strong>“ACDC_vol_1.”<em>Kaggle</em>,https://www.kaggle.com/code/ravitejakandimalla/acdc-vol-1/edit. Accessed 18 Apr. 2023.</p><p>Thanks for reading, have a nice day🙂.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=62deb6a7eaeb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[If your Unet model not segmenting well, then try these…]]></title>
            <link>https://medium.com/@Ravitejakandimalla/if-your-unet-model-not-segmenting-well-then-try-these-e1ed9a19ba12?source=rss-1b42a797764b------2</link>
            <guid isPermaLink="false">https://medium.com/p/e1ed9a19ba12</guid>
            <dc:creator><![CDATA[Ravi Teja Kandimalla]]></dc:creator>
            <pubDate>Fri, 24 Mar 2023 09:32:29 GMT</pubDate>
            <atom:updated>2023-03-24T09:37:07.636Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lvXoKMHoPJMKpKK7keZMEA.png" /><figcaption><a href="https://www.google.com/search?q=unet&amp;tbm=isch&amp;ved=2ahUKEwjcgZ6nlPT9AhVm73MBHU8oDu4Q2-cCegQIABAA&amp;oq=unet&amp;gs_lcp=CgNpbWcQAzIECCMQJzIHCAAQigUQQzIHCAAQigUQQzIFCAAQgAQyBQgAEIAEMgUIABCABDIFCAAQgAQyBQgAEIAEMgUIABCABDIFCAAQgAQ6CAgAEIAEELEDOgQIABADOggIABCxAxCDAToKCAAQigUQsQMQQ1DZCljzDmCqEGgAcAB4AIABa4gB6AOSAQMzLjKYAQCgAQGqAQtnd3Mtd2l6LWltZ8ABAQ&amp;sclient=img&amp;ei=tWAdZJzTFubez7sPz9C48A4&amp;bih=911&amp;biw=1866#imgrc=K-wr6kKnRJ4HPM"><strong>Source</strong></a></figcaption></figure><p>Overview of Unet architect</p><p>U-Net is used in many image segmentation tasks for biomedical images. And U-Net has elegant architecture, the expansive path is more or less symmetric, and yields a u-shaped architecture.</p><p>Look like a typical CNN architecture, by consecutive stacking two 3x3 convolutions followed by a 2x2 max pooling for downsampling. At each downsampling step, the number of channels is doubled. And this generally knows as <strong>downsampling</strong>. On the other side, we have upsampling as well i.e A 2x2 up-convolution for upsampling and two 3x3 convolutions. At each upsampling step, the number of channels is halved. After each 2x2 up-convolution, a concatenation of feature maps with corresponding layers from the contracting path, provides localization information from the contraction path to the expansion path, due to the loss of border pixels in every convolution.</p><p><strong>Final layer<br></strong>A 1x1 convolution to map the feature map to the desired number of classes.</p><p>Now let&#39;s see how can we improve the performance of the model, to do so we have a few things one must try with Unet for better results. I have tried these techniques in my MSc final year project i.e Cardiac MRI Left Ventricle segmentation. I will show the results as well.</p><h4>1. Loss function:-</h4><p>Use an appropriate loss function for your task. The most common loss function for image segmentation is the Dice coefficient loss or Jaccard loss, which <em>measures the overlap between the predicted and ground truth segmentation masks.</em></p><h4>2. Data Augmentation:-</h4><p>Generally, we will have a small amount of data in our hands when we are working in the medical domain. Augmenting your data is a common technique used to increase the size of the training dataset and prevent overfitting. You can use techniques such as random rotations, flips, zooms, and shifts.</p><h4>3. Early stopping:-</h4><p>Use early stopping to prevent overfitting. Early stopping involves stopping the training process once the performance of the model on a validation set starts to degrade.</p><h4>4. Optimizer:-</h4><p>Experiment with different optimizers such as Adam, SGD, or RMSprop to find the one that works best for your task.</p><h4>5. Architecture modifications:-</h4><p>Experiment with modifying the U-Net architecture by adding or removing layers or changing the number of filters in each layer to improve the performance of the model.</p><p>Before using these techniques model performance in segmenting the Left ventricle of a cardiac MRI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/668/1*lKWNEPL9oj31v-Y7t2Xt9Q.png" /><figcaption>Series of Left ventricle segmentation of a Cardiac MRI</figcaption></figure><p>Changes in the model</p><blockquote>I have used the DICE LOSS function.</blockquote><blockquote>Basically, I have very fewer data so I tried three types of agumentations.</blockquote><blockquote>Optimizer that I have used is Adam.</blockquote><blockquote>I have added one more layer to the original architecture.</blockquote><p>Results are like</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/663/1*66iHqeYL2SmZzKcyEsYc1Q.png" /><figcaption>Series of Left ventricle segmentation of a Cardiac MRI</figcaption></figure><p>Thanks for reading this article, hope you find it useful…🙂</p><h3>References:-</h3><p><a href="https://neptune.ai/blog/image-segmentation-tips-and-tricks-from-kaggle-competitions">https://neptune.ai/blog/image-segmentation-tips-and-tricks-from-kaggle-competitions</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e1ed9a19ba12" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Variational Autoencoder vs PCA(PyTorch)]]></title>
            <link>https://medium.com/@Ravitejakandimalla/variational-autoencoder-vs-pca-pytorch-3469e7ad12a1?source=rss-1b42a797764b------2</link>
            <guid isPermaLink="false">https://medium.com/p/3469e7ad12a1</guid>
            <dc:creator><![CDATA[Ravi Teja Kandimalla]]></dc:creator>
            <pubDate>Tue, 14 Mar 2023 06:35:51 GMT</pubDate>
            <atom:updated>2023-03-14T06:35:51.951Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4_yz9RA9I_qyU5we.png" /></figure><p>In this article, we will see two types of dimensionality reduction for tabular data: PCA and Autoencoders. And we will use PyTorch and will create the PCA with 3- dimensions. Usually, VAs are used for Image processing and creating new data like GANS Models. However, we can adapt this approach to use it on tabular data. This way the VAs helps us reduce the dimensionality of data and also reduce noise.</p><p>Let’s get started with the dataset, and link to the dataset <a href="https://archive.ics.uci.edu/ml/datasets/Wine">wine uci</a>.</p><p>A quick review of the data…</p><pre>DATA_PATH = &#39;./Wine.csv&#39;<br>pd.read_csv(DATA_PATH, sep=&#39;,&#39;, header=None, <br>            names=[&#39;Wine&#39;, &#39;Mg&#39;, &#39;Phenols&#39;, &#39;Flavanoids&#39;,&#39;Nonflavanoid.phenols&#39;,<br>                   &#39;Proanth&#39;,&#39;Color.int&#39;,&#39;Hue&#39;, &#39;OD&#39;,&#39;Proline&#39;]).head()<br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/817/1*3kovewitX3zJ34e7L_Bkgg.png" /></figure><p>Defining the required functions</p><pre>def load_data(path):<br>    df = df.fillna(-99) # replace nan with -99<br>    df_base = df.iloc[:, 1:]<br>    df_wine = df.iloc[:,0].values# get wine Label<br>    x = df_base.values.reshape(-1, df_base.shape[1]).astype(&#39;float32&#39;)<br>    standardizer = preprocessing.StandardScaler() # stadardize values<br>    x = standardizer.fit_transform(x)    <br>    return x, standardizer, df_wine # 3- Dimensions<br><br>def numpyToTensor(x):<br>    x_train = torch.from_numpy(x).to(device)<br>    return x_train</pre><p>Now we will call the load_data function to create the 3 - dimensions of the data and create the data frame with those principal components(1,2,3).</p><pre>x_pca, standardizer, df_wine = load_data(DATA_PATH)<br><br>pca = PCA(n_components=3)<br>principalComponents = pca.fit_transform(x_pca)<br>principalDf = pd.DataFrame(data = principalComponents,<br>             columns = [&#39;principal component 1&#39;, &#39;principal component 2&#39;, &#39;principal component 3&#39;])<br><br>finalDf = pd.concat([principalDf, pd.DataFrame(df_wine, columns = [&#39;wine&#39;])], axis = 1)<br>finalDf.head()</pre><p>And the output of the data frame is</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/482/1*-rwQALxXFG1nVhYx1FYpkA.png" /></figure><p>Now we will start with PyTorch Autoencoder, building the data loader, and model to train.</p><pre>class DataBuilder(Dataset):<br>    def __init__(self, path):<br>        self.x, self.standardizer, self.wine = load_data(DATA_PATH)<br>        self.x = numpyToTensor(self.x)<br>        self.len=self.x.shape[0]<br>    def __getitem__(self,index):      <br>        return self.x[index]<br>    def __len__(self):<br>        return self.len<br> <br>data_set=DataBuilder(DATA_PATH)<br>trainloader=DataLoader(dataset=data_set,batch_size=1024)</pre><p>batch size is 1024 and the train loader type will be tensor, now will start with building the model i.e Autoencoder.</p><pre>class Autoencoder(nn.Module):<br>    def __init__(self,D_in,H=50,H2=12,latent_dim=3):<br>        <br>        #Encoder<br>        super(Autoencoder,self).__init__()<br>        self.linear1=nn.Linear(D_in,H)<br>        self.lin_bn1 = nn.BatchNorm1d(num_features=H)# Batch normalization<br>        self.linear2=nn.Linear(H,H2)<br>        self.lin_bn2 = nn.BatchNorm1d(num_features=H2)# Batch normalization<br>        self.linear3=nn.Linear(H2,H2)<br>        self.lin_bn3 = nn.BatchNorm1d(num_features=H2)# Batch normalization<br>        # Latent vectors mu and sigma<br>        self.fc1 = nn.Linear(H2, latent_dim)<br>        self.bn1 = nn.BatchNorm1d(num_features=latent_dim)<br>        self.fc21 = nn.Linear(latent_dim, latent_dim)<br>        self.fc22 = nn.Linear(latent_dim, latent_dim)<br>        # Sampling vector<br>        self.fc3 = nn.Linear(latent_dim, latent_dim)<br>        self.fc_bn3 = nn.BatchNorm1d(latent_dim)<br>        self.fc4 = nn.Linear(latent_dim, H2)<br>        self.fc_bn4 = nn.BatchNorm1d(H2)# Batch normalization   <br>        # Decoder<br>        self.linear4=nn.Linear(H2,H2)<br>        self.lin_bn4 = nn.BatchNorm1d(num_features=H2)<br>        self.linear5=nn.Linear(H2,H)<br>        self.lin_bn5 = nn.BatchNorm1d(num_features=H)<br>        self.linear6=nn.Linear(H,D_in)<br>        self.lin_bn6 = nn.BatchNorm1d(num_features=D_in)<br>        self.relu = nn.ReLU()# Activation Function<br>        <br>    def encode(self, x):<br>        lin1 = self.relu(self.lin_bn1(self.linear1(x)))<br>        lin2 = self.relu(self.lin_bn2(self.linear2(lin1)))<br>        lin3 = self.relu(self.lin_bn3(self.linear3(lin2)))<br>        fc1 = F.relu(self.bn1(self.fc1(lin3)))<br>        r1 = self.fc21(fc1)<br>        r2 = self.fc22(fc1)<br>        return r1, r2<br>    <br>    def reparameterize(self, mu, logvar):<br>        if self.training:<br>            std = logvar.mul(0.5).exp_()<br>            eps = Variable(std.data.new(std.size()).normal_())<br>            return eps.mul(std).add_(mu)<br>        else:<br>            return mu<br>        <br>    def decode(self, z):<br>        fc3 = self.relu(self.fc_bn3(self.fc3(z)))<br>        fc4 = self.relu(self.fc_bn4(self.fc4(fc3)))<br>        lin4 = self.relu(self.lin_bn4(self.linear4(fc4)))<br>        lin5 = self.relu(self.lin_bn5(self.linear5(lin4)))<br>        return self.lin_bn6(self.linear6(lin5))<br>        <br>    def forward(self, x):<br>        mu, logvar = self.encode(x)<br>        z = self.reparameterize(mu, logvar)<br>        return self.decode(z), mu, logvar</pre><p>Now we build a custom loss function commonly used in VAE models to balance the reconstruction accuracy and the regularization of the latent representation. That combines the reconstruction loss and the Kullback-Leibler divergence (KLD) loss. The custom loss function calculates the mean squared error (MSE) between the reconstruction (x_recon) and the original input data (x). It also calculates the KLD between the encoder’s latent distribution and standard normal distribution.</p><pre>class customLoss(nn.Module):<br>    def __init__(self):<br>        super(customLoss, self).__init__()<br>        self.mse_loss = nn.MSELoss(reduction=&quot;sum&quot;)<br>    <br>    # x_recon ist der im forward im Model erstellte recon_batch, x ist der originale x Batch, mu ist mu und logvar ist logvar <br>    def forward(self, x_recon, x, mu, logvar):<br>        loss_MSE = self.mse_loss(x_recon, x)<br>        loss_KLD = -0.5 * torch.sum(1 + logvar - mu.pow(2) - logvar.exp())<br>        return loss_MSE + loss_KLD<br><br><br># takes in a module and applies the specified weight initialization<br>def weights_init_uniform_rule(m):<br>    classname = m.__class__.__name__<br>    # for every Linear layer in a model..<br>    if classname.find(&#39;Linear&#39;) != -1:<br>        # get the number of the inputs<br>        n = m.in_features<br>        y = 1.0/np.sqrt(n)<br>        m.weight.data.uniform_(-y, y)<br>        m.bias.data.fill_(0)</pre><p>We have built the all required functions that are necessary to train the model, now start training the model…</p><pre>D_in = data_set.x.shape[1]<br>H = 50<br>H2 = 12<br>model = Autoencoder(D_in, H, H2).to(device)<br>model.apply(weights_init_uniform_rule)<br>optimizer = optim.Adam(model.parameters(), lr=1e-3)<br>loss_mse = customLoss()#LOSS<br><br># Traning the Model<br>def train(epoch):<br>    model.train()<br>    train_loss = 0<br>    for batch_idx, data in enumerate(trainloader):<br>        data = data.to(device)<br>        optimizer.zero_grad()<br>        recon_batch, mu, logvar = model(data)<br>        loss = loss_mse(recon_batch, data, mu, logvar)<br>        loss.backward()<br>        train_loss += loss.item()<br>        optimizer.step()<br><br>    if epoch % 200 == 0:        <br>        print(&#39;====&gt; Epoch: {} Average loss: {:.4f}&#39;.format(<br>            epoch, train_loss / len(trainloader.dataset)))<br>        train_losses.append(train_loss / len(trainloader.dataset))</pre><p>Now run the train function according to the number of epochs</p><pre>for epoch in range(1, epochs + 1):<br>    train(epoch)<br><br><br># OUTOUT<br>====&gt; Epoch: 200 Average loss: 10.7176<br>====&gt; Epoch: 400 Average loss: 9.3970<br>====&gt; Epoch: 600 Average loss: 8.7004<br>====&gt; Epoch: 800 Average loss: 8.2701<br>====&gt; Epoch: 1000 Average loss: 8.1218<br>====&gt; Epoch: 1200 Average loss: 8.1025<br>====&gt; Epoch: 1400 Average loss: 8.0290</pre><p>Evaluate</p><pre># This ensures that the input data is scaled in the same way as the <br># training data, which can improve the performance of the model.<br>standardizer = trainloader.dataset.standardizer<br><br>model.eval()<br>test_loss = 0<br># no_grad() bedeutet wir nehmen die vorher berechneten Gewichte und erneuern sie nicht<br>with torch.no_grad():<br>    for i, data in enumerate(trainloader):<br>        data = data.to(device)<br>        recon_batch, mu, logvar = model(data)<br><br>standardizer.inverse_transform(recon_batch[65].cpu().numpy())<br>standardizer.inverse_transform(data[65].cpu().numpy())</pre><p>It&#39;s time to get the Embeddings of VAs used to obtain the training dataset’s latent variables’ overall distribution, which can be useful for analyzing the model’s behavior…</p><pre>mu_output = []<br>logvar_output = []<br><br>with torch.no_grad():<br>    for i, (data) in enumerate(trainloader):<br>            data = data.to(device)<br>            optimizer.zero_grad()<br>            recon_batch, mu, logvar = model(data)<br><br>            mu_tensor = mu   <br>            mu_output.append(mu_tensor)<br>            mu_result = torch.cat(mu_output, dim=0)<br><br>            logvar_tensor = logvar   <br>            logvar_output.append(logvar_tensor)<br>            logvar_result = torch.cat(logvar_output, dim=0)<br><br>mu_result.shape # torch.Size([178, 3])</pre><p>These are the embeddings calculated by our VAE. And now we will plot the Embeddings of PCA</p><pre>ax = plt.axes(projection=&#39;3d&#39;)<br># Data for three-dimensional scattered points<br>winetype = finalDf.iloc[:,3].values<br>zdata = finalDf.iloc[:,0].values<br>xdata = finalDf.iloc[:,1].values<br>ydata = finalDf.iloc[:,2].values<br>ax.scatter3D(xdata, ydata, zdata, c=winetype);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/346/1*CF3DEB6ZKRMH4ieIrmVqTw.png" /></figure><p>Plotting the Embeddings of VAE</p><pre>ax = plt.axes(projection=&#39;3d&#39;)<br># Data for three-dimensional scattered points<br>winetype = data_set.wine<br>zdata = mu_result[:,0].cpu().numpy()<br>xdata = mu_result[:,1].cpu().numpy()<br>ydata = mu_result[:,2].cpu().numpy()<br>ax.scatter3D(xdata, ydata, zdata, c=winetype);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/335/1*iLGmlxUqrYZDNQgLWezd5w.png" /></figure><p>If there are any questions, feel free to ask.🙂</p><h4>References: -</h4><ul><li><a href="https://towardsdatascience.com/autoencoders-vs-pca-when-to-use-which-73de063f5d7">Autoencoders vs PCA: when to use which ?</a></li><li><a href="https://avandekleut.github.io/vae/">Variational AutoEncoders (VAE) with PyTorch</a></li></ul><p>Thanks for reading……………..….😇</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3469e7ad12a1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cardiac MRI Publicly Available Datasets]]></title>
            <link>https://medium.com/@Ravitejakandimalla/cardiac-mri-publicly-available-datasets-70dde5621c87?source=rss-1b42a797764b------2</link>
            <guid isPermaLink="false">https://medium.com/p/70dde5621c87</guid>
            <dc:creator><![CDATA[Ravi Teja Kandimalla]]></dc:creator>
            <pubDate>Fri, 10 Mar 2023 15:58:24 GMT</pubDate>
            <atom:updated>2023-03-10T15:58:24.585Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/630/0*1ORmzHZq7AEjDPc_.jpg" /></figure><p>The reason I am writing this blog is that many of us difficult to find medical datasets, especially Cardiac MRI. So this blog will help you out by showing 4 paths to access the Cardiac MRI datasets.</p><p><strong>Firstly…</strong></p><h4>ACDC (Automated Cardiac Diagnosis Challenge)</h4><p>The dataset is composed of 150 exams (all from different patients) divided into 5 evenly distributed subgroups (4 pathological plus 1 healthy subject group) as described below. Furthermore, each patient comes with the following additional information: weight, and height, as well as diastolic and systolic phase instants.</p><p>Click here to access the dataset <a href="https://humanheart-project.creatis.insa-lyon.fr/database/#collection/637218c173e9f0047faa00fb/folder/637218e573e9f0047faa00fc">link</a>.</p><p><strong>Secondly...</strong></p><h3>Sunnybrook Cardiac Data</h3><p>The Sunnybrook Cardiac Data (SCD), also known as the 2009 Cardiac MR Left Ventricle Segmentation Challenge data, consists of 45 cine-MRI images from a mix of patients and pathologies: healthy, hypertrophy, heart failure with infarction, and heart failure without infarction. A Subset of this data set was first used in the automated myocardium segmentation challenge from short-axis MRI, held by a MICCAI workshop in 2009.</p><p>Click here to access the dataset <a href="https://www.cardiacatlas.org/sunnybrook-cardiac-data/">link</a>.</p><p><strong>Thirdly…</strong></p><h3>Second Annual Data Science Bowl</h3><p>In this dataset, you are given hundreds of cardiac MRI images in <a href="https://en.wikipedia.org/wiki/DICOM">DICOM</a> format. These are 2D cine images that contain approximately 30 images across the cardiac cycle. Each slice is acquired on a separate breath hold. This is important since the registration from slice to slice is expected to be imperfect.</p><p>Click here to access the dataset <a href="https://www.kaggle.com/competitions/second-annual-data-science-bowl/data?select=validate.csv">link</a>.</p><p><strong>Finally…</strong></p><p>The details of this dataset don’t know, but it it is having around 11,000 cardiac MRI images and their left ventricle mask as well.</p><p>Click here to access the dataset <a href="https://codeload.github.com/juliandewit/kaggle_ndsb2/zip/refs/heads/master">link</a>.</p><p>Hope this helps you to try out Deep Learning techniques on medical images…</p><p>Thanks for reading🙂</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=70dde5621c87" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Advanced NumPy]]></title>
            <link>https://medium.com/@Ravitejakandimalla/advanced-numpy-a570bef7c87e?source=rss-1b42a797764b------2</link>
            <guid isPermaLink="false">https://medium.com/p/a570bef7c87e</guid>
            <dc:creator><![CDATA[Ravi Teja Kandimalla]]></dc:creator>
            <pubDate>Mon, 06 Mar 2023 15:56:56 GMT</pubDate>
            <atom:updated>2023-03-06T15:56:56.251Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/225/1*jPmZUNZ1WmVEonhAhCWGHg.png" /></figure><p>Let’s see a few facts about NumPy….</p><blockquote>It is a Homogeneous data type.</blockquote><blockquote>Every element in a NumPy array uniformly occupies n bytes.</blockquote><blockquote>NumPy arrays are stored contiguously in memory.</blockquote><blockquote>Fixed size</blockquote><p>Now let us see a few advanced functions of NumPy</p><h4>allclose() function</h4><ul><li>A comparison function that checks whether two arrays are equal or pretty similar.</li><li>Compares two arrays of the data item elementwise within a threshold.</li><li>Then returns a Boolean value as a result.</li></ul><pre>a = np.array([0.16,0.26,0.365])<br>b = np.array([0.15,0.25,0.36])<br>tolerance1 = 0.1<br>tolerance2 = 0.05<br>print(np.allclose(a,b,tolerance1))<br>print(np.allclose(a,b,tolerance2))<br><br><br>Output<br>True<br>False</pre><h3>2. where() function</h3><ul><li>Where() is a function that returns elements from an array that meets a set of criteria.</li></ul><pre>list1 = np.array([1,4,7,6,1,7,3,8,9])<br># Where the elements in list1 are less than 7, returns the index position<br>np.where(list1&lt;7)<br><br><br>output:<br>(array([0, 1, 3, 4, 6]),)</pre><h3>3. extract() function</h3><ul><li>Extract() is used to retrieve specific members with an array depending on criteria.</li></ul><pre>array_test = np.random.randint(18, size=12)<br>array_test<br><br>output:<br>array([ 5, 12,  8,  4,  1,  3,  4,  0, 17, 10,  2, 16])<br><br>cond = np.mod(array_test, 2)==1<br>cond<br><br>output:<br>array([ True, False, False, False,  True,  True, False, False,  True,<br>       False, False, False])<br><br>np.extract(cond, array_test)<br><br>output:<br>array([ 5,  1,  3, 17])</pre><h3>4. einsum() function</h3><ul><li>The einsum() function in NumPy (short for “Einstein summation”) allows for advanced indexing and summation of multi-dimensional arrays.</li></ul><pre>a = np.array([[1,2,3],[4,5,6],[7,8,9]])<br>a_diag = np.einsum(&#39;ii-&gt;i&#39;, a)<br>print(&quot;option1\n&quot;,a_diag)<br>print(&#39;option2\n&#39;,np.einsum(a,[0,0],[0]))<br>output:<br><br>option1<br> [1 5 9]<br>option2<br> [1 5 9]<br><br>a_transpose = np.einsum(&quot;ij-&gt;ji&quot;,a)<br>print(&quot;option1\n&quot;,a_transpose)<br>print(&quot;option2\n&quot;,np.einsum(a,[1,0]))<br>output:<br><br>option1<br> [[1 4 7]<br> [2 5 8]<br> [3 6 9]]<br>option2<br> [[1 4 7]<br> [2 5 8]<br> [3 6 9]]</pre><h3>5. clip() function</h3><ul><li>The clip() function in NumPy is a method for limiting the values in an array to a specified range.</li></ul><pre>x = np.array([3, 4, 12, 20, 2, 2, 3, 7, 1, 2, 12, 0])<br>print(np.clip(x,2,5))<br><br>output:<br>[3 4 5 5 2 2 3 5 2 2 5 2]</pre><h3>conclusion:-</h3><p>These are just a few functions of NumPy, there are many more to look at, few more are there here in this link.</p><h3>References:-</h3><p><a href="http://scipy-lectures.org/advanced/advanced_numpy/">2.2. Advanced NumPy - Scipy lecture notes</a></p><p>Thanks for reading, hope it was helpful.🙂</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a570bef7c87e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scikit-learn pipeline]]></title>
            <link>https://medium.com/@Ravitejakandimalla/scikit-learn-pipeline-6c285cdd4664?source=rss-1b42a797764b------2</link>
            <guid isPermaLink="false">https://medium.com/p/6c285cdd4664</guid>
            <dc:creator><![CDATA[Ravi Teja Kandimalla]]></dc:creator>
            <pubDate>Fri, 24 Feb 2023 10:17:29 GMT</pubDate>
            <atom:updated>2023-02-24T10:17:29.431Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zJ2PhVDZjIpVNgNl3YJ8CQ.png" /><figcaption><a href="https://www.google.com/search?sxsrf=AJOqlzVHgM_uIoDtvO65DCYMOtgwHcrNDg:1677231626623&amp;q=Scikit-learn+pipeline&amp;tbm=isch&amp;sa=X&amp;ved=2ahUKEwj5ir7a7q39AhWGVmwGHcm9BmsQ0pQJegQICxAB&amp;biw=1696&amp;bih=828&amp;dpr=1.1#imgrc=Aq-Rw11x-Es3VM&amp;imgdii=wKj15Icap28UOM">Source</a></figcaption></figure><p>Before we dive in, first, let’s understand why pipelines are needed for model workflows. To deploy a model, it needs a sequence of tasks such as processing data, training a model, hyperparameter tuning, evaluation, packaging the model artifacts, model deployment, and retraining cycle. With pipelines, each step in the model process runs in its own container. This lets you develop steps independently and track the input and output from each step in a reproducible way.</p><p>Now let us try to learn how to use <strong>pipelines</strong> to clean up your modeling code. Let&#39;s learn this by taking one dataset.</p><pre>melb_data_path = &quot;/kaggle/input/pipeline/melb_data.csv/melb_data.csv&quot;<br>data = pd.read_csv(melb_data_path)# Read the dat<br>y = data.Price # Separate target from predictors<br>X = data.drop([&#39;Price&#39;], axis=1)<br>X_train_full, X_valid_full, y_train, y_valid = train_test_split(X, y, train_size=0.8, test_size=0.2,random_state=0)<br><br># &quot;Cardinality&quot; means the number of unique values in a column<br>categorical_cols = [cname for cname in X_train_full.columns if X_train_full[cname].nunique() &lt; 10 and X_train_full[cname].dtype == &quot;object&quot;]<br>print(type(categorical_cols))<br>print(&quot;categorical columns&quot;,categorical_cols)<br><br># Select numerical columns<br>numerical_cols = [cname for cname in X_train_full.columns if X_train_full[cname].dtype in [&#39;int64&#39;, &#39;float64&#39;]]<br>print(type(numerical_cols))<br>print(&quot;NUmerical columns&quot;,numerical_cols)<br><br>my_cols = categorical_cols + numerical_cols<br>print(&quot;Selected columns&quot;, my_cols)<br>X_train = X_train_full[my_cols].copy()<br>print(&quot;\n\nX- train&quot;,X_train)<br>X_valid = X_valid_full[my_cols].copy()<br>print(&quot;\n\nX- valid&quot;,X_valid)</pre><p>Now we will construct the full pipeline in <strong>three</strong> steps.</p><h4>Step-1 We will define the processing steps:-</h4><p>we use the ColumnTransformer class to bundle together different preprocessing steps</p><ul><li>That imputes missing values in numerical data.</li><li>Imputes missing values and applies a one-hot encoding to categorical data.</li></ul><pre># Preprocessing for numerical data<br>numerical_transformer = SimpleImputer(strategy=&#39;constant&#39;) <br>categorical_transformer = Pipeline(steps=[(&#39;imputer&#39;, SimpleImputer(strategy=&#39;most_frequent&#39;)),(&#39;onehot&#39;, OneHotEncoder(handle_unknown=&#39;ignore&#39;))]) # Preprocessing for categorical data<br><br># Bundle preprocessing for numerical and categorical data<br>preprocessor = ColumnTransformer(transformers=[(&#39;num&#39;, numerical_transformer, numerical_cols),(&#39;cat&#39;, categorical_transformer, categorical_cols)])<br>preprocessor</pre><h4>Step-2 Define a model:-</h4><ul><li>Here we will define the RandomForestRegressor.</li></ul><pre>my_model = RandomForestRegressor(n_estimators=100, random_state=0)</pre><h4>Step-3 Create and evaluate the pipeline:-</h4><ul><li>Here we use the <strong>Pipeline class</strong> to define a pipeline that bundles the preprocessing and modeling steps.</li><li>With the pipeline, we preprocess the training data and fit the model in a single line of code.</li><li>Next the unprocessed features in X_valid to the predict().</li><li>Then pipeline automatically preprocesses the features before generating predictions.</li></ul><pre>my_pipeline = Pipeline(steps=[(&#39;preprocessor&#39;, preprocessor),(&#39;model&#39;, my_model)])# Bundle preprocessing and modeling code in a pipeline<br>my_pipeline.fit(X_train, y_train)# Preprocessing of training data, fit model <br>preds = my_pipeline.predict(X_valid)# Preprocessing of validation data, get predictions<br>score = mean_absolute_error(y_valid, preds)# Evaluate the model<br>print(&#39;Mean Absolute Error:&#39;, score)</pre><h3>Conclusion:-</h3><p>Pipelines are valuable for cleaning up the models and avoiding errors and are especially useful for workflows with sophisticated data preprocessing.</p><p>Code:- <a href="https://www.kaggle.com/ravitejakandimalla/pipeline-learned">Link</a></p><h3>References:-</h3><p><a href="https://scikit-learn.org/stable/modules/generated/sklearn.pipeline.Pipeline.html">sklearn.pipeline.Pipeline</a></p><p>Hope this is useful…….thank you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6c285cdd4664" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[20 Pandas functions important for Data analysis]]></title>
            <link>https://medium.com/@Ravitejakandimalla/20-pandas-functions-important-for-data-analysis-f1746ebf82a7?source=rss-1b42a797764b------2</link>
            <guid isPermaLink="false">https://medium.com/p/f1746ebf82a7</guid>
            <dc:creator><![CDATA[Ravi Teja Kandimalla]]></dc:creator>
            <pubDate>Wed, 15 Feb 2023 07:54:12 GMT</pubDate>
            <atom:updated>2023-02-15T07:54:12.859Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sbYxcoG1gqdsi4wdbNVOLg.jpeg" /></figure><p>Pandas stand for “<strong>Python Data Analysis Library</strong> ”. It is an open-source Python package that is most widely used for data science/data analysis and machine learning tasks. Pandas is built on top of two core Python libraries — matplotlib for data visualization and NumPy for mathematical operations. Pandas acts as a wrapper over these libraries, allowing you to access many of <strong>matplotlib’s </strong>and<strong> NumPy’s methods.</strong></p><h3>1. pd.read_csv()</h3><p>pd.read_csv is a function in the pandas that is used to read a CSV file and convert it into a pandas DataFrame.</p><pre>df = pd.read_csv(path + &#39;accidents_2017.csv&#39;)</pre><h3><strong>2. df.describe()</strong></h3><p>df.describe() gives the summary statistics of a data frame. Returns a new data frame that contains the count, mean, standard deviation, minimum, 25th percentile, median, 75th percentile, and maximum of each numerical column in the original data frame.</p><pre>print(df.describe())<br>df.describe(include=&#39;all&#39;)  # include all columns<br>df.describe(exclude=&#39;number&#39;) # exclude numerical columns</pre><h3>3. df.info()</h3><p>df.info() is a method in pandas that is used to get a concise summary of the DataFrame</p><pre>print(df.info())</pre><h3>4. df.plot()</h3><p><strong>Pandas</strong> uses the <strong>plot</strong>() method to create diagrams. We can use Pyplot, a submodule of the Matplotlib library to visualize the diagram on the screen.</p><pre>df[&#39;Mild injuries&#39;].value_counts().plot(kind=&#39;bar&#39;)<br>df[&#39;Vehicles involved&#39;].value_counts().plot(kind=&#39;pie&#39;)  </pre><h3>5. df.iloc()</h3><p>Pandas’ .iloc() the function is used to select rows and columns by their integer-based index in a data frame. It is used to select rows and columns by their integer-based location.</p><pre>df.iloc[0]# Select the first row<br>print(df.iloc[:, 4])# Select the first 4 rows<br>print(df.iloc[:, :3])# Select the first t columns</pre><h3>6. df.loc()</h3><p>Pandas’ .loc() a function is used to select rows and columns by their label-based index in a DataFrame.</p><pre>print(df.loc[:,&#39;Hour&#39;])# Select the column name &#39;Hour&#39;<br>print(df.loc[:, [&#39;Day&#39;, &#39;Hour&#39;]])# Select the columns named &#39;Year of Birth&#39; and &#39;Gender&#39;</pre><h3>7. df.assign()</h3><p>Pandas’ .assign() function is used to add new columns to a DataFrame.It allows you to add new columns to a DataFrame without modifying the original dataFrame.</p><pre>df_new = df.assign(count_plus_5=df[&#39;Victims&#39;] + 5)<br>df_new.head()</pre><h3>8. df.query()</h3><p>Pandas’ .query() function allows you to filter a DataFrame based on a Boolean expression. It allows you to select rows from a DataFrame using a query string similar to SQL.</p><pre>df_query = df.query(&#39;Hour &gt; 3 and Victims &gt; 3&#39;)<br>print(df_query.head())<br>df_query = df.query(&quot;Month  == &#39;December&#39;&quot;)<br>print(df_query.head())</pre><h3>9. df.sort_values()</h3><p>Pandas’ .sort_values() function allows you to sort a DataFrame by one or multiple columns. It sorts the DataFrame based on the values of one or more columns, in ascending or descending order.</p><pre>df_sorted = df.sort_values(by=&#39;Weekday&#39;)<br>print(df_sorted.head())<br>df_sorted = df.sort_values(by=&#39;Mild injuries&#39;)<br>print(df_sorted.head())</pre><h3>10. df.sample()</h3><p>Pandas’ .sample() function allows you to randomly select rows from a DataFrame. It returns a new DataFrame containing the randomly selected rows.</p><pre>df_sample = df.sample(n=5, replace=True, random_state=1)<br>df_sample</pre><h3>11. df.isnull()</h3><p>The isnull() method in Pandas returns a DataFrame of the same shape as the original DataFrame, but with True or False values indicating whether each value in the original DataFrame is missing or not. Missing values, such as NaN or None, will be True in the resulting DataFrame, while non-missing values will be False.</p><pre>df.isnull()</pre><h3>12. df.fillna()</h3><p>The fillna() method in Pandas is used to fill in missing values in a DataFrame with a specified value or method. By default, it replaces missing values with NaN, but you can specify a different value to use instead as shown below:</p><p><strong>Value</strong>: Specifies the value to use to fill in the missing values.<br><strong>Method</strong>: Specify the method to use for filling in missing values. <br><strong>Axis</strong>: Specifies the axis along which to fill in missing values. I<br><strong>In place</strong>: Whether to fill in the missing values in place or to return a new DataFrame with the missing values filled in.<br><strong>Limit</strong>: Specifies the maximum No of consecutive missing values to fill.</p><pre>df.fillna(0)  # fill missing values with 0<br>df.fillna(method=&#39;ffill&#39;)# forward-fill missing values (propagates last valid observation forward to next)<br>df.fillna(method=&#39;bfill&#39;)# backward-fill missing values (propagates next valid observation backward to last)<br>df.interpolate()# fill missing values using interpolation</pre><h3>13. df.dropna()</h3><p>df.dropna() is a method used in the Pandas library to remove missing or null values from a DataFrame. It removes rows or columns from the DataFrame where at least one element is missing.</p><pre>df = df.dropna()</pre><h3>14. df.drop()</h3><p>df.drop() is a method used in the Pandas library to remove rows or columns from a DataFrame by specifying the corresponding labels.</p><pre>df_drop = df.drop(0) # Removes the first row of the data frame<br>df_drop = df.drop([0,1]) # Drops the multiple rows from the data frame<br>df_drop = df.drop([&#39;Hour&#39;, &#39;Weekday&#39;], axis=1) # dropping the columns by name the column names </pre><h3><strong>15. pd.pivot_table()</strong></h3><p>pd.pivot_table() is a method in the Pandas library that is used to create a pivot table from a DataFrame. A pivot table is a table that summarizes and aggregates data in a more meaningful and organized way.</p><pre>pivot_table = pd.pivot_table(df, index=&#39;Id&#39;, values=&#39;Victims&#39;, aggfunc=&#39;sum&#39;)<br>pivot_table.head()<br>pivot_tables = pd.pivot_table(df, index = &#39;Month&#39;, values = &#39;Mild injuries&#39;, aggfunc = &#39;sum&#39; )<br>pivot_tables.head()</pre><h3>16. df.groupby()</h3><p>df.groupby() is a method in the Pandas library that is used to group rows of a DataFrame based on one or multiple columns. This allows us to perform aggregate operations on the groups, such as calculating the<br>- mean<br>- sum or count of the values in each group.</p><pre>grouped = df.groupby(&#39;Victims&#39;)<br>print(grouped.mean())</pre><h3><strong>17. df.transpose()</strong></h3><p>df.transpose() is a method in the Pandas library used to transpose the rows and columns of a DataFrame? This means that the rows become columns and the columns become rows.</p><pre>df_transposed = df.transpose()<br>df_transposed.head()</pre><h3>18. df.merge()</h3><p>df.merge() is a pandas function that allows you to combine two DataFrames based on one or more common columns. It is similar to SQL JOINs.</p><pre>df1 = pd.DataFrame({&#39;key&#39;: [&#39;A&#39;, &#39;B&#39;, &#39;C&#39;, &#39;D&#39;],&#39;value&#39;: [1, 2, 3, 4]})<br>df2 = pd.DataFrame({&#39;key&#39;: [&#39;B&#39;, &#39;D&#39;, &#39;E&#39;, &#39;F&#39;],&#39;value&#39;: [5, 6, 7, 8]})<br>merged_df = df1.merge(df2, on=&#39;key&#39;)<br>print(df1)<br>print(df2)<br>print(merged_df)</pre><h3>19. df.rename()</h3><p>df.rename() is a pandas function that allows you to change the name of one or more columns or rows in a DataFrame</p><pre># Rename column &#39;Count&#39; to &#39;count&#39;<br>df_rename = df.rename(columns={&#39;Weekday&#39;: &#39;Day&#39;})<br>df_rename.head()</pre><h3>20. df.to_csv()</h3><p>df.to_csv() is a method used in the Pandas library to export a DataFrame to a CSV file.</p><pre>df.to_csv(path + &#39;data.csv&#39;)</pre><h4>Thank you for taking the time to read my article. I hope you found it informative and engaging. 😇</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f1746ebf82a7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[NLP: Word Segmentation, Maximal Matching-1]]></title>
            <link>https://medium.com/@Ravitejakandimalla/nlp-word-segmentation-maximal-matching-1-ed2ad5cab4fc?source=rss-1b42a797764b------2</link>
            <guid isPermaLink="false">https://medium.com/p/ed2ad5cab4fc</guid>
            <dc:creator><![CDATA[Ravi Teja Kandimalla]]></dc:creator>
            <pubDate>Sun, 22 Jan 2023 09:06:07 GMT</pubDate>
            <atom:updated>2023-01-22T09:06:07.418Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/813/1*aWCHGnf8zafAuSEJCkh6gQ.png" /><figcaption><a href="https://www.google.com/search?q=maximal+matching+in+nlp+&amp;tbm=isch&amp;ved=2ahUKEwiui_bAtdj8AhVDyaACHQIICjcQ2-cCegQIABAA&amp;oq=maximal+matching+in+nlp+&amp;gs_lcp=CgNpbWcQAzoECAAQQzoFCAAQgAQ6BwgAEIAEEBg6BAgAEB5Q0gtY0DNg8z9oAHAAeACAAXqIAewFkgEDOC4xmAEAoAEBqgELZ3dzLXdpei1pbWfAAQE&amp;sclient=img&amp;ei=jrnLY66MGsOSg8UPgpCouAM&amp;bih=919&amp;biw=1866#imgrc=0HOU9P2II52bkM">Source</a></figcaption></figure><p>This is the way to avoid matching the shortest word is to find the longest sequence of characters in the dictionary instead. This approach is called the <strong>longest matching algorithm </strong>or<strong> maximal matching. </strong>This is a greedy algorithm that matches the longest word.</p><p>Let’s start with a small example “<strong>themendinehere” </strong>as shown in the figure.</p><p>For the first word, we would find: <strong><em>the</em></strong><em>,</em> <strong><em>them</em></strong>, <strong><em>theme</em></strong><em>,</em> and no word would match after that. Now we just choose the <em>longest</em> which is “<strong><em>theme</em></strong>”, then start again from ’<strong>n</strong>’. But now we don’t have any word in this series “<strong><em>ndine</em></strong>…”. When we can’t match a word, we just mark the first character as unknown. So in “<strong><em>ndineh</em></strong>…”, we just took ’<strong><em>n</em></strong>’ out as an unknown word and matched the next word starting with ‘<strong><em>d’</em></strong>. Assuming the word “<strong>din</strong>” or “<strong>re</strong>” are not in our dictionary, we would get the series of words as<em> “</em><strong><em>theme n dine here”</em></strong><em>.</em><strong><em> </em></strong>We only get one unknown word for the chosen example in this case.</p><p><em>But as you can see the longest word can make incorrect segmentation</em>. This result in overextending the first-word “theme” into a part of the second word “men” making the next word unknown “n”.</p><p>To avoid this problem there is something called <strong><em>Bi-Directional Maximal Matching, </em></strong>which we will see in the next article.</p><p>One of the most common applications of this algorithm is in spell checker, where a misspelled word can be corrected by finding the closest matching word in a dictionary, based on the longest matching substring.</p><h4>Advantages:-</h4><p>One of the main advantages of maximal matching is its <strong>computational efficiency.</strong> It can be implemented using simple string-matching algorithms, such as the <a href="https://www.geeksforgeeks.org/boyer-moore-algorithm-for-pattern-searching/">Boyer-Moore algorithm</a>, which have a <strong>linear time complexity.</strong> This makes it well-suited for large-scale text mining and information retrieval tasks.</p><h4>Conclusion:-</h4><p>In conclusion, maximal matching is a simple and efficient technique that can be used to extract relevant information from text, it can be used as a preprocessing step for more advanced NLP techniques, but it also has some limitations as well.</p><p>Thank you for reading the article. I hope it was informative and helpful in understanding the concept and use of maximal matching in natural language processing. If you have any further questions or need more information, feel free to ask.</p><h4>References:-</h4><p><a href="https://www.youtube.com/watch?v=9LXq3oQEEIA&amp;list=PL8FFE3F391203C98C&amp;index=6">https://www.youtube.com/watch?v=CXpZnZM63Gg&amp;list=PL8FFE3F391203C98C</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ed2ad5cab4fc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to measure a Model!!!]]></title>
            <link>https://medium.com/@Ravitejakandimalla/how-to-measure-a-model-ce97a4647b30?source=rss-1b42a797764b------2</link>
            <guid isPermaLink="false">https://medium.com/p/ce97a4647b30</guid>
            <dc:creator><![CDATA[Ravi Teja Kandimalla]]></dc:creator>
            <pubDate>Fri, 25 Nov 2022 09:07:36 GMT</pubDate>
            <atom:updated>2022-11-25T09:07:36.393Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-Ma-nFne2PGLBOSx.gif" /><figcaption><a href="https://www.google.com/search?q=which+ML+model+is+good&amp;sxsrf=ALiCzsblUt8CovAf73LPLEYvYvNMorEu5Q:1669359600301&amp;source=lnms&amp;tbm=isch&amp;sa=X&amp;ved=2ahUKEwjItumP4cj7AhUfRmwGHRUdDcQQ_AUoAnoECAIQBA#imgrc=uwCAW_okLkTuOM">Source</a></figcaption></figure><p>In this article, we will discuss the various ways to check the performance of our machine-learning or deep-learning models...</p><ol><li>Confusion matrix.</li><li>Accuracy.</li><li>Precision.</li><li>Recall.</li><li>Specificity.</li><li>F1 score.</li><li>Precision-Recall or PR curve.</li><li>ROC (Receiver Operating Characteristics) curve.</li><li>R-Square.</li><li>Kappa score</li></ol><p>For a simple understanding of all these measures, we will keep Binary classification in our mind. So let’s get started!</p><p><strong>1. Confusion matrix:- </strong>It is one of the core elements that can be used to measure the performance of the ML classification model, it is a table with two dimensions showing actual values and predicted values. For more details, I have written an article on this please click <a href="https://medium.com/@Ravitejakandimalla/different-trade-offs-in-ml-38cfaa502bb9#:~:text=%C2%B7%20True%20Positive%3A%20When%20the%20model%20predicted,not%20Rose%20and%20it%20is%20actually%20a%20Rose.">here</a>.</p><p><strong>2. Accuracy:-</strong> We calculate accuracy by dividing the number of correct predictions (the corresponding diagonal in the matrix) by the total number of samples. And the result tells us that our model achieved a so-and-so accuracy on the problem that is there in our hand. Here are the most widely used examples:</p><ul><li><a href="https://scikit-learn.org/stable/modules/model_evaluation.html#balanced-accuracy-score">Balanced Accuracy</a></li><li><a href="https://deepchecks.com/glossary/top-1-error-rate/">Top-K Accuracy</a></li><li><a href="https://en.wikipedia.org/wiki/Brier_score">Accuracy of probability predictions</a></li></ul><p><strong>3. Precision:- </strong>Precision is a metric that quantifies the number of correct positive predictions made. Calculates the accuracy for the minority class. It is calculated as the ratio of correctly predicted positive examples divided by the total number of positive examples that were predicted. <strong>Why use it?</strong> Precision does well in cases when you need to or can avoid False Negatives but can’t ignore False Positives.</p><p><strong>4. Recall:- </strong>Recall is a metric that quantifies the number of correct positive predictions made out of all positive predictions that could have been made.</p><p><strong>Recall = TruePositives / (TruePositives + FalseNegatives).</strong></p><p>Recall provides an indication of missed positive predictions.</p><p><strong>5. Specificity:-</strong> Specificity is the proportion of actual negatives that the model has correctly identified as such out of all negatives. It shows the True Negative Rate that is calculated as all True Negatives divided by the sum of True Negatives and False Positives in the data.</p><p><strong>Specificity = (True Negative)/(True Negative + False Positive)</strong></p><p>Generally, the model would be expected to have a very high specificity or true negative rate. The lower value of specificity would mean a lower value of the true negative and a higher value of the false positive.</p><h4>Conclusion:-</h4><p>So far we have seen the 5 different measures of how a model can be measured, so let us see the next five measures in the next article ….</p><p>Thank you for reading………………………..🙂</p><h4>References:-</h4><p><a href="https://deepchecks.com/glossary/top-1-error-rate/">https://</a>scikit-learn.org</p><ul><li><a href="https://deepchecks.com/glossary/top-1-error-rate/">What is Top-1 error rate | Deepchecks</a></li><li><a href="https://vitalflux.com/ml-metrics-sensitivity-vs-specificity-difference/">Machine Learning - Sensitivity vs Specificity Difference - Data Analytics</a></li></ul><p><a href="https://www.altexsoft.com/blog/machine-learning-metrics/">https://www.altexsoft.com/blog/machine-learning-metrics/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ce97a4647b30" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Adversarial Variational Autoencoders (aVAEs).]]></title>
            <link>https://medium.com/@Ravitejakandimalla/adversarial-variational-autoencoders-avaes-d2682f753451?source=rss-1b42a797764b------2</link>
            <guid isPermaLink="false">https://medium.com/p/d2682f753451</guid>
            <dc:creator><![CDATA[Ravi Teja Kandimalla]]></dc:creator>
            <pubDate>Sat, 29 Oct 2022 09:51:29 GMT</pubDate>
            <atom:updated>2022-10-29T09:54:44.714Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/330/1*aKRcl4fNlOHYusf6XOIAPA.png" /><figcaption><strong>aVAE</strong> workflow (<a href="https://www.google.com/search?q=Adversarial+Variational+Autoencoders+(aVAE).&amp;sxsrf=ALiCzsYeg35ibxtmo3neHbHA39vjmW-ZPQ:1667035957726&amp;source=lnms&amp;tbm=isch&amp;sa=X&amp;ved=2ahUKEwjV4NnwkIX7AhUgS2wGHYxkCLoQ_AUoAXoECAEQAw&amp;biw=1866&amp;bih=911&amp;dpr=1#imgrc=TrJyJ0uhQgQ0MM&amp;imgdii=580NBfDdWidBMM">source</a>)</figcaption></figure><p>Semi-supervised learning is sought for leveraging unlabelled data when labeled data is difficult or expensive to acquire. Deep generative models (e.g., Variational Autoencoder (<strong>VAE</strong>)) and semisupervised Generative Adversarial Networks (<strong>GANs</strong>) have recently shown promising performance in semi-supervised classification for excellent discriminative representing ability. However, the latent code learned by the traditional VAE is not exclusive to a specific input sample, which prevents it from excellent classification performance.</p><p>Moreover, the semi-supervised GAN models generate data from pre-defined distribution (e.g., Gaussian noises) which is independent of the input data distribution and may obstruct the convergence and is difficult to control the distribution of the generated data. To address the problem, we propose a novel <strong>Adversarial Variational Embedding </strong>(<strong>AVAE</strong>) framework for robust and effective semi-supervised learning to leverage both the advantage of GAN as a high-quality generative model and VAE as a posterior distribution learner.</p><p><strong>which confirms that the combination ofVAE++ and GAN can provide significant improvements in semi-supervised classification.</strong></p><p>Let us try to look at the positives and negatives of VAEs and GANs before we discuss methods that combine them.</p><h4>VAEs</h4><ul><li><strong>+VE — — </strong>In VAEs, the biggest positive is learning a very strong inference mechanism or machine by mapping data to a latent space with the distribution of choice with a fast, effective inference step.</li><li><strong>-VE — — T</strong>he negative is because of the use of KL divergence, VAEs tend to distribute the probability mass diffusely over the data space and may not cover the entire space, which is one reason for VAEs to result in blurry or low-quality image samples.</li></ul><h4>GANs</h4><ul><li>+<strong>VE — — </strong>GANs do not have an inference step. We do not try to learn<br>a latent from data. For GANs, you just give a Gaussian vector this input without worrying about whether that is the real latent manifold, which captures the data distribution.</li><li><strong>-VE — — </strong>The negative is that GAN slacked that inference mechanism, which could prevent reasoning about data at an abstract level.</li></ul><p>There comes the aVAEs by combining both VAE and GAN.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/878/1*FUmYWdvJRraSF7sj4dOnDA.png" /><figcaption><strong>VAE-GAN is the aVAEs</strong></figcaption></figure><p>Hope you have got better clarity of aVAEs.</p><p>I would like to extend my thanks to <strong>Prof. Vineeth N Balasubramanian, </strong>for his fantastic NPTEL course content<strong>.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d2682f753451" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>