<?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 Jayashree Mallipudi on Medium]]></title>
        <description><![CDATA[Stories by Jayashree Mallipudi on Medium]]></description>
        <link>https://medium.com/@_MJ_?source=rss-723d2a0e9981------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*-V4a6wg1o3uDMbel6Sn3bg.png</url>
            <title>Stories by Jayashree Mallipudi on Medium</title>
            <link>https://medium.com/@_MJ_?source=rss-723d2a0e9981------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 08:31:47 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@_MJ_/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[The Engineer’s Field Guide to AI Concepts That Actually Matter]]></title>
            <link>https://medium.com/@_MJ_/the-engineers-field-guide-to-ai-concepts-that-actually-matter-2e45469616b8?source=rss-723d2a0e9981------2</link>
            <guid isPermaLink="false">https://medium.com/p/2e45469616b8</guid>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[attention-is-all-you-need]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[vector-database]]></category>
            <dc:creator><![CDATA[Jayashree Mallipudi]]></dc:creator>
            <pubDate>Wed, 03 Jun 2026 02:16:31 GMT</pubDate>
            <atom:updated>2026-06-03T02:16:31.596Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Quick-reference revision notes — 17 essential concepts, no fluff.</em></p><h3>Part I: From Text to Meaning</h3><h3>1. Large Language Model (LLM)</h3><p>A neural network that predicts the next token given an input sequence. Feed it tokens, it outputs a probability distribution over what comes next, samples from it, appends, repeats. Everything else in AI engineering exists to make this prediction better, faster, or cheaper.</p><p>Emergent capabilities (reasoning, creativity, world knowledge) were never explicitly designed. They arose from optimizing next-token prediction at massive scale.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HvTXie0jo0JyYUOE.png" /></figure><h3>2. Tokenization</h3><p>Splitting raw text into discrete units (tokens) the model can process. Not just whitespace splitting — sub-word units carry meaning (“transform” + “ative”, “un” + “break” + “able”).</p><p>The most common algorithm is Byte-Pair Encoding (BPE) — starts with characters, iteratively merges frequent pairs until reaching a target vocab size (32k–100k tokens).</p><p>Token count directly equals cost and latency. Non-Latin scripts often tokenize less efficiently, creating real cost disparities across languages.</p><h3>3. Vectorization (Embeddings)</h3><p>Mapping each token to a dense numerical vector (typically 768–4096 dimensions) that encodes its meaning. Proximity in vector space equals semantic similarity.</p><p>Relationships are learned from co-occurrence patterns across billions of sentences. Vector arithmetic works: Vector(“Tokyo”) — Vector(“Japan”) + Vector(“France”) ≈ Vector(“Paris”). The model discovers geography, tense, formality as directions in its space without being explicitly taught.</p><p>When you hear “embedding,” think “a token’s coordinate in meaning-space.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VNfMMWA794_khWOM.png" /></figure><h3>4. Attention</h3><p>Mechanism that lets tokens influence each other’s representations based on context. Solves polysemy — the same word having different meanings depending on surroundings.</p><p>Each token produces a Query (what am I looking for?), a Key (what do I offer?), and a Value (what information do I carry?). Attention scores are computed by matching Queries against Keys. The output for each position is a weighted sum of all Values.</p><p>Every position can attend to every other position, discovering relationships across the full sequence. This is O(n²) in sequence length — the fundamental reason why context window size is a hard constraint.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/437/0*ZRBDVHXUEuRwf4Ua.png" /></figure><h3>5. Self-Supervised Learning</h3><p>Training paradigm where the data provides its own labels — no human annotation needed. The method: mask or remove part of input, train the model to predict it.</p><p>For text, this means predicting the next token given preceding tokens. For images, mask patches and predict them. For video, predict how objects move between frames.</p><p>This is what made modern AI scalable. Training data became effectively unlimited — the entire written internet is a free training set. This single insight enabled the jump from GPT-2 to GPT-4.</p><h3>Part II: Training and Refinement</h3><h3>6. Transformer</h3><p>The dominant architecture inside LLMs. A repeated stack of two components: multi-head attention (tokens exchange contextual information) followed by a feedforward neural network (processes enriched representations per position).</p><p>Stacked 12–120+ layers deep. Early layers handle syntax, middle layers handle semantics, deep layers handle pragmatics like tone and implication.</p><p>Could theoretically be replaced by state-space models or diffusion architectures. But transformers scale predictably — double the compute, get proportionally better results — and that predictability is worth enormous engineering confidence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*EdovZQQdOxlhABpa.png" /></figure><h3>7. Fine-Tuning</h3><p>Taking a pre-trained base model and training it further on curated domain-specific (input, output) pairs. Teaches desired behavior AND suppresses unwanted behavior.</p><p>The same base model can spawn multiple fine-tuned variants — one for legal, one for medical, one for customer support. Base training is expensive and happens once. Fine-tuning is cheap and happens per use case.</p><p>Fine-tuning permanently changes model weights. This is what differentiates it from prompting techniques that only change the input.</p><h3>8. Reinforcement Learning from Human Feedback (RLHF)</h3><p>Training from preferences rather than examples. The model generates two responses, a human picks the better one. The chosen path gets reinforced (+1), the rejected path gets penalized (-1).</p><p>Over millions of comparisons, this builds a reward model that predicts human preference. Then the LLM is optimized to maximize reward model scores.</p><p>The strength: humans are much better at comparing outputs than specifying ideal outputs from scratch. The risk: it amplifies whatever preferences you measure, including flawed ones — like rewarding confident-sounding answers regardless of accuracy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tY4uGnkyfillMkqb.png" /></figure><h3>Part III: Production Systems</h3><h3>9. Retrieval Augmented Generation (RAG)</h3><p>Injecting relevant knowledge into the prompt at query time so the model answers from your data, not its training memory.</p><p>The flow: user query arrives, a retrieval system searches your knowledge base for relevant passages, those passages get injected into the prompt as context, and the model synthesizes an answer grounded in the provided material. This solves hallucination, knowledge cutoff, and proprietary data access in one architecture.</p><p>The retrieval typically uses a vector database — documents stored as embedding vectors with similarity search via algorithms like HNSW. This handles semantic mismatches that keyword search can’t. “Package never arrived” matches documents about “undelivered shipment procedures” despite zero word overlap because they’re neighbors in embedding space.</p><p>The quality bottleneck is almost always retrieval, not the LLM. Always try RAG before reaching for fine-tuning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/898/0*BTp_gFn_SYMSwqP6.jpg" /></figure><h3>10. Model Context Protocol (MCP)</h3><p>Standardized interface for models to invoke external tools and receive structured responses in real time.</p><p>An MCP server wraps any service — database, API, CRM, calendar — and exposes it to models through a consistent interface. The model decides when to call tools, interprets responses, and chains multiple calls together.</p><p>This enables real-time data access, multi-step actions, and read-write operations. Models go from passive question-answerers to active problem-solvers. The engineering challenges are permissions, error handling, and timeout management.</p><h3>11. Context Engineering</h3><p>The discipline of dynamically assembling optimal model input per query, given constraints. It encompasses system prompts, few-shot examples (providing input-output examples in the prompt to demonstrate desired format), RAG documents, MCP tool outputs, conversation history, and user preferences.</p><p>The key distinction from prompt engineering: prompt engineering is static (same system prompt every time). Context engineering is dynamic — it adapts based on who’s asking, what they’ve discussed before, and what knowledge is most relevant right now.</p><p>The hard problems are prioritization (50 relevant docs but room for 5), summarization (compressing long chat history), and cost management (every token of context costs money and adds latency).</p><h3>12. Agents</h3><p>An LLM wrapped in a loop with tool access and persistent state. The loop: receive goal, think, act (call a tool), observe the result, think again, act again, until the goal is met or a stopping condition is reached.</p><p>What separates agents from a single LLM call is multi-step strategy, state maintained across steps, error recovery, and tool orchestration. An agent can decompose complex goals into subtasks and adjust its approach when something fails.</p><p>Engineering reality: agents are fragile. They need guardrails — token budgets, step limits, human-in-the-loop checkpoints, and fallback strategies. The LLM provides intelligence; you provide reliability infrastructure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WozphkdBm_vwE_YS.png" /></figure><h3>Part IV: Reasoning</h3><h3>13. Reasoning Models</h3><p>Models that dynamically scale thinking depth based on problem difficulty. A trivial question gets a fast response. A complex proof generates hundreds of intermediate reasoning steps before committing to an answer.</p><p>The underlying technique is Chain of Thought — generating step-by-step reasoning before a final answer. Each generated token is a forward pass through the network, so intermediate steps literally add computation capacity. The explanation IS the reasoning, not just a byproduct.</p><p>These models are trained to backtrack (wait, that won’t work because…), verify (let me check: does this satisfy the constraint?), and explore alternatives. Examples include OpenAI’s o1/o3 and DeepSeek-R1.</p><p>The engineering impact: cost per query is no longer fixed. Your billing and latency budgets need to account for variable compute — easy queries are cheap and fast, hard queries are expensive and slow.</p><h3>14. Multi-Modal Models</h3><p>Models that process and generate across text, images, audio, and video. The key finding is that multi-modal training improves performance on each individual modality compared to single-modality specialists.</p><p>Training on images alongside text grounds the model’s understanding in physical reality. When it reads the word “bridge,” it has associated visual features — arches, cables, water — that enrich its representation beyond what text statistics alone could provide.</p><p>Applications span visual question answering, image generation, video summarization, and document understanding with layout awareness.</p><h3>Part V: Deployment Economics</h3><h3>15. Small Language Models (SLMs)</h3><p>Purpose-built models with 1B–7B parameters, designed for constrained tasks. They offer 10x faster inference than frontier models and can run on a single GPU or even a CPU.</p><p>Data stays on your infrastructure, which solves privacy concerns. Narrow training produces predictable behavior. A fine-tuned 3B model often outperforms GPT-4 on your specific task because it’s overfit to exactly what you need.</p><p>The tradeoff is zero generality. These models are expert at one thing and useless at everything else. That’s perfectly fine when you know exactly what success looks like.</p><h3>16. Distillation</h3><p>Transferring knowledge from a large “teacher” model to a small “student” model. Same inputs are fed to both — the student learns to match the teacher’s output distributions.</p><p>The teacher provides soft labels (70% A, 25% B, 5% C) rather than binary right/wrong signals. This richer training signal transfers knowledge more efficiently. The result is typically a 10–50x smaller model retaining 85–95% of teacher capability on the target task.</p><p>Most AI actually deployed in production is distilled models running on edge devices and cost-sensitive infrastructure — not frontier models.</p><h3>17. Quantization</h3><p>Reducing numerical precision of model weights for cheaper deployment. Going from 32-bit to 8-bit saves 75% of memory. Going from 16-bit to 4-bit does the same.</p><p>This happens AFTER training — you first train the best possible full-precision model, then compress for deployment. Training cost stays the same. Inference cost drops dramatically.</p><p>The tradeoff is slight quality degradation at the margins — rare words, subtle distinctions, high-precision numerical tasks. For most practical applications, the quality loss is imperceptible while the cost and latency improvements are transformative. This often makes the difference between needing a GPU cluster and running on a laptop.</p><h3>Decision Cheat Sheet</h3><p><strong>RAG or fine-tune?</strong> RAG first. Fine-tune only when the model needs to think differently, not just know more.</p><p><strong>How big a model?</strong> Smallest that works on your task. Measure on your data, not benchmarks.</p><p><strong>Agents or simple prompt?</strong> Simple first. Agents only when the task genuinely requires multi-step tool use.</p><p><strong>Context window full?</strong> Prioritize ruthlessly. Summarize history with a cheap model. Retrieve only the top-relevant docs.</p><h3>The Stack (bottom-up)</h3><pre>ARCHITECTURE:  Tokenization → Vectors → Attention → Transformer<br>TRAINING:      Self-Supervised → Fine-Tuning → RLHF<br>REASONING:     Reasoning Models (with CoT) → Multi-Modal<br>APPLICATIONS:  RAG (with Vector DB) → MCP → Context Engineering (with Few-Shot) → Agents<br>DEPLOYMENT:    Small Models → Distillation → Quantization</pre><h3>References</h3><p>[1] Vaswani, A., Shazeer, N., Parmar, N., Uszkoreit, J., Jones, L., Gomez, A.N., Kaiser, L., and Polosukhin, I. (2017). Attention Is All You Need. <em>Advances in Neural Information Processing Systems</em>, 30.</p><p>[2] Sen, G. (2025). 20 AI Concepts Explained in 40 Minutes. <em>YouTube, gkcs</em></p><p>[3] Devlin, J., Chang, M.W., Lee, K., and Toutanova, K. (2018). BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding. <em>arXiv preprint arXiv:1810.04805</em>.</p><p>[4] Brown, T.B., Mann, B., Ryder, N., Subbiah, M., et al. (2020). Language Models are Few-Shot Learners. <em>Advances in Neural Information Processing Systems</em>, 33.</p><p>[5] Ouyang, L., Wu, J., Jiang, X., Almeida, D., et al. (2022). Training Language Models to Follow Instructions with Human Feedback. <em>Advances in Neural Information Processing Systems</em>, 35.</p><p>[6] Lewis, P., Perez, E., Piktus, A., Petroni, F., et al. (2020). Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks. <em>Advances in Neural Information Processing Systems</em>, 33.</p><p>[7] Gu, A. and Dao, T. (2023). Mamba: Linear-Time Sequence Modeling with Selective State Spaces. <em>arXiv preprint arXiv:2312.00752</em>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2e45469616b8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting started with Practical Deep Learning]]></title>
            <link>https://medium.com/@_MJ_/getting-started-with-practical-deep-learning-cbe2a083c994?source=rss-723d2a0e9981------2</link>
            <guid isPermaLink="false">https://medium.com/p/cbe2a083c994</guid>
            <category><![CDATA[convolution-neural-net]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[pretrained-language-model]]></category>
            <category><![CDATA[large-language-models]]></category>
            <dc:creator><![CDATA[Jayashree Mallipudi]]></dc:creator>
            <pubDate>Fri, 23 Feb 2024 05:59:25 GMT</pubDate>
            <atom:updated>2024-02-23T05:59:25.494Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/873/0*_k1IlqA4nIQJAteB.jpg" /></figure><p>These days AI is been on quite a trend so lets try to understand on the basics on where is all started and slowly we will go to the today’s large language models.</p><p>In this article I am going to start on the hello world of deep learning (which is nothing but image classification) and then lets go deep.</p><p>The Hello world I am talking about in today’s world is MNIST digit classification problem</p><pre><strong>Index Of Contents</strong><br>1. Downloading the Dataset<br>2. Data Preparation and Cleaning<br>    a. Reshaping<br>    b. Normalizing<br>    c. Categorizing<br>3. Build the modal and <br>4. compiling<br>5. Modal Training<br>6. Analyze<br>7. Methods to Improve<br>    a. Data Augmentation<br>8. Save the Model<br>9. Testing<br>10.Pre Trained Models<br>11.Ways to improve <br>12.Other Advanced Works<br></pre><p>Steps to be followed for any regular classification tasks would be:</p><h4><strong>1. Load the dataset</strong></h4><p>I would suggest few ways for this</p><pre>from tensorflow.keras.datasets import mnist #for our hello world<br>#Load a custom dataset and then read the csv file using<br>import pandas as pd<br>pd.read_csv(&quot;file_path/filename.csv&quot;)</pre><h4>2. Preprocessing the data</h4><p>Next big thing is to divide the dataset into training and validation sets and then preprocess</p><pre>(x_train, y_train), (x_valid, y_valid) = mnist.load_data()<br>#if there are in diffrent files load them separatly<br>train_df = pd.read_csv(&quot;filepath/filename_train.csv&quot;)<br>valid_df = pd.read_csv(&quot;filepath/filename_valid.csv&quot;)<br># Separate out our target values<br>y_train = train_df[&#39;label&#39;]<br>y_valid = valid_df[&#39;label&#39;]<br>del train_df[&#39;label&#39;]<br>del valid_df[&#39;label&#39;]<br># Separate out our image vectors<br>x_train = train_df.values<br>x_valid = valid_df.values</pre><p>preprocessing generally might include</p><p><em>a. Reshaping the data</em></p><pre>#If needed this is incase of MNIST dataset we convert it into <br>#single array of 784 continuous pixels (note: 28x28 = 784)<br>#This is also called flattening the image to make it simple although for more advanced models you<br>#mmight want to have original shape to get features<br>x_train = x_train.reshape(60000, 784)<br>x_valid = x_valid.reshape(10000, 784)</pre><p><em>b.Normalizing</em></p><pre>#Normalize x_train and x_valid.<br>x_train = x_train / 255<br>x_valid = x_valid / 255<br>#Another way<br>x_train = train_df.values / 255<br>x_valid = valid_df.values / 255</pre><p><em>c.Categorizing</em></p><pre><br>import tensorflow.keras as keras<br>#its 10 in case of mnist since it can only categorize between 0 to 9  <br>num_categories = 10<br><br>y_train = keras.utils.to_categorical(y_train, num_categories)<br>y_valid = keras.utils.to_categorical(y_valid, num_categories)</pre><h4>3. Building the model</h4><p>Using tensorflow for this article</p><p>Model typically consists of these things</p><ol><li>An input layer, which will receive data in some expected format</li><li>Several <a href="https://developers.google.com/machine-learning/glossary#hidden-layer">hidden layers</a>, each comprised of many <em>neurons</em>. Each <a href="https://developers.google.com/machine-learning/glossary#neuron">neuron</a> will have the ability to affect the network’s guess with its <em>weights</em>, which are values that will be updated over many iterations as the network gets feedback on its performance and learns</li><li>An output layer, which will depict the network’s guess for a given image</li></ol><pre>from tensorflow.keras.models import Sequential<br>from tensorflow.keras.layers import Dense<br>#Instantiating the Model<br>model = Sequential()<br>#Input layer<br>model.add(Dense(units=512, activation=&#39;relu&#39;, input_shape=(784,)))<br>#Hidden layer<br>model.add(Dense(units = 512, activation=&#39;relu&#39;))<br>#output layer<br>model.add(Dense(units = 24, activation=&#39;softmax&#39;))</pre><h4>4. Compiling the model before training</h4><p>Here we specify a <a href="https://developers.google.com/machine-learning/glossary#loss">loss function</a> which will be used for the model to understand how well it is performing during training. We also specify that we would like to track accuracy while the model trains</p><pre>model.compile(loss=&#39;categorical_crossentropy&#39;, metrics=[&#39;accuracy&#39;])</pre><h4>5. Training the model</h4><p>When fitting (training) a model with Keras, we use the model’s <a href="https://www.tensorflow.org/api_docs/python/tf/keras/Model#fit">fit</a> method. It expects the following arguments:</p><ul><li>The training data</li><li>The labels for the training data</li><li>The number of times it should train on the entire training dataset (called an <em>epoch</em>)</li><li>The validation or test data, and its labels</li></ul><pre>history = model.fit(<br>    x_train, y_train, epochs=5, verbose=1, validation_data=(x_valid, y_valid)<br>)</pre><h4>6. Analyzing</h4><p>Once the model is trained you could find out its accuracy from validation set and analyze its performance, if its too good on the training set and bad on the validation then it could signify overfitting.</p><p>You need to change the model architecture accordingly such that it could handle the overfitting one such advance method for image classification is convolutional neural network.</p><p>These are the sample model structure of a convulutional neural network.</p><pre>from tensorflow.keras.models import Sequential<br>from tensorflow.keras.layers import (<br>    Dense,<br>    Conv2D,<br>    MaxPool2D,<br>    Flatten,<br>    Dropout,<br>    BatchNormalization,<br>)<br><br>model = Sequential()<br>model.add(Conv2D(75, (3, 3), strides=1, padding=&quot;same&quot;, activation=&quot;relu&quot;, <br>                 input_shape=(28, 28, 1)))<br>model.add(BatchNormalization())<br>model.add(MaxPool2D((2, 2), strides=2, padding=&quot;same&quot;))<br>model.add(Conv2D(50, (3, 3), strides=1, padding=&quot;same&quot;, activation=&quot;relu&quot;))<br>model.add(Dropout(0.2))<br>model.add(BatchNormalization())<br>model.add(MaxPool2D((2, 2), strides=2, padding=&quot;same&quot;))<br>model.add(Conv2D(25, (3, 3), strides=1, padding=&quot;same&quot;, activation=&quot;relu&quot;))<br>model.add(BatchNormalization())<br>model.add(MaxPool2D((2, 2), strides=2, padding=&quot;same&quot;))<br>model.add(Flatten())<br>model.add(Dense(units=512, activation=&quot;relu&quot;))<br>model.add(Dropout(0.3))<br>model.add(Dense(units=num_classes, activation=&quot;softmax&quot;))</pre><p>Let me explain these layers and what they do</p><p><strong>Conv2D</strong></p><p>These are our 2D convolutional layers. Small kernels will go over the input image and detect features that are important for classification. Earlier convolutions in the model will detect simple features such as lines. Later convolutions will detect more complex features. Let’s look at our first Conv2D layer:</p><pre>model.add(Conv2D(75 , (3,3) , strides = 1 , padding = &#39;same&#39;...)</pre><p>75 refers to the number of filters that will be learned. (3,3) refers to the size of those filters. Strides refer to the step size that the filter will take as it passes over the image. Padding refers to whether the output image that’s created from the filter will match the size of the input image.</p><p><a href="https://www.tensorflow.org/api_docs/python/tf/keras/layers/BatchNormalization"><strong>BatchNormalization</strong></a></p><p>Like normalizing our inputs, batch normalization scales the values in the hidden layers to improve training</p><p><strong>MaxPooling</strong></p><p>Max pooling takes an image and essentially shrinks it to a lower resolution. It does this to help the model be robust to translation (objects moving side to side), and also makes our model faster.</p><p><strong>Dropout</strong></p><p>Dropout is a technique for preventing overfitting. Dropout randomly selects a subset of neurons and turns them off, so that they do not participate in forward or backward propagation in that particular pass. This helps to make sure that the network is robust and redundant, and does not rely on any one area to come up with answers.</p><p><a href="https://www.tensorflow.org/api_docs/python/tf/keras/layers/Flatten"><strong>Flatten</strong></a></p><p>Flatten takes the output of one layer which is multidimensional, and flattens it into a one-dimensional array. The output is called a feature vector and will be connected to the final classification layer.</p><p><a href="https://www.tensorflow.org/api_docs/python/tf/keras/layers/Dense"><strong>Dense</strong></a></p><p>We have seen dense layers before in our earlier models. Our first dense layer (512 units) takes the feature vector as input and learns which features will contribute to a particular classification. The second dense layer (24 units) is the final classification layer that outputs our prediction.</p><h4>7. Methods to Improve</h4><p>To further improve the performance of the model there is a technique called data Augmentation.</p><p><strong>a. Data Augmentation</strong></p><p>In order to teach our model to be more robust when looking at new data, we’re going to programmatically increase the size and variance in our dataset. This is known as <a href="https://link.springer.com/article/10.1186/s40537-019-0197-0"><em>data augmentation</em></a>, a useful technique for many deep learning applications.</p><p>The increase in size gives the model more images to learn from while training. The increase in variance helps the model ignore unimportant features and select only the features that are truly important in classification, allowing it to generalize better.</p><p>Same image you could generate 100 different images by performing some augmentations(flip,channel shifting,rotate) on top making more robust model</p><p>while performing augmentation need to keep in mind if the dataset generated makes sense to the original dataset it need to a possible data not all kinds of augmentation makes sense to our dataset s choose wisely shouldnot change the meaning of the dataset.</p><p>We perform augmentation only on traning not on validation to make it unbiased.</p><pre>from tensorflow.keras.preprocessing.image import ImageDataGenerator<br><br>datagen = ImageDataGenerator(<br>    rotation_range=10,  # randomly rotate images in the range (degrees, 0 to 180)<br>    zoom_range=0.1,  # Randomly zoom image<br>    width_shift_range=0.1,  # randomly shift images horizontally (fraction of total width)<br>    height_shift_range=0.1,  # randomly shift images vertically (fraction of total height)<br>    horizontal_flip=True,  # randomly flip images horizontally<br>    vertical_flip=False, # Don&#39;t randomly flip images vertically<br>)  </pre><p>ImageDataGenerator generates in <a href="https://machinelearningmastery.com/how-to-control-the-speed-and-stability-of-training-neural-networks-with-gradient-descent-batch-size/">batches</a> of our data so that our model can train on a random sample</p><pre>import matplotlib.pyplot as plt<br>import numpy as np<br>batch_size = 32<br>img_iter = datagen.flow(x_train, y_train, batch_size=batch_size)<br><br>datagen.fit(x_train)</pre><p>After this we do regular compiling and traning</p><pre>model.compile(loss=&#39;categorical_crossentropy&#39;, metrics=[&#39;accuracy&#39;])<br>model.fit(img_iter,<br>          epochs=10,<br>          steps_per_epoch=len(x_train)/batch_size, # Run same number of steps we would if we were not using a generator.<br>          validation_data=(x_valid, y_valid)) </pre><h4>8.Save the model</h4><p>Once our model is performing well and we are satisfied we need to save the model in order to test it on the new data</p><pre>model.save(&#39;model_name&#39;)</pre><h4>9. Testing</h4><p>In order to test it load the model</p><pre>from tensorflow import keras<br><br>model = keras.models.load_model(&#39;model_name&#39;)</pre><p>While predicting with model the input must match the shape of the data that the model was trained on.</p><pre><br>import matplotlib.pyplot as plt<br>import matplotlib.image as mpimg<br><br>def show_image(image_path):<br>    image = mpimg.imread(image_path)<br>    plt.imshow(image, cmap=&#39;gray&#39;)<br>#change the color if inpust is not matching <br>from tensorflow.keras.preprocessing import image as image_utils<br><br>def load_and_scale_image(image_path):<br>    image = image_utils.load_img(image_path, color_mode=&quot;grayscale&quot;, target_size=(28,28))<br>    return image<br><br><br>def predict_letter(file_path):<br>    # Show image<br>    show_image(file_path)<br>    <br>    # Load and scale image<br>    image = load_and_scale_image(file_path)<br>    # Convert to array<br>    image = image_utils.img_to_array(image)<br>    # Reshape image<br>    image = image.reshape(1,28,28,1)<br>    # Normalize image<br>    image = image/255<br>    # Make prediction<br>    prediction = model.predict(image)<br>    <br>    # Return prediction<br>    return prediction   <br>predict_letter(&quot;image_path&quot;)<br></pre><h4>10. Pre Trained Models</h4><p>Other Option is to use Pre trained models so that we could directly use the models that are trained by large datasets.</p><p>One such model for image dataset(Imagenet) is VGG16 so let see how to use them.</p><pre>from tensorflow.keras.applications import VGG16<br>  <br># load the VGG16 network *pre-trained* on the ImageNet dataset<br>model = VGG16(weights=&quot;imagenet&quot;)<br>model.summary()</pre><p>and then we do the same preprocess and prediction directly without any training necessary.</p><pre><br>from tensorflow.keras.applications.vgg16 import decode_predictions<br><br>def readable_prediction(image_path):<br>    # Show image<br>    show_image(image_path)<br>    # Load and pre-process image<br>    image = load_and_process_image(image_path)<br>    # Make predictions<br>    predictions = model.predict(image)<br>    # Print predictions in readable form<br>    print(&#39;Predicted:&#39;, decode_predictions(predictions, top=3))</pre><p>In case we cannot find a pre-trained model that matches our needs</p><h4>11. Ways to further improve</h4><p>Transfer Learning and Fine Tuning</p><p>Here we have the concept of transfer learning and fine tuning where we freeze the model to some extent and then for last few layers we fine tune so that its particular to our dataset.</p><p>Original architecture can be intact or can change a few layers as well in the model of our pre trained model</p><p>To do this we first freeze the baseline model (trainable as false)and then ad on extra layers.</p><pre>from tensorflow import keras<br><br>base_model = keras.applications.VGG16(<br>    weights=&#39;imagenet&#39;,  # Load weights pre-trained on ImageNet.<br>    input_shape=(224, 224, 3),<br>    include_top=False)<br>#Freezing<br>base_model.trainable = False<br>#Adding new layers<br>inputs = keras.Input(shape=(224, 224, 3))<br># Separately from setting trainable on the model, we set training to False <br>x = base_model(inputs, training=False)<br>x = keras.layers.GlobalAveragePooling2D()(x)<br># A Dense classifier with a single unit (binary classification)<br>outputs = keras.layers.Dense(1)(x)<br>model = keras.Model(inputs, outputs)Note:</pre><p>and then compile and run data augmentation(if needed) and train</p><p>But if this is not performing well.You can also do finetuning for that strat with unfreezing the base model and fine tune train with small learning rate</p><pre># Unfreeze the base model<br>base_model.trainable = True<br><br># It&#39;s important to recompile your model after you make any changes<br># to the `trainable` attribute of any inner layer, so that your changes<br># are taken into account<br>model.compile(optimizer=keras.optimizers.RMSprop(learning_rate = .00001),  # Very low learning rate<br>              loss=keras.losses.BinaryCrossentropy(from_logits=True),<br>              metrics=[keras.metrics.BinaryAccuracy()])<br>model.fit(train_it, steps_per_epoch=12, validation_data=valid_it, validation_steps=4, epochs=10)</pre><blockquote><strong>Other Models that are Available</strong></blockquote><p>Now not always we need convolutional neural networks we have many others as well not just in the field of computer vision one such is natural language processing since system only understands numbers we convert words to numbers using dictionary map using am embedding.</p><p>Recurrent neural network build on of it and then we have LSTM(long short term memory).</p><p>Autoencoders help in reducing the size of the input using embedding and then decoding back here in between we could cut the encoding part add more things into it just like with pretrained models.</p><p>Embedding is the major point which means we higher dimensional representation of your data is embedding into a lower dimension representation. Embedding data doesnot look or correlate to original data but can decode into original data.</p><p>Generative Adversarial networks(GAN) is from random noise we could generate a realistic images. while descrimator rejects all the fake images such that generator improves to make it realistic.But recently we have more advanced methods like stable diffusion.</p><p>These days, many data scientists start their projects by borrowing model properties from a similar project. Assuming the problem is not totally unique, there’s a great chance that people have created models that will perform well which are posted in online repositories like <a href="https://www.tensorflow.org/hub">TensorFlow Hub</a> and the <a href="https://ngc.nvidia.com/catalog/models">NGC Catalog</a>.</p><p>Hope this gives you as insight of actual deep learning processes.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cbe2a083c994" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploratory Data Analysis using Python —  A Case Study]]></title>
            <link>https://medium.com/@_MJ_/exploratory-data-analysis-using-python-a-case-study-78aa34e5922e?source=rss-723d2a0e9981------2</link>
            <guid isPermaLink="false">https://medium.com/p/78aa34e5922e</guid>
            <category><![CDATA[jovian-ml]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[exploratory-data-analysis]]></category>
            <category><![CDATA[matplotlib]]></category>
            <dc:creator><![CDATA[Jayashree Mallipudi]]></dc:creator>
            <pubDate>Thu, 07 Jul 2022 10:36:02 GMT</pubDate>
            <atom:updated>2022-07-11T14:38:04.851Z</atom:updated>
            <content:encoded><![CDATA[<h4>Data Science</h4><h3>Exploratory Data Analysis using Python — A Case Study</h3><h4><strong>Analyzing agricultural-raw-material-prices dataset over the years.</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/1*UXoKwYkYkGPrmkrczEB3Vw.png" /><figcaption>Exploratory data analysis on raw-materials dataset</figcaption></figure><p>This dataset consists of prices and price % change for coarse wool, copra, cotton, fine wool, hard log, hard sawn wood, hide, plywood, rubber, soft log, soft sawn wood, and wood pulp.</p><p><strong>The following topics are covered in this article:</strong></p><pre><strong>Index Of Contents</strong><br>· <a href="#a7f6">Downloading the Dataset</a><br>· <a href="#9a64">Data Preparation and Cleaning</a><br>· <a href="#971a">Exploratory Analysis and Visualization</a><br>· <a href="#94e2">Asking and Answering Questions</a><br>· <a href="#0ded">Inferences and Conclusion</a><br>· <a href="#e69a">Future Work</a><br>· <a href="#203a">References</a></pre><h3>Downloading the Dataset</h3><p>In this tutorial, we’ll analyze the agricultural-raw-material-prices dataset.</p><p>There are several options for getting the dataset into Jupyter:</p><ul><li>Download the CSV manually and upload it via Jupyter’s GUI</li><li>Use the urlretrieve function from the urllib.request to download CSV files from a raw URL</li><li>Use a helper library, e.g., <a href="https://jovian.ai/outlink?url=https%3A%2F%2Fgithub.com%2FJovianML%2Fopendatasets">opendatasets</a>, which contains a collection of curated datasets and provides a helper function for direct download.</li></ul><p>We’ll use the opendatasets helper library to download the files.</p><p>Let’s begin by downloading the data, and listing the files within the dataset.</p><pre>dataset_url = &#39;https://www.kaggle.com/kianwee/agricultural-raw-material-prices-19902020&#39;</pre><pre>import opendatasets as od<br>od.download(dataset_url)</pre><h3>Data Preparation and Cleaning</h3><pre><em># </em><strong><em>Import required packages</em></strong><br>import numpy as np<br>import pandas as pd</pre><p><strong>Loading the dataset into a data frame using Pandas</strong></p><pre>df=pd.read_csv(&#39;./agricultural-raw-material-prices-19902020/agricultural_raw_material.csv&#39;)</pre><p><strong>Exploring the dataset</strong></p><pre>df.shape (361, 25)</pre><pre>df.info<br><strong><em>#Checking Null Values of each column</em></strong><br>df.isnull().sum()</pre><p><strong>Handle missing, incorrect and invalid data</strong></p><pre><em># Replacing %, &quot;,&quot; and &quot;-&quot;</em><br>df = df.replace(&#39;%&#39;, &#39;&#39;, regex=True)<br>df = df.replace(&#39;,&#39;, &#39;&#39;, regex=True)<br>df = df.replace(&#39;-&#39;, &#39;&#39;, regex=True)<br>df = df.replace(&#39;&#39;, np.nan)<br>df = df.replace(&#39;MAY90&#39;, np.nan)</pre><pre><em># Dropping rows with NaN values</em><br>df = df.dropna()</pre><pre><em># Check to see if all NaN values are resolved</em><br>df.isnull().sum()</pre><pre><em># Converting data type to float</em><br>lst = [&quot;Coarse wool Price&quot;, &quot;Coarse wool price % Change&quot;, &quot;Copra Price&quot;, &quot;Copra price % Change&quot;, &quot;Cotton price % Change&quot;,&quot;Fine wool Price&quot;, &quot;Fine wool price % Change&quot;, &quot;Hard log price % Change&quot;, &quot;Hard sawnwood price % Change&quot;, &quot;Hide price % change&quot;, &quot;Plywood price % Change&quot;, &quot;Rubber price % Change&quot;, &quot;Softlog price % Change&quot;, &quot;Soft sawnwood price % Change&quot;, &quot;Wood pulp price % Change&quot;]<br>df[lst] = df[lst].astype(&quot;float&quot;)</pre><pre>df.dtypes</pre><p><strong>DateTime columns</strong></p><p>formatting the datetime column and setting it as index for the dataset</p><pre>df.Month  = pd.to_datetime(df.Month.str.upper(), format=&#39;%b%y&#39;, yearfirst=False)</pre><pre><em># Indexing month</em><br>df = df.set_index(&#39;Month&#39;)</pre><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ai%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ai%2Fjayashreemallipudi3%2Fagricultural-raw-material-prices-project%2Fv%2F26%26cellId%3D29&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ai%2Fjayashreemallipudi3%2Fagricultural-raw-material-prices-project%2Fv%2F26%26cellId%3D29&amp;image=https%3A%2F%2Fapi.jovian.ai%2Fapi%2Fgist%2Fbbc36d5a4e3e40878bb3cc3c69b5221b%2Fpreview%2Fda85e565fa564d498ba9212a9ddf41aa&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/e429a722b5fef398379be4e737886c77/href">https://medium.com/media/e429a722b5fef398379be4e737886c77/href</a></iframe><h3>Exploratory Analysis and Visualization</h3><p>Let’s begin by importingmatplotlib.pyplot and seaborn.</p><pre>import seaborn as sns<br>import matplotlib<br>import matplotlib.pyplot as plt<br>%matplotlib inline</pre><pre>sns.set_style(&#39;darkgrid&#39;)<br>matplotlib.rcParams[&#39;font.size&#39;] = 14<br>matplotlib.rcParams[&#39;figure.figsize&#39;] = (9, 5)<br>matplotlib.rcParams[&#39;figure.facecolor&#39;] = &#39;#00000000&#39;</pre><p><strong>Heatmap</strong></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ai%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ai%2Fjayashreemallipudi3%2Fagricultural-raw-material-prices-project%2Fv%2F26%26cellId%3D36&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ai%2Fjayashreemallipudi3%2Fagricultural-raw-material-prices-project%2Fv%2F26%26cellId%3D36&amp;image=https%3A%2F%2Fapi.jovian.ai%2Fapi%2Fgist%2Fbbc36d5a4e3e40878bb3cc3c69b5221b%2Fpreview%2Fda85e565fa564d498ba9212a9ddf41aa&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/665f5ad748487c9880a6d4fffd288f97/href">https://medium.com/media/665f5ad748487c9880a6d4fffd288f97/href</a></iframe><p>The Heatmap depicts correlation between the raw-materials higher the correlated value higher chance of being two raw-materials related but not necessarily</p><p>Explore one or more columns by plotting a graph below, and add some explanation about it <strong>Correlation matrix</strong></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ai%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ai%2Fjayashreemallipudi3%2Fagricultural-raw-material-prices-project%2Fv%2F26%26cellId%3D39&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ai%2Fjayashreemallipudi3%2Fagricultural-raw-material-prices-project%2Fv%2F26%26cellId%3D39&amp;image=https%3A%2F%2Fapi.jovian.ai%2Fapi%2Fgist%2Fbbc36d5a4e3e40878bb3cc3c69b5221b%2Fpreview%2Fda85e565fa564d498ba9212a9ddf41aa&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/e2b3484b9001411353b2b6d1c8c7d16d/href">https://medium.com/media/e2b3484b9001411353b2b6d1c8c7d16d/href</a></iframe><p>From this plot we can say that there is almost no relation between % change of raw-material prices</p><ol><li>the negative value implies two variables are negatively correlated (one increase,other decrease)</li><li>Zero implies no relation</li><li>other wise higher the value higher the chance of relation.</li></ol><h3>prices and their % change plots</h3><h4>Coarse wool</h4><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ai%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ai%2Fjayashreemallipudi3%2Fagricultural-raw-material-prices-project%2Fv%2F26%26cellId%3D43&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ai%2Fjayashreemallipudi3%2Fagricultural-raw-material-prices-project%2Fv%2F26%26cellId%3D43&amp;image=https%3A%2F%2Fapi.jovian.ai%2Fapi%2Fgist%2Fbbc36d5a4e3e40878bb3cc3c69b5221b%2Fpreview%2Fda85e565fa564d498ba9212a9ddf41aa&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/ea18166d4eb7371ae30a86801916992a/href">https://medium.com/media/ea18166d4eb7371ae30a86801916992a/href</a></iframe><p>Similarly we could find the visualization of all other features given in dataset.</p><h3>Asking and Answering Questions</h3><p>Q1: Find out the normal price change for each raw material</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ai%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ai%2Fjayashreemallipudi3%2Fagricultural-raw-material-prices-project%2Fv%2F26%26cellId%3D71&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ai%2Fjayashreemallipudi3%2Fagricultural-raw-material-prices-project%2Fv%2F26%26cellId%3D71&amp;image=https%3A%2F%2Fapi.jovian.ai%2Fapi%2Fgist%2Fbbc36d5a4e3e40878bb3cc3c69b5221b%2Fpreview%2Fda85e565fa564d498ba9212a9ddf41aa&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/b9f3048fea7c30c6b88397b64eaec287/href">https://medium.com/media/b9f3048fea7c30c6b88397b64eaec287/href</a></iframe><p>We can observe that most raw-materials have ideal frequent %change less than 5%</p><p>Q2: Find the raw-material that has lowest price over years</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ai%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ai%2Fjayashreemallipudi3%2Fagricultural-raw-material-prices-project%2Fv%2F26%26cellId%3D75&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ai%2Fjayashreemallipudi3%2Fagricultural-raw-material-prices-project%2Fv%2F26%26cellId%3D75&amp;image=https%3A%2F%2Fapi.jovian.ai%2Fapi%2Fgist%2Fbbc36d5a4e3e40878bb3cc3c69b5221b%2Fpreview%2Fda85e565fa564d498ba9212a9ddf41aa&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/51f490e9521402f7fe8611ef81cb5062/href">https://medium.com/media/51f490e9521402f7fe8611ef81cb5062/href</a></iframe><ol><li>We can see cotton and rubber are of lowest prices</li><li>lets compare prices to better understand which is lowest</li></ol><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ai%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ai%2Fjayashreemallipudi3%2Fagricultural-raw-material-prices-project%2Fv%2F26%26cellId%3D77&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ai%2Fjayashreemallipudi3%2Fagricultural-raw-material-prices-project%2Fv%2F26%26cellId%3D77&amp;image=https%3A%2F%2Fapi.jovian.ai%2Fapi%2Fgist%2Fbbc36d5a4e3e40878bb3cc3c69b5221b%2Fpreview%2Fda85e565fa564d498ba9212a9ddf41aa&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/d97f3c3ed689e2ebd61d8ec50292d94d/href">https://medium.com/media/d97f3c3ed689e2ebd61d8ec50292d94d/href</a></iframe><p><strong>cotton is lowest price rawmaterials in recent years</strong></p><p>Both cotton and rubber are low price materials</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ai%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ai%2Fjayashreemallipudi3%2Fagricultural-raw-material-prices-project%2Fv%2F26%26cellId%3D79&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ai%2Fjayashreemallipudi3%2Fagricultural-raw-material-prices-project%2Fv%2F26%26cellId%3D79&amp;image=https%3A%2F%2Fapi.jovian.ai%2Fapi%2Fgist%2Fbbc36d5a4e3e40878bb3cc3c69b5221b%2Fpreview%2Fda85e565fa564d498ba9212a9ddf41aa&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/d6e30a53ba26c6e61dd51d3c85a5e7ad/href">https://medium.com/media/d6e30a53ba26c6e61dd51d3c85a5e7ad/href</a></iframe><p>From the graphs we could analyze raw materials into types according their price over years</p><p>low price materials</p><p>-cotton,hide,softlog,Hard log,Soft sawnwood Price,rubber</p><p>High price materials</p><p>-coarse wool,copra,fine wool,hard sawnwood,woodpulp,plywood</p><p>Q3: which raw material has the highest and lowest price % change</p><pre>import random as random</pre><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ai%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ai%2Fjayashreemallipudi3%2Fagricultural-raw-material-prices-project%2Fv%2F26%26cellId%3D83&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ai%2Fjayashreemallipudi3%2Fagricultural-raw-material-prices-project%2Fv%2F26%26cellId%3D83&amp;image=https%3A%2F%2Fapi.jovian.ai%2Fapi%2Fgist%2Fbbc36d5a4e3e40878bb3cc3c69b5221b%2Fpreview%2Fda85e565fa564d498ba9212a9ddf41aa&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/367c333ecbc234a7e3f144859b1096ba/href">https://medium.com/media/367c333ecbc234a7e3f144859b1096ba/href</a></iframe><p>We can see the highest % change at more than 60 for soft sawnwood and lowest % change is for plywood at less at 20</p><p>Q4: Find the raw materials with drastic price change</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ai%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ai%2Fjayashreemallipudi3%2Fagricultural-raw-material-prices-project%2Fv%2F26%26cellId%3D87&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ai%2Fjayashreemallipudi3%2Fagricultural-raw-material-prices-project%2Fv%2F26%26cellId%3D87&amp;image=https%3A%2F%2Fapi.jovian.ai%2Fapi%2Fgist%2Fbbc36d5a4e3e40878bb3cc3c69b5221b%2Fpreview%2Fda85e565fa564d498ba9212a9ddf41aa&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/b3dccad7b1835d374efda40961fda3c6/href">https://medium.com/media/b3dccad7b1835d374efda40961fda3c6/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ai%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ai%2Fjayashreemallipudi3%2Fagricultural-raw-material-prices-project%2Fv%2F26%26cellId%3D88&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ai%2Fjayashreemallipudi3%2Fagricultural-raw-material-prices-project%2Fv%2F26%26cellId%3D88&amp;image=https%3A%2F%2Fapi.jovian.ai%2Fapi%2Fgist%2Fbbc36d5a4e3e40878bb3cc3c69b5221b%2Fpreview%2Fda85e565fa564d498ba9212a9ddf41aa&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/1387d0b0b8e4178d07017b4ccea482a9/href">https://medium.com/media/1387d0b0b8e4178d07017b4ccea482a9/href</a></iframe><p>Price change is drastic for hard log price among low price range materials and Among high price materials it is Fine wool prices</p><p>Q5: Figure out the price range of low priced raw-materials</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ai%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ai%2Fjayashreemallipudi3%2Fagricultural-raw-material-prices-project%2Fv%2F26%26cellId%3D91&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ai%2Fjayashreemallipudi3%2Fagricultural-raw-material-prices-project%2Fv%2F26%26cellId%3D91&amp;image=https%3A%2F%2Fapi.jovian.ai%2Fapi%2Fgist%2Fbbc36d5a4e3e40878bb3cc3c69b5221b%2Fpreview%2Fda85e565fa564d498ba9212a9ddf41aa&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/d40fc2fff1db235775e20280d1fcf983/href">https://medium.com/media/d40fc2fff1db235775e20280d1fcf983/href</a></iframe><p>Box Plot gives us the distribution of data</p><p>It includes: Inter quartile range is between Q3 and Q1 minimum, first quartile (Q1), median, third quartile (Q3), and maximum and outliers</p><p>Let us save and upload our work to Jovian before continuing.</p><h3>Inferences and Conclusion</h3><ol><li>We found out the high range and low range raw-materials according to their prices.</li><li>high and low %Change materials</li><li>We could identify the the range of prices change over the years.</li><li>Correlation between them using a heatmap</li></ol><h3>Future Work</h3><ol><li>Further we could find out relationship between raw-materials in details and with the help of business knowledge we could figure out the closest related raw materials</li><li>We could also predict the prices of raw-materials by analysing the previous years</li><li>Predicting the range of price change and based on that we could plan our raw material usage in advance for the coming the year and figure out any alternative materials.</li></ol><h3>References</h3><p>Dataset link : <a href="https://www.kaggle.com/datasets/kianwee/agricultural-raw-material-prices-19902020">https://www.kaggle.com/datasets/kianwee/agricultural-raw-material-prices-19902020</a></p><p>Thanks for reading out …</p><p>Hope you find this article helpful:)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=78aa34e5922e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tensors Explained]]></title>
            <link>https://medium.com/@_MJ_/tensors-explained-1e267fd8260?source=rss-723d2a0e9981------2</link>
            <guid isPermaLink="false">https://medium.com/p/1e267fd8260</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[tensor]]></category>
            <category><![CDATA[tensorflow]]></category>
            <dc:creator><![CDATA[Jayashree Mallipudi]]></dc:creator>
            <pubDate>Thu, 19 May 2022 10:36:54 GMT</pubDate>
            <atom:updated>2022-05-19T10:36:54.107Z</atom:updated>
            <content:encoded><![CDATA[<p>A Container for numbers</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eRe-bEB5b_jOzQwkxE2W0w.png" /></figure><p>Tensors is a data structure(container to store numbers)</p><p>It is a common term for storing numbers — Nd array</p><p>0D array-scaler ,1D-vector, 2D -matrix</p><p>Creating of Nd tensors-&gt;collection of (N-1)d tensors</p><pre>np.array(4)# single number 0D tensor<br>np.array([1,2,3,4])#1D tensor/vector <br>Here ,dim of tensor is 1,dim of vector is 4<br>mat=np.array([1,2,3],[4,5,6],[7,8,9])#2D Tensor</pre><p><strong>Properties of tensors</strong></p><p>Axes, rank, dimensions — No of axes=rank=dimension of tensor</p><p>Shape(no of rows, no of cols)</p><p>size of tensor(tot no of items)rows x cols</p><p>Examples</p><ol><li>Machine learning tabular data each row can be considered as a 1D tensor i.e [feature1,feature2,feature3 of each row] is a 3D vector but every row represents a datapoint in 1D tensor #no matter how many features in a row it is a 1D tensor</li><li>2D tensor collection of 1D tensor i.e tabular data of n no of rows where each row is a 1D tensor</li><li>3D tensor in NLP text data here using vectorization we convert text into numbers vectors Here, each word convert into a 1D tensor since each text has multiple words its a collection of 1D which is 2D tensor, data represents multiple text(2D) so it is a 3D tensors.</li><li>Time series data is a 3D tensors are used 10yrs,365 days,(high, low each day) each day 1D ,365 days 2D,10yrs 3D shape is(10,365,2)</li><li>Image processing 4D tensors each image is a 3D tensor(3,1200,800)RGB pixels for each images and batches of images is a 4D tensors</li><li>Videos is a 5D tensors,480p resolution -480x720(3 channels rgb)480x720x3 60sec videos at 30fps frames per sec speed=1800 images collection of 4 videos (4,(1800,480,720,3)) is 5D tensor</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1e267fd8260" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Visualization with Python]]></title>
            <link>https://python.plainenglish.io/data-visualization-with-python-8ce66744ccbd?source=rss-723d2a0e9981------2</link>
            <guid isPermaLink="false">https://medium.com/p/8ce66744ccbd</guid>
            <category><![CDATA[seaborn]]></category>
            <category><![CDATA[matplotlib]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-visualization]]></category>
            <dc:creator><![CDATA[Jayashree Mallipudi]]></dc:creator>
            <pubDate>Wed, 09 Mar 2022 12:38:56 GMT</pubDate>
            <atom:updated>2022-03-14T09:28:47.708Z</atom:updated>
            <content:encoded><![CDATA[<h4>Using Python libraries Matplotlib and seaborn to apply some popular data visualization techniques.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uHk03mQjMX1-sJdcWN5jBg.png" /><figcaption>credits: jovian.ai</figcaption></figure><p>Data visualization is an essential part of data analysis. Here we will use Python libraries Matplotlib and seaborn to apply some popular data visualization techniques.</p><p><strong>Importing Libraries</strong></p><pre>import matplotlib.pyplot as plt<br>import seaborn as sns<br>%matplotlib inline # to make sure our plots display in same window</pre><h3><strong>Line Chart</strong></h3><p>plot function on default draws a lineplot.</p><p><strong>Basic plot</strong></p><pre>plt.plot(y_axisdata)#plots against count on x-axis(for each datapoint) on default</pre><pre>y_axisdata=[0.5,0.4,0.7,0.99,0.1]<br>X_axisdata=[1999,2000,2001]</pre><pre>plt.plot(xaxisdata,y_axisdata);#semicolon at end helps to display only the plot without returning the plot list that are drawn </pre><p>Multiple plots within the same graph with a marker to differentiate data points.</p><pre>plt.plot( x_axisdata1,y_axisdata, marker=&#39;o&#39;)<br>plt.plot( x_axisdata2,y_axisdata, marker=&#39;x&#39;)</pre><p><strong>Adding labels</strong></p><pre>plt.xlabel(&#39;X-axis label&#39;)<br>plt.ylabel(&#39;Y-axis label&#39;)<br><br>plt.title(&quot;Graph title&quot;)<br>plt.legend([&#39;graphline1 name&#39;, &#39;graphline2 name&#39;])#incase of multiple plots within same graph</pre><p><strong>Styling graph plots</strong></p><p>color or c: Set the color of the line (<a href="https://matplotlib.org/3.1.0/gallery/color/named_colors.html">supported colors</a>)</p><p>linestyle or ls: Choose between a solid or dashed line</p><p>linewidth or lw: Set the width of a line</p><p>markersize or ms: Set the size of markers</p><p>markeredgecolor or mec: Set the edge color for markers</p><p>markeredgewidth or mew: Set the edge width for markers</p><p>markerfacecolor or mfc: Set the fill color for markers</p><p>alpha: Opacity of the plot</p><pre>plt.plot(x_axisdata, y_axisdata, marker=&#39;s&#39;, c=&#39;b&#39;, ls=&#39;-&#39;, lw=2, ms=8, mew=2, mec=&#39;navy&#39;)<br>plt.plot(x_axisdata, y_axisdata, marker=&#39;o&#39;, c=&#39;r&#39;, ls=&#39;--&#39;, lw=3, ms=10, alpha=.5)</pre><p>Multiple styles in one argument:</p><pre>plt.plot(x_axisdata, y_axisdata,&#39;s--b&#39;)#marker shape, line style, and line color.<br>plt.plot(x_axisdata, y_axisdata,&#39;sb&#39;)#considers only marker shape and line color.</pre><p>Changing figure size:</p><pre>plt.figure(figsize=(12, 6))</pre><p>Using sample seaborn styles:</p><pre>sns.set_style(&quot;whitegrid&quot;)<br>sns.set_style(&quot;darkgrid&quot;)</pre><p>Changing default matplotlib styles.</p><p>Use rcparams:</p><pre>matplotlib.rcParams[&#39;font.size&#39;] = 16<br>matplotlib.rcParams[&#39;figure.figsize&#39;] = (7, 4)<br>matplotlib.rcParams[&#39;figure.facecolor&#39;] = &#39;#00000000&#39;</pre><h3><strong>Scatter Plot</strong></h3><pre>sns.scatterplot(x=dataset_df.col1, y=dataset_df.col2, hue=dataset_df.col3, s=100);</pre><p>Hues are the third feature that helps to distinguish all the data points of a dataset, it gives us insights between different categories(in different colors) in the dataset, s is the size of a datapoint.</p><p>Plotting using a dataframe:</p><pre># Load data into a Pandas dataframe<br>dataset_df = sns.load_dataset(&quot;dataset_name&quot;)<br>sns.scatterplot(x=&#39;col1&#39;, <br>                y=&#39;col2&#39;, <br>                hue=&#39;col3&#39;,<br>                s=100,<br>                data=dataset_df);</pre><h3>Histogram</h3><p>This helps us to identify the interval/range of our data points in from of bins:</p><pre>plt.hist(dataset_df.colname);</pre><p>Controlling the bin range:</p><pre>plt.hist(dataset_df.colname,bins=np.arange(2, 5, 0.25));<br>plt.hist(dataset_df.colname,bins=5);<br>plt.hist(dataset_df.colname,bins=[1, 3, 4, 4.5])</pre><p>Multiple plots:</p><p>By changing the opacity we can have the plots one on another.</p><pre>plt.hist(dataset_df.col2, alpha=0.4, bins=np.arange(2, 5, 0.25));<br>plt.hist(dataset_df.col1, alpha=0.4, bins=np.arange(2, 5, 0.25));</pre><p>Stack multiple histograms one on another.</p><pre>plt.hist([dataset_df.col1, dataset_df.col2,dataset_df.col3], <br>         bins=np.arange(2, 5, 0.25), <br>         stacked=True);</pre><h3>Bar chart</h3><p>Similar to line chart where instead of the line we will see a bar for each data point.</p><p>Similar to histograms we can stack bars one on another using the “bottom” argument.</p><pre>plt.bar(x_axisdata, y_axisdata1, bottom=y_axisdata2);</pre><p>Plotting dataset for barchart in the same way of scatter plot.</p><p>it needs x, y, hue, size(s), and dataset as parameters.</p><h3>Heatmap</h3><p>A heatmap is used to visualize 2-dimensional data like a matrix or a table using colors.</p><p>For example dataset_df contains year(columns), month(rows), sales(values in matrix for each month in each year).</p><p>In this scenario, heatmap represents a year on the x-axis and a month on the y-axis and data represents sales with different shades of colors from dark to bright.</p><p>Brighter shades represent the higher sales with respect to year and month.</p><pre>sns.heatmap(dataset_df, fmt=&quot;d&quot;, annot=True, cmap=&#39;Blues&#39;);<br>#annot=true helps to show actual values in each block<br>#cmap argument to change the color palette </pre><h3>Contour Plot</h3><p>It uses color-coded regions to visualize 3 variables (x-axis, y-axis, value point (described by color gradient) in two dimensions.</p><pre>sns.kdeplot(dataset_df.col1, dataset_df.col2, shade=True, cmap=&#39;Reds&#39;, shade_lowest=False)</pre><h3>Box Plot</h3><p>Distribution of data along single axes</p><pre>sns.boxplot(dataset_df.col1, dataset_df.col2, hue=dataset_df.categorycolname);</pre><h3><strong>Images</strong></h3><p>We can use Matplotlib to display images.</p><p>Downloading image from URL into a file.</p><pre>from urllib.request import urlretrieve<br>urlretrieve(&#39;<a href="https://i.imgur.com/SkPbq.jpg&#39;">https://image_url.jpg&#39;</a>, &#39;filenametobesaved.jpg&#39;);</pre><p>Read Image into memory first using PIL module.</p><p>Image is loaded into a 3D array with (RGB)pixel intensities.</p><pre>from PIL import Image<br>img = Image.open(&#39;filenametobesaved.jpg&#39;)<br>img_array = np.array(img)<br>plt.imshow(img);</pre><p>The image will be displayed inside an array so in order to remove them and to display only the image we need to turn off the grid, axes:</p><pre>plt.grid(False)<br>plt.axis(&#39;off&#39;)<br>plt.imshow(img); </pre><p>Displaying a part of the image using a slice of NumPy array:</p><pre>plt.imshow(img_array[125:325,105:305]);</pre><h3>Multiple Charts in a grid</h3><p>We need multiple axes for multiple plots in the same grid. We use a subplot for this purpose which returns multiple axes.</p><pre>#Here we divide grid into 2 rows and 3 columns each can have a plot of figure size(16,8)-&gt;total 6 plots<br>fig, axes = plt.subplots(2, 3, figsize=(16, 8))</pre><p>Axes subplot can be accessed in form of:</p><pre>axes[0,0]-&gt;1st row and 1st col axes<br>axes[0,0].plot(x_axisdata, y_axisdata,&#39;s--b&#39;)</pre><p>In the same way we can use axes to assign label,styles,title,legend,Instead of plt.function() we use as axes[row,col].function() since axes is a part of plot.</p><p><strong>Plotting by passing axes</strong></p><p>Another way of plotting is by passing axes as parameters.</p><pre>sns.scatterplot(x=dataset_df.col1, <br>                y=dataset_df.col2, <br>                hue=dataset_df.col3, <br>                s=100, <br>                ax=axes[0,1]);</pre><h3>Pair Plots</h3><p>Within the dataframe, if you want to have a plot between every two pairs of features we could use pair plot.</p><pre>sns.pairplot(dataset_df, hue=&#39;col_name(category with which you want to compare pair of features)&#39;);</pre><h3><strong>Getting code together</strong></h3><pre>import matplotlib.pyplot as plt<br>import seaborn as sns<br>%matplotlib inline</pre><pre><strong>#common for any plot</strong><br>plt.xlabel(&#39;X-axis label&#39;)<br>plt.ylabel(&#39;Y-axis label&#39;)<br>plt.title(&quot;Graph title&quot;)<br>plt.legend([&#39;graphline1 name&#39;, &#39;graphline2 name&#39;])</pre><pre><strong>#line plot</strong><br>plt.plot(x_axisdata, y_axisdata,&#39;s--b&#39;)</pre><pre><strong>#Scatter plot</strong><br>dataset_df = sns.load_dataset(&quot;dataset_name&quot;)<br>sns.scatterplot(x=&#39;col1&#39;, y=&#39;col2&#39;, hue=&#39;col3&#39;,s=100,       data=dataset_df)</pre><pre><strong>#Histogram</strong><br>plt.hist(dataset_df.col1, alpha=0.4, bins=np.arange(2, 5, 0.25))</pre><pre><strong>#stacked histogram<br></strong>plt.hist([dataset_df.col1, dataset_df.col2,dataset_df.col3], <br>         bins=np.arange(2, 5, 0.25), <br>         stacked=True);</pre><pre><strong>#Bar chart</strong><br>plt.bar(x_axisdata, y_axisdata1, bottom=y_axisdata2);</pre><pre><strong>#Heatmap</strong><br>sns.heatmap(dataset_df, fmt=&quot;d&quot;, annot=True, cmap=&#39;Blues&#39;);</pre><pre><strong>#Contour plot</strong><br>sns.kdeplot(dataset_df.col1, dataset_df.col2, shade=True, cmap=&#39;Reds&#39;, shade_lowest=False)</pre><pre><strong>#box plot</strong><br>sns.boxplot(dataset_df.col1, dataset_df.col2, hue=dataset_df.categorycolname);</pre><pre><strong>#images</strong><br>from PIL import Image<br>img = Image.open(&#39;filenametobesaved.jpg&#39;)<br>img_array = np.array(img)<br>plt.imshow(img)</pre><pre><strong>#multiple plots using subplots<br></strong>fig, axes = plt.subplots(2, 3, figsize=(16, 8))<br>axes[0,0].plot(x_axisdata, y_axisdata,&#39;s--b&#39;)<br>(or)<br>sns.scatterplot(x=dataset_df.col1, <br>                y=dataset_df.col2, <br>                hue=dataset_df.col3, <br>                s=100, <br>                ax=axes[0,1]);</pre><pre><strong>#Pair Plots</strong><br>sns.pairplot(dataset_df, hue=&#39;col_name(category with which you want to compare pair of features)&#39;)</pre><h3>Conclusion</h3><p>This article provides the introduction to different types of data visualization techniques with help of code samples.</p><p>Hope you find this helpful.</p><p><em>More content at </em><a href="https://plainenglish.io/"><strong><em>PlainEnglish.io</em></strong></a><em>. Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. Follow us on </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>Twitter</em></strong></a><em> and </em><a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a><em>. Join our </em><a href="https://discord.gg/GtDtUAvyhW"><strong><em>community Discord</em></strong></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8ce66744ccbd" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/data-visualization-with-python-8ce66744ccbd">Data Visualization with Python</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Short Guide for Numpy]]></title>
            <link>https://medium.com/@_MJ_/short-guide-for-numpy-d8b8bf4603b?source=rss-723d2a0e9981------2</link>
            <guid isPermaLink="false">https://medium.com/p/d8b8bf4603b</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[numpy]]></category>
            <category><![CDATA[numpy-tutorial]]></category>
            <dc:creator><![CDATA[Jayashree Mallipudi]]></dc:creator>
            <pubDate>Tue, 22 Feb 2022 17:41:34 GMT</pubDate>
            <atom:updated>2022-02-22T17:41:34.802Z</atom:updated>
            <content:encoded><![CDATA[<p>Everything you need to get started</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5UWC84uhut28Pip7NAxB5w.png" /><figcaption>Numerical computing with help of numpy</figcaption></figure><h4><strong>What is Numpy?</strong></h4><p>Numpy is a Multi dimensional array library provides specialized data structures, functions and other tools for numerical computing in python.</p><h4>Why Numpy?</h4><p>Because it is easy to use and is very fast compared to lists because numpy uses Fixed Type while lists(includes size,ref count,obj type,obj value) so it needs much more memory</p><p>Numpy operations and functions are internally implemented in C++ ,which makes it much faster than python (since they are interpreted at runtime)</p><p>Loading numpy(After pip install)</p><pre>import numpy as np</pre><p>Creating an numpy array</p><pre>arr = np.array([[1,2,3,4],[5,6,7,8]],dtype=&#39;int32&#39;) dtype is optional</pre><p>Methods</p><pre>#get dimension            #get shape        #get datatype<br>arr.ndim                  arr.shape          arr.dtype   <br>#4bytes for int           #get total bytes  #get no of elements<br>arr.itemsize              arr.nbytes         arr.size</pre><pre>#total size<br>arr.itemsize*arr.size=arr.nbytes</pre><p>Accessing elements</p><pre>#get specific element[row,col]<br>arr[1,5] <br>arr[0,:] first row <br>arr[:,2] third column<br>arr[0,1:6:2]startindex:endindex:stepsize</pre><p>Assigning values</p><pre>arr[1,5]=20               a[:,3]=[1,2]</pre><p>Initializing different types of arrays</p><pre>All Zeroes                                All Ones<br>np.zeros((2,3))2x3 matrix of 0’s          np.ones((4,2,2))<br>Initialize with value                     initialize with random no<br>np.full((2,2),99)                         np.random.rand(4,2)<br>with random int                           Identity matrix<br>np.random.randint(min,max,size=(3,3))     np.identity(5)<br>copy array                                Repeat array<br>b=a.copy()                                np.repeat(arr,3,axis=0)<br>#start,end,step                           Equally spaced nos<br>np.arange(10,90,3)                        np.linspace(3,27,9)</pre><p>Includes all mathematical operations + ,*,-,**, /,%</p><p>Numpy provides hundreds of functions for performing operations on arrays.Here are some commonly used functions:</p><ul><li>Mathematics: np.sum, np.exp, np.round, arithemtic operators</li><li>Array manipulation: np.reshape(row,col), np.stack, np.concatenate, np.split,np.vstack([arr1,arr2])(vertical stack),np.hstack(horizontal stack)</li><li>Linear Algebra: np.matmul(arr1,arr2)(matrix multiplication), np.dot, np.transpose, np.eigvals,np.linalg.det(arr)(finding determinant)</li><li>Statistics: np.mean, np.median, np.std, np.max ,np.min(arr,axis=1) (1=row wise,0=col wise)</li></ul><p>Load data from a text file</p><p>To read the file into a numpy array, we can use the genfromtxt function.</p><pre>file=np.genfromtxt(&#39;data.txt&#39;,delimitor=&#39;,&#39;)<br>file=file.astype(&#39;int32&#39;)</pre><h3>Conclusion</h3><p>In this article we discussed about initializing numpy array and its functions, methods all important code you need to know in order to dive into any project ,feel free to check reference article and official documentation for indepth understanding of any function, method discussed.</p><h3>Reference Links</h3><p>Provide links to your references and other interesting articles about Numpy arrays:</p><ul><li>Numpy official tutorial : <a href="https://numpy.org/doc/stable/user/quickstart.html">https://numpy.org/doc/stable/user/quickstart.html</a></li><li>In this article included an indepth discussion about 5 most used numpy functions feel free to check it. <a href="https://medium.com/@_MJ_/5-interesting-numpy-functions-cecbc5b0eb1a">https://medium.com/@_MJ_/5-interesting-numpy-functions-cecbc5b0eb1a</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d8b8bf4603b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[5 Interesting Numpy Functions]]></title>
            <link>https://medium.com/@_MJ_/5-interesting-numpy-functions-cecbc5b0eb1a?source=rss-723d2a0e9981------2</link>
            <guid isPermaLink="false">https://medium.com/p/cecbc5b0eb1a</guid>
            <category><![CDATA[function]]></category>
            <category><![CDATA[python3]]></category>
            <category><![CDATA[numpy]]></category>
            <dc:creator><![CDATA[Jayashree Mallipudi]]></dc:creator>
            <pubDate>Tue, 22 Feb 2022 15:14:59 GMT</pubDate>
            <atom:updated>2022-02-22T15:14:59.154Z</atom:updated>
            <content:encoded><![CDATA[<p>Detailed explanation of the functions and common errors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/834/1*kb1rhBIJli9GaCDNfLD_yg.jpeg" /><figcaption>Numpy Functions</figcaption></figure><h3>5 Numpy functions</h3><p>list of the chosen numpy functions.</p><ul><li>argmax</li><li>sort</li><li>average</li><li>transpose</li><li>split</li></ul><p>Let’s begin by importing Numpy and listing out the functions covered in this story.</p><pre><strong>import</strong> numpy <strong>as</strong> np<br><em># List of functions explained </em><br>function1 <strong>=</strong> np<strong>.</strong>argmax<br>function2 <strong>=</strong> np<strong>.</strong>sort<br>function3 <strong>=</strong> np<strong>.</strong>average<br>function4 <strong>=</strong> np<strong>.</strong>transpose<br>function5 <strong>=</strong> np<strong>.</strong>split</pre><h3>Function 1 — np.argmax</h3><p>This function returns the maximum element indices based on axis.</p><pre><em># Example 1 - working</em><br>arr1<strong>=</strong>np<strong>.</strong>random<strong>.</strong>randint(16,size<strong>=</strong>(4,4))<br>print(arr1)<br>print(np<strong>.</strong>argmax(arr1))</pre><pre>result:<br>[[ 1  6 12 13]<br> [13  5  0  4]<br> [11 10  5  0]<br> [ 1  9  7  6]]<br>3</pre><p>Here,argmax returns indices of maximum element.</p><pre><em># Example 2 -working sort</em><br>prob<strong>=</strong>np<strong>.</strong>random<strong>.</strong>rand(4,4)<br>print(prob)<br>print(np<strong>.</strong>argmax(prob,axis<strong>=</strong>0))<br>print(np<strong>.</strong>argmax(prob,axis<strong>=</strong>1))</pre><pre>Result:<br>[[0.57753095 0.84995965 0.23614245 0.8725152 ]<br> [0.29165751 0.060839   0.15813323 0.52923348]<br> [0.12625635 0.07084457 0.71222193 0.11301533]<br> [0.2303861  0.12119381 0.43109111 0.44414143]]<br>[0 0 2 0]<br>[3 3 2 3]</pre><p>In the above Example argmax returns indices of maximum element in a particular axis if specified 0-&gt;maximum indices by column,1-&gt;maximum indices by row, if not specifies returns the maximum of entire array.</p><pre><em># Example 3 - breaking (to illustrate when it breaks)</em><br><em>#mean</em></pre><pre>arr1 <strong>=</strong> [[5, 6, 7], <br>        [8, 9, 10]]</pre><pre>np<strong>.</strong>argmax(arr1, axis<strong>=</strong>2)<br>Error:<br>--------------------------------------------------------------------<br>AxisError                                 Traceback (most recent call last)<br>/tmp/ipykernel_35/605736401.py in &lt;module&gt;<br><strong>      5</strong>         [8, 9, 10]]<br><strong>      6</strong> <br>----&gt; 7 np.argmax(arr1, axis=2)</pre><pre>&lt;__array_function__ internals&gt; in argmax(*args, **kwargs)</pre><pre>/opt/conda/lib/python3.9/site-packages/numpy/core/fromnumeric.py in argmax(a, axis, out)<br><strong>   1191</strong> <br><strong>   1192</strong>     &quot;&quot;&quot;<br>-&gt; 1193     return _wrapfunc(a, &#39;argmax&#39;, axis=axis, out=out)<br><strong>   1194</strong> <br><strong>   1195</strong> </pre><pre>/opt/conda/lib/python3.9/site-packages/numpy/core/fromnumeric.py in _wrapfunc(obj, method, *args, **kwds)<br><strong>     53</strong>     bound = getattr(obj, method, None)<br><strong>     54</strong>     if bound is None:<br>---&gt; 55         return _wrapit(obj, method, *args, **kwds)<br><strong>     56</strong> <br><strong>     57</strong>     try:</pre><pre>/opt/conda/lib/python3.9/site-packages/numpy/core/fromnumeric.py in _wrapit(obj, method, *args, **kwds)<br><strong>     42</strong>     except AttributeError:<br><strong>     43</strong>         wrap = None<br>---&gt; 44     result = getattr(asarray(obj), method)(*args, **kwds)<br><strong>     45</strong>     if wrap:<br><strong>     46</strong>         if not isinstance(result, mu.ndarray):</pre><pre>AxisError: axis 2 is out of bounds for array of dimension 2</pre><p>In the example (why it breaks and how to fix it): This example failed due to axis value it can only be 0 ,1,-1 not 2 so changing axis value fixes the error</p><p>Some closing comments about when to use this function. when ever need to find maximum index,could be maximum probablity of some use case</p><h3>Function 2 — sort</h3><p>to sort elements in an ordered sequence</p><pre><em># Example 1 - working</em><br>a <strong>=</strong> np<strong>.</strong>array([[12, 15], [10, 1]])<br>print(np<strong>.</strong>sort(a,kind<strong>=</strong>&#39;mergesort&#39;))</pre><p>In the example np.sort returns a copy of a sorted array using kind we can use different sorting algorithms(eg:quicksort,mergesort,heapsort)</p><pre><em># Example 2 - working</em><br>arr1 <strong>=</strong> np<strong>.</strong>sort(a, axis <strong>=</strong> 0) <em>#along  axis 0 sorts contents along each column</em><br>print(arr1)<br>print(np<strong>.</strong>sort(a, axis <strong>=</strong> <strong>-</strong>1))  <em>#along  last axis  sorts contents along each row</em></pre><pre>Result:<br>[[10  1]<br> [12 15]]<br>[[12 15]<br> [ 1 10]]</pre><p>Explanation :Axis along which to sort. If None, the array is flattened before sorting. The default is -1, which sorts along the last axis</p><pre><em># Example 3 - breaking (to illustrate when it breaks)</em><br>dtype <strong>=</strong> [(&#39;name&#39;, &#39;S10&#39;), (&#39;height&#39;, float), (&#39;age&#39;, int)]<br>values <strong>=</strong> [(&#39;Arthur&#39;, 1.6, 41), (&#39;Lancelot&#39;, 1.9, 38),<br>          (&#39;Galahad&#39;, 1.4, 38)]<br>a <strong>=</strong> np<strong>.</strong>array(values) <br>np<strong>.</strong>sort(a,order<strong>=</strong>[&#39;name&#39;])</pre><pre>------------------------------------------------------------------<br>ValueError                                Traceback (most recent call last)<br>/tmp/ipykernel_35/3397319452.py in &lt;module&gt;<br><strong>      4</strong>           (&#39;Galahad&#39;, 1.4, 38)]<br><strong>      5</strong> a = np.array(values)<br>----&gt; 6 np.sort(a,order=[&#39;name&#39;])</pre><pre>&lt;__array_function__ internals&gt; in sort(*args, **kwargs)</pre><pre>/opt/conda/lib/python3.9/site-packages/numpy/core/fromnumeric.py in sort(a, axis, kind, order)<br><strong>    994</strong>     else:<br><strong>    995</strong>         a = asanyarray(a).copy(order=&quot;K&quot;)<br>--&gt; 996     a.sort(axis=axis, kind=kind, order=order)<br><strong>    997</strong>     return a<br><strong>    998</strong> </pre><pre>ValueError: Cannot specify order when the array has no fields.</pre><p>Explanation:(why it breaks and how to fix it) In the example in order to sort using order parameter we need to have fields so adding dtype in above example into np.array will resolve this a=np.array(values,dtype)</p><h3>Function 3 — average</h3><p>Average function calculates weighted average along specified axis</p><pre><em># Example 1 - working</em><br>data <strong>=</strong> np<strong>.</strong>arange(1, 11)<br>np<strong>.</strong>average(data, weights<strong>=</strong>np<strong>.</strong>arange(10, 0, <strong>-</strong>1))</pre><pre>Result:<br>[10  9  8  7  6  5  4  3  2  1]</pre><p>Explanation: In the above example First pass the parameters data and its corresponding weights to find weighted average</p><pre><em># Example 2 - working</em><br>data <strong>=</strong> np<strong>.</strong>arange(8)<strong>.</strong>reshape((4,2))<br>print(data)<br>np<strong>.</strong>average(data, axis<strong>=</strong>1, weights<strong>=</strong>[1.<strong>/</strong>4, 3.<strong>/</strong>4])<br>Result:<br>[[0 1]<br> [2 3]<br> [4 5]<br> [6 7]]<br>array([0.75, 2.75, 4.75, 6.75])</pre><p>Explanation: In the example using axis since array and its associated weights differ</p><pre><em># Example 3 - breaking (to illustrate when it breaks)</em><br>data <strong>=</strong> np<strong>.</strong>arange(6)<strong>.</strong>reshape((3,2))<br>print(data)<br>np<strong>.</strong>average(data, weights<strong>=</strong>[1.<strong>/</strong>4, 3.<strong>/</strong>4])<br>Results:<br>[[0 1]<br> [2 3]<br> [4 5]]<br>-----------------------------------------------------------<br>TypeError                                 Traceback (most recent call last)<br>/tmp/ipykernel_35/3459501547.py in &lt;module&gt;<br><strong>      2</strong> data = np.arange(6).reshape((3,2))<br><strong>      3</strong> print(data)<br>----&gt; 4 np.average(data, weights=[1./4, 3./4])</pre><pre>&lt;__array_function__ internals&gt; in average(*args, **kwargs)</pre><pre>/opt/conda/lib/python3.9/site-packages/numpy/lib/function_base.py in average(a, axis, weights, returned)<br><strong>    391</strong>         if a.shape != wgt.shape:<br><strong>    392</strong>             if axis is None:<br>--&gt; 393                 raise TypeError(<br><strong>    394</strong>                     &quot;Axis must be specified when shapes of a and weights &quot;<br><strong>    395</strong>                     &quot;differ.&quot;)</pre><pre>TypeError: Axis must be specified when shapes of a and weights differ.</pre><p>Explanation about example (why it breaks and how to fix it) In this scenario axis must be specified because with out it function will not get which sense of direction to work</p><h3>Function 4 — Transpose</h3><p>This function helps to return transpose of matrix(switches rows and columns of array)</p><pre><em># Example 1 - working</em><br>x<strong>=</strong>np<strong>.</strong>array([[1,2,3],[4,5,6]])<br>np<strong>.</strong>transpose(x)</pre><p>Explanation about example we got the 3x2 matrix which is transpose of 2x3</p><pre><em># Example 2 - working</em><br>x <strong>=</strong> np<strong>.</strong>ones((1, 2, 3))<br>np<strong>.</strong>transpose(x, (1, 0, 2))<strong>.</strong>shape</pre><p>Explanation about example Here in transpose function second argument is axes(tuple) which helps to permute the axes in a given order</p><pre><em># Example 3 - breaking (to illustrate when it breaks)</em><br>x <strong>=</strong> np<strong>.</strong>ones((1, 2, 3))<br>np<strong>.</strong>transpose(x, (1, 0, 2,3))<strong>.</strong>shape<br>--------------------------------------------------------------------<br>ValueError                                Traceback (most recent call last)<br>/tmp/ipykernel_35/2967030568.py in &lt;module&gt;<br><strong>      1</strong> # Example 3 - breaking (to illustrate when it breaks)<br><strong>      2</strong> x = np.ones((1, 2, 3))<br>----&gt; 3 np.transpose(x, (1, 0, 2,3)).shape</pre><pre>&lt;__array_function__ internals&gt; in transpose(*args, **kwargs)</pre><pre>/opt/conda/lib/python3.9/site-packages/numpy/core/fromnumeric.py in transpose(a, axes)<br><strong>    656</strong> <br><strong>    657</strong>     &quot;&quot;&quot;<br>--&gt; 658     return _wrapfunc(a, &#39;transpose&#39;, axes)<br><strong>    659</strong> <br><strong>    660</strong> </pre><pre>/opt/conda/lib/python3.9/site-packages/numpy/core/fromnumeric.py in _wrapfunc(obj, method, *args, **kwds)<br><strong>     56</strong> <br><strong>     57</strong>     try:<br>---&gt; 58         return bound(*args, **kwds)<br><strong>     59</strong>     except TypeError:<br><strong>     60</strong>         # A TypeError occurs if the object does have such a method in its</pre><pre>ValueError: axes don&#39;t match array</pre><p>Explanation about example (why it breaks and how to fix it), The second argument doesnot have right number of axes so the function doesnot get how to reshape Here reducing axis tuple fixes the issue.</p><h3>Function 5 — Split</h3><p>Splitting an array into multiple sub arrays</p><pre><em># Example 1 - working</em><br>x <strong>=</strong> np<strong>.</strong>arange(20.0)<br>np<strong>.</strong>split(x, 2)</pre><p>Explanation about example This function helps to split the array into 2 sub arrays</p><pre><em># Example 2 - working</em><br>x <strong>=</strong> np<strong>.</strong>arange(8.0)<br>np<strong>.</strong>split(x, [3, 5, 6,10])</pre><p>Explanation about example</p><p>In This example second argument the entries indicate where along axis array can split As we can see if the array don’t have 10 element split returns empty array</p><pre><em># Example 3 - breaking (to illustrate when it breaks)</em><br>x<strong>=</strong>np<strong>.</strong>arange(7)<br>np<strong>.</strong>split(x,3)<br>-------------------------------------------------------------------<br>ValueError                                Traceback (most recent call last)<br>/tmp/ipykernel_35/3892306710.py in &lt;module&gt;<br><strong>      1</strong> # Example 3 - breaking (to illustrate when it breaks)<br><strong>      2</strong> x=np.arange(7)<br>----&gt; 3 np.split(x,3)</pre><pre>&lt;__array_function__ internals&gt; in split(*args, **kwargs)</pre><pre>/opt/conda/lib/python3.9/site-packages/numpy/lib/shape_base.py in split(ary, indices_or_sections, axis)<br><strong>    870</strong>         N = ary.shape[axis]<br><strong>    871</strong>         if N % sections:<br>--&gt; 872             raise ValueError(<br><strong>    873</strong>                 &#39;array split does not result in an equal division&#39;) from None<br><strong>    874</strong>     return array_split(ary, indices_or_sections, axis)</pre><pre>ValueError: array split does not result in an equal division</pre><p>Explanation about example (why it breaks and how to fix it)</p><p>Here array needs to be split into 3 equal arrays but our array size doesn’t match so changing either array size or spilt size resolves the error</p><h3>Conclusion</h3><p>This article has gone over some basic examples of how to use five NumPy functions, as well as some frequent problems that can occur when using these functions for the first time. Even if some of the functions aren’t widely used in Data Analysis, they might be incredibly useful in solving specific situations.</p><h3>Reference Links</h3><p>Provide links to your references and other interesting articles about Numpy arrays:</p><ul><li>Numpy official tutorial : <a href="https://numpy.org/doc/stable/user/quickstart.html">https://numpy.org/doc/stable/user/quickstart.html</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cecbc5b0eb1a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting Started With Pandas]]></title>
            <link>https://medium.com/@_MJ_/all-in-one-notes-for-pandas-1b510c84567f?source=rss-723d2a0e9981------2</link>
            <guid isPermaLink="false">https://medium.com/p/1b510c84567f</guid>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[pandas-dataframe]]></category>
            <category><![CDATA[data-analysis]]></category>
            <dc:creator><![CDATA[Jayashree Mallipudi]]></dc:creator>
            <pubDate>Tue, 04 Jan 2022 17:25:33 GMT</pubDate>
            <atom:updated>2022-03-01T07:42:19.984Z</atom:updated>
            <content:encoded><![CDATA[<p>Everything you will ever need for data Analysis using pandas.</p><figure><img alt="Getting started with pandas" src="https://cdn-images-1.medium.com/max/399/1*BULwTfynXVAEDRtDYrB5dQ.png" /><figcaption>Most essential tool to do real world data analysis in python</figcaption></figure><p>We have many sources to dive in pandas but the main idea of this article is to give exact commands you will need to use in solving real world data analysis problems(a cheat code).Let’s get started…</p><p><strong>We have two data in Structures in Pandas</strong>(pd)</p><ol><li>Series (1D array using numpy) x=pd.Series([34.2,3.6,7.4])</li><li>DataFrame(df)(2D array with rows &amp;columns, most widely needed)</li></ol><p><strong>Ways to create a Data Frame</strong></p><ol><li>Using arrays, lists, dictionaries</li></ol><p>df=pd.DataFrame(data, index=[‘r1’,’r2&#39;,’r3&#39;],columns=[‘col1’,’col2’]) The data here could be a n<strong><em>umpy array </em></strong>data=np.array([[1,3],[2,4],[5,7]]) or a <strong><em>normal list </em></strong>data=[[1,3],[2,4],[5,7]] or <strong>a <em>dictionary</em></strong> dict_states={‘states’:[‘California’ ,’Texas’ ,’Florida’],’Population’:[1232434,45456567,4565768]}</p><p>2.Using Data files df=pd.read_csv(‘abc.csv’) or pd.read_csv(‘abc.txt’,delimiter=’\t’) or pd.read_excel(‘abc.xlsx’)</p><p>3.Getting dataset from url</p><pre>from urllib.request import urlretrieve<br>file_url = &#39;<a href="https://gist.githubusercontent.com/aakashns/f6a004fa20c84fec53262f9a8bfee775/raw/f309558b1cf5103424cef58e2ecb8704dcd4d74c/italy-covid-daywise.csv&#39;">https://someurl/file.csv&#39;</a></pre><pre>urlretrieve(file_url, &#39;datasetname.csv&#39;)</pre><p>Now lets get onto some Attributes(Value associated with object) that pandas provides us. These attributes helps us to find out some details of our dataFrame like shape, index, columns, dtypes details could be used with a dot (i.e df.shape)</p><p>Few of the Methods includes df.head()#gives us default first 5 rows or df.head(10)</p><p>using head/tail only the first &amp; last five rows are displayed by default .We can change some display options to view all the rows.</p><pre>from IPython.display import display <br>with pd.option_context(&#39;display.max_rows&#39;, df.shape[0]):<br>    display(df)</pre><p>df.info()#gives the description of dataframe,df.describe() provides all stats ,df.iterrows() can be used in loops.</p><p>Some Functions pandas provides are len(df),max(df),min(df.index),type(df),round(df,2)#round is used if df has float values.</p><p><strong>Ways to retrieve data from data frame</strong></p><ol><li>Direct selecting columns df[[‘col1’,’col2’]] [0:5] to get first 5 rows of those columns</li><li>using iloc operator used only with integers df.iloc[1:4] gets 4 top rows to get the specific location use df.iloc[rowPosition,columnPosition]</li><li>using loc this is used when dealing with labels/attributes instead of integers which is also widely used as df.loc[df[‘colName’]]</li></ol><p>We can make most out of these by using them along with different filtering functions/conditionals.</p><p><em>Some of the examples include:</em></p><p>df[‘new col’]=np.arange(0,1000) adding new column with range of nos between 0 to 1000</p><p>df[‘colname’].sum(),df[‘colname’].count(),df[‘colname’].mean(), df[‘colname’].std(),df[‘colname’].min(),df[‘colname’].max() ,to count by category use value_counts df[‘colname’].value_counts(normalize=True)#optional parameter to get percentages we can also get these parameters from df.describe() but to get any column specific stats we can use these</p><p><strong>Conditional Changes(==,&amp;,~,|,sorting,filtering)</strong></p><p>1.use case of using loc</p><p>Single condition — df.loc[df[&#39;colname&#39;]==’some value’,’colname’]=’newVal’ Multiple conditions — df.loc[df[‘col1’]&gt;500,[‘col2’,’col3&#39;]]=[‘col2valtobeChanged’,’col3valtobeChanged’]</p><p><em>Filtering data</em></p><p>df.loc[~df[‘col’].str.contains(‘TextToCompare’)] ~is used as not</p><p><em>using regular expressions(import re)for string comparisions.</em></p><p>df.loc[~df[‘col’].str.contains(‘^pi[a-z]’,flags=re.I,regex=True)] flag re.I is to ignore case while comparing with regex expression which checks all words that startswith ‘pi’ and alphabets (a-z)</p><p>2.Normal conditional checks</p><p>df[‘new col’]=(df[‘col1’]+df[‘col2’])/2</p><p><em>Rearranging columns.</em></p><p>cols=list(df.columns.values) to get all column names</p><p>df=df[cols[0:4]+[cols[-1]]+cols[4:12]] This gives first 4 columns and then last column(since its only 1 column while appending need to be wraped inside a list[] and columns from 4 to 12)</p><p><em>Sorting a dataframe by one column</em></p><p>df.sort_values(’colname’,ascending=False) sort by colname default is ascending</p><p><em>sorting by multiple columns</em></p><p>df.sort_values([‘col1’,’col2’],ascending=[1,0])we can use as ascending false if you want col1 to be ascending while col2 to be descending use as 1,0.</p><p>There is another argument called inplace=True which if added overwrites values as sorted in the df</p><p>df.sort_values(‘textcol’,key=lambda col:col.str.lower(),inplace=True) to sort using textual data of column.</p><p><em>Aggregate stats(Group By)</em></p><p>df.groupby([‘col1’]).mean().sort_values(‘col2’)</p><p>df.groupby([‘col1’,’col2’]).count()[‘count’] to only display two columns and its count after grouping.</p><p>Here col1,2,3 are displayed after grouping by month column and then does sum for each month</p><pre>month_df = df.groupby(&#39;month&#39;)[[&#39;col1&#39;, &#39;col2&#39;, &#39;col3&#39;]].sum()</pre><p>another form of aggregation is the running or cumulative sum of column, We can use the cumsum method to compute the cumulative sum of a column as a new series.</p><pre>df[&#39;total_col&#39;] = df.col1.cumsum()</pre><p>3. using iloc</p><p>df[‘new col’]=df.iloc[:,4:9].sum(axis=1) This selects all rows(:)and from column 4 to 9 adding horizontally(axis=1)for vertical addition (use axis=0)</p><p><strong>Working with dates</strong></p><p>Having a column date pandas consider it as object so to convert into datetime</p><pre>df[&#39;date&#39;] = pd.to_datetime(df.date)#it now has datetime64 datatype</pre><p>Extract different parts of date into columns</p><pre>df[&#39;year&#39;] = pd.DatetimeIndex(df.date).year<br>df[&#39;month&#39;] = pd.DatetimeIndex(df.date).month<br>df[&#39;day&#39;] = pd.DatetimeIndex(df.date).day<br>df[&#39;weekday&#39;] = pd.DatetimeIndex(df.date).weekday</pre><p><strong>Merging data from multiple datasets</strong></p><p>let two data sets be df1,df2</p><pre>merged_df = df1.merge(df2, on=&quot;column name on which both can be merged&quot;)</pre><p><strong>Saving your changes</strong></p><p>we will have many changes done to our original dataframe but we donot want to disturb our original file so in those scenarios we need to save our modified dataframe (mdf).</p><p>mdf.to_csv(‘modifiedNewFileName.csv’,sep=’\t’,index=False)any separator can be used and we will be having a default index(1,2,3..) if not needed set it to false.</p><p>mdf.to_excel(‘modifiedNewFileName.xlsx’,index=False)</p><p>mdf.reset_index(drop=True,inplace=True)drop is for if you donot want old index to be seen in the table after some filtering in our data.</p><p><strong>Basic plotting with pandas</strong></p><pre>df.col_name.plot()</pre><p>Plotting would be better if we have an index in dataframe For example if we have a data column we could add that as index before plotting</p><pre>df.set_index(&#39;date&#39;, inplace=True)<br>df.col_name.plot()<br>new_col = df.total_col / result_df.col3<br>new_col.plot(title=&#39;add title for graph&#39;);<br>df.col_name.plot(kind=&#39;bar&#39;);</pre><p><strong>Few golden rules :</strong></p><p>**Never use direct integers **while doing any conditionals or filtering operations because data can always change try using names, attributes</p><p>**always have a habit of checking the documentation**but before that we need to get the idea of what features that pandas can provide once we get the idea we can always check the document for syntax.</p><p>I hope this article helps to achieve that.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1b510c84567f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>