<?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 Alex Zargarov on Medium]]></title>
        <description><![CDATA[Stories by Alex Zargarov on Medium]]></description>
        <link>https://medium.com/@alexzargarov?source=rss-44d0bf3a948c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*CTisA3w-4NC1MDASNbdUgQ.png</url>
            <title>Stories by Alex Zargarov on Medium</title>
            <link>https://medium.com/@alexzargarov?source=rss-44d0bf3a948c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 06:43:04 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@alexzargarov/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[These Prompting Techniques Will Get You Standing Tall]]></title>
            <link>https://medium.com/data-has-better-idea/these-prompting-techniques-will-get-you-standing-tall-5b9581be9ff9?source=rss-44d0bf3a948c------2</link>
            <guid isPermaLink="false">https://medium.com/p/5b9581be9ff9</guid>
            <category><![CDATA[prompting-technique]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Alex Zargarov]]></dc:creator>
            <pubDate>Sun, 11 May 2025 08:22:44 GMT</pubDate>
            <atom:updated>2025-05-11T08:22:44.026Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CtIeT5uMeXigxryU1g5TAA.jpeg" /></figure><p>The evolution of prompt engineering has been from a simple “ask and answer” to sophisticated styles that extract maximum performance from Large Language Models (LLMs). Diverse families of LLMs (e.g., OpenAI’s GPT and Google’s Gemini) show both unique and overlapping parameters. It is essential for practitioners to fully understand the strict limits of context, the precise selection of words, and the impact of these keywords on output quality.</p><blockquote>Keyword Catalog: GPT vs. Gemini</blockquote><blockquote><strong>Parameter</strong></blockquote><blockquote><strong>GPT (OpenAI)</strong></blockquote><blockquote><strong>Gemini (Google Cloud)</strong></blockquote><blockquote><strong>Model selection</strong></blockquote><blockquote>model=”gpt-4&quot; / “gpt-4-turbo” / “gpt-3.5-turbo”</blockquote><blockquote>model=”gemini-instant” / “gemini-pro” / “gemini-ultra”</blockquote><blockquote><strong>Max tokens</strong></blockquote><blockquote>max_tokens=512 (response length cap)</blockquote><blockquote>max_output_tokens=512</blockquote><blockquote><strong>Temperature</strong></blockquote><blockquote>temperature=0.7 (controls randomness)</blockquote><blockquote>temperature=0.7</blockquote><blockquote><strong>Top-p</strong></blockquote><blockquote>top_p=0.9 (nucleus sampling)</blockquote><blockquote>top_p=0.9</blockquote><blockquote><strong>Sampling controls</strong></blockquote><blockquote>frequency_penalty, presence_penalty</blockquote><blockquote>rep_penalty, top_k (k-sampling cutoff)</blockquote><blockquote><strong>Stopping</strong></blockquote><blockquote>stop=[“\nUser:”] (end generation)</blockquote><blockquote>stop_sequences=[“\nUser:”]</blockquote><blockquote><strong>System vs. user</strong></blockquote><blockquote>System prompts prefaced by role: “role”:”system” then “role”:”user”/”assistant”</blockquote><blockquote>Instruction block and user block separated in JSON payload</blockquote><blockquote><strong>Additional hints</strong></blockquote><blockquote>user=”You are a helpful assistant.”</blockquote><blockquote>context=”…” (full prior dialogue or documents)</blockquote><blockquote><strong><em>Footnote 1:</em></strong><em> A </em>system prompt<em> sets global behavior, while </em>user<em> and </em>assistant<em> messages form the dynamic exchange.¹</em></blockquote><p>Every model can only “remember” up to a fixed number of tokens. When you exceed that, the oldest tokens are evicted. The chart below compares common GPT and Gemini context windows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pyXJixF8KmVOFxtWUHlLNg.png" /></figure><p>Interpretation:</p><ul><li><strong>GPT-3.5 Turbo</strong>: ~4 k tokens</li><li><strong>GPT-4 Turbo</strong>: ~8 k tokens</li><li><strong>Gemini Instant</strong>: ~8 k tokens</li><li><strong>Gemini Pro</strong>: ~32 k tokens</li></ul><p>If your prompt (plus expected answer) approaches these ceilings, consider:</p><ul><li>Splitting conversation threads</li><li>Summarizing or compressing earlier content</li><li>Using retrieval-augmented generation (RAG) to fetch external context on demand</li></ul><h3>4. Style Variations in Prompting</h3><ol><li><strong>Zero-Shot / Direct</strong></li></ol><ul><li><em>Example:</em> “Translate this sentence to French.”</li><li><strong>When to use:</strong> Clear, narrow tasks.</li></ul><p><strong>2. Few-Shot</strong></p><ul><li><em>Example:</em></li></ul><pre>Q: 2 + 2 = ?  <br>A: 4  </pre><pre>Q: 3 + 5 = ?  <br>A: 8  </pre><pre>Q: 7 + 6 = ?</pre><ul><li><strong>Benefit:</strong> Provides pattern examples so the model infers “what you want done.”</li></ul><p><strong>3. Chain-of-Thought (CoT)</strong></p><ul><li><em>Example:</em> “Explain your reasoning step by step before giving the final answer.”</li><li><strong>Use case:</strong> Complex reasoning; increases accuracy at the expense of longer output.</li></ul><p><strong>4. System-/Assistant-Framed</strong></p><ul><li>Embed instructions in a system persona:</li></ul><pre>You are an expert coder. When asked, respond with concise code snippets only.</pre><ul><li><strong>Strength:</strong> Models respect the persona consistently.</li></ul><h3>Wording-Level Optimizations</h3><ul><li><strong>Specific vs. Generic</strong></li><li>“List three causes of X” &gt; “Tell me about X”</li><li><strong>Directive Verbs</strong></li><li>Use “summarize,” “compare,” “contrast,” “analyze,” “plan.”</li><li><strong>Constraints</strong></li><li>Word limits: “In ≤100 words,…”</li><li>Format: “Answer in JSON with keys ‘name’ and ‘date.’”</li><li><strong>Vocabulary Tuning</strong></li><li>Prefer unambiguous terms: “purchase” vs. “buy” — both work, but consistency helps.</li><li><strong>Prompt Decomposition</strong></li><li>Break multi-step tasks: first gather data, then analyze.</li></ul><h3>Putting It All Together</h3><blockquote><strong><em>Example (GPT):</em></strong></blockquote><pre>[<br>  {&quot;role&quot;:&quot;system&quot;,&quot;content&quot;:&quot;You are a concise historian.&quot;},<br>  {&quot;role&quot;:&quot;user&quot;,&quot;content&quot;:&quot;In ≤50 words, summarize the impact of Gutenberg’s press.&quot;}<br>]</pre><blockquote><strong><em>Example (Gemini):</em></strong></blockquote><pre>{<br>  &quot;model&quot;:&quot;gemini-pro&quot;,<br>  &quot;context&quot;:&quot;You are a concise historian.&quot;,<br>  &quot;user_input&quot;:&quot;Summarize the impact of Gutenberg’s press in JSON: {\&quot;impact\&quot;:…} format. Max 50 words.&quot;<br>}</pre><p>Mastering prompting styles involves:</p><ol><li>Knowing each model’s keywords and parameters</li><li>Staying within context-window bounds</li><li>Carefully choosing verbs, constraints, and examples</li></ol><p>With these tools, you can optimize model behavior — whether you need creative prose, strict JSON data, or step-by-step reasoning.</p><h3>Footnotes</h3><ol><li>Roles and message types are described in OpenAI’s <a href="https://beta.openai.com/docs/api-reference/chat">API docs</a>.</li><li>Context limits sourced from OpenAI and Google technical announcements (May 2025).</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5b9581be9ff9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-has-better-idea/these-prompting-techniques-will-get-you-standing-tall-5b9581be9ff9">These Prompting Techniques Will Get You Standing Tall</a> was originally published in <a href="https://medium.com/data-has-better-idea">Data Has Better Idea</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AI-Based Anomaly Detection: Integrating Autoencoders and Isolation Forests]]></title>
            <link>https://medium.com/data-has-better-idea/ai-based-anomaly-detection-integrating-autoencoders-and-isolation-forests-d1cc5314e486?source=rss-44d0bf3a948c------2</link>
            <guid isPermaLink="false">https://medium.com/p/d1cc5314e486</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[isolation-forests]]></category>
            <category><![CDATA[anomaly-detection]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Alex Zargarov]]></dc:creator>
            <pubDate>Thu, 17 Apr 2025 08:39:29 GMT</pubDate>
            <atom:updated>2025-04-30T05:52:03.685Z</atom:updated>
            <content:encoded><![CDATA[<p>This technical report presents a detailed overview of an improved anomaly detection system that combines an autoencoder neural network with an isolation forest model. This methodology utilizes the capabilities of unsupervised deep learning combined with ensemble techniques to detect anomalies within intricate datasets. Our implementation utilizes a comprehensive Python class that encapsulates both methods, facilitating a side-by-side comparison of the results obtained from anomaly detection.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bbBOIcXoLDaFef-qsgGbbQ.png" /></figure><p>From fraud detection to network intrusion detection to system health monitoring, anomaly detection is absolutely essential in many different fields. When faced with complicated data patterns, conventional statistical methods usually show insufficient performance. Effective capture and reconstruction of the normal behavior of data is provided by autoencoders in unsupervised learning. One important metric is the reconstruction error; large departures of fresh data from the learnt representation produce high error values. Using a tree-based ensemble approach, isolation trees find anomalies throughout the random partitioning of the feature space.<br>This approach uses normal data to train an autoencoder then computes reconstruction error to find anomalies. Concurrent with this is training an isolation forest on the same dataset. The two detection techniques are then compared using a graphic that shows the decision function scores provided by the isolation forest against the reconstruction mistakes created by the autoencoder.</p><p>The autoencoder uses a straightforward dense layout:</p><ul><li><strong>Encoder:</strong> Maps the input characteristics into a lower-dimensional latent space with a dense layer running ReLU activation.</li><li><strong>Decoder: </strong>Reconstructs the latent representation’s original input using a dense layer with sigmoid activation.</li></ul><p>The <strong>mean squared error (MSE) </strong>between the original input and its reconstruction is minimised in the training aim.</p><p>An ensemble technique called “<strong>Isolation Forest</strong>” separates anomalies instead of regular data profile.</p><ul><li>It divides the data at random based on the idea that, being scarce and unique, anomalous points are simpler to separate. Here the isolation forest learns using the same normal data.</li><li>Examining the sign of the decision function helps one to detect abnormalities by means of values below a threshold (usually zero).</li></ul><p>We create a two-panel graph to evaluate the two techniques:</p><ul><li>Left Panel: Shows for every sample the autoencoder’s reconstruction error from the left panel. An anomaly threshold is indicated by a horizontal line; anomalous sample points are underlined.</li><li>Right Panel: Shows the decision scores of the isolation forest with a threshold (usually set at 0). Found abnormalities show as separate markers.</li></ul><p>Below is the complete Python code for the anomaly detection system that integrates both the autoencoder and isolation forest models:</p><pre>import numpy as np<br>import matplotlib.pyplot as plt<br>from tensorflow.keras.models import Model<br>from tensorflow.keras.layers import Input, Dense<br>from tensorflow.keras.optimizers import Adam<br>from sklearn.ensemble import IsolationForest<br><br>class AnomalyDetector:<br>    def __init__(self, input_dim, encoding_dim=32, epochs=50, batch_size=32):<br>        self.input_dim = input_dim<br>        self.encoding_dim = encoding_dim<br>        self.epochs = epochs<br>        self.batch_size = batch_size<br>        self.model = self.build_model()<br>        self.iforest = None  # Placeholder for the isolation forest model<br>    <br>    def build_model(self):<br>        input_layer = Input(shape=(self.input_dim,))<br>        # Encoder: compresses the input<br>        encoded = Dense(self.encoding_dim, activation=&#39;relu&#39;)(input_layer)<br>        # Decoder: reconstructs the input<br>        decoded = Dense(self.input_dim, activation=&#39;sigmoid&#39;)(encoded)<br>        <br>        autoencoder = Model(inputs=input_layer, outputs=decoded)<br>        autoencoder.compile(optimizer=Adam(), loss=&#39;mse&#39;)<br>        return autoencoder<br>    <br>    def train(self, X_train, validation_data=None):<br>        history = self.model.fit(X_train, X_train,<br>                                 epochs=self.epochs,<br>                                 batch_size=self.batch_size,<br>                                 shuffle=True,<br>                                 validation_data=validation_data,<br>                                 verbose=1)<br>        return history<br>    def reconstruction_error(self, X):<br>        X_pred = self.model.predict(X)<br>        mse = np.mean(np.power(X - X_pred, 2), axis=1)<br>        return mse<br>    def detect_anomalies(self, X, threshold):<br>        errors = self.reconstruction_error(X)<br>        anomalies = np.where(errors &gt; threshold)[0]<br>        return anomalies, errors<br>    def train_isolation_forest(self, X_train, contamination=0.05, random_state=42):<br>        self.iforest = IsolationForest(contamination=contamination, random_state=random_state)<br>        self.iforest.fit(X_train)<br>    def detect_anomalies_iforest(self, X):<br>        # 1 for normal, -1 for anomaly<br>        predictions = self.iforest.predict(X)  <br>        anomalies = np.where(predictions == -1)[0]<br>        scores = self.iforest.decision_function(X)<br>        return anomalies, scores<br>    def plot_comparison(self, X, ae_threshold, iforest_threshold=0.0):<br>        # Autoencoder results<br>        ae_anomalies, ae_errors = self.detect_anomalies(X, ae_threshold)<br>        # Isolation forest results<br>        if_anomalies, if_scores = self.detect_anomalies_iforest(X)<br>        <br>        fig, axs = plt.subplots(1, 2, figsize=(14, 6))<br>        <br>        # Plot Autoencoder reconstruction error<br>        axs[0].plot(ae_errors, label=&quot;Reconstruction Error&quot;)<br>        axs[0].scatter(ae_anomalies, ae_errors[ae_anomalies], color=&#39;red&#39;, label=&quot;Anomalies Detected&quot;)<br>        axs[0].axhline(y=ae_threshold, color=&#39;green&#39;, linestyle=&#39;--&#39;, label=&quot;Threshold&quot;)<br>        axs[0].set_title(&quot;Autoencoder Reconstruction Error&quot;)<br>        axs[0].set_xlabel(&quot;Sample Index&quot;)<br>        axs[0].set_ylabel(&quot;MSE&quot;)<br>        axs[0].legend()<br>        <br>        # Plot Isolation Forest decision function values<br>        axs[1].plot(if_scores, label=&quot;Decision Function Scores&quot;)<br>        axs[1].scatter(if_anomalies, if_scores[if_anomalies], color=&#39;red&#39;, label=&quot;Anomalies Detected&quot;)<br>        axs[1].axhline(y=iforest_threshold, color=&#39;green&#39;, linestyle=&#39;--&#39;, label=&quot;Threshold&quot;)<br>        axs[1].set_title(&quot;Isolation Forest Decision Function&quot;)<br>        axs[1].set_xlabel(&quot;Sample Index&quot;)<br>        axs[1].set_ylabel(&quot;Decision Score&quot;)<br>        axs[1].legend()<br>        <br>        plt.tight_layout()<br>        plt.show()<br><br># Example usage of the AnomalyDetector class:<br>if __name__ == &#39;__main__&#39;:<br>    # Seed for reproducibility<br>    np.random.seed(42)<br>    <br>    # Generate synthetic data<br>    # Normal data: 1000 samples, 20 features<br>    X_normal = np.random.rand(1000, 20)<br>    # Anomalous data: 50 samples, 20 features with an offset<br>    X_anomaly = np.random.rand(50, 20) + 3<br>    # Training on normal data only; testing on combined dataset<br>    X_train = X_normal<br>    X_test = np.vstack([X_normal, X_anomaly])<br>    <br>    # Initialize the detector<br>    detector = AnomalyDetector(input_dim=X_normal.shape[1], encoding_dim=10, epochs=10, batch_size=32)<br>    <br>    # Train autoencoder<br>    detector.train(X_train)<br>    <br>    # Train isolation forest on normal data<br>    detector.train_isolation_forest(X_train, contamination=0.05)<br>    <br>    # Set a threshold for autoencoder reconstruction error<br>    ae_threshold = 0.1  # This value should be tuned based on your data<br>    <br>    # Compare anomaly detection performance with a plot<br>    detector.plot_comparison(X_test, ae_threshold=ae_threshold, iforest_threshold=0.0)<br>    <br>    # Print detected anomaly indices for both models for further analysis<br>    ae_anomalies, ae_errors = detector.detect_anomalies(X_test, ae_threshold)<br>    if_anomalies, if_scores = detector.detect_anomalies_iforest(X_test)<br>    <br>    print(&quot;Autoencoder detected anomalies at indices:&quot;, ae_anomalies)<br>    print(&quot;Isolation Forest detected anomalies at indices:&quot;, if_anomalies)</pre><p>Apart from the autoencoder model, we combined an isolation forest inside the same class. Train_isolation_Forest starts and uses just standard data to create an isolation forest. Detect_anomalies_iforest uses this model later on to find anomalous samples by looking at the decision function output — typically with negative scores indicating anomalies.</p><p>The plot_comparison method creates a two-panel visualization:</p><ul><li><strong>Left Panel (Autoencoder):</strong></li><li>The reconstruction error for each sample is plotted, with a horizontal threshold line drawn. Red markers denote the samples flagged as anomalies.</li><li><strong>Right Panel (Isolation Forest):</strong></li><li>The decision function scores are plotted. Similarly, red markers highlight anomalies as determined by the isolation forest. The default threshold is set at 0.0.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ab3a4nAF97tZcjqm9fWdzg.png" /><figcaption>Figure 1</figcaption></figure><p>Using two different approaches — an autoencoder and an isolation forest — Figure 1 shows a comparison representation of anomaly detection outcomes. Plotting the autoencoder’s reconstruction error across sample indices in the left panel shows a noticeable spike in Mean Squared Error (MSE) for the anomalous data points — which are underlined in red. The detection threshold is shown by the green dashed line; samples above this line are labelled as anomalies. Once more, anomalies are emphasized in red, happening where the score falls below the zero threshold; the right panel shows the decision function scores from the isolation forest. Although both models effectively identify the injected anomalies toward the end of the dataset, the autoencoder shows a stronger contrast in error, suggesting it might be more sensitive to this particular kind of anomaly in the particular data.</p><p>This visual comparison helps in assessing the consistency and differences between the two methods, particularly important when dealing with critical applications where False Positives and False Negatives must be minimized.</p><blockquote><strong>This integrated approach can be further refined by:</strong></blockquote><blockquote><strong>Tuning the respective thresholds using cross-validation.</strong></blockquote><blockquote><strong>Exploring more complex autoencoder architectures (e.g., adding multiple layers or using convolutional architectures for image data).</strong></blockquote><blockquote><strong>Investigating fusion methods that combine the scores of both models to improve detection accuracy.</strong></blockquote><blockquote><strong>Expanding the framework to incorporate additional anomaly detection algorithms for robust ensemble methods.</strong></blockquote><p>We have presented a complete Python implementation of an anomaly detecting system combining isolation forest modeling with autoencoder-based unsupervised learning. The method not only finds abnormalities efficiently but also offers a clear, side-by-side visual contrast of two detection methods. Such integration provides a useful toolkit for handling challenging data in real-world anomaly detection situations and creates the foundation for next study and optimization in hybrid detection systems.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d1cc5314e486" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-has-better-idea/ai-based-anomaly-detection-integrating-autoencoders-and-isolation-forests-d1cc5314e486">AI-Based Anomaly Detection: Integrating Autoencoders and Isolation Forests</a> was originally published in <a href="https://medium.com/data-has-better-idea">Data Has Better Idea</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>