<?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 Jim Wang on Medium]]></title>
        <description><![CDATA[Stories by Jim Wang on Medium]]></description>
        <link>https://medium.com/@jimwang3589?source=rss-4882b9de694e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*-n2HM9F4L5XKnFG3ZzjcGg.png</url>
            <title>Stories by Jim Wang on Medium</title>
            <link>https://medium.com/@jimwang3589?source=rss-4882b9de694e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 04:04:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jimwang3589/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[From Molecules to Predictions: How Deep Learning Learns Chemical Features for Drug Discovery]]></title>
            <link>https://medium.com/@jimwang3589/from-molecules-to-predictions-how-deep-learning-learns-chemical-features-for-drug-discovery-20190e042a02?source=rss-4882b9de694e------2</link>
            <guid isPermaLink="false">https://medium.com/p/20190e042a02</guid>
            <dc:creator><![CDATA[Jim Wang]]></dc:creator>
            <pubDate>Mon, 02 Nov 2026 14:41:15 GMT</pubDate>
            <atom:updated>2026-11-02T14:41:15.753Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pT65z8G2L4kc1fcP76mWjw.png" /></figure><h3>1. Introduction: Can AI Discover New Drugs?</h3><p>One of the fundamental challenges in drug discovery is identifying molecules that can treat a disease without causing unacceptable harm to the human body.</p><p>Imagine that researchers have millions of candidate molecules, but only a small fraction may have the desired biological activity. Testing every molecule in a laboratory is expensive and time-consuming.</p><p>Machine learning offers a potential solution. We can train a model using molecules whose biological activity has already been measured, then use the trained model to predict which untested molecules are worth investigating.</p><p>But this raises an important question:</p><p><strong>How can a machine learning model understand a molecule in the first place?</strong></p><p>Traditional machine learning often relies on feature engineering. Scientists or engineers extract useful information from each molecule, such as its molecular weight, the number of oxygen atoms, and the connections between atoms.</p><p>Deep learning offers another approach: instead of relying entirely on manually designed features, we can train a neural network to learn useful representations directly from molecular data.</p><p>To understand how this works, let’s start with the raw data.</p><h3>2. What Does Raw Molecular Data Look Like?</h3><p>Before training a deep learning model, we need to represent each molecule in a format that a computer can process.</p><p>A molecule is made of atoms connected by chemical bonds. Different atoms and different arrangements produce different molecules with different chemical properties.</p><p>For example, water consists of two hydrogen atoms and one oxygen atom. Its chemical formula is H₂O.</p><p>A computer cannot directly understand a molecule in the same way a chemist does. We therefore need a digital representation of its chemical structure.</p><p>There are several common ways to represent molecules.</p><h3>2.1 Molecular Formula</h3><p>The simplest representation is a molecular formula.</p><p>For example:</p><ul><li>Water: H₂O</li><li>Carbon dioxide: CO₂</li><li>Ethanol: C₂H₆O</li></ul><p>The formula tells us which types of atoms are present and how many of each type exist.</p><p>However, a molecular formula has an important limitation: it does not fully describe how the atoms are connected.</p><p>Two molecules can have the same molecular formula but different structures and properties.</p><p>Consequently, molecular formulas alone are generally insufficient for predicting biological activity.</p><h3>2.2 SMILES: Representing Molecules as Text</h3><p>One widely used representation is called <strong>SMILES</strong>, which stands for Simplified Molecular Input Line Entry System.</p><p>SMILES represents a molecule’s chemical structure using a string of characters.</p><p>For example, ethanol can be represented as:</p><pre>CCO</pre><p>Let’s break this down.</p><ul><li>C represents a carbon atom.</li><li>Another C represents a second carbon atom.</li><li>O represents an oxygen atom.</li></ul><p>The sequence describes a structure in which two carbon atoms are connected, followed by an oxygen atom.</p><p>A more complicated molecule might have a much longer SMILES string containing additional atoms, branches, and ring structures.</p><p>For example:</p><pre>CC(=O)O</pre><p>This represents acetic acid.</p><p>In this string:</p><ul><li>C represents carbon.</li><li>O represents oxygen.</li><li>= indicates a double bond.</li><li>Parentheses indicate a branch in the molecular structure.</li></ul><p>SMILES is useful because it allows us to store millions of molecular structures in a database and process them programmatically.</p><p>However, there is an important distinction.</p><p><strong>A SMILES string is a textual representation of a molecule, not a list of its biological properties.</strong></p><p>The string describes the chemical structure. A machine learning model must learn which structural patterns are associated with biological activity.</p><h3>2.3 Molecular Graphs: Representing Atoms and Bonds</h3><p>Another important representation is a molecular graph.</p><p>If SMILES represents a molecule as text, a molecular graph represents it as a network.</p><p>A graph consists of two fundamental components:</p><p><strong>Nodes:</strong> The atoms in the molecule.</p><p><strong>Edges:</strong> The chemical bonds connecting those atoms.</p><p>Consider ethanol again.</p><p>Its molecular graph contains:</p><ul><li>Two carbon atoms.</li><li>One oxygen atom.</li><li>Bonds connecting the atoms in the molecular structure.</li></ul><p>In a real molecular graph, hydrogen atoms may be represented explicitly or handled implicitly, depending on the chosen representation.</p><p>A graph can also attach information to each node and edge.</p><p>For an atom, this information might include:</p><ul><li>Its element type, such as carbon, oxygen, or nitrogen.</li><li>Its chemical charge.</li><li>The number of bonds it forms.</li><li>Whether it belongs to a chemical ring.</li></ul><p>For a bond, the information might include:</p><ul><li>The types of atoms it connects.</li><li>Whether it is a single, double, or triple bond.</li><li>Whether it belongs to a ring.</li></ul><p>This representation gives a model more direct access to the structure of the molecule.</p><p>It also provides a natural input for a family of deep learning models called <strong>Graph Neural Networks</strong>, or GNNs.</p><p>We will explore those models shortly.</p><h3>3. Traditional Feature Engineering Versus Deep Learning</h3><p>Now that we understand the raw data, let’s examine the central machine learning problem.</p><p>Suppose we want to predict whether a molecule is active against a particular biological target associated with a disease.</p><p>We have a dataset containing thousands of previously tested molecules. For each molecule, we also have an experimental result indicating whether it meets our definition of active or inactive.</p><p>Our goal is to learn a model that can predict the activity of previously untested molecules.</p><p>There are two broad approaches.</p><h3>3.1 Approach One: Traditional Feature Engineering</h3><p>In traditional machine learning, we first transform each molecule into a collection of numerical features.</p><p>For example, we might calculate:</p><ul><li>Molecular weight.</li><li>Number of carbon atoms.</li><li>Number of oxygen atoms.</li><li>Number of nitrogen atoms.</li><li>Number of hydrogen-bond donors.</li><li>Number of hydrogen-bond acceptors.</li><li>A measure of molecular lipophilicity, which describes how much a molecule tends to favor fatty environments over water.</li></ul><p>These features describe different aspects of a molecule’s chemical structure and behavior.</p><p>We can then use these features to train a model such as Random Forest or XGBoost.</p><p>The process looks like this:</p><p><strong>Raw molecular data → Feature engineering → Numerical feature vector → Machine learning model → Activity prediction</strong></p><p>The advantage is that these features are relatively easy to understand.</p><p>The disadvantage is that the model can only learn from the information we provide.</p><p>If our features fail to capture an important structural pattern, the model may struggle to recognize it.</p><p>Traditional molecular fingerprints offer another useful approach. They encode the presence or absence of particular structural patterns as a vector of numbers, often binary values.</p><p>These fingerprints can capture structural information that simple counts of atoms cannot.</p><h3>3.2 Approach Two: Deep Learning</h3><p>Deep learning changes how we approach feature engineering.</p><p>Instead of manually specifying every feature that might be useful, we can give a neural network a representation of the molecular structure and train it to learn useful patterns from the training data.</p><p>For example, we can provide a molecular graph containing atoms and bonds.</p><p>A Graph Neural Network can then learn representations of individual atoms and their surrounding chemical environments.</p><p>As information passes through the network, each atom’s representation can incorporate information about neighboring atoms, the bonds connecting them, and increasingly larger parts of the molecular structure.</p><p>The model can combine these learned representations to produce a representation of the entire molecule.</p><p>That representation is then used to predict biological activity.</p><p>The overall process becomes:</p><p><strong>Raw molecular data → Molecular graph → Graph Neural Network → Learned molecular representation → Activity prediction</strong></p><p>The key difference is that the neural network learns the features during training instead of relying entirely on features designed in advance.</p><p>However, deep learning does not eliminate all feature engineering.</p><p>We still need to choose an appropriate molecular representation, prepare the training data, select a model architecture, and decide what the model should predict.</p><h3>4. How Does a Graph Neural Network Learn Molecular Features?</h3><p>Let’s examine this process more closely.</p><p>Imagine that we represent a molecule as a graph.</p><p>Each atom becomes a node, and each chemical bond becomes an edge.</p><p>Initially, each atom has a basic numerical representation containing information such as its element type and chemical environment.</p><p>The neural network then processes this information through multiple layers.</p><h3>Step 1: Represent Each Atom</h3><p>The model begins by converting the information associated with each atom into numerical vectors.</p><p>For example, a carbon atom and an oxygen atom will have different representations because they have different chemical properties.</p><p>The model may also receive information about bonds and other structural characteristics.</p><p>At this stage, the representations are based primarily on the input features.</p><h3>Step 2: Learn Local Chemical Environments</h3><p>The first graph neural network layer allows each atom to incorporate information from its neighboring atoms.</p><p>Consider an oxygen atom connected to a carbon atom.</p><p>The oxygen’s representation can now reflect the presence and characteristics of that neighboring carbon, as well as the bond connecting them.</p><p>After this step, the representation contains more information than the atom’s element type alone.</p><p>It describes something about the atom’s local chemical environment.</p><h3>Step 3: Learn Larger Structural Patterns</h3><p>Additional layers allow information to travel farther through the molecular graph.</p><p>After another layer, an atom can incorporate information from its neighbors’ neighbors.</p><p>As a result, the network can learn representations that capture increasingly larger structural patterns.</p><p>These patterns may correspond to chemically meaningful arrangements, such as particular functional groups or combinations of neighboring atoms.</p><p>The model does not necessarily assign human-readable names to these patterns. Instead, it learns numerical representations that help it perform its training task.</p><h3>Step 4: Create a Representation of the Entire Molecule</h3><p>Once the network has processed the atoms, the model combines their representations into a representation of the whole molecule.</p><p>This step is often called graph pooling or graph readout.</p><p>The resulting vector summarizes information learned from the molecular graph.</p><p>It becomes the input to the final prediction layers.</p><h3>Step 5: Predict Biological Activity</h3><p>The final layers use the learned molecular representation to predict the outcome.</p><p>For a binary classification task, the model might output a score representing the estimated probability that the molecule belongs to the active class.</p><p>For example, the model might estimate a 0.85 probability of activity under the conditions represented by its training data.</p><p>This does not mean the molecule has an 85% chance of curing a patient.</p><p>It means the model estimates an 85% probability of the defined activity outcome, assuming the model’s probability estimates are meaningful and appropriately calibrated.</p><p>That distinction is critical in drug discovery.</p><p>A molecule that is active against a biological target in a laboratory experiment may still fail as a drug because of toxicity, poor absorption, rapid metabolism, or other problems.</p><p><strong>Predicting biological activity is one step in drug discovery, not a prediction of whether a molecule will cure a disease.</strong></p><h3>5. What Data Do We Need to Train the Model?</h3><p>The molecular structure alone is not enough to train a supervised activity prediction model.</p><p>We also need experimental results.</p><p>For example, our dataset might contain the following conceptual records.</p><p><strong>Molecule A</strong></p><ul><li>Input: Molecular structure.</li><li>Experimental result: Active against the selected target.</li></ul><p><strong>Molecule B</strong></p><ul><li>Input: Molecular structure.</li><li>Experimental result: Inactive against the selected target under the tested conditions.</li></ul><p><strong>Molecule C</strong></p><ul><li>Input: Molecular structure.</li><li>Experimental result: Active against the selected target.</li></ul><p>The model learns relationships between the molecular structures and the observed experimental outcomes.</p><p>After training, we can provide a molecule that has not been tested and ask the model to estimate its activity.</p><p>This is the central idea behind supervised molecular property prediction.</p><h3>A Critical Detail: What Does Active Mean?</h3><p>In drug discovery, active does not necessarily mean that a molecule cures a disease.</p><p>Activity depends on the specific experiment.</p><p>For example, a molecule might inhibit a protein involved in a disease process. Researchers may measure how much of the molecule is needed to produce a particular level of inhibition.</p><p>That measurement can help determine whether the molecule is worth investigating further.</p><p>However, activity against a protein in a laboratory experiment does not automatically establish that the molecule will work inside a human body.</p><p>For this reason, a real drug discovery project must carefully define its prediction target.</p><p>Possible targets include:</p><ul><li>Whether a molecule inhibits a particular protein.</li><li>How strongly a molecule binds to a target.</li><li>The concentration required to achieve a specified biological effect.</li><li>Whether a molecule causes toxicity in a particular assay.</li></ul><p>These are different prediction tasks and require appropriately labeled training data.</p><h3>6. Should We Predict Activity and Toxicity With One Model?</h3><p>Not necessarily.</p><p>Activity and toxicity are separate properties.</p><p>A molecule may be active against the intended target but also harmful to human cells.</p><p>Another molecule may be relatively non-toxic but have no useful biological activity.</p><p>Consequently, a practical drug discovery system often evaluates several properties rather than relying on a single classification model.</p><p>For example, we might train:</p><p><strong>Model A: Activity prediction</strong></p><p>Estimates whether a molecule is likely to show the desired activity against the biological target.</p><p><strong>Model B: Toxicity prediction</strong></p><p>Estimates whether a molecule is likely to cause an adverse effect measured by a particular toxicity assay.</p><p><strong>Model C: Additional property prediction</strong></p><p>Estimates properties such as solubility or metabolic stability that can influence whether the molecule is suitable for further development.</p><p>These models can help researchers prioritize candidates for laboratory testing.</p><p>However, predicted toxicity is not a guarantee of safety. A molecule may pass the toxicity assays represented in the training data and still cause harmful effects that those assays do not capture.</p><p>Similarly, a promising computational prediction must be confirmed experimentally.</p><h3>7. Can We Use a Transformer Instead of a Graph Neural Network?</h3><p>Yes.</p><p>A molecular graph is not the only representation suitable for deep learning.</p><p>A Transformer can also learn molecular representations from SMILES strings.</p><p>Recall the ethanol SMILES string:</p><pre>CCO</pre><p>A Transformer-based model can tokenize a SMILES string into units and convert those tokens into numerical representations.</p><p>The model then learns relationships among the tokens through its attention mechanism.</p><p>With suitable training, it can learn structural patterns associated with molecular properties.</p><p>There are two common ways to use this approach.</p><h3>Train a Model for a Specific Prediction Task</h3><p>We can train a Transformer-based model using molecules with known experimental activity.</p><p>The model learns to predict the activity labels directly from molecular representations.</p><p>This approach is useful when the primary objective is to solve a particular prediction task.</p><h3>Start With a Pretrained Molecular Model</h3><p>Alternatively, we can use a model that has already been pretrained on a large collection of molecular structures.</p><p>Pretraining can help the model learn general patterns in chemical representations before it is trained on a specific biological activity dataset.</p><p>We can then fine-tune the model using experimentally tested molecules relevant to our target.</p><p>This is especially useful when the target-specific dataset is relatively small, although the benefit depends on the quality of the pretrained model, the training data, and the prediction task.</p><p>The important point is that <strong>a model pretrained on molecular structures does not automatically know which molecules will treat a particular disease</strong>.</p><p>It must learn the relationship between molecular structure and the relevant biological outcome through suitable training or fine-tuning.</p><h3>8. What About Generating New Molecules?</h3><p>So far, we have focused on predicting the properties of existing molecules.</p><p>But AI can also help researchers propose new molecular structures.</p><p>This is a related but different problem.</p><p>A molecular generation model attempts to produce plausible candidate structures rather than simply classify molecules supplied as input.</p><p>For example, a generative model might propose new SMILES strings representing candidate molecules.</p><p>A screening system can then evaluate these candidates using models that predict activity, toxicity, and other relevant properties.</p><p>The workflow might look like this:</p><p><strong>Generate candidate molecules → Check chemical validity → Predict biological activity → Evaluate toxicity and other properties → Select candidates for laboratory testing</strong></p><p>This creates an iterative process in which generation and prediction can support one another.</p><p>However, generating a valid molecular structure does not guarantee that the molecule can be synthesized, will behave as predicted, or will be safe and effective in humans.</p><p>Experimental testing remains essential.</p><h3>9. How Would You Build a Practical Drug Discovery ML Project?</h3><p>If you want to implement this as a machine learning engineering project, I would recommend starting with molecular activity prediction rather than trying to build a complete drug discovery platform.</p><p>A practical initial project could use Python, RDKit, and PyTorch.</p><h3>Step 1: Define the Biological Target</h3><p>Choose a specific protein or biological target associated with a disease.</p><p>Do not begin with the vague goal of discovering a cure for an entire disease.</p><p>Instead, define a measurable prediction task, such as whether a molecule inhibits the selected target in a particular experimental assay.</p><h3>Step 2: Collect Experimental Data</h3><p>Obtain molecular structures and their corresponding experimental activity measurements.</p><p>Public resources such as <a href="https://pubchem.ncbi.nlm.nih.gov/?utm_source=chatgpt.com">PubChem</a> and <a href="https://www.ebi.ac.uk/chembl/?utm_source=chatgpt.com">ChEMBL</a> provide chemical and bioactivity data that can support this type of research.</p><p>The data preparation process should account for duplicate molecules, inconsistent measurements, missing values, and differences between experimental assays.</p><p>You should also define how active and inactive labels are assigned.</p><h3>Step 3: Convert the Raw Data Into Model Inputs</h3><p>Use RDKit to parse molecular structures represented as SMILES.</p><p>You can begin with traditional molecular fingerprints and descriptors to establish a baseline.</p><p>Then construct molecular graphs for a graph neural network, or tokenize SMILES strings for a Transformer-based model.</p><h3>Step 4: Train a Baseline Model</h3><p>Start with a Random Forest or XGBoost classifier using molecular fingerprints.</p><p>This gives you a baseline against which to compare more sophisticated models.</p><p>It is often a mistake to begin with a complicated deep learning architecture before establishing whether the data and prediction task are suitable.</p><h3>Step 5: Train a Deep Learning Model</h3><p>Next, train a graph neural network or fine-tune a pretrained molecular model.</p><p>Use the same underlying prediction task so you can compare the models fairly.</p><p>Evaluate not only classification accuracy but also metrics such as precision-recall AUC, ROC-AUC, and precision among the highest-ranked candidates.</p><p>For imbalanced datasets, precision-recall analysis is particularly useful because the number of truly active molecules may be small relative to the number of inactive molecules.</p><h3>Step 6: Test Generalization Carefully</h3><p>A model that performs well on randomly selected test molecules may struggle when asked to predict structurally different molecules.</p><p>For this reason, consider a scaffold-based data split, which separates molecules according to their core chemical structures.</p><p>This can provide a more demanding evaluation of whether the model generalizes to unfamiliar chemical structures.</p><p>You should also avoid data leakage and account for related molecules that might otherwise appear in both training and test sets.</p><h3>Step 7: Prioritize Candidates for Experimental Testing</h3><p>Once the model has been evaluated, use it to rank untested molecules.</p><p>Select promising candidates for further investigation based on activity predictions, uncertainty, toxicity predictions, and other relevant criteria.</p><p>Finally, validate the predictions through laboratory experiments.</p><p>The purpose of the model is to help researchers decide which experiments are most worthwhile — not to eliminate experimental validation.</p><h3>10. Final Takeaway</h3><p>The central idea is straightforward.</p><p>A molecule has a chemical structure. We represent that structure in a form that a computer can process, such as a SMILES string or a molecular graph.</p><p>Traditional machine learning typically uses engineered descriptors or molecular fingerprints to represent that structure.</p><p>Deep learning can learn useful molecular representations directly from structural inputs, reducing the need to manually specify every feature.</p><p>A trained model then uses those representations to predict properties such as biological activity.</p><p>The model can help researchers prioritize candidate molecules for experimental testing, potentially reducing the number of expensive experiments required.</p><p>But the real challenge is not simply predicting whether a molecule is active. It is finding a molecule that has the desired biological effect, reaches the relevant target in the body, has acceptable safety and other drug-like properties, and ultimately demonstrates clinical benefit.</p><p><strong>The most important concept to remember: Deep learning can learn useful representations of molecular structures, but experimentally validated biological data is what connects those structures to the drug discovery problem we want to solve.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=20190e042a02" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From SMILES to Predictions: Using Graph Neural Networks for Molecular Activity Prediction]]></title>
            <link>https://medium.com/@jimwang3589/from-smiles-to-predictions-using-graph-neural-networks-for-molecular-activity-prediction-8478778fcf9f?source=rss-4882b9de694e------2</link>
            <guid isPermaLink="false">https://medium.com/p/8478778fcf9f</guid>
            <dc:creator><![CDATA[Jim Wang]]></dc:creator>
            <pubDate>Mon, 02 Nov 2026 14:11:58 GMT</pubDate>
            <atom:updated>2026-11-02T14:11:58.615Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bR59iNfcOmY1xxcsTe38Vg.png" /></figure><h3>Introduction</h3><p>Drug discovery is an expensive and time-consuming process. Before a potential drug can become a treatment, researchers need to evaluate thousands or even millions of chemical compounds to determine whether they might have the desired biological activity.</p><p>One important task in early-stage drug discovery is molecular activity prediction: given a chemical molecule, predict whether it is likely to be active against a particular biological target.</p><p>Traditional machine learning approaches often represent molecules using manually designed molecular descriptors or fingerprints. These representations can be effective, but they may also lose some of the structural information contained in a molecule.</p><p>Graph Neural Networks (GNNs) provide an alternative approach. Instead of converting a molecule into a predefined feature vector, GNNs learn directly from its graph structure, allowing neural networks to discover useful molecular patterns automatically.</p><p>In this article, we will walk through the fundamental concepts of molecular activity prediction, from representing molecules as graphs to using message passing and graph pooling to produce a final activity prediction.</p><h3>1. Understanding the Molecular Data</h3><p>Before building a deep learning model, we need to understand what the input data looks like.</p><p>A molecule consists of atoms connected by chemical bonds. Different combinations of atoms and bonds produce different molecular structures.</p><p>For example, ethanol has three main atoms:</p><ul><li>Carbon</li><li>Carbon</li><li>Oxygen</li></ul><p>These atoms are connected through chemical bonds, forming the molecular structure.</p><p>In machine learning, we need a machine-readable representation of this structure.</p><h3>SMILES: Representing Molecules as Text</h3><p>One popular representation is SMILES, which stands for Simplified Molecular Input Line Entry System.</p><p>SMILES represents a molecular structure using a sequence of characters.</p><p>For example, ethanol can be represented as:</p><p>CCO</p><p>Each character represents an atom, while the arrangement of characters describes how atoms are connected.</p><p>SMILES also supports more complicated structures, including:</p><ul><li>Double and triple bonds</li><li>Ring structures</li><li>Branches</li><li>Different types of atoms</li><li>Charges and stereochemistry</li></ul><p>Although SMILES looks like ordinary text, it contains information about the molecular structure.</p><p>However, rather than feeding SMILES directly into a traditional neural network, we can first convert it into a molecular graph.</p><h3>2. Converting SMILES into a Molecular Graph</h3><p>A molecular graph is a natural representation of a chemical molecule.</p><p>It contains two fundamental components:</p><p><strong>Nodes represent atoms.</strong></p><p>Each atom becomes a node in the graph. We can associate each node with features describing its chemical properties.</p><p>For example, atom features can include:</p><ul><li>Atomic number</li><li>Number of neighboring atoms</li><li>Formal electrical charge</li><li>Atom type</li><li>Number of hydrogen atoms</li><li>Whether the atom belongs to a ring</li><li>Whether the atom is aromatic</li></ul><p>These features provide the initial numerical representation of each atom.</p><p><strong>Edges represent chemical bonds.</strong></p><p>Each chemical bond becomes an edge connecting two atom nodes.</p><p>Edges can also contain their own features, such as:</p><ul><li>Bond type: single, double, or triple</li><li>Whether the bond is aromatic</li><li>Whether the bond is in a ring</li><li>Bond stereochemistry</li></ul><p>Therefore, a molecular graph contains both atom-level information and bond-level information.</p><p>This is important because molecular activity depends not only on which atoms are present, but also on how those atoms are connected.</p><h3>Using RDKit to Generate Molecular Graphs</h3><p>RDKit is one of the most widely used open-source cheminformatics libraries.</p><p>It provides functionality for parsing SMILES strings, identifying atoms and bonds, calculating molecular properties, and generating molecular fingerprints.</p><p>A typical preprocessing pipeline looks like this:</p><ol><li>Read a SMILES string.</li><li>Use RDKit to parse the molecular structure.</li><li>Extract atom features.</li><li>Extract bond features.</li><li>Construct the graph representation.</li><li>Convert the graph into tensors for deep learning.</li></ol><p>The resulting graph can then be passed to a Graph Neural Network.</p><h3>3. Molecular Fingerprints: A Traditional Machine Learning Approach</h3><p>Before discussing GNNs, it is useful to understand an important traditional approach: molecular fingerprints.</p><p>One popular fingerprint algorithm is Morgan fingerprinting, also known as the Extended Connectivity Fingerprint (ECFP).</p><p>The basic idea is to describe a molecule by identifying local chemical environments around its atoms.</p><p>The algorithm starts with individual atoms and examines their neighboring atoms. It then expands the neighborhood to include atoms further away.</p><p>For example, it might examine:</p><ul><li>An atom by itself.</li><li>An atom and its immediate neighbors.</li><li>An atom and its neighbors two bonds away.</li></ul><p>Each local chemical environment is converted into a numerical identifier through a hashing process.</p><p>These identifiers are then mapped into a fixed-length binary vector.</p><p>A commonly used fingerprint size is 2,048 bits.</p><p>Each position in the vector indicates whether a particular hashed chemical pattern is present. A count-based representation can also record how frequently patterns occur.</p><p>The fingerprint can then be used as input to traditional machine learning algorithms such as:</p><ul><li>Random Forest</li><li>Support Vector Machine</li><li>Gradient Boosting</li><li>XGBoost</li></ul><p>For example, a Random Forest model can learn associations between molecular fingerprints and experimentally observed biological activity.</p><p>This approach is relatively simple, computationally efficient, and often provides a strong baseline for molecular activity prediction.</p><p>However, the fingerprint length is fixed, and hashing can cause different chemical environments to map to the same position.</p><p>GNNs offer another way to learn molecular representations directly from graph structures.</p><h3>4. Introduction to Graph Neural Networks</h3><p>A Graph Neural Network is a neural network designed to process graph-structured data.</p><p>Unlike conventional neural networks that typically process fixed-size vectors or regular image grids, GNNs operate on nodes and edges.</p><p>For molecular activity prediction, the graph represents a molecule:</p><ul><li>Nodes represent atoms.</li><li>Edges represent chemical bonds.</li><li>Node features describe atom properties.</li><li>Edge features describe bond properties.</li></ul><p>The central idea behind many GNN architectures is called message passing.</p><p>Message passing allows atoms to exchange information with their neighboring atoms through the chemical bonds connecting them.</p><p>This process enables the model to learn increasingly rich representations of molecular structures.</p><h3>5. Understanding Message Passing</h3><p>Message passing is the fundamental mechanism behind many modern GNN architectures.</p><p>The process consists of three major operations:</p><h3>Step 1: Initialize Atom Embeddings</h3><p>First, each atom has an initial feature vector describing its chemical properties.</p><p>For example, a carbon atom might have features describing its atomic number, formal charge, and number of neighboring atoms.</p><p>These initial features are transformed into numerical vectors called embeddings.</p><p>An embedding is simply a numerical representation that a neural network can learn to make useful for a particular prediction task.</p><p>The embedding dimensions do not necessarily correspond to specific chemical properties. Instead, the network learns useful numerical representations during training.</p><h3>Step 2: Generate Messages</h3><p>Next, each atom sends information to its neighboring atoms.</p><p>A chemical bond acts as the connection through which information travels.</p><p>The GNN uses a mathematical function, typically implemented with learnable neural network parameters, to generate messages.</p><p>The message can depend on:</p><ul><li>The source atom’s current embedding.</li><li>The bond features.</li><li>Sometimes the destination atom’s embedding.</li></ul><p>For example, when a carbon atom sends information to an oxygen atom, the model transforms the carbon atom’s embedding into a message vector.</p><p>The oxygen atom receives messages from its connected neighbors.</p><p>This is not simply copying the original atom features. The message function is learned during training, allowing the model to discover which information is useful.</p><h3>Step 3: Aggregate and Update Atom Embeddings</h3><p>After receiving messages from neighboring atoms, each atom aggregates them into a single vector.</p><p>Common aggregation operations include:</p><ul><li>Sum</li><li>Mean</li><li>Maximum</li></ul><p>The aggregated message is then combined with the atom’s existing embedding.</p><p>An update function, usually a neural network, transforms this information into a new atom embedding.</p><p>The updated embedding now contains information about both the atom itself and its surrounding chemical environment.</p><p>This process can be repeated across multiple GNN layers.</p><p>After one layer, an atom can incorporate information from its immediate neighbors.</p><p>After two layers, it can incorporate information from atoms two bonds away.</p><p>With additional layers, the model can learn increasingly broader molecular environments.</p><p>This is how GNNs gradually build contextual representations of molecular structures.</p><h3>6. Popular GNN Architectures</h3><p>There are several approaches to implementing message passing. Three important architectures are GCN, GAT, and GIN.</p><h3>Graph Convolutional Network (GCN)</h3><p>GCN stands for Graph Convolutional Network.</p><p>Its main idea is to aggregate information from neighboring nodes using graph-based normalization.</p><p>Before aggregation, GCN typically adds self-connections, allowing each atom to retain information about itself.</p><p>It then combines the features of neighboring atoms using normalized weights derived from the graph structure.</p><p>After normalization, the aggregated features are multiplied by a learnable weight matrix.</p><p>This weight matrix transforms and mixes the feature dimensions, similar in spirit to how convolutional filters learn feature transformations in computer vision.</p><p>The result is a new embedding for each atom.</p><p>GCN is a relatively simple and effective architecture for graph representation learning.</p><h3>Graph Attention Network (GAT)</h3><p>GAT stands for Graph Attention Network.</p><p>Unlike GCN, which uses graph-based normalization, GAT learns attention weights for neighboring nodes.</p><p>The basic idea is that not every neighboring atom should necessarily contribute equally to an atom’s updated representation.</p><p>For example, when updating an atom’s embedding, the model might learn to assign different importance to its neighboring atoms.</p><p>The attention mechanism calculates a weight for each neighboring atom.</p><p>These weights are used to combine neighboring embeddings into a weighted representation.</p><p>The model learns the attention mechanism during training.</p><p>This provides a flexible way to model relationships between neighboring atoms.</p><h3>Graph Isomorphism Network (GIN)</h3><p>GIN stands for Graph Isomorphism Network.</p><p>Its central idea is to use summation to aggregate neighboring node embeddings.</p><p>Unlike attention-based aggregation, the basic GIN aggregation does not calculate a separate attention weight for every neighbor.</p><p>Instead, it performs a straightforward element-wise summation.</p><p>It combines the atom’s own embedding with the summed embeddings of its neighboring atoms.</p><p>The resulting vector is passed through a Multi-Layer Perceptron (MLP), which produces the updated atom embedding.</p><p>The MLP contains learnable weights and nonlinear activation functions.</p><p>GIN is particularly interesting because its aggregation mechanism has strong theoretical expressive power for distinguishing graph structures.</p><p>This makes it an important architecture for molecular graph learning.</p><h3>7. From Atom Embeddings to a Molecular Embedding</h3><p>After several message-passing layers, every atom has an updated embedding containing information about its local molecular environment.</p><p>However, our prediction target is the entire molecule, not an individual atom.</p><p>We therefore need to combine all atom embeddings into a single molecular representation.</p><p>This operation is called graph pooling or global pooling.</p><p>There are several common approaches.</p><p><strong>Sum pooling</strong></p><p>Sum pooling adds the embeddings of all atoms together, producing one vector representing the molecule.</p><p><strong>Mean pooling</strong></p><p>Mean pooling calculates the average of all atom embeddings.</p><p>This produces a representation that is less directly dependent on the number of atoms.</p><p><strong>Attention pooling</strong></p><p>Attention pooling learns to assign different importance weights to different atoms.</p><p>This allows the model to emphasize atoms or molecular regions that are particularly informative for the prediction task.</p><p>After pooling, regardless of the number of atoms in the original molecule, we obtain a fixed-dimensional molecular embedding.</p><p>This is an important step because traditional classification layers expect a fixed-size input vector.</p><h3>8. Predicting Molecular Activity with an MLP</h3><p>Now we have a single embedding representing the entire molecule.</p><p>The next step is to predict whether the molecule is biologically active.</p><p>We can accomplish this using a Multi-Layer Perceptron (MLP) as a classification head.</p><p>The MLP receives the molecular embedding and processes it through one or more fully connected neural network layers.</p><p>The final layer produces a prediction score.</p><p>For binary classification, we can use a sigmoid activation function to convert the score into a probability between zero and one.</p><p>For example:</p><ul><li>A probability close to 1 indicates a high predicted likelihood of activity.</li><li>A probability close to 0 indicates a low predicted likelihood of activity.</li></ul><p>We can then apply a threshold to classify the molecule as active or inactive.</p><p>The complete architecture can be understood as a sequence of operations:</p><ol><li>SMILES input.</li><li>Molecular graph construction.</li><li>Atom and bond feature extraction.</li><li>Initial atom embeddings.</li><li>GNN message-passing layers.</li><li>Global graph pooling.</li><li>Molecular embedding.</li><li>MLP classification head.</li><li>Predicted activity probability.</li></ol><p>This is the complete process of using a GNN to predict molecular activity.</p><h3>9. Training the Model</h3><p>A GNN cannot predict molecular activity reliably without learning from examples.</p><p>We need a labeled dataset containing molecules whose biological activities have already been experimentally measured.</p><p>For example, each training sample might contain:</p><ul><li>A SMILES string representing a molecule.</li><li>An experimentally determined activity label.</li></ul><p>The label could be binary:</p><ul><li>Active: 1</li><li>Inactive: 0</li></ul><p>During training, the model processes each molecule and generates an activity probability.</p><p>The prediction is compared with the experimental label using a loss function.</p><p>For binary classification, Binary Cross-Entropy is a common choice.</p><p>Backpropagation calculates gradients, and an optimizer such as Adam updates the model’s trainable parameters.</p><p>Over multiple training iterations, the model learns molecular representations and classification patterns associated with biological activity.</p><p>One important consideration is that drug discovery datasets are often highly imbalanced. There may be many more inactive molecules than active ones.</p><p>In such situations, researchers may consider weighted loss functions, focal loss, or sampling strategies to improve learning.</p><p>Model evaluation should also use appropriate metrics, such as:</p><ul><li>ROC-AUC</li><li>PR-AUC</li><li>Precision</li><li>Recall</li><li>F1-score</li></ul><p>For drug discovery, PR-AUC can be particularly informative when active compounds are rare.</p><p>It is also important to split the data carefully. Random splitting alone can produce overly optimistic results when chemically similar molecules appear in both training and test sets.</p><p>A scaffold-based split is often useful because it tests whether the model can generalize to different molecular structures.</p><h3>10. Implementing Molecular GNNs with PyTorch Geometric</h3><p>PyTorch Geometric, commonly known as PyG, is one of the most popular libraries for building Graph Neural Networks using PyTorch.</p><p>It provides implementations of many GNN layers, including:</p><ul><li>GCNConv</li><li>GATConv</li><li>GINConv</li><li>GraphSAGE</li></ul><p>It also provides utilities for batching multiple graphs and performing graph-level pooling.</p><p>A typical molecular activity prediction implementation involves three major components.</p><p><strong>Molecular preprocessing</strong></p><p>Use RDKit to convert SMILES strings into molecular graphs, extracting atom features, bond features, and connectivity information.</p><p><strong>Graph neural network</strong></p><p>Use PyTorch Geometric to implement message-passing layers. These layers learn atom embeddings by exchanging information across molecular bonds.</p><p><strong>Classification head</strong></p><p>Apply global pooling to generate molecular embeddings, followed by an MLP to predict biological activity.</p><p>A practical technology stack might look like this:</p><ul><li>RDKit: Molecular structure processing.</li><li>PyTorch: Deep learning framework.</li><li>PyTorch Geometric: Graph neural network implementation.</li><li>Scikit-learn: Evaluation metrics and baseline models.</li></ul><p>This combination provides a flexible foundation for building molecular activity prediction systems.</p><h3>11. Important Considerations in Real-World Drug Discovery</h3><p>Although GNNs are powerful, predicting molecular activity is not the same as discovering an effective drug.</p><p>Biological activity depends on many factors beyond molecular structure alone.</p><p>For example, a compound may bind strongly to a target protein but still fail as a potential drug because of poor solubility, toxicity, or insufficient absorption.</p><p>It is also important to distinguish between predicting activity against a particular protein target and predicting whether a molecule can treat a disease.</p><p>A molecule may interact with a protein without producing a beneficial therapeutic effect.</p><p>For more advanced drug discovery applications, researchers may combine molecular GNNs with protein representations, protein structures, molecular docking, and experimental biological data.</p><p>This can help build more comprehensive models of molecular interactions.</p><h3>Conclusion</h3><p>Graph Neural Networks provide a powerful approach to molecular activity prediction by learning directly from the graph structure of chemical molecules.</p><p>The process begins with a SMILES string, which is converted into a molecular graph using RDKit.</p><p>Atoms become nodes, chemical bonds become edges, and their chemical properties become numerical features.</p><p>Through message passing, atoms exchange information with their neighbors and gradually develop richer embeddings.</p><p>Architectures such as GCN, GAT, and GIN implement different mechanisms for aggregating and updating these embeddings.</p><p>Finally, graph pooling combines all atom embeddings into a single molecular representation, which is passed through an MLP classifier to predict biological activity.</p><p>The key advantage is that the model can learn useful molecular representations automatically instead of relying entirely on manually designed molecular fingerprints.</p><p>For anyone interested in applying deep learning to drug discovery, understanding this pipeline is an excellent starting point.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8478778fcf9f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[16 Essential Deep Learning Interview Questions and Answers: A Technical Guide]]></title>
            <link>https://medium.com/@jimwang3589/16-essential-deep-learning-interview-questions-and-answers-a-technical-guide-59509c4840bd?source=rss-4882b9de694e------2</link>
            <guid isPermaLink="false">https://medium.com/p/59509c4840bd</guid>
            <dc:creator><![CDATA[Jim Wang]]></dc:creator>
            <pubDate>Mon, 02 Nov 2026 13:58:53 GMT</pubDate>
            <atom:updated>2026-11-02T13:58:53.631Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LDnp1zbCSb-oj34eTECPBQ.png" /></figure><p>Deep learning interviews frequently test fundamental concepts, neural network architectures, optimization techniques, and practical model-training strategies.</p><p>This guide covers 16 important deep learning interview questions, with concise explanations and practical examples. It is designed to help candidates understand the concepts and explain them confidently during technical interviews.</p><h3>1. What Are Vanishing and Exploding Gradients?</h3><p>Vanishing gradients occur when gradients become extremely small during backpropagation, making it difficult for earlier layers to learn.</p><p>Exploding gradients occur when gradients become excessively large, causing unstable parameter updates and potentially preventing convergence.</p><p>Common solutions include:</p><ul><li>Using ReLU or its variants instead of sigmoid or tanh in hidden layers.</li><li>Applying proper weight initialization, such as Xavier or He initialization.</li><li>Using batch normalization to stabilize training.</li><li>Applying gradient clipping to prevent exploding gradients.</li><li>Using LSTM or GRU architectures for sequential data.</li></ul><h3>2. What Is Weight Initialization? What Are Xavier and He Initialization?</h3><p>Weight initialization determines the starting values of neural network parameters before training.</p><p>Poor initialization can cause vanishing or exploding activations and gradients.</p><p>Two popular approaches are:</p><p>Xavier Initialization: Designed primarily for sigmoid and tanh activations. It considers both the number of input and output connections to maintain activation variance across layers.</p><p>He Initialization: Designed primarily for ReLU and its variants. It accounts for the fact that ReLU sets negative activations to zero.</p><p>Proper initialization helps stabilize training and improves convergence.</p><h3>3. What Are the Differences Between SGD, Mini-Batch Gradient Descent, and Adam?</h3><p>Gradient descent algorithms update model parameters to minimize the loss function.</p><p>Batch Gradient Descent calculates gradients using the entire training dataset before each update. It provides stable updates but can be computationally expensive.</p><p>Stochastic Gradient Descent (SGD) updates parameters using one training example at a time. It is computationally lightweight but produces noisy updates.</p><p>Mini-Batch Gradient Descent uses a small subset of training examples for each update. It balances computational efficiency and gradient stability.</p><p>Adam combines momentum with adaptive learning rates. It maintains moving averages of gradients and squared gradients, allowing different parameters to have different effective learning rates.</p><p>Adam is often a good starting point, while SGD can perform well with appropriate learning-rate scheduling.</p><h3>4. What Is Overfitting, and How Can We Prevent It?</h3><p>Overfitting occurs when a model performs very well on training data but poorly on unseen data.</p><p>The model learns specific patterns and noise from the training dataset instead of generalizing effectively.</p><p>Common prevention techniques include:</p><p>Dropout: Randomly disables a proportion of neurons during training, reducing excessive dependence on individual neurons.</p><p>L1 Regularization: Adds a penalty based on the absolute values of model weights. It encourages sparse solutions.</p><p>L2 Regularization: Adds a penalty based on squared weight values. It discourages excessively large weights.</p><p>Early Stopping: Monitors validation performance and stops training when validation loss stops improving.</p><p>Data Augmentation: Generates additional training examples through transformations such as rotation, cropping, and flipping.</p><h3>5. What Is Batch Normalization, and How Does It Work?</h3><p>Batch Normalization normalizes intermediate activations using the mean and variance calculated from a mini-batch.</p><p>It then introduces two learnable parameters, gamma and beta, allowing the network to adjust the normalized values.</p><p>Batch normalization offers several benefits:</p><ul><li>Stabilizes the distribution of activations during training.</li><li>Often allows higher learning rates.</li><li>Can improve training stability and convergence.</li><li>Provides a mild regularization effect due to mini-batch statistics.</li></ul><p>It can also reduce the risk of activation saturation in sigmoid and tanh networks, although it does not directly eliminate vanishing gradients.</p><h3>6. What Are the Differences Between CNN and RNN?</h3><p>Convolutional Neural Networks (CNNs) are designed to extract local patterns from structured data, particularly images.</p><p>CNNs use convolutional filters to detect features such as edges, textures, and shapes. Deeper layers combine these features into more complex representations.</p><p>Recurrent Neural Networks (RNNs) are designed for sequential data, such as text, speech, and time series.</p><p>RNNs process sequences one step at a time and maintain a hidden state that carries information from previous time steps.</p><p>The main difference is that CNNs focus on local spatial patterns, while RNNs model sequential dependencies.</p><h3>7. What Are LSTM and GRU? How Are They Different?</h3><p>Standard RNNs struggle with long-term dependencies because gradients can vanish during backpropagation through many time steps.</p><p>LSTM and GRU address this problem using gating mechanisms.</p><p>LSTM (Long Short-Term Memory) maintains two states:</p><ul><li>Cell state: Carries information across time steps.</li><li>Hidden state: Represents the current output.</li></ul><p>It uses three gates:</p><ul><li>Forget gate: Determines what information to remove from the cell state.</li><li>Input gate: Determines what new information to store.</li><li>Output gate: Determines what information to expose as the hidden state.</li></ul><p>GRU (Gated Recurrent Unit) simplifies the LSTM architecture.</p><p>It maintains only one hidden state and uses two gates:</p><ul><li>Update gate: Controls how much previous information to retain versus how much new information to incorporate.</li><li>Reset gate: Controls how much previous information to use when calculating new candidate information.</li></ul><p>GRU generally has fewer parameters and can train faster than LSTM, although performance depends on the task and dataset.</p><h3>8. What Is the Attention Mechanism? What Are Query, Key, and Value?</h3><p>Attention allows a model to focus on relevant information when processing a sequence.</p><p>Instead of treating every token equally, attention calculates how strongly different tokens relate to one another.</p><p>It uses three vectors:</p><p>Query (Q): Represents what information the current token is looking for.</p><p>Key (K): Represents features used to determine how relevant another token is to the query.</p><p>Value (V): Represents the information that will be combined according to the attention weights.</p><p>The query and key vectors are compared to calculate attention scores. Softmax converts these scores into normalized attention weights.</p><p>These weights are then applied to the value vectors to produce the attention output.</p><p>An important distinction is that keys and values are derived from the same input representations through different learned linear transformations. They are not identical vectors.</p><h3>9. What Is Multi-Head Attention?</h3><p>Multi-head attention allows a Transformer to learn different relationships between tokens simultaneously.</p><p>Each attention head has its own learned query, key, and value projections.</p><p>For example, consider:</p><p>“The student gave the teacher a book because she requested it.”</p><p>Different attention heads may learn to focus on:</p><ul><li>Relationships between pronouns and their possible references.</li><li>Relationships between actions and the people performing them.</li><li>Connections between verbs and their objects.</li><li>Long-distance relationships between words.</li><li>Semantic relationships between different parts of the sentence.</li></ul><p>The outputs from multiple heads are combined to produce a richer representation.</p><p>This allows the model to capture different types of information simultaneously.</p><h3>10. What Is the Transformer Architecture?</h3><p>The Transformer is a neural network architecture based primarily on attention mechanisms rather than recurrent processing.</p><p>Its main components include:</p><p>Embedding Layer: Converts input tokens into numerical vectors.</p><p>Positional Encoding: Adds information about token positions because attention alone does not inherently represent sequence order.</p><p>Multi-Head Attention: Captures relationships between different tokens.</p><p>Feed-Forward Network: Applies additional nonlinear transformations to each token representation.</p><p>Residual Connections: Add input representations to layer outputs, helping information and gradients flow through deep networks.</p><p>Layer Normalization: Normalizes activations to improve training stability.</p><p>The original Transformer uses an encoder-decoder architecture and was introduced for machine translation.</p><h3>11. What Are the Differences Between Encoder-Only, Decoder-Only, and Encoder-Decoder Transformers?</h3><p>Transformer models generally fall into three architectural categories.</p><p>Encoder-Only Models</p><p>Example: BERT.</p><p>Encoder-only models use bidirectional self-attention to understand relationships between tokens in both directions.</p><p>They generate contextualized representations that can be used for:</p><ul><li>Text classification.</li><li>Sentiment analysis.</li><li>Named entity recognition.</li><li>Semantic similarity.</li></ul><p>Decoder-Only Models</p><p>Example: GPT.</p><p>Decoder-only models use causal self-attention, meaning each token can only attend to previous tokens and itself.</p><p>They generate text autoregressively, predicting the next token based on previously generated tokens.</p><p>Common applications include text generation, conversational AI, and code generation.</p><p>Encoder-Decoder Models</p><p>Example: The original Transformer.</p><p>The encoder processes the input sequence, while the decoder generates the output sequence.</p><p>Cross-attention allows the decoder to access information from the encoder.</p><p>This architecture is particularly useful for machine translation, summarization, and other sequence-to-sequence tasks.</p><h3>12. What Is the Difference Between Self-Attention and Cross-Attention?</h3><p>Self-Attention calculates attention within the same sequence.</p><p>Queries, keys, and values are derived from the same sequence representations.</p><p>For example, when processing “I love machine learning,” each token can attend to other tokens to understand the sentence context.</p><p>Cross-Attention connects two different sequences.</p><p>Queries come from one sequence, while keys and values come from another.</p><p>For example, in machine translation:</p><ul><li>The encoder reads the English sentence.</li><li>The decoder generates the French translation.</li><li>The decoder produces queries.</li><li>The encoder outputs provide keys and values.</li></ul><p>Cross-attention allows the decoder to focus on relevant parts of the original English sentence while generating French words.</p><p>Self-attention models relationships within a sequence, while cross-attention connects information across sequences.</p><h3>13. What Is LoRA (Low-Rank Adaptation)?</h3><p>LoRA is a parameter-efficient fine-tuning technique that adapts large pretrained models without updating their original weights.</p><p>During traditional fine-tuning, many or all pretrained model parameters are updated, requiring substantial memory and computational resources.</p><p>LoRA takes a different approach:</p><ol><li>Freeze the original pretrained weight matrices.</li><li>Introduce two smaller trainable matrices, commonly called A and B.</li><li>Use their product to represent the weight update.</li><li>Train only these additional matrices while keeping the original weights unchanged.</li></ol><p>The key idea is low-rank decomposition.</p><p>Instead of directly learning a large weight update matrix, LoRA approximates that update using two smaller matrices.</p><p>The effective weight becomes the original weight plus the low-rank update.</p><p>LoRA reduces the number of trainable parameters, memory requirements, and computational costs.</p><p>It is particularly useful when fine-tuning large language models for specialized tasks.</p><h3>14. What Is QLoRA, and How Is It Different from LoRA?</h3><p>QLoRA stands for Quantized Low-Rank Adaptation.</p><p>It combines quantization with LoRA to reduce memory requirements even further.</p><p>LoRA freezes the original model weights and trains small additional matrices.</p><p>QLoRA additionally stores the frozen pretrained model weights in a low-bit representation, commonly 4-bit quantization.</p><p>Its main characteristics include:</p><ul><li>Quantizing pretrained model weights.</li><li>Freezing the quantized base model.</li><li>Training LoRA adapter parameters.</li><li>Reducing GPU memory requirements.</li></ul><p>QLoRA makes fine-tuning large language models more accessible on hardware with limited memory.</p><h3>15. What Are the Most Popular Activation Functions and Their Advantages and Disadvantages?</h3><p>Activation functions introduce nonlinearity into neural networks, allowing them to learn complex patterns.</p><p>Sigmoid</p><p>Outputs values between zero and one.</p><p>Advantages:</p><ul><li>Useful for binary classification output layers.</li><li>Produces values that can be interpreted as probabilities.</li></ul><p>Disadvantages:</p><ul><li>Can cause vanishing gradients.</li><li>Outputs are not zero-centered.</li></ul><p>Tanh</p><p>Outputs values between negative one and positive one.</p><p>Advantages:</p><ul><li>Zero-centered outputs.</li><li>Often works better than sigmoid in certain hidden-layer applications.</li></ul><p>Disadvantages:</p><p>- Can still suffer from vanishing gradients.</p><p>ReLU (Rectified Linear Unit)</p><p>Outputs zero for negative inputs and the original input for positive inputs.</p><p>Advantages:</p><ul><li>Computationally efficient.</li><li>Helps reduce vanishing gradients for positive activations.</li><li>Widely used in CNNs and other deep networks.</li></ul><p>Disadvantages:</p><ul><li>Can suffer from the dying ReLU problem.</li><li>Negative inputs produce zero gradients.</li></ul><p>Leaky ReLU</p><p>Allows a small negative slope instead of setting all negative inputs to zero.</p><p>Advantages:</p><ul><li>Helps address the dying ReLU problem.</li><li>Maintains a nonzero gradient for negative inputs.</li></ul><p>Disadvantages:</p><p>- Requires choosing a negative slope parameter.</p><p>PReLU (Parametric ReLU)</p><p>Similar to Leaky ReLU, but its negative slope is a learnable parameter.</p><p>Advantages:</p><ul><li>Allows the model to learn the appropriate negative slope.</li><li>Helps address dying ReLU.</li></ul><p>Disadvantages:</p><p>- Introduces additional trainable parameters.</p><p>GELU (Gaussian Error Linear Unit)</p><p>A smooth activation function commonly used in Transformer architectures such as BERT.</p><p>Advantages:</p><ul><li>Smoothly activates inputs rather than applying a hard threshold.</li><li>Performs well in many Transformer architectures.</li></ul><p>Disadvantages:</p><p>- More computationally expensive than standard ReLU.</p><p>SiLU (Sigmoid Linear Unit)</p><p>Also known as Swish, SiLU multiplies the input by its sigmoid activation.</p><p>Advantages:</p><ul><li>Smooth and differentiable.</li><li>Used in modern deep learning architectures.</li></ul><p>Disadvantages:</p><p>- More computationally expensive than ReLU.</p><h3>16. What Are Residual Connections, and Why Are They Important?</h3><p>Residual connections allow a neural network layer to pass its input directly to a later layer.</p><p>Instead of learning the complete output transformation, a layer learns a residual transformation that is added to the original input.</p><p>This creates a shortcut path through the network.</p><p>Residual connections offer several benefits:</p><ul><li>Improve gradient flow during backpropagation.</li><li>Help reduce optimization difficulties in very deep networks.</li><li>Make it easier to train deeper architectures.</li><li>Preserve information from earlier layers.</li></ul><p>Residual connections are a fundamental component of ResNet and are also widely used in Transformer architectures.</p><h3>Conclusion</h3><p>Understanding deep learning requires more than memorizing definitions. Technical interviews often focus on why an architecture works, what problem it solves, and what trade-offs it introduces.</p><p>The most important concepts to master include gradient optimization, regularization, neural network architectures, attention mechanisms, Transformers, and parameter-efficient fine-tuning.</p><p>A strong interview answer should explain three things: the underlying mechanism, the problem being addressed, and the practical advantages and limitations.</p><p>These fundamentals provide a solid foundation for more advanced topics in modern deep learning and large language models.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=59509c4840bd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Types of Prompt for LLM]]></title>
            <link>https://medium.com/@jimwang3589/types-of-prompt-for-llm-d3d07bb90a6e?source=rss-4882b9de694e------2</link>
            <guid isPermaLink="false">https://medium.com/p/d3d07bb90a6e</guid>
            <dc:creator><![CDATA[Jim Wang]]></dc:creator>
            <pubDate>Wed, 18 Dec 2024 01:05:36 GMT</pubDate>
            <atom:updated>2024-12-18T01:05:36.900Z</atom:updated>
            <content:encoded><![CDATA[<p>Here are different <strong>types of prompts</strong> used in prompt engineering, categorized based on their purpose and structure:</p><h3>1. Instruction-Based Prompts</h3><p>These prompts provide clear instructions for the model to follow.</p><ul><li><strong>Example</strong>:<br><em>“Summarize the following article in three sentences, focusing on the main idea.”</em></li><li><strong>Use Case</strong>:<br>Tasks like summarization, explanations, or question-answering.</li></ul><h3>2. Role-Based Prompts</h3><p>The model is assigned a specific role to adopt, which influences the tone, style, and content of the output.</p><ul><li><strong>Example</strong>:<br><em>“You are a financial advisor. Provide investment tips for someone new to the stock market.”</em></li><li><strong>Use Case</strong>:<br>Scenarios requiring expertise, such as technical advice, creative writing, or professional tasks.</li></ul><h3>3. Contextual Prompts</h3><p>Prompts where additional background or context is given to guide the model’s response.</p><ul><li><strong>Example</strong>:<br><em>“In the year 2030, space travel has become commercial. Write a story about a family’s first trip to Mars.”</em></li><li><strong>Use Case</strong>:<br>Creative writing, storytelling, or technical problems requiring context.</li></ul><h3>4. Input-Output Examples (Few-Shot Prompts)</h3><p>The model is given examples of inputs and desired outputs to set the pattern for the task.</p><ul><li><strong>Example</strong>:<br>*”Convert the following sentences into active voice:</li><li>Input: ‘The cake was eaten by John.’</li><li>Output: ‘John ate the cake.’<br>Now, convert: ‘The project was completed by Sarah.’”*</li><li><strong>Use Case</strong>:<br>NLP tasks, such as text conversion, sentiment analysis, and formatting.</li></ul><h3>5. Zero-Shot Prompts</h3><p>No examples are provided; the model must rely solely on instructions.</p><ul><li><strong>Example</strong>:<br><em>“Translate this sentence into French: ‘How are you today?’”</em></li><li><strong>Use Case</strong>:<br>General tasks where the model can infer patterns directly.</li></ul><h3>6. Chain-of-Thought (CoT) Prompts</h3><p>Prompts that encourage step-by-step reasoning to solve a problem or explain an answer.</p><ul><li><strong>Example</strong>:<br><em>“Solve this problem step-by-step: If a train travels 60 miles per hour for 3 hours, how far does it travel?”</em></li><li><strong>Use Case</strong>:<br>Math problems, logical reasoning, or complex explanations.</li></ul><h3>7. Multi-Turn Prompts</h3><p>Prompts designed for dialogue or multi-step interactions, often seen in conversational AI.</p><ul><li><strong>Example</strong>:<br><em>“User: What’s the weather like today?<br>Assistant: It’s sunny and 75 degrees.<br>User: Should I wear a jacket?<br>Assistant: No, a light shirt will be enough for today.”</em></li><li><strong>Use Case</strong>:<br>Conversational systems, like chatbots.</li></ul><h3>8. Persona-Based Prompts</h3><p>The model adopts a specific personality, voice, or behavior.</p><ul><li><strong>Example</strong>:<br><em>“Act as a motivational coach. Encourage me to start exercising daily.”</em></li><li><strong>Use Case</strong>:<br>Role-playing scenarios, personalized advice, and specific tones.</li></ul><h3>9. Format-Specific Prompts</h3><p>The desired output format (e.g., bullet points, tables, or code snippets) is explicitly defined.</p><ul><li><strong>Example</strong>:<br><em>“List the benefits of exercise in bullet points.”</em></li><li><strong>Use Case</strong>:<br>Structured outputs like lists, tables, or code.</li></ul><h3>10. Delimiters-Based Prompts</h3><p>Delimiters (like &quot;&quot;&quot; or &lt;&gt;) are used to clearly define input, instructions, or boundaries.</p><ul><li><strong>Example</strong>:<br><em>“Summarize the text between the triple quotes:<br>“””<br>Artificial Intelligence is transforming industries…<br>“”” “</em></li><li><strong>Use Case</strong>:<br>Tasks requiring clear separation of input and instructions.</li></ul><h3>11. Iterative Refinement Prompts</h3><p>Prompts that ask the model to refine or improve previous outputs.</p><ul><li><strong>Example</strong>:<br><em>“Revise the following paragraph to make it more concise while keeping the key points intact.”</em></li><li><strong>Use Case</strong>:<br>Editing, revising, and improving generated content.</li></ul><h3>12. Interactive Prompts</h3><p>Prompts that enable step-by-step collaboration with the model.</p><ul><li><strong>Example</strong>:<br><em>“Let’s write a story together. I’ll start: ‘Once upon a time, in a distant kingdom…’. Now, you continue.”</em></li><li><strong>Use Case</strong>:<br>Collaborative creative tasks or multi-turn tasks.</li></ul><h3>13. Coding Prompts</h3><p>Prompts designed for programming-related tasks.</p><ul><li><strong>Example</strong>:<br><em>“Write a Python function to calculate the factorial of a number.”</em></li><li><strong>Use Case</strong>:<br>Code generation, debugging, or explanation.</li></ul><h3>14. Visual or Multimodal Prompts</h3><p>Prompts that involve text and visual inputs (for models supporting image input).</p><ul><li><strong>Example</strong>:<br><em>“Describe the content of this image and suggest a relevant caption.”</em></li><li><strong>Use Case</strong>:<br>Tasks requiring vision-language understanding.</li></ul><h3>15. Few-Shot Chain-of-Thought Prompts</h3><p>Combines <strong>few-shot learning</strong> with <strong>step-by-step reasoning</strong>.</p><ul><li><strong>Example</strong>:<br><em>“Here is an example:<br>Q: There are 5 apples, and you take away 3. How many are left?<br>A: Step 1: There were 5 apples originally.<br>Step 2: I took away 3 apples.<br>Step 3: 5–3 = 2 apples.<br>Final Answer: 2 apples.<br>Now solve: There are 12 oranges, and you take away 7. How many are left?”</em></li><li><strong>Use Case</strong>:<br>Complex reasoning tasks, math, and problem-solving.</li></ul><p>By combining these prompt types strategically, you can tailor responses for a variety of applications — NLP tasks, content creation, code generation, or reasoning-based tasks.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d3d07bb90a6e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Reward Hacking: Insights from Lilian Weng’s Blog]]></title>
            <link>https://medium.com/@jimwang3589/understanding-reward-hacking-insights-from-lilian-wengs-blog-6641b2132b7b?source=rss-4882b9de694e------2</link>
            <guid isPermaLink="false">https://medium.com/p/6641b2132b7b</guid>
            <dc:creator><![CDATA[Jim Wang]]></dc:creator>
            <pubDate>Mon, 02 Dec 2024 19:25:01 GMT</pubDate>
            <atom:updated>2024-12-02T19:25:01.910Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/610/1*LCuq5o3SsohKuPcqnvBRrw.png" /></figure><p>Lilian Weng’s recent blog <a href="https://lilianweng.github.io/posts/2024-11-28-reward-hacking/">https://lilianweng.github.io/posts/2024-11-28-reward-hacking/</a> dives deep into <em>reward hacking</em>, a phenomenon where AI systems exploit poorly designed reward structures, leading to undesirable or unintended outcomes. Here’s a simplified summary of the key insights:</p><ol><li><strong>What is Reward Hacking?</strong></li></ol><p>Reward hacking occurs when AI systems discover ways to achieve high reward scores by exploiting loopholes in the reward mechanism instead of completing the task as intended. For instance, a reinforcement learning agent may find shortcuts that technically fulfill reward conditions without actually solving the problem.</p><p><strong>2. Why Does it Happen?</strong></p><ul><li><em>Incomplete Reward Design</em>: If the reward system is not comprehensive, the AI might over-optimize for one aspect while ignoring others.</li><li><em>Ambiguity in Goals</em>: Misaligned objectives or poorly defined metrics can cause AI to focus on unintended behaviors.</li><li><em>Complex Environments</em>: In dynamic or uncertain scenarios, agents may find unexpected ways to “game” the system.</li></ul><p>3. <strong>Examples and Implications</strong></p><p>Weng highlights illustrative cases where reinforcement learning systems achieve high rewards in ways that contradict the designers’ intent. For example, in game environments, agents might exploit bugs or unintended mechanics rather than playing as intended.</p><p>4. <strong>Solutions to Mitigate Reward Hacking</strong></p><ul><li><strong>Better Reward Design</strong>: Ensure reward functions cover all critical aspects of desired behavior.</li><li><strong>Robust Evaluation</strong>: Test agents in diverse scenarios to uncover unintended behaviors.</li><li><strong>Multi-Objective Optimization</strong>: Incorporate multiple metrics to balance trade-offs and reduce single-goal exploitation.</li><li><strong>Human Oversight</strong>: Use human-in-the-loop systems to monitor and intervene during learning.</li></ul><p>5. <strong>Broader Impacts</strong></p><p>Reward hacking not only affects performance but also raises ethical concerns, especially in applications like autonomous systems and safety-critical tasks. The insights call for more cautious reward system design and iterative testing to align AI behavior with human values and intentions.</p><p>To delve deeper into the intricacies of reward hacking and its implications, visit the original blog <a href="https://lilianweng.github.io/posts/2024-11-28-reward-hacking/">https://lilianweng.github.io/posts/2024-11-28-reward-hacking/</a> .</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6641b2132b7b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[OpenAI Embedding API]]></title>
            <link>https://medium.com/@jimwang3589/openai-embedding-api-0e69d36a610f?source=rss-4882b9de694e------2</link>
            <guid isPermaLink="false">https://medium.com/p/0e69d36a610f</guid>
            <dc:creator><![CDATA[Jim Wang]]></dc:creator>
            <pubDate>Tue, 12 Nov 2024 22:35:48 GMT</pubDate>
            <atom:updated>2024-11-12T22:35:48.475Z</atom:updated>
            <content:encoded><![CDATA[<p>The OpenAI Embedding API allows you to convert text into dense vector representations (embeddings), which can then be used for various tasks such as semantic search, clustering, and recommendation systems. It’s typically based on large language models (LLMs) like GPT.</p><h3>Using OpenAI Embedding API</h3><p>To use the OpenAI Embedding API, you can follow these steps:</p><ol><li>Setup API Key: Ensure you have an API key from OpenAI. You can obtain it by creating an account and navigating to the API section of the OpenAI website.</li><li>Install OpenAI Python Package: You can install the OpenAI Python package if you haven’t already:</li></ol><pre>pip install openai</pre><p>3. Make an Embedding API Request: You can send a request to the embedding API to obtain embeddings for text. Here’s an example using Python:</p><pre>import openai<br><br># Set up the OpenAI API key<br>openai.api_key = &#39;your-api-key&#39;<br><br># Request to get embeddings<br>response = openai.Embedding.create(<br>    model=&quot;text-embedding-ada-002&quot;,  # or another embedding model<br>    input=[&quot;This is a test sentence.&quot;, &quot;Another text input.&quot;]<br>)<br><br># Extract embeddings<br>embeddings = response[&#39;data&#39;]<br>print(embeddings)</pre><p>In this example:</p><ul><li>The model text-embedding-ada-002 is used for generating embeddings. You can choose other models based on your requirements.</li><li>The input text is provided as a list. The API will return embeddings for each input text.</li></ul><p>4. Use Case: Once you have embeddings, you can use them for:</p><ul><li>Semantic Search: Compare the similarity between different pieces of text.</li><li>Clustering: Group similar pieces of text based on the embeddings.</li><li>Recommendation Systems: Recommend items based on the similarity of their embeddings to user queries or preferences.</li></ul><h3>Fine-Tuning OpenAI Embedding Models</h3><p>OpenAI does not currently support fine-tuning the embedding models directly. The embeddings provided by OpenAI’s models (e.g., text-embedding-ada-002) are pre-trained and designed for general use. However, you can adapt the embeddings to your specific use case with some post-processing techniques.</p><p>Here are some ways you can tailor embeddings to fit specific tasks:</p><ol><li>Domain-Specific Embeddings:</li></ol><ul><li>Fine-Tune via Supervised Learning: You can create a machine learning model that takes OpenAI’s embeddings as input and fine-tunes a downstream model (e.g., a classifier or regressor) for specific tasks.</li><li>Contextual Embeddings: Use additional context or modify how embeddings are retrieved. For instance, you can prepend specific domain knowledge or keywords to the text before generating embeddings.</li></ul><p>2. Embedding Transformation:</p><ul><li>You can train a separate model (e.g., a neural network) to project the OpenAI embeddings into a new space that better represents your specific task or domain.</li></ul><p>3. Data Augmentation:</p><ul><li>Use data augmentation techniques to increase the diversity of the inputs and improve the embeddings’ ability to generalize across different contexts or domains.</li></ul><p>4. Retraining/Custom Models:</p><ul><li>For highly specialized tasks, you could explore using other embedding models (such as those available through Hugging Face’s Transformers library) and train them with your own dataset, though this requires a separate process compared to fine-tuning OpenAI’s models.</li></ul><p>While OpenAI’s embedding models cannot be fine-tuned directly, their embeddings can be integrated into other machine learning workflows, where further fine-tuning of downstream models is possible.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0e69d36a610f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[OpenAI’s fine-tuning feature]]></title>
            <link>https://medium.com/@jimwang3589/openais-fine-tuning-feature-2f61ef5d3eba?source=rss-4882b9de694e------2</link>
            <guid isPermaLink="false">https://medium.com/p/2f61ef5d3eba</guid>
            <dc:creator><![CDATA[Jim Wang]]></dc:creator>
            <pubDate>Tue, 12 Nov 2024 22:29:28 GMT</pubDate>
            <atom:updated>2024-11-12T22:29:28.445Z</atom:updated>
            <content:encoded><![CDATA[<p>OpenAI’s fine-tuning feature allows you to train their models on your own data for custom performance. Fine-tuning lets you personalize models, improving their responses for specific tasks or domains. Here’s how to use fine-tuning functions effectively:</p><h3>1. Prepare Your Dataset</h3><ul><li>Format: Fine-tuning data must be in JSONL format, with each line containing a {&quot;prompt&quot;: &quot;...&quot;, &quot;completion&quot;: &quot;...&quot;} object.</li><li>Prompt: The prompt is the input text or question.</li><li>Completion: The desired model response to the prompt.</li><li>Guidelines:</li><li>Use clear, concise prompts and completions.</li><li>Limit completions to what you want the model to produce; avoid extraneous text.</li><li>For good results, aim for several hundred examples covering diverse scenarios.</li></ul><p>Example JSONL content:</p><pre>{&quot;prompt&quot;: &quot;Translate &#39;Hello&#39; to Spanish:&quot;, &quot;completion&quot;: &quot;Hola&quot;}<br>{&quot;prompt&quot;: &quot;Summarize the following: OpenAI is...&quot;, &quot;completion&quot;: &quot;OpenAI focuses on AI research.&quot;}</pre><h3>2. Upload the Dataset to OpenAI</h3><ul><li>Use the OpenAI CLI to upload your dataset for fine-tuning:</li></ul><pre>openai tools fine_tunes.prepare_data -f path/to/your_file.jsonl</pre><ul><li>This command validates and prepares your file by ensuring it meets OpenAI’s requirements.</li></ul><h3>3. Initiate Fine-Tuning</h3><ul><li>Start fine-tuning with OpenAI’s CLI, specifying the base model (e.g., gpt-3.5-turbo or davinci) and your prepared data file:</li></ul><pre>openai api fine_tunes.create -t &quot;file-XXXXXXXXXX&quot; -m &quot;gpt-3.5-turbo&quot;</pre><ul><li>Replace &quot;file-XXXXXXXXXX&quot; with the file ID returned after uploading your dataset.</li><li>Hyperparameters: Optional, though OpenAI manages most parameters automatically. You can adjust learning rates or epochs if needed, but defaults work well for most cases.</li></ul><h3>4. Monitoring Fine-Tuning Progress</h3><ul><li>Monitor the fine-tuning process by checking status and progress through the CLI:</li></ul><pre>openai api fine_tunes.list</pre><ul><li>You’ll receive a notification when the fine-tuning completes, and a new model ID will be created for the fine-tuned model.</li></ul><h3>5. Using the Fine-Tuned Model</h3><ul><li>Once the model is fine-tuned, invoke it with the new model ID:</li></ul><pre>import openai<br><br>openai.api_key = &quot;your_api_key&quot;<br><br>response = openai.Completion.create(<br>    model=&quot;ft-XXXXXX&quot;,  # replace with your fine-tuned model ID<br>    prompt=&quot;Translate &#39;Goodbye&#39; to Spanish:&quot;,<br>    max_tokens=50<br>)<br><br>print(response.choices[0].text.strip())</pre><ul><li>This lets you use the fine-tuned model with improved, task-specific performance.</li></ul><h3>6. Testing and Iterating</h3><ul><li>Test the fine-tuned model to ensure it meets your needs. If performance isn’t optimal, consider refining your dataset with more examples or adjusting prompts.</li></ul><h3>7. Cost Management</h3><ul><li>Fine-tuning models incurs costs for both training and usage, with rates higher than non-fine-tuned models. Monitor usage in OpenAI’s dashboard.</li></ul><p>By following these steps, you can fine-tune OpenAI’s models to fit specific use cases, improving accuracy and tailoring responses for your application’s needs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2f61ef5d3eba" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Chat-GPT model fine-tuning of different tasks]]></title>
            <link>https://medium.com/@jimwang3589/chat-gpt-model-fine-tuning-of-different-tasks-04dad5695f16?source=rss-4882b9de694e------2</link>
            <guid isPermaLink="false">https://medium.com/p/04dad5695f16</guid>
            <dc:creator><![CDATA[Jim Wang]]></dc:creator>
            <pubDate>Tue, 12 Nov 2024 22:19:53 GMT</pubDate>
            <atom:updated>2024-11-12T22:19:53.953Z</atom:updated>
            <content:encoded><![CDATA[<p>OpenAI’s fine-tuning capabilities allow you to customize the behavior of models like GPT-3 and GPT-4 for specific tasks. Fine-tuning can be applied to a variety of use cases to improve performance for specialized tasks. Below are some common tasks for model fine-tuning, along with examples of how to set up the fine-tuning process in Python.</p><h3>1. Customer Support Chatbot</h3><p>Fine-tuning a model to handle customer service inquiries with specific responses.</p><p>Task: Train the model to respond to customer queries in a helpful and accurate manner based on your company’s FAQs.</p><p>Example Dataset (JSONL format):</p><pre>{&quot;prompt&quot;: &quot;What is the return policy?&quot;, &quot;completion&quot;: &quot;You can return items within 30 days for a full refund.&quot;}<br>{&quot;prompt&quot;: &quot;How can I contact customer support?&quot;, &quot;completion&quot;: &quot;You can contact customer support by emailing support@company.com.&quot;}</pre><p>Fine-tuning Example:</p><pre>import openai<br><br># Set up the OpenAI API key<br>openai.api_key = &quot;your-api-key&quot;<br><br># Prepare the dataset for fine-tuning<br>openai.File.create(<br>    file=open(&quot;customer_support_data.jsonl&quot;),<br>    purpose=&#39;fine-tune&#39;<br>)<br><br># Fine-tune the model<br>fine_tune_response = openai.FineTune.create(<br>    training_file=&quot;file-xxxxxxxxxxxx&quot;,  # Replace with the file ID after upload<br>    model=&quot;davinci&quot;  # You can choose from available base models like &#39;davinci&#39;, &#39;curie&#39;, etc.<br>)</pre><p>Using the Fine-Tuned Model:</p><pre>response = openai.Completion.create(<br>    model=&quot;ft-xxxxxxxxxxxx&quot;,  # Fine-tuned model ID<br>    prompt=&quot;What is the return policy?&quot;,<br>    max_tokens=50<br>)<br>print(response.choices[0].text.strip())</pre><h3>2. Sentiment Analysis</h3><p>Fine-tuning a model to classify the sentiment (positive, negative, neutral) of text.</p><p>Task: Train the model to understand and classify the sentiment of customer reviews.</p><p>Example Dataset (JSONL format):</p><pre>{&quot;prompt&quot;: &quot;I love this product!&quot;, &quot;completion&quot;: &quot;Positive&quot;}<br>{&quot;prompt&quot;: &quot;This is the worst experience I&#39;ve had.&quot;, &quot;completion&quot;: &quot;Negative&quot;}<br>{&quot;prompt&quot;: &quot;The service was okay, not great, not bad.&quot;, &quot;completion&quot;: &quot;Neutral&quot;}</pre><p>Fine-tuning Example:</p><pre>import openai<br><br>openai.api_key = &quot;your-api-key&quot;<br><br># Prepare the dataset for fine-tuning<br>openai.File.create(<br>    file=open(&quot;sentiment_analysis_data.jsonl&quot;),<br>    purpose=&#39;fine-tune&#39;<br>)<br><br># Fine-tune the model<br>fine_tune_response = openai.FineTune.create(<br>    training_file=&quot;file-xxxxxxxxxxxx&quot;,  # Replace with your file ID<br>    model=&quot;davinci&quot;  # You can choose a base model<br>)</pre><p>Using the Fine-Tuned Model:</p><pre>response = openai.Completion.create(<br>    model=&quot;ft-xxxxxxxxxxxx&quot;,  # Fine-tuned model ID<br>    prompt=&quot;I love this product!&quot;,<br>    max_tokens=50<br>)<br>print(response.choices[0].text.strip())  # Output: Positive</pre><h3>3. Text Summarization</h3><p>Fine-tuning the model to summarize longer pieces of text or articles into concise summaries.</p><p>Task: Train the model to generate summaries for news articles or reports.</p><p>Example Dataset (JSONL format):</p><pre>{&quot;prompt&quot;: &quot;Summarize the following: The economic impact of the COVID-19 pandemic has been severe, leading to millions of job losses and economic contraction worldwide.&quot;, &quot;completion&quot;: &quot;The COVID-19 pandemic caused severe economic impacts, including millions of job losses and a global economic contraction.&quot;}</pre><p>Fine-tuning Example:</p><pre>import openai<br><br>openai.api_key = &quot;your-api-key&quot;<br><br># Prepare the dataset for fine-tuning<br>openai.File.create(<br>    file=open(&quot;summarization_data.jsonl&quot;),<br>    purpose=&#39;fine-tune&#39;<br>)<br><br># Fine-tune the model<br>fine_tune_response = openai.FineTune.create(<br>    training_file=&quot;file-xxxxxxxxxxxx&quot;,  # Replace with your file ID<br>    model=&quot;davinci&quot;  # Choose an appropriate base model<br>)</pre><p>Using the Fine-Tuned Model:</p><pre>response = openai.Completion.create(<br>    model=&quot;ft-xxxxxxxxxxxx&quot;,  # Fine-tuned model ID<br>    prompt=&quot;Summarize the following: The economic impact of the COVID-19 pandemic has been severe, leading to millions of job losses and economic contraction worldwide.&quot;,<br>    max_tokens=50<br>)<br><br>print(response.choices[0].text.strip())  # Output: The COVID-19 pandemic caused severe economic impacts, including millions of job losses and a global economic contraction.</pre><h3>4. Translation</h3><p>Fine-tuning a model to perform translation tasks, such as translating between different languages.</p><p>Task: Train the model to translate text from English to Spanish.</p><p>Example Dataset (JSONL format):</p><pre>{&quot;prompt&quot;: &quot;Translate &#39;Hello, how are you?&#39; into Spanish.&quot;, &quot;completion&quot;: &quot;Hola, ¿cómo estás?&quot;}<br>{&quot;prompt&quot;: &quot;Translate &#39;I love learning new languages.&#39; into Spanish.&quot;, &quot;completion&quot;: &quot;Me encanta aprender nuevos idiomas.&quot;}</pre><p>Fine-tuning Example:</p><pre>import openai<br><br>openai.api_key = &quot;your-api-key&quot;<br><br># Prepare the dataset for fine-tuning<br>openai.File.create(<br>    file=open(&quot;translation_data.jsonl&quot;),<br>    purpose=&#39;fine-tune&#39;<br>)<br><br># Fine-tune the model<br>fine_tune_response = openai.FineTune.create(<br>    training_file=&quot;file-xxxxxxxxxxxx&quot;,  # Replace with your file ID<br>    model=&quot;davinci&quot;  # You can choose a model like davinci for translation tasks<br>)</pre><p>Using the Fine-Tuned Model:</p><pre>response = openai.Completion.create(<br>    model=&quot;ft-xxxxxxxxxxxx&quot;,  # Fine-tuned model ID<br>    prompt=&quot;Translate &#39;Hello, how are you?&#39; into Spanish.&quot;,<br>    max_tokens=50<br>)<br>print(response.choices[0].text.strip())  # Output: Hola, ¿cómo estás?</pre><h3>5. Code Generation or Code Completion</h3><p>Fine-tuning a model to write or complete code based on partial code or description.</p><p>Task: Train the model to generate Python code for specific tasks.</p><p>Example Dataset (JSONL format):</p><pre>{&quot;prompt&quot;: &quot;Write a Python function to calculate the factorial of a number.&quot;, &quot;completion&quot;: &quot;def factorial(n):\n    if n == 0:\n        return 1\n    return n * factorial(n-1)&quot;}</pre><p>Fine-tuning Example:</p><pre>import openai<br><br>openai.api_key = &quot;your-api-key&quot;<br><br># Prepare the dataset for fine-tuning<br>openai.File.create(<br>    file=open(&quot;code_generation_data.jsonl&quot;),<br>    purpose=&#39;fine-tune&#39;<br>)<br><br># Fine-tune the model<br>fine_tune_response = openai.FineTune.create(<br>    training_file=&quot;file-xxxxxxxxxxxx&quot;,  # Replace with your file ID<br>    model=&quot;davinci-codex&quot;  # Codex model is optimized for code generation<br>)</pre><p>Using the Fine-Tuned Model:</p><pre>response = openai.Completion.create(<br>    model=&quot;ft-xxxxxxxxxxxx&quot;,  # Fine-tuned model ID<br>    prompt=&quot;Write a Python function to calculate the factorial of a number.&quot;,<br>    max_tokens=100<br>)<br>print(response.choices[0].text.strip())  # Output: def factorial(n):\n    if n == 0:\n        return 1\n    return n * factorial(n-1)</pre><h3>Summary of Fine-Tuning Tasks</h3><ul><li>Customer Support: Customize responses for FAQs or specific scenarios.</li><li>Sentiment Analysis: Train the model to classify sentiment in text.</li><li>Text Summarization: Teach the model to summarize long texts.</li><li>Translation: Fine-tune models for language translation tasks.</li><li>Code Generation: Customize the model to generate or complete code for specific programming tasks.</li></ul><p>By fine-tuning models, you can tailor their behavior to your specific use case, improving their accuracy and effectiveness. Fine-tuning allows for highly customized performance, particularly for domain-specific tasks.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=04dad5695f16" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Prompt Types of Open AI Chat-GPT]]></title>
            <link>https://medium.com/@jimwang3589/prompt-types-of-open-ai-chat-gpt-a37d4743c24e?source=rss-4882b9de694e------2</link>
            <guid isPermaLink="false">https://medium.com/p/a37d4743c24e</guid>
            <dc:creator><![CDATA[Jim Wang]]></dc:creator>
            <pubDate>Tue, 12 Nov 2024 22:10:23 GMT</pubDate>
            <atom:updated>2024-11-12T22:10:23.868Z</atom:updated>
            <content:encoded><![CDATA[<p>OpenAI LLMs, like GPT-4 and GPT-3, can be used with various types of prompts depending on the task or the outcome you need. Here are the main types of prompts and some common examples:</p><h3>1. Instructional Prompts</h3><ul><li>Direct the model to perform specific tasks.</li><li>Examples:</li><li>“Explain the theory of relativity in simple terms.”</li><li>“List five benefits of exercise.”</li><li>“Generate an email for a customer service inquiry.”</li></ul><h3>2. Informational or Factual Prompts</h3><ul><li>Request factual information or specific details.</li><li>Examples:</li><li>“What is the capital of France?”</li><li>“Tell me about the history of the Roman Empire.”</li><li>“Who are the top influencers in AI research?”</li></ul><h3>3. Conversational Prompts</h3><ul><li>Mimic a dialogue, making the model behave as a conversational partner.</li><li>Examples:</li><li>“Hi, how are you?”</li><li>“Can you help me plan a trip to Japan?”</li><li>“What do you think about AI in healthcare?”</li></ul><h3>4. Creative Writing Prompts</h3><ul><li>Encourage the model to generate creative content.</li><li>Examples:</li><li>“Write a short story about a time traveler.”</li><li>“Compose a poem about the ocean at night.”</li><li>“Generate a horror story setting in a haunted house.”</li></ul><h3>5. Completion Prompts</h3><ul><li>Provide partial text and let the model complete it.</li><li>Examples:</li><li>“Once upon a time, there was a…”</li><li>“In the future, people will no longer…”</li><li>“The best way to learn is by…”</li></ul><h3>6. Question-Answering Prompts</h3><ul><li>Ask questions for which the model can generate answers.</li><li>Examples:</li><li>“What causes thunderstorms?”</li><li>“How does quantum computing work?”</li><li>“Why do plants need sunlight?”</li></ul><h3>7. Role-Playing Prompts</h3><ul><li>Ask the model to assume a specific persona or role.</li><li>Examples:</li><li>“Pretend you are a doctor giving advice about healthy eating.”</li><li>“Imagine you’re a travel agent planning a trip to Italy.”</li><li>“You are a customer support agent. Answer the following question about our product.”</li></ul><h3>8. Programming and Code Generation Prompts</h3><ul><li>Request the model to write or debug code.</li><li>Examples:</li><li>“Write a Python function to calculate factorial.”</li><li>“Fix the bug in this code: def add_numbers(a, b) a + b&quot;</li><li>“Generate HTML and CSS code for a simple website layout.”</li></ul><h3>9. Summarization Prompts</h3><ul><li>Request a summary of a longer text.</li><li>Examples:</li><li>“Summarize this article on climate change.”</li><li>“Condense the following paragraph into one sentence.”</li><li>“Provide a short summary of this news article.”</li></ul><h3>10. Translation Prompts</h3><ul><li>Ask the model to translate text from one language to another.</li><li>Examples:</li><li>“Translate ‘Hello, how are you?’ into French.”</li><li>“Translate the following text to Spanish: ‘The weather is beautiful today.’”</li><li>“Convert this sentence from English to Japanese.”</li></ul><h3>11. Analysis or Critique Prompts</h3><ul><li>Request an analysis or critical review of a piece of text or an idea.</li><li>Examples:</li><li>“Analyze the theme of sacrifice in the novel <em>The Great Gatsby</em>.”</li><li>“Provide a critique of the following argument.”</li><li>“Identify the main weaknesses in this business proposal.”</li></ul><h3>12. Comparison Prompts</h3><ul><li>Ask the model to compare concepts, ideas, or options.</li><li>Examples:</li><li>“Compare socialism and capitalism.”</li><li>“What’s the difference between deep learning and machine learning?”</li><li>“List pros and cons of electric cars vs. gasoline cars.”</li></ul><h3>13. Data Extraction Prompts</h3><ul><li>Request specific information from structured or semi-structured text.</li><li>Examples:</li><li>“Extract names and dates from the following text.”</li><li>“List all email addresses found in this text.”</li><li>“Identify key points from this meeting transcript.”</li></ul><h3>14. Code Explanation Prompts</h3><ul><li>Ask the model to explain code or programming concepts.</li><li>Examples:</li><li>“Explain this Python code step-by-step.”</li><li>“Describe how this algorithm works.”</li><li>“What does this SQL query do?”</li></ul><h3>15. Style or Tone Change Prompts</h3><ul><li>Request changes in the tone or style of text.</li><li>Examples:</li><li>“Rewrite this text in a formal tone.”</li><li>“Make this sentence sound friendlier.”</li><li>“Rewrite this paragraph as if it were written in the 19th century.”</li></ul><h3>16. Classification and Tagging Prompts</h3><ul><li>Ask the model to classify or tag text based on content or sentiment.</li><li>Examples:</li><li>“Classify the sentiment of this review: ‘I loved the product!’”</li><li>“Tag the following text with appropriate keywords.”</li><li>“Determine if this email is spam or not.”</li></ul><p>These types can often be combined or tailored to meet specific needs. Experimenting with prompt types and structures is essential to unlocking the full potential of OpenAI’s models.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a37d4743c24e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GraphQL: specify exactly what data they need and retrieve it in a single request]]></title>
            <link>https://medium.com/@jimwang3589/graphql-specify-exactly-what-data-they-need-and-retrieve-it-in-a-single-request-0760204ab676?source=rss-4882b9de694e------2</link>
            <guid isPermaLink="false">https://medium.com/p/0760204ab676</guid>
            <dc:creator><![CDATA[Jim Wang]]></dc:creator>
            <pubDate>Sat, 09 Nov 2024 03:40:34 GMT</pubDate>
            <atom:updated>2024-11-09T03:40:34.755Z</atom:updated>
            <content:encoded><![CDATA[<p>GraphQL is a query language for APIs, developed by Facebook in 2012, and released publicly in 2015. It provides a more flexible, efficient alternative to REST by allowing clients to specify exactly what data they need and retrieve it in a single request. Unlike REST, where multiple endpoints often have to be called to get data, GraphQL allows the client to query multiple resources in one request and receive only the required data, reducing over-fetching and under-fetching.</p><p>Here’s a walkthrough of a simple GraphQL project. This project involves building a small server that allows users to retrieve and create data on books and authors.</p><h3>Project Setup</h3><ol><li>Install Node.js if not already installed.</li><li>Initialize a new project and install dependencies:</li></ol><pre>mkdir graphql-books<br>cd graphql-books<br>npm init -y<br>npm install express express-graphql graphql</pre><h3>Step 1: Define Schema</h3><p>A GraphQL schema defines the structure of the API. It includes types, queries, and mutations (for modifying data).</p><p><strong>File</strong>: schema.js</p><pre>const { GraphQLObjectType, GraphQLString, GraphQLInt, GraphQLSchema, GraphQLList, GraphQLNonNull } = require(&#39;graphql&#39;);<br><br>// Dummy data<br>const books = [<br>  { id: 1, name: &#39;1984&#39;, genre: &#39;Dystopian&#39;, authorId: 1 },<br>  { id: 2, name: &#39;To Kill a Mockingbird&#39;, genre: &#39;Fiction&#39;, authorId: 2 }<br>];<br>const authors = [<br>  { id: 1, name: &#39;George Orwell&#39; },<br>  { id: 2, name: &#39;Harper Lee&#39; }<br>];<br><br>// Book type<br>const BookType = new GraphQLObjectType({<br>  name: &#39;Book&#39;,<br>  fields: () =&gt; ({<br>    id: { type: GraphQLInt },<br>    name: { type: GraphQLString },<br>    genre: { type: GraphQLString },<br>    author: {<br>      type: AuthorType,<br>      resolve: (book) =&gt; authors.find(author =&gt; author.id === book.authorId)<br>    }<br>  })<br>});<br><br>// Author type<br>const AuthorType = new GraphQLObjectType({<br>  name: &#39;Author&#39;,<br>  fields: () =&gt; ({<br>    id: { type: GraphQLInt },<br>    name: { type: GraphQLString },<br>    books: {<br>      type: new GraphQLList(BookType),<br>      resolve: (author) =&gt; books.filter(book =&gt; book.authorId === author.id)<br>    }<br>  })<br>});<br><br>// Root query<br>const RootQuery = new GraphQLObjectType({<br>  name: &#39;RootQueryType&#39;,<br>  fields: {<br>    book: {<br>      type: BookType,<br>      args: { id: { type: GraphQLInt } },<br>      resolve: (parent, args) =&gt; books.find(book =&gt; book.id === args.id)<br>    },<br>    author: {<br>      type: AuthorType,<br>      args: { id: { type: GraphQLInt } },<br>      resolve: (parent, args) =&gt; authors.find(author =&gt; author.id === args.id)<br>    },<br>    books: {<br>      type: new GraphQLList(BookType),<br>      resolve: () =&gt; books<br>    },<br>    authors: {<br>      type: new GraphQLList(AuthorType),<br>      resolve: () =&gt; authors<br>    }<br>  }<br>});<br><br>// Mutation for adding a new book<br>const Mutation = new GraphQLObjectType({<br>  name: &#39;Mutation&#39;,<br>  fields: {<br>    addBook: {<br>      type: BookType,<br>      args: {<br>        name: { type: new GraphQLNonNull(GraphQLString) },<br>        genre: { type: new GraphQLNonNull(GraphQLString) },<br>        authorId: { type: new GraphQLNonNull(GraphQLInt) }<br>      },<br>      resolve: (parent, args) =&gt; {<br>        const book = {<br>          id: books.length + 1,<br>          name: args.name,<br>          genre: args.genre,<br>          authorId: args.authorId<br>        };<br>        books.push(book);<br>        return book;<br>      }<br>    }<br>  }<br>});<br><br>module.exports = new GraphQLSchema({<br>  query: RootQuery,<br>  mutation: Mutation<br>});</pre><p><strong>Explanation</strong>:</p><ul><li>GraphQLObjectType: Defines a GraphQL object type (like Book or Author) with specific fields.</li><li>GraphQLList: Represents a list of a specific type, used for arrays (e.g., a list of books).</li><li>GraphQLNonNull: Indicates a field is required.</li><li>resolve: A function that retrieves data for a specific field when queried.</li></ul><h3>Step 2: Set Up Server</h3><p>Now, create an Express server to serve the GraphQL endpoint.</p><p><strong>File</strong>: server.js</p><pre>const express = require(&#39;express&#39;);<br>const { graphqlHTTP } = require(&#39;express-graphql&#39;);<br>const schema = require(&#39;./schema&#39;);<br><br>const app = express();<br><br>app.use(&#39;/graphql&#39;, graphqlHTTP({<br>  schema,<br>  graphiql: true // Enable GraphiQL tool for querying<br>}));<br><br>app.listen(4000, () =&gt; console.log(&#39;Server running on http://localhost:4000/graphql&#39;));</pre><p><strong>Explanation</strong>:</p><ul><li>express-graphql: Middleware that connects GraphQL and Express.</li><li>graphiql: true: Enables GraphiQL, a built-in tool for testing GraphQL queries in the browser.</li></ul><h3>Step 3: Run the Server</h3><p>Start the server:</p><pre>node server.js</pre><h3>Step 4: Querying with GraphQL</h3><p>With the server running, go to <a href="http://localhost:4000/graphql">http://localhost:4000/graphql</a> to query the API.</p><h4>Example Queries</h4><ol><li><strong>Get All Books</strong>:</li></ol><pre>{<br>  books {<br>    id<br>    name<br>    genre<br>    author {<br>      name<br>    }<br>  }<br>}</pre><p><strong>2. Get All Authors with Their Books</strong>:</p><pre>{<br>  authors {<br>    id<br>    name<br>    books {<br>      name<br>    }<br>  }<br>}</pre><p><strong>3. Add a New Book</strong>:</p><pre>mutation {<br>  addBook(name: &quot;Brave New World&quot;, genre: &quot;Dystopian&quot;, authorId: 1) {<br>    id<br>    name<br>    genre<br>  }<br>}</pre><p><strong>Explanation</strong>:</p><ul><li>The query structure allows you to retrieve data with flexible fields.</li><li>The mutation structure allows you to add, update, or delete data.</li></ul><h3>Line-by-Line Explanation of Key Parts in schema.js</h3><ol><li><strong>Define Types (</strong><strong>BookType and </strong><strong>AuthorType)</strong>:</li></ol><ul><li>GraphQLObjectType: Defines the structure of a data model (like Book).</li><li>Fields like id, name, and genre define the properties and their data types.</li><li>Each field has a type (e.g., GraphQLString for strings).</li><li>resolve functions tell GraphQL how to retrieve data (like matching authorId to find an author).</li></ul><p><strong>2. Root Query</strong>:</p><ul><li>Defines top-level queries available, such as book, author, books, and authors.</li><li>The args object specifies arguments for the query (e.g., book by id).</li><li>resolve functions use arguments to fetch the correct data.</li></ul><p>3. <strong>Mutation</strong>:</p><ul><li>Defines how to modify data, with required fields marked as GraphQLNonNull.</li><li>resolve in addBook mutation creates a new book with provided data, adds it to the books array, and returns it.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0760204ab676" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>