<?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 Busra Oguzoglu on Medium]]></title>
        <description><![CDATA[Stories by Busra Oguzoglu on Medium]]></description>
        <link>https://medium.com/@busra.oguzoglu?source=rss-6bc4ddbdded0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ndWvFZeMt2eV3W7JShaOFA@2x.jpeg</url>
            <title>Stories by Busra Oguzoglu on Medium</title>
            <link>https://medium.com/@busra.oguzoglu?source=rss-6bc4ddbdded0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 19:15:49 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@busra.oguzoglu/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[How to Fine-Tune LLMs like Llama, Mistral, and Qwen using LoRA on Custom Tasks]]></title>
            <link>https://pub.aimind.so/how-to-fine-tune-llms-like-llama-mistral-and-qwen-using-lora-on-custom-tasks-7c36eceae38f?source=rss-6bc4ddbdded0------2</link>
            <guid isPermaLink="false">https://medium.com/p/7c36eceae38f</guid>
            <category><![CDATA[fine-tuning]]></category>
            <category><![CDATA[qwen2-5]]></category>
            <category><![CDATA[llama-3]]></category>
            <category><![CDATA[llm-finetuning]]></category>
            <category><![CDATA[mistral]]></category>
            <dc:creator><![CDATA[Busra Oguzoglu]]></dc:creator>
            <pubDate>Sun, 15 Jun 2025 10:20:15 GMT</pubDate>
            <atom:updated>2025-06-19T13:10:40.915Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S5pcKEACjXcnS4LoaYiePQ.png" /></figure><p>Fine-tuning large language models (LLMs) like Llama, Mistral, and Qwen can significantly boost performance on specialized tasks with domain-specific data. This guide walks through how to fine-tune these models efficiently using LoRA (Low-Rank Adaptation) with Hugging Face, PEFT, and BitsAndBytes.</p><p>We cover both the <strong>general recipe</strong> and <strong>model-specific nuances</strong> encountered during real-world fine-tuning workflows.</p><h3>Environment Setup</h3><p>Ensure the following libraries are installed:</p><pre>pip install transformers datasets peft accelerate bitsandbytes</pre><p>Note that all experiments used CUDA-enabled GPUs (All works with A100 on Google Colab) with torch.bfloat16 or torch.float16, depending on the model.</p><p><em>Note: If you have any questions regarding environment setup (library versions etc.), you can contact me and I can try to help</em></p><h3>Model Loading with 4-bit Quantization</h3><pre>def create_bnb_config():<br>    return BitsAndBytesConfig(<br>        load_in_4bit=True,<br>        bnb_4bit_use_double_quant=True,<br>        bnb_4bit_quant_type=&quot;nf4&quot;,<br>        bnb_4bit_compute_dtype=torch.bfloat16,<br>    )<br><br>def load_model(model_name, bnb_config):<br>    model = AutoModelForCausalLM.from_pretrained(<br>        model_name,<br>        quantization_config=bnb_config,<br>        device_map=&quot;auto&quot;,<br>        trust_remote_code=False<br>    )<br><br>    tokenizer = AutoTokenizer.from_pretrained(<br>        model_name,<br>        use_fast=True,<br>        trust_remote_code=False<br>    )<br>    tokenizer.pad_token = tokenizer.eos_token<br>    tokenizer.padding_side = &quot;right&quot;<br><br>    return model, tokenizer</pre><ul><li>trust_remote_code=True is needed for <strong>Mistral</strong>.</li><li>trust_remote_code=False works for <strong>Qwen</strong> and <strong>Llama</strong>. (&gt;Llama3, Qwen2.5)</li><li>torch_dtype should be adjusted for inference: It is observed and noted that Qwen2.5 works best with torch.float16.</li></ul><h3>Prompt Format Templates</h3><h4>Prompt Format Templates (Generic Task: Paragraph Summarization)</h4><h4>LLaMA 2 / 3.1 / 4:</h4><pre># Prompt Template for Training<br><br>def create_prompt_formats(sample):<br>    sample[&quot;text&quot;] = f&quot;[INST] Summarize the key information from the following paragraph:\n\n{sample[&#39;text&#39;]} [/INST] {sample[&#39;summary&#39;]}&quot;<br>    return sample</pre><pre># Prompt Template for Inference<br><br>def create_prompt_for_inference(sample):<br>    return f&quot;[INST] Summarize the key information from the following paragraph:\n\n{sample[&#39;text&#39;]} [/INST]&quot;</pre><h4>Mistral (Instruct v0.3):</h4><pre># Prompt Template for Training<br><br>def create_prompt_formats(sample):<br>    sample[&quot;text&quot;] = f&quot;&lt;s&gt;[INST] Summarize the key information from the following paragraph:\n\n{sample[&#39;text&#39;]} [/INST] {sample[&#39;summary&#39;]}&quot;<br>    return sample</pre><pre># Prompt Template for Inference<br><br>def create_prompt_for_inference(sample):<br>    return f&quot;&lt;s&gt;[INST] Summarize the key information from the following paragraph:\n\n{sample[&#39;text&#39;]} [/INST]&quot;</pre><h4>Qwen 2.5:</h4><pre># Prompt Template for Training<br><br>def create_prompt_formats(sample):<br>    sample[&quot;text&quot;] = f&quot;&lt;|im_start|&gt;user\nSummarize the key information from the following paragraph:\n\n{sample[&#39;text&#39;]}&lt;|im_end|&gt;\n&lt;|im_start|&gt;assistant\n{sample[&#39;summary&#39;]}&lt;|im_end|&gt;&quot;<br>    return sample</pre><pre># Prompt Template for Inference<br><br>def create_prompt_for_inference(sample):<br>    return f&quot;&lt;|im_start|&gt;user\nSummarize the key information from the following paragraph:\n\n{sample[&#39;text&#39;]}&lt;|im_end|&gt;\n&lt;|im_start|&gt;assistant\n&quot;</pre><h3>Dataset Preprocessing</h3><p>The dataset must be converted into a format the LLM understands, using a consistent prompt pattern. This step also includes tokenization and length filtering to ensure samples fit the model’s context window.</p><h3>Preprocessing Steps:</h3><ol><li><strong>Format Inputs:</strong> Using create_prompt_formats, we convert each row of the dataset into a prompt-response format depending on the model.</li><li><strong>Tokenize Texts:</strong> The tokenizer encodes the prompt into input_ids and attention_mask.</li><li><strong>Truncate &amp; Filter:</strong> Samples that exceed max_length are discarded to prevent runtime errors.</li><li><strong>Shuffle:</strong> The dataset is shuffled with a fixed seed for reproducibility.</li></ol><pre>def preprocess_batch(batch, tokenizer, max_length):<br>    return tokenizer(batch[&quot;text&quot;], max_length=max_length, truncation=True)<br><br>def preprocess_dataset(tokenizer, max_length, seed, dataset):<br>    dataset = dataset.map(create_prompt_formats)<br>    f = partial(preprocess_batch, tokenizer=tokenizer, max_length=max_length)<br>    dataset = dataset.map(f, batched=True)<br>    dataset = dataset.filter(lambda x: len(x[&quot;input_ids&quot;]) &lt; max_length)<br>    return dataset.shuffle(seed=seed)</pre><p>This preprocessing function is <strong>task-agnostic</strong> and works for any task where the text and summary (or label) fields can be restructured into input-output pairs. You can adapt this for tasks like classification, QA, or generation by adjusting create_prompt_formats() accordingly.</p><h4>Model-Specific Prompting vs General Dataset Preprocessing</h4><p>The <strong>tokenization and filtering steps</strong> are general and apply to all LLMs.</p><p>But the <strong>prompt formatting</strong> (create_prompt_formats) depends heavily on the model:</p><ul><li>Llama uses [INST] ... [/INST] format.</li><li>Mistral wraps prompts in &lt;s&gt;[INST] ... [/INST].</li><li>Qwen uses chat-style roles with &lt;|im_start|&gt;user.</li></ul><p>Likewise, model loading must respect specific settings:</p><ul><li>Qwen prefers trust_remote_code=False, Mistral requires True.</li><li>Dtype mismatches (e.g., float vs half) can break inference in Qwen if inputs aren’t carefully handled.</li></ul><h3>LoRA Adapter Configuration</h3><pre>def create_peft_config(target_modules):<br>    return LoraConfig(<br>        r=8,<br>        lora_alpha=32,<br>        target_modules=target_modules,<br>        lora_dropout=0.0,<br>        bias=&quot;none&quot;,<br>        task_type=&quot;CAUSAL_LM&quot;,<br>    )<br><br>def find_all_linear_names(model):<br>    cls = torch.nn.Linear<br>    return list({name.split(&quot;.&quot;)[-1] for name, mod in model.named_modules() if isinstance(mod, cls)})</pre><h4>Model-Specific Notes on LoRA Configuration</h4><p><strong>target_modules Selections:</strong></p><ul><li>Llama &amp; Mistral: [&quot;q_proj&quot;, &quot;k_proj&quot;, &quot;v_proj&quot;, &quot;o_proj&quot;, &quot;gate_proj&quot;, &quot;up_proj&quot;, &quot;down_proj&quot;]</li><li>Qwen2.5: Different! This works: [&quot;w1&quot;, &quot;w2&quot;, &quot;w3&quot;, &quot;out_proj&quot;, &quot;lm_head&quot;]</li><li>or use find_all_linear_names(model)</li></ul><h4>Common Pitfalls:</h4><ul><li>Double wrapping the model with LoRA causes:</li></ul><pre>You are trying to modify a model with PEFT for a second time.</pre><p>Solution: Call model = model.unload() before re-wrapping.</p><ul><li>Unsupported layers (e.g., Identity() in Qwen) raise:</li></ul><pre>ValueError: Target module Identity() is not supported.</pre><p>Solution: Use only supported layers such as Linear or explicitly known modules. (See previous section)</p><h3>Training</h3><pre>def train(model, tokenizer, train_dataset, val_dataset, output_dir):<br>    model.gradient_checkpointing_enable()<br>    model = prepare_model_for_kbit_training(model)<br><br>    target_modules = [&quot;q_proj&quot;, &quot;k_proj&quot;, &quot;v_proj&quot;, &quot;o_proj&quot;, &quot;gate_proj&quot;, &quot;up_proj&quot;, &quot;down_proj&quot;]<br>    peft_config = create_peft_config(target_modules)<br>    model = get_peft_model(model, peft_config)<br><br>    total = sum(p.numel() for p in model.parameters())<br>    trainable = sum(p.numel() for p in model.parameters() if p.requires_grad)<br>    print(f&quot;Trainable params: {trainable:,} / {total:,} ({100 * trainable / total:.2f}%)&quot;)<br><br>    trainer = Trainer(<br>        model=model,<br>        train_dataset=train_dataset,<br>        eval_dataset=val_dataset,<br>        args=TrainingArguments(<br>            output_dir=output_dir,<br>            per_device_train_batch_size=4,            # A100 can handle 4 easily<br>            num_train_epochs=4,<br>            gradient_accumulation_steps=4,<br>            learning_rate=2e-4,<br>            bf16=True,                                # Ideal for A100<br>            fp16=False,                               # fp16 is False<br>            logging_steps=1,<br>            eval_strategy=&quot;steps&quot;,<br>            save_strategy=&quot;steps&quot;,<br>            eval_steps=5,<br>            load_best_model_at_end=True,<br>            metric_for_best_model=&quot;eval_loss&quot;,<br>            report_to=None<br>        ),<br>        data_collator=DataCollatorForLanguageModeling(tokenizer, mlm=False),<br>        callbacks=[EarlyStoppingCallback(early_stopping_patience=1)]<br>    )<br><br>    trainer.train()<br>    trainer.save_model(output_dir)<br>    tokenizer.save_pretrained(output_dir)</pre><p>This train() function allows full control of gradient checkpointing, 4-bit training, PEFT wrapping, and Hugging Face training loop with early stopping. It&#39;s general enough to work with all models by adjusting the target_modules field.</p><h3>Inference (Minimal Memory)</h3><p>Efficient inference is crucial when dealing with 7B+ models. After training, we can reload the fine-tuned model with minimal GPU memory usage using quantized weights and no_grad mode.</p><pre># Qwen 2.5 as example<br># trust_remote_code = True for Mistral, Llama &gt;= 3<br><br>model = AutoPeftModelForCausalLM.from_pretrained(<br>    &quot;results/qwen2.5_colab&quot;,<br>    torch_dtype=torch.float16,<br>    device_map=&quot;auto&quot;<br>)<br>tokenizer = AutoTokenizer.from_pretrained(&quot;results/qwen2.5_colab&quot;, trust_remote_code=False)</pre><p>this part is shared:</p><pre>text = create_prompt_for_inference(sample)<br>inputs = tokenizer(text, return_tensors=&quot;pt&quot;).to(model.device)<br><br>with torch.no_grad():<br>    outputs = model.generate(**inputs, max_new_tokens=50)<br>    decoded = tokenizer.decode(outputs[0], skip_special_tokens=True)</pre><p>Always use .to(model.device) to avoid dtype mismatch. Don’t move tensors manually to .half() or .bfloat16. It causes type errors.</p><h3>Troubleshooting Notes</h3><ul><li><strong>OutOfMemoryError:</strong> Try torch_dtype=torch.float16 and reduce max_new_tokens.</li><li><strong>Expected scalar type Float but found Half:</strong> Don’t move tokenized inputs to .half() manually; use model’s device with native dtype.</li><li><strong>trust_remote_code</strong>: Mistral requires True, Qwen works best with False.</li><li><strong>Tokenizer Errors:</strong> Always set tokenizer.pad_token = tokenizer.eos_token to avoid padding errors.</li></ul><h3>Conclusion</h3><p>This guide walks through a reproducible path for LoRA-based fine-tuning on multiple powerful LLMs. With proper dtype management, quantization, and prompt engineering, it’s possible to fine-tune models like Llama 3.1 (generally &gt;3, 4 included), Mistral, and Qwen2.5 on consumer-grade GPUs (Worked with A100 on Colab, contact me for your questions).</p><blockquote><em>Feedback or contributions? Drop a comment or connect on GitHub and LinkedIn! (</em><a href="https://github.com/busraoguzoglu">https://github.com/busraoguzoglu</a>, <a href="https://www.linkedin.com/in/busraoguzoglu/">https://www.linkedin.com/in/busraoguzoglu/</a><em>)</em></blockquote><h4>A Message from AI Mind</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/0*5Wm7sOfTpe5DEbhg.gif" /></figure><p>Thanks for being a part of our community! Before you go:</p><ul><li>👏 Clap for the story and follow the author 👉</li><li>📰 View more content in the <a href="https://pub.aimind.so/">AI Mind Publication</a></li><li>🧠 Improve your <a href="https://www.aimind.so/prompt-generator?utm_source=pub&amp;utm_medium=message">AI prompts effortlessly and FREE</a></li><li><strong>🧰 Discover </strong><a href="https://www.aimind.so/?utm_source=pub&amp;utm_medium=message"><strong>Intuitive AI Tools</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7c36eceae38f" width="1" height="1" alt=""><hr><p><a href="https://pub.aimind.so/how-to-fine-tune-llms-like-llama-mistral-and-qwen-using-lora-on-custom-tasks-7c36eceae38f">How to Fine-Tune LLMs like Llama, Mistral, and Qwen using LoRA on Custom Tasks</a> was originally published in <a href="https://pub.aimind.so/">AI Mind</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fully Open Source RAG with Llama.cpp and LLaVA]]></title>
            <link>https://pub.aimind.so/fully-open-source-rag-with-llama-cpp-and-llava-images-included-ce9b66ab21df?source=rss-6bc4ddbdded0------2</link>
            <guid isPermaLink="false">https://medium.com/p/ce9b66ab21df</guid>
            <category><![CDATA[llama-3]]></category>
            <category><![CDATA[llama-cpp]]></category>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[llava]]></category>
            <dc:creator><![CDATA[Busra Oguzoglu]]></dc:creator>
            <pubDate>Wed, 04 Dec 2024 12:57:00 GMT</pubDate>
            <atom:updated>2025-06-19T13:10:38.768Z</atom:updated>
            <content:encoded><![CDATA[<p>Retrieval-Augmented Generation (RAG) systems are powerful tools for extracting insights from unstructured data. With advancements in open-source technologies, it’s now possible to build a fully open-source RAG system that handles both text and images. In this tutorial, we’ll walk through the design choices and tools used to construct such a system. We will be using Llama as LLM (you can use <strong>Llama.cpp, </strong>you can also use Llama from<strong> Transformers </strong>library<strong> </strong>for language processing and <strong>LLaVA</strong> for visual data integration.)</p><p>By the end of this post, you’ll understand how to combine text and images in a robust RAG pipeline, using only open-source components.</p><p>Full code is available on my GitHub page (link is at the end)</p><h3>Why Open Source for RAG?</h3><ul><li><strong>Cost-Effective</strong>: Open-source tools eliminate licensing costs, making advanced systems accessible to all.</li><li><strong>Customizable</strong>: Developers can fine-tune every component to suit specific use cases.</li><li><strong>Privacy-Friendly</strong>: Running models locally keeps sensitive data secure.</li><li><strong>Community Support</strong>: Open-source projects benefit from continuous improvements by a global community.</li><li><strong>Good For Learning: </strong>Not all of us have access to fancy environments and many of us only have our old computer to learn, and Open Source is such a good way for that.</li></ul><h3>System Overview</h3><p>Our RAG system processes textual and visual data to answer queries accurately and provide actionable insights. Here’s a high-level overview of the architecture:</p><ol><li><strong>Textual Retrieval and Generation</strong>: Using <strong>Llama.cpp</strong> for efficient on-device text processing.</li><li><strong>Visual Integration</strong>: Summarizing images (charts, graphs, etc.) with <strong>LLaVA</strong>.</li><li><strong>Embedding and Retrieval</strong>: Storing and retrieving document embeddings via <strong>Pgvector</strong>. (Qdrant and ChromaDB are also great options)</li><li><strong>Pipeline Orchestration</strong>: Managing retrieval and response generation with <strong>llama-index</strong>. (You can use Langchain too)</li></ol><p>This is how the architecture looks:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PgTRT9uZfaKM5qSmnmU9Bg.png" /><figcaption>Pipeline for the PMC RAG system</figcaption></figure><h3>Key Design Choices</h3><h3>1. PDF Preprocessing</h3><p>A robust preprocessing pipeline is critical for ensuring high-quality inputs to your RAG system. Inconsistent formatting, unnecessary artifacts, and broken structures in raw data can significantly degrade model performance.</p><p>First part is textual preprocessing:</p><pre>from llama_index.readers.file import PyMuPDFReader<br>import re<br>from llama_index.readers.file import PyMuPDFReader<br>import fitz  # PyMuPDF for image extraction<br><br># Define stop keywords<br># My keywords are as follows because of my data domain: Academic papers<br>stop_keywords = [&quot;References&quot;, &quot;Conflict of interest&quot;, <br>                 &quot;Acknowledgements&quot;, &quot;Supplementary Materials&quot;, &quot;Author details&quot;, &quot;Publishers Note&quot;]<br><br># Regex to capture figures<br>figure_pattern = r&#39;\b(Figure|Fig\.)\s*\d+[a-zA-Z]*\b.*?(\n.*?)*?(?=\n\n|\Z)&#39;<br><br>def preprocess_text(text, stop_keywords):<br>    &quot;&quot;&quot;Preprocess text by stopping at the earliest occurrence of any keyword, ignoring case.&quot;&quot;&quot;<br>    earliest_position = len(text)  # Default to the end of the text<br>    <br>    for keyword in stop_keywords:<br>        pattern = rf&quot;\b{re.escape(keyword)}\b&quot;  # Match exact word boundaries<br>        match = re.search(pattern, text, re.IGNORECASE)<br>        if match:<br>            earliest_position = min(earliest_position, match.start())<br>    <br>    return text[:earliest_position]<br><br>def clean_text(block_text):<br>    &quot;&quot;&quot;Clean and process individual blocks of text.&quot;&quot;&quot;<br>    block_text = &quot; &quot;.join(block_text.split())  # Remove extra spaces and newlines<br>    block_text = re.sub(r&#39;^\d+\.\s+&#39;, &#39;&#39;, block_text)  # Remove section numbering<br>    block_text = re.sub(r&#39;[^A-Za-z0-9\s,.]&#39;, &#39;&#39;, block_text)  # Keep only basic punctuation and letters<br><br>    if len(block_text) &lt; 10 or re.match(r&#39;Page \d+&#39;, block_text):<br>        return None  # Skip short blocks or page numbers<br><br>    if re.search(r&#39;\d{2,}&#39;, block_text) and re.search(r&#39;(\d+\.\d+|\d+%)&#39;, block_text):<br>        return None  # Skip blocks with many numeric values<br><br>    if re.search(r&#39;\b(Table|Effect|Mediation|Summary|IV|Mediator|Cont)\b&#39;, block_text, re.IGNORECASE):<br>        return None<br><br>    return block_text</pre><p>We also need to extract the images from the PDF and save them for further processing:</p><pre>def extract_figures(text):<br>    &quot;&quot;&quot;Extract figure captions or descriptions from the text.&quot;&quot;&quot;<br>    figures = re.findall(figure_pattern, text, re.IGNORECASE | re.DOTALL)<br>    return [&quot; &quot;.join(fig).strip() for fig in figures if len(&quot; &quot;.join(fig).strip()) &gt; 5]  # Filter out short/no-content matches<br><br>def extract_images_from_pdf(pdf_path, output_dir, pdf_name):<br>    &quot;&quot;&quot;Extract images from a PDF and save them to output_dir.&quot;&quot;&quot;<br>    document = fitz.open(pdf_path)<br>    for page_idx in range(len(document)):<br>        page = document.load_page(page_idx)<br>        images = page.get_images(full=True)<br>        <br>        for img_index, img in enumerate(images):<br>            xref = img[0]<br>            base_image = document.extract_image(xref)<br>            image_bytes = base_image[&quot;image&quot;]<br>            image_ext = base_image[&quot;ext&quot;]<br>            <br>            # Save the image<br>            image_filename = output_dir / f&quot;{pdf_name}_page{page_idx}_img{img_index}.{image_ext}&quot;<br>            with image_filename.open(&quot;wb&quot;) as img_file:<br>                img_file.write(image_bytes)<br>            <br>            print(f&quot;Saved image: {image_filename}&quot;)<br><br>    document.close()</pre><h3>2. Language Model: Llama.cpp</h3><p><strong>Why Llama.cpp?</strong></p><ul><li>Optimized for local deployment with minimal resources.</li><li>Efficient quantization support for running models like <strong>Llama-2–13B-chat</strong> on commodity hardware.</li><li>No dependency on GPUs, reducing setup complexity.</li></ul><p><strong>Implementation Tip:</strong></p><ul><li>Use pre-quantized GGML models to avoid lengthy quantization steps.</li><li>Fine-tune prompts for retrieval-augmented tasks to ensure relevant, concise answers.</li></ul><pre>from llama_index.llms.llama_cpp import LlamaCPP<br>#from langchain_community.llms import LlamaCpp (alternative)<br><br>model_path = &quot;your_path_here/llama-2-13b-chat.Q4_0.gguf&quot;<br><br># Extra parameters<br># n_gpu_layers = -1  # The number of layers to put on the GPU. The rest will be on the CPU. If you don&#39;t know how many layers there are, you can use -1 to move all to GPU.<br># n_batch = 512  # Should be between 1 and n_ctx, consider the amount of VRAM in your GPU.<br><br>llm = LlamaCPP(<br>    model_path=model_path,<br>    temperature=0.1,<br>    max_new_tokens=256,<br>    context_window=4000,<br>    generate_kwargs={},<br>    model_kwargs={&quot;n_gpu_layers&quot;: 1},<br>    #f16_kv=True,  # For M2: MUST set to True, otherwise you will run into problem after a couple of calls<br>    #callback_manager=callback_manager, # Need to call with langchain<br>    verbose=True,<br>)</pre><h3>2. Visual Summarization: LLaVA</h3><p><strong>Why Text Summaries for Images?</strong></p><ul><li>Many datasets have sparse visual content, making multimodal embeddings less effective.</li><li>Converting charts and diagrams into text ensures compatibility with text-based pipelines.</li><li>If you want to use models like <strong>CLIP</strong> or <strong>ALIGN</strong>, you may lose a lot of info from the textual side.</li></ul><p><strong>How to Use LLaVA:</strong></p><ul><li>Extract visual elements from documents using libraries like <strong>PyMuPDF</strong> or <strong>Pillow</strong>.</li><li>Pass images through <strong>LLaVA</strong> to generate textual summaries.</li><li>Embed these summaries alongside document text using <strong>sentence-transformers</strong>.</li></ul><pre>from transformers import AutoProcessor, LlavaForConditionalGeneration<br><br># Load LLaVA processor and model<br>model_name = &quot;llava-hf/llava-1.5-7b-hf&quot;<br>processor = AutoProcessor.from_pretrained(model_name)<br>model = LlavaForConditionalGeneration.from_pretrained(model_name, torch_dtype=torch.float16, device_map=&quot;auto&quot;)</pre><pre># Create summaries for images<br># Prompt can become more specific<br># Example: Add context from the latest text chunk<br><br>image = Image.open(image_file).convert(&quot;RGB&quot;)<br>    <br># Define the conversation template for generating a detailed description<br>conversation = [<br>    {<br>        &quot;role&quot;: &quot;user&quot;,<br>        &quot;content&quot;: [<br>            {&quot;type&quot;: &quot;image&quot;},  # Image placeholder<br>            {&quot;type&quot;: &quot;text&quot;, &quot;text&quot;: &quot;What is shown in this image?&quot;}<br>        ],<br>    }<br>]<br><br># Apply chat template and prepare inputs<br>text_prompt = processor.apply_chat_template(conversation, add_generation_prompt=True)<br>inputs = processor(text=[text_prompt], images=[image], return_tensors=&quot;pt&quot;).to(device)  # Ensure inputs are on the same device<br><br># Generate response<br>with torch.no_grad():<br>    outputs = model.generate(**inputs, max_new_tokens=256)<br><br>summary = processor.decode(outputs[0], skip_special_tokens=True)<br><br># Extract only the assistant&#39;s response<br>assistant_reply = summary.split(&quot;ASSISTANT:&quot;)[1].strip() if &quot;ASSISTANT:&quot; in summary else summary<br>image_summaries[image_file.name] = assistant_reply<br>print(f&quot;Generated summary for {image_file.name}:\n{assistant_reply}\n&quot;)</pre><h3>4. Embedding and Retrieval: Pgvector</h3><p><strong>Why Pgvector?</strong></p><ul><li>Seamlessly integrates with PostgreSQL for scalable vector storage.</li><li>Allows efficient similarity searches using embeddings.</li></ul><p><strong>Setup Tip:</strong></p><ul><li>Use sentence-transformers (e.g., BAAI/bge-small-en) for lightweight and effective text embeddings. We can use other models as well, integration is easy.</li><li>Regularly index new embeddings for dynamic datasets.</li></ul><pre># DB Connection:<br><br>db_name = &quot;rag_db&quot;  # Use the database name<br>host = &quot;localhost&quot;<br>password = &quot;password&quot; <br>port = &quot;5432&quot;  # Default PostgreSQL port<br>user = &quot;myuser&quot; <br><br>conn = psycopg2.connect(<br>    dbname=db_name,<br>    host=host,<br>    password=password,<br>    port=port,<br>    user=user,<br>)<br>conn.autocommit = True</pre><p>It makes sense to add checks to the DB part of your code, since we do not need to add same embeddings to the same table over and over again, here is an example of how to do that:</p><pre>from sqlalchemy import create_engine, text<br>from sqlalchemy.exc import OperationalError<br>from llama_index.vector_stores.postgres import PGVectorStore<br><br># Connection parameters<br>db_params = {<br>    &quot;user&quot;: &quot;myuser&quot;,      <br>    &quot;password&quot;: &quot;password&quot;, <br>    &quot;host&quot;: &quot;localhost&quot;,   <br>    &quot;port&quot;: &quot;5432&quot;,       <br>    &quot;database&quot;: &quot;rag_db&quot;  <br>}<br><br># Create SQLAlchemy engine<br>engine = create_engine(f&quot;postgresql://{db_params[&#39;user&#39;]}:{db_params[&#39;password&#39;]}@{db_params[&#39;host&#39;]}:{db_params[&#39;port&#39;]}/{db_params[&#39;database&#39;]}&quot;)<br><br># Update table name to include &#39;data_&#39; prefix<br>table_name = &quot;data_pmc_table&quot;  # Postgre adds &#39;data&#39; in front of table_name<br>embed_dim = 384  # Embedding dimension<br><br>try:<br>    with engine.connect() as conn:<br>        # Check if the table exists<br>        result = conn.execute(text(f&quot;&quot;&quot;<br>            SELECT EXISTS (<br>                SELECT FROM information_schema.tables <br>                WHERE table_schema = &#39;public&#39; AND table_name = :table_name<br>            );<br>        &quot;&quot;&quot;), {&quot;table_name&quot;: table_name}).scalar()<br><br>        if result:<br>            print(f&quot;Table &#39;{table_name}&#39; exists. Cleaning it...&quot;)<br>            conn.execute(text(f&quot;DROP TABLE {table_name} CASCADE;&quot;))<br>        else:<br>            print(f&quot;Table &#39;{table_name}&#39; does not exist. Creating it...&quot;)<br><br>        # Create a new table for vector store<br>        vector_store = PGVectorStore.from_params(<br>            database=db_params[&quot;database&quot;],<br>            host=db_params[&quot;host&quot;],<br>            password=db_params[&quot;password&quot;],<br>            port=db_params[&quot;port&quot;],<br>            user=db_params[&quot;user&quot;],<br>            table_name=&quot;pmc_table&quot;,  # Use unprefixed name; PGVectorStore adds &#39;data_&#39; automatically<br>            embed_dim=embed_dim,<br>        )<br>        print(f&quot;Table &#39;{table_name}&#39; has been created.&quot;)<br>except OperationalError as e:<br>    print(f&quot;Error: {e}&quot;)<br>    print(&quot;Make sure the database exists and connection parameters are correct.&quot;)</pre><h3>5. Orchestration: llama-index</h3><p><strong>Why llama-index?</strong></p><ul><li>Simplifies retrieval pipelines for complex document structures.</li><li>Supports multimodal extensions, enabling integration of text and image summaries.</li></ul><p><strong>Design Note:</strong></p><ul><li>Consider switching to <strong>LangChain</strong> and use <strong>LangGraph</strong> if advanced agentic capabilities are needed. You can do agentic RAG with llama-index as well, but I found LangGraph to be easily understandable.</li></ul><h3>6. Evaluation</h3><p>Evaluation is crucial for assessing the system’s accuracy, coherence, and overall utility. We can use a mix of automated metrics and human evaluations tailored to both textual and visual components.</p><p>We can also use <strong>DeepEval </strong>for LLM based evaluation. As default, it uses GPT models. I will try to use Llama3 with DeepEval to evaluate this project and share in a later blog post.</p><h3>Challenges</h3><ol><li><strong>Hardware Limitations</strong>: Deploying large models like Llama3 locally requires substantial resources. Quantization and model optimization are critical.</li><li><strong>Image Integration</strong>: Direct multimodal embeddings often lack precision. Summarizing visuals into text proved more effective for this use case.</li><li><strong>Evaluation</strong>: Balancing textual and visual data accuracy requires rigorous testing, including human evaluations.</li></ol><p><strong>Conclusion</strong></p><p>Building a fully open-source RAG system is an exciting challenge that offers immense value. By combining <strong>Llama.cpp</strong>, <strong>LLaVA</strong>, and other open-source tools, we’ve created a versatile pipeline that bridges the gap between textual and visual data.</p><p>This tutorial offers a blueprint for constructing your own RAG system, empowering you to adapt it to diverse domains. Share your thoughts or questions in the comments — I’d love to hear about your projects and ideas!</p><p>You can visit my GitHub profile for this project and other projects: <a href="https://github.com/busraoguzoglu">https://github.com/busraoguzoglu</a></p><h4>A Message from AI Mind</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/0*5Wm7sOfTpe5DEbhg.gif" /></figure><p>Thanks for being a part of our community! Before you go:</p><ul><li>👏 Clap for the story and follow the author 👉</li><li>📰 View more content in the <a href="https://pub.aimind.so/">AI Mind Publication</a></li><li>🧠 Improve your <a href="https://www.aimind.so/prompt-generator?utm_source=pub&amp;utm_medium=message">AI prompts effortlessly and FREE</a></li><li><strong>🧰 Discover </strong><a href="https://www.aimind.so/?utm_source=pub&amp;utm_medium=message"><strong>Intuitive AI Tools</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ce9b66ab21df" width="1" height="1" alt=""><hr><p><a href="https://pub.aimind.so/fully-open-source-rag-with-llama-cpp-and-llava-images-included-ce9b66ab21df">Fully Open Source RAG with Llama.cpp and LLaVA</a> was originally published in <a href="https://pub.aimind.so/">AI Mind</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating Embeddings from Knowledge Graphs Using Graph Neural Networks]]></title>
            <link>https://medium.com/@busra.oguzoglu/creating-embeddings-from-knowledge-graphs-using-graph-neural-networks-ffc6cc62275c?source=rss-6bc4ddbdded0------2</link>
            <guid isPermaLink="false">https://medium.com/p/ffc6cc62275c</guid>
            <category><![CDATA[embedding]]></category>
            <category><![CDATA[gnn]]></category>
            <category><![CDATA[knowledge-graph]]></category>
            <category><![CDATA[knowledge-representation]]></category>
            <category><![CDATA[knowledge-graph-embedding]]></category>
            <dc:creator><![CDATA[Busra Oguzoglu]]></dc:creator>
            <pubDate>Mon, 18 Nov 2024 06:19:52 GMT</pubDate>
            <atom:updated>2024-11-18T06:19:52.888Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-wmQZDtOcjm80RXugr1CVA.png" /><figcaption>Image Generated by DALL-E3, Showing Knowledge Graphs and Usage of GNN’s to get Knowledge Representations</figcaption></figure><p><strong>Knowledge Graphs (KGs)</strong> have emerged as a powerful tool for representing complex relationships between entities. They are good for representation however, can further be utilized by their ability to enable advanced analytics and machine learning tasks. One of the key innovations in this space is the use of <strong>Graph Neural Networks (GNNs)</strong> for creating embeddings — numerical representations of graph elements that capture their structural and semantic information. This blog explores how GNNs can be used for embedding creation.</p><h3>What Are Graph Neural Networks?</h3><p><strong>Graph Neural Networks (GNNs)</strong> are a special type of neural network that are designed to operate on graph-structured data. Unlike traditional neural networks that work on fixed-size inputs like images or sequences, GNNs can process graphs of arbitrary size and topology. They do this by iteratively aggregating and transforming information from a node’s neighbors, effectively capturing both local and global graph structures.</p><h3>Why Use GNNs for Knowledge Graph Embeddings?</h3><p>Creating embeddings for knowledge graphs involves converting nodes, edges, or subgraphs into dense vector representations. These embeddings serve as input features for downstream tasks such as classification, clustering, and recommendation. GNNs excel in this area for several reasons:</p><ol><li><strong>Contextual Awareness</strong>: GNNs capture not only the features of individual nodes but also the rich context provided by their neighbors. This is crucial in KGs, where relationships between entities are as important as the entities themselves.</li><li><strong>Flexibility</strong>: GNNs can handle heterogeneous graphs, where nodes and edges can have different types and attributes, a common scenario in KGs.</li><li><strong>Scalability</strong>: By leveraging techniques like mini-batching and sampling, GNNs can efficiently process large-scale graphs, making them suitable for bigger data sources.</li></ol><h3>How GNNs Generate Embeddings</h3><p>The process of generating embeddings using GNNs typically involves the following steps:</p><ol><li><strong>Feature Initialization</strong>: Each node starts with an initial feature vector, often based on its attributes or a simple encoding.</li><li><strong>Message Passing</strong>: Nodes exchange information with their neighbors through a series of message-passing layers. Each node aggregates information from its neighbors using functions like mean, sum, or attention mechanisms.</li><li><strong>Feature Transformation</strong>: The aggregated messages are transformed using learnable weight matrices and non-linear activation functions, enabling the network to learn complex patterns.</li><li><strong>Readout</strong>: After several layers of message passing, a final representation (embedding) is generated for each node or edge. These embeddings can be used directly or further processed for specific tasks.</li></ol><h3>Popular GNN Architectures for Knowledge Graphs</h3><p>Several GNN architectures have been developed to cater to the unique challenges posed by knowledge graphs:</p><ul><li><strong>Graph Convolutional Networks (GCNs)</strong>: Use convolution-like operations to aggregate and transform neighbor information.</li><li><strong>Graph Attention Networks (GATs)</strong>: Introduce attention mechanisms to weigh the importance of different neighbors dynamically.</li><li><strong>Relational Graph Convolutional Networks (RGCN)</strong>: Specifically designed for multi-relational graphs, handling diverse edge types efficiently.</li></ul><h3>Real-World Applications</h3><p>The embeddings generated by GNNs unlock a wide range of applications:</p><ul><li><strong>Recommendation Systems</strong>: By embedding users and products, GNNs enhance personalized recommendations.</li><li><strong>Drug Discovery, Protein Interaction Prediction</strong>: In biomedical KGs, GNN embeddings help predict interactions between drugs and targets. We can also use the embeddings for biomedical compounds for further downstream tasks.</li><li><strong>Fraud Detection</strong>: Financial institutions use GNNs to identify suspicious activities by analyzing transaction graphs.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ffc6cc62275c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Airtest: A Beginner’s Guide for iOS]]></title>
            <link>https://medium.com/@busra.oguzoglu/airtest-a-beginners-guide-for-ios-0f0505503346?source=rss-6bc4ddbdded0------2</link>
            <guid isPermaLink="false">https://medium.com/p/0f0505503346</guid>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[game-testing]]></category>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[airtest]]></category>
            <dc:creator><![CDATA[Busra Oguzoglu]]></dc:creator>
            <pubDate>Thu, 07 Nov 2024 08:48:10 GMT</pubDate>
            <atom:updated>2024-11-07T08:48:56.466Z</atom:updated>
            <content:encoded><![CDATA[<p>Game testing is an indispensable phase in game development, ensuring a seamless and engaging player experience. From detecting bugs to enhancing performance, testers work tirelessly to deliver a polished product. The critical areas of focus include:</p><ul><li><strong>Functionality Testing</strong>: Ensures core game features, such as character actions and scoring systems, operate as expected.</li><li><strong>Performance Testing</strong>: Monitors system resource usage to guarantee stable frame rates and quick load times.</li><li><strong>Usability Testing</strong>: Focuses on intuitive game interfaces for an optimal player experience.</li><li><strong>Compatibility Testing</strong>: Verifies the game’s performance across various devices, operating systems, and screen sizes.</li></ul><h3>Challenges in Game Testing</h3><p>Game testing isn’t without its hurdles:</p><ul><li><strong>Device Diversity</strong>: Testing for compatibility across different devices is especially challenging in the fragmented Android ecosystem.</li><li><strong>Consistency in Gameplay</strong>: Ensures predictable, bug-free player experiences.</li><li><strong>Detecting Subtle Bugs</strong>: Issues like memory leaks or animation glitches may not be immediately obvious but can impact long-term gameplay.</li><li><strong>Balancing Performance and Quality</strong>: High-quality visuals shouldn’t compromise performance, especially on lower-end devices.</li></ul><h3>Enter Airtest: Test Automation</h3><p>Developed by NetEase, Airtest is a robust, cross-platform testing framework designed to simplify game and app testing. It supports Android, iOS, and Windows platforms, offering two core frameworks:</p><ol><li><strong>Airtest</strong>: A visual testing framework leveraging image recognition and Python scripting for GUI-based automation.</li><li><strong>Poco</strong>: A UI object-based framework that enables direct interaction with UI elements, ideal for games built on Unity or native Android/iOS apps.</li></ol><h4>Key Features of Airtest:</h4><ul><li><strong>Cross-Platform Compatibility</strong>: Test apps across Android, iOS, and Windows.</li><li><strong>Image Recognition</strong>: Automates GUI interactions through visual matching.</li><li><strong>Python Scripting</strong>: Offers powerful, flexible automation scripting.</li><li><strong>Airtest IDE</strong>: User-friendly interface for test creation, debugging, and execution.</li><li><strong>Poco Integration</strong>: Provides enhanced UI element interaction.</li><li><strong>Record &amp; Playback</strong>: Simplifies test creation with minimal coding.</li></ul><h3>Setting Up Airtest for iOS</h3><p>To maximize Airtest’s potential, you need its IDE, which provides visual feedback and a streamlined interface for test case creation. We will look at the case for iOS devices. To test automate iOS devices, <strong>iOS-Tagent</strong> facilitates connectivity, ensuring smooth integration between your device and the IDE.</p><p>We can follow the instructions in Github page: <a href="https://github.com/AirtestProject/iOS-Tagent">https://github.com/AirtestProject/iOS-Tagent</a></p><p>You need Macbook and XCode running:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9PI32nbz68sk4-JJ" /><figcaption>WebDriverAgentRunner on XCode</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*m8jAXCFTyTvs44Nb" /><figcaption>Check the logs</figcaption></figure><p>Then you need to run proxy:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qEMvWC3dhTpTmvp4" /><figcaption>Check the status</figcaption></figure><h3>Example Use Case: Testing with Poco Assistant</h3><p>Poco Assistant allows testers to retrieve window components and their details, logging critical information for analysis. This feature ensures that even intricate UI elements are tested efficiently.</p><p>Select ‘record’ button from Poco Assistant (top right) then start clicking, scrolling and recording your actions from the screen on the right. Below you can see the components in the Poco assistant screen. They are gathered from the XML that shows the screen component on the phone, it is not based on image recognition (it will come later)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/824/0*AiYMZqdj2UZS8ykl" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qr5h08s3tlajQqrx" /><figcaption>We can see the ‘clicks’ are recorded in the script</figcaption></figure><p>After we record our actions, we can see them on the script. When we run the script, the automation should run on the phone screen and we can see how our simple test works.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qqeXEGnS2PJsix41" /></figure><p>On the screen above, we can see that we can record many actions like scroll, click, opening the lockscreen etc.</p><p>Another thing we can do is to find and locate the components in the screen by using the image recognition functions. We can use ‘exists’ and ‘assert exists’ functions to do that. We can select our ‘picture’ on the screen by drawing a bounding box. After running our script, we can see the location of the image on logs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IBMsz0xaa19ZZZT2" /><figcaption>Searching for the selected picture on the screen</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yfKx7jjliEK_tZ7Y" /><figcaption>Check the logs</figcaption></figure><h3>Conclusion</h3><p>Airtest is a great idea that can revolutionize the game testing landscape, offering flexibility and power for complex testing scenarios. Whether you’re developing on Unity or testing native apps, Airtest provides the tools to deliver a seamless gaming experience. Explore its <a href="https://airtest.netease.com/">official website</a> and <a href="https://github.com/AirtestProject/Airtest">GitHub repository</a> to get started.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0f0505503346" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Notes on Using Knowledge Graphs for Retrieval Augmented Generation (RAG)]]></title>
            <link>https://medium.com/@busra.oguzoglu/notes-on-using-knowledge-graphs-for-retrieval-augmented-generation-rag-9cc4052a531c?source=rss-6bc4ddbdded0------2</link>
            <guid isPermaLink="false">https://medium.com/p/9cc4052a531c</guid>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[neo4j]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Busra Oguzoglu]]></dc:creator>
            <pubDate>Fri, 25 Oct 2024 10:19:10 GMT</pubDate>
            <atom:updated>2024-10-25T10:19:52.258Z</atom:updated>
            <content:encoded><![CDATA[<p>Knowledge graphs offer a way to structure complex data relationships, making them a useful tool when building AI applications. By organizing data into nodes (representing entities) and edges (representing relationships), knowledge graphs can model real-world scenarios and provide rich context that improves search and retrieval tasks.</p><p>In this post, we’ll go over some of the basics of using knowledge graphs in RAG applications, including a few code examples to get started.</p><h4>Why Use Knowledge Graphs?</h4><p>Unlike traditional databases, knowledge graphs can connect structured (e.g., databases) and unstructured data (e.g., text documents), offering a more flexible way to explore relationships. This makes them ideal for:</p><ul><li><strong>Enhanced search</strong>: Retrieve data through more complex queries.</li><li><strong>Supporting LLMs</strong>: Provide structured data context, leading to better responses from language models. They can also help the system for the hallucination problem.</li><li><strong>Combining data</strong>: Integrate multiple data sources for a broader view.</li></ul><h4>Getting Started with Neo4j and Cypher</h4><p>Let’s use <strong>Neo4j </strong>to explore the basics. Neo4j allows us to query graph data using <strong>Cypher</strong>, a query language designed for this purpose. Here’s an example that sets up a simple movie graph:</p><pre>from langchain import Neo4jGraph<br><br># Set up Neo4j connection (Make sure Neo4j is running locally)<br># For setup follow: https://python.langchain.com/docs/integrations/graphs/neo4j_cypher/<br>neo4j_url = &quot;bolt://localhost:7687&quot;<br>neo4j_auth = (&quot;neo4j&quot;, &quot;password&quot;)<br>graph = Neo4jGraph(url=neo4j_url, username=neo4j_auth[0], password=neo4j_auth[1])<br><br># Create nodes and relationships using a Cypher query<br>graph.run_cypher(&quot;&quot;&quot;<br>    CREATE (m:Movie {title: &#39;Inception&#39;, year: 2010})<br>    CREATE (a:Actor {name: &#39;Leonardo DiCaprio&#39;})<br>    CREATE (a)-[:ACTED_IN]-&gt;(m)<br>&quot;&quot;&quot;)</pre><p>This example sets up a <strong>Movie</strong> node and an <strong>Actor</strong> node, with a relationship indicating that Leonardo DiCaprio acted in <em>Inception</em>.</p><h4>Querying with Cypher in LangChain</h4><p>We can execute Cypher queries to extract insights from the Neo4j database. Here’s an example to find all movies an actor has appeared in:</p><pre># Define the query to find movies an actor has starred in<br>query = &quot;&quot;&quot;<br>    MATCH (a:Actor {name: &#39;Leonardo DiCaprio&#39;})-[:ACTED_IN]-&gt;(m:Movie)<br>    RETURN m.title, m.year<br>&quot;&quot;&quot;<br><br># Run the query and print the results<br>results = graph.run_cypher(query)<br>for record in results:<br>    print(f&quot;Title: {record[&#39;m.title&#39;]}, Year: {record[&#39;m.year&#39;]}&quot;)</pre><p>This query retrieves movies featuring Leonardo DiCaprio, showing their titles and release years.</p><h4>Adding Vector Search Capabilities with LangChain</h4><p>With LangChain, we can also integrate vector indexes to include unstructured text data in our knowledge graph, enabling semantic search capabilities. Here’s a simplified example of how we might do this:</p><pre>from langchain.vectorstores import Chroma<br>from langchain.embeddings.openai import OpenAIEmbeddings<br><br># Create a vector store for unstructured text<br>embeddings = OpenAIEmbeddings()<br>vector_store = Chroma(collection_name=&quot;documents&quot;, embedding_function=embeddings)<br><br># Example: Store and retrieve embeddings in Neo4j for semantic search<br>document = {&quot;content&quot;: &quot;TechCorp is a leading software company.&quot;}<br>vector_store.add_document(document)<br><br># Find similar documents using vector similarity search<br>query_embedding = embeddings.embed_query(&quot;Find information about TechCorp&quot;)<br>results = vector_store.similarity_search(query_embedding, top_k=3)<br>for result in results:<br>    print(result[&quot;content&quot;])</pre><p>In this example, we create a vector store using <strong>Chroma</strong> and <strong>OpenAIEmbeddings</strong>, allowing us to add text documents and perform similarity searches.</p><h4>Building a Knowledge Graph from Text Documents</h4><p>To create a knowledge graph from unstructured text, follow these steps:</p><ol><li><strong>Extract entities</strong> (e.g., companies, people) using NLP methodologies.</li><li><strong>Create nodes</strong> for each entity.</li><li><strong>Define relationships</strong> between entities.</li><li><strong>Insert into Neo4j</strong> for querying.</li></ol><p>For example:</p><pre># Example: Creating a node from extracted text data<br>graph.run_cypher(&quot;&quot;&quot;<br>    CREATE (c:Company {name: &#39;TechCorp&#39;, sector: &#39;Software&#39;})<br>    CREATE (p:Person {name: &#39;Alice&#39;})<br>    CREATE (p)-[:WORKS_AT]-&gt;(c)<br>&quot;&quot;&quot;)</pre><p>This code adds a <strong>Company</strong> node and a <strong>Person</strong> node, with a relationship indicating that Alice works at TechCorp.</p><h4>Using Knowledge Graphs to Improve RAG</h4><p>Knowledge graphs can add context to LLMs in RAG setups. We can query the graph for specific information and include it directly in prompts to guide the LLM:</p><pre># Query to retrieve relevant data for LLM prompt<br>prompt_data = graph.run_cypher(&quot;&quot;&quot;<br>    MATCH (c:Company {name: &#39;TechCorp&#39;})-[:WORKS_AT]-(p:Person)<br>    RETURN p.name<br>&quot;&quot;&quot;)<br><br># Format the prompt for the LLM<br>employee_name = prompt_data[0][&#39;p.name&#39;]<br>prompt = f&quot;Generate a report about TechCorp employees, including {employee_name}.&quot;</pre><p>This integration makes LLM responses more accurate by grounding them in the structured context of the graph, therefore making them less prone to hallucination as well.</p><h4>Notes</h4><p>You can find code examples and documentation for Neo4j LangChain integration: <a href="https://python.langchain.com/docs/integrations/graphs/neo4j_cypher/">https://python.langchain.com/docs/integrations/graphs/neo4j_cypher/</a></p><p>Py2neo: <a href="https://pypi.org/project/py2neo/">https://pypi.org/project/py2neo/</a> can also be used instead of LangChain but it is no longer supported, so it is not recommended.</p><p>A short course on the topic that we can follow: <a href="https://www.deeplearning.ai/short-courses/knowledge-graphs-rag/">https://www.deeplearning.ai/short-courses/knowledge-graphs-rag/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9cc4052a531c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Social Semantic Web and Ontologies Can Be Used to Empower Retrieval Augmented Generation (RAG)…]]></title>
            <link>https://medium.com/@busra.oguzoglu/how-social-semantic-web-and-ontologies-can-be-used-to-empower-rag-systems-7f96757d05ab?source=rss-6bc4ddbdded0------2</link>
            <guid isPermaLink="false">https://medium.com/p/7f96757d05ab</guid>
            <category><![CDATA[semanticweb]]></category>
            <category><![CDATA[knowledge-graph]]></category>
            <category><![CDATA[rag-system]]></category>
            <category><![CDATA[ontology]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Busra Oguzoglu]]></dc:creator>
            <pubDate>Tue, 08 Oct 2024 07:03:32 GMT</pubDate>
            <atom:updated>2024-10-25T10:06:00.545Z</atom:updated>
            <content:encoded><![CDATA[<h3>How Social Semantic Web and Ontologies Can Be Used to Empower Retrieval Augmented Generation (RAG) Systems</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RwoWRUajgXMnpiCC6noftA.png" /><figcaption>Image Generated with DALL-E 3</figcaption></figure><p>The <strong>Social Semantic Web</strong> can be seen as the next step in web development, combining the social interactions of online platforms with the structured, machine-readable data of the <strong>Semantic Web</strong>. For <strong>Retrieval-Augmented Generation (RAG)</strong> systems, which rely on <strong>retrieving information</strong> and <strong>creating natural language responses</strong>, the Social Semantic Web can provide a powerful way to organize and connect data. Ontologies, like those from the <strong>SIOC (Semantically Interlinked Online Communities)</strong> project, can be the key to making this data useful for RAG systems, especially when combined with methods like <strong>knowledge graphs</strong>.</p><p>Let’s take a look at how the Social Semantic Web, SIOC, and ontologies can boost RAG systems by enabling smarter, more context-aware knowledge retrieval and response generation:</p><h3>Understanding the Social Semantic Web and Ontologies</h3><p>The <strong>Social Semantic Web</strong> combines two main ideas:</p><ol><li>The <strong>Social Web</strong>: Where people share and interact through platforms like social media, blogs, and forums.</li><li>The <strong>Semantic Web</strong>: Where data is structured and machine-readable, allowing it to be connected and understood by computers.</li></ol><p>Ontologies like <strong>FOAF (Friend of a Friend)</strong> and <strong>SIOC (Semantically Interlinked Online Communities)</strong> create <strong>structured vocabularies</strong> that define relationships between people and content. For example, SIOC helps modeling <strong>online communities</strong>, connecting discussions, blogs, and user interactions across different platforms in a standardized format. These ontologies can help AI systems to understand not just <strong>what</strong> the data is but also <strong>how</strong> it relates to other information, especially in a social context.</p><h3>How Ontologies Like SIOC can be Used to Boost RAG Systems</h3><p><strong>RAG systems</strong> works by the combination of <strong>information retrieval</strong> from different data sources and <strong>generating natural language answers</strong>. The representation of the information have a big impact on how these systems work. Ontologies like <strong>SIOC</strong> can greatly improve RAG systems by providing structured knowledge about online communities and user-generated content. Here’s how:</p><ol><li><strong>Improving Knowledge Retrieval</strong>: Ontologies like SIOC organize data across social platforms, helping RAG systems pull <strong>relevant information</strong> based on relationships between users, discussions, and content. For example, in an online community, SIOC can link a blog post with forum discussions, user comments, and related content, giving the RAG system richer data to retrieve from, as well as the relationship between the given data.</li><li><strong>Understanding User Interactions</strong>: SIOC helps a RAG system understand <strong>how people interact</strong> in online communities. If the system needs to retrieve information from a forum, SIOC can provide context about who participated, what the discussion was about, and how it links to other related content. This leads to more <strong>accurate</strong>and <strong>context-aware</strong> retrieval, therefore potentially reduce hallucination as well.</li><li><strong>Building Knowledge Graphs</strong>: Knowledge graphs are built on <strong>linked data</strong>, where information is connected across platforms. Using SIOC and other ontologies, RAG systems can create <strong>interconnected knowledge graphs</strong> that represent discussions, user interactions, and content in a way that computers can understand. This helps the system pull in the most relevant, connected data, improving the quality of the responses it generates.</li></ol><p>Ontologies like <strong>SIOC</strong> and the idea of <strong>Social Semantic Web</strong> can be critical to improve <strong>RAG systems</strong> especially in social context by offering structured, context-rich data from different social platforms. These technologies can help RAG systems retrieve more relevant information, understand user interactions, and build interconnected knowledge graphs, all of which enhance the system’s ability to generate accurate and meaningful responses. As AI continues to evolve, the integration of ontologies and knowledge graphs will become increasingly important in making data smarter, more connected, and more useful for retrieval and generation tasks. By leveraging the strengths of the Social Semantic Web, we can push RAG systems to new levels of performance and intelligence.</p><p>For more info on SIOC, visit: <a href="http://www.sioc-project.org/">http://www.sioc-project.org/</a></p><h4>Further reading:</h4><ul><li>John G. Breslin, Uldis Bojārs, Alexandre Passant, Sergio Fernández, <a href="https://en.wikipedia.org/wiki/Stefan_Decker">Stefan Decker</a>. <a href="http://www.w3.org/2008/09/msnws/papers/sioc.html">SIOC: Content Exchange and Semantic Interoperability Between Social Networks</a>. W3C Workshop on the Future of Social Networking, 15–16 January 2009, Barcelona, Spain.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7f96757d05ab" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The EU AI Act: How Will It Shape the Future of Social Media?]]></title>
            <link>https://medium.com/@busra.oguzoglu/the-eu-ai-act-how-will-it-shape-the-future-of-social-media-320c29376052?source=rss-6bc4ddbdded0------2</link>
            <guid isPermaLink="false">https://medium.com/p/320c29376052</guid>
            <category><![CDATA[ai-ethics]]></category>
            <category><![CDATA[eu-ai-act]]></category>
            <category><![CDATA[ai-safety]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[ai-act-compliance]]></category>
            <dc:creator><![CDATA[Busra Oguzoglu]]></dc:creator>
            <pubDate>Wed, 02 Oct 2024 10:47:21 GMT</pubDate>
            <atom:updated>2024-10-02T10:47:21.896Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction to the EU AI Act</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nJ7gbPWWn64MMfdx7c5nfA.png" /><figcaption>Generated with DALL-E 3</figcaption></figure><p>Artificial Intelligence (AI) has become a key player in the evolution of social media, driving everything from personalized content recommendations to automated moderation systems. However, as AI’s influence grows, so too do concerns over privacy, transparency, and ethical issues like algorithmic bias and the spread of misinformation. Recognizing the potential risks and benefits of AI, the European Union has introduced the <strong>EU AI Act</strong> — a pioneering regulatory framework aimed at ensuring the responsible use of AI across all sectors, including social media.</p><p>The <strong>EU AI Act</strong> is designed to be the world’s first comprehensive regulation of AI, classifying AI systems based on their risk level and setting strict standards for their use. This regulation is crucial for companies operating in the European market, as it will shape how they design, deploy, and monitor AI-powered technologies. Social media platforms, in particular, will be significantly impacted by these regulations, as AI plays a central role in how content is curated, moderated, and distributed on their platforms.</p><p>In this blog post, we will explore how the EU AI Act is likely to affect social media, from requiring more transparent algorithms to regulating AI-driven moderation tools, ultimately reshaping how platforms interact with their users and protect public interests.</p><h3>AI in Social Media Today</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O123hEsmXQGRkClU7ejzkQ.png" /><figcaption>Generated with DALL-E 3</figcaption></figure><p>Artificial Intelligence has become the driving force behind many features on social media platforms, influencing everything from what we see in our newsfeeds to how content is moderated. AI tools play a critical role in shaping user experiences, ensuring that platforms can operate efficiently while catering to individual preferences at scale.</p><h4>1. Content Recommendations</h4><p>One of the most prominent uses of AI in social media is content recommendation. AI algorithms analyze vast amounts of user data, such as likes, shares, search history, and interactions, to predict what content a user would like to see. Platforms like Instagram, X and TikTok use AI to curate personalized feeds, keeping users engaged by showing them content that aligns with their interests. While this enhances user experience, it also raises concerns about the creation of “filter bubbles,” where users are only exposed to viewpoints that reinforce their existing beliefs.</p><h4>2. Automated Content Moderation</h4><p>With billions of posts and comments generated daily, AI-driven content moderation is crucial for maintaining community standards. Platforms like YouTube and X rely on models to automatically detect and remove content that violates policies, such as hate speech, misinformation, or graphic material. Although AI helps flag harmful content at scale, it has been criticized for its limitations in understanding context, often resulting in the wrongful removal of content or allowing harmful material to slip through. (Or creating biased content, “filter bubbles”)</p><h4>3. Targeted Advertising</h4><p>Social media platforms generate significant revenue through targeted advertising, and AI is central to this process. AI systems analyze user behavior and preferences to serve personalized ads to users. By leveraging advanced data analytics and machine learning models, advertisers can reach specific demographics with pinpoint accuracy. However, this raises questions about user privacy, as AI systems often rely on collecting vast amounts of personal data to deliver tailored ad experiences.</p><h4>4. Chatbots and Customer Engagement</h4><p>AI-driven chatbots have transformed how businesses engage with customers on social media. These bots, powered by natural language processing (NLP) and machine learning, can provide real-time responses to customer inquiries, helping brands deliver seamless support experiences.</p><p>While AI offers exciting possibilities for social media innovation, it also introduces challenges. Algorithmic bias, privacy concerns, and the spread of misinformation are significant issues that must be addressed. The upcoming EU AI Act will aim to address many of these challenges, pushing platforms toward more ethical and transparent AI usage.</p><h3>EU AI Act’s Impact on Social Media</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3zhL4BUq40ZTEdpI7TWv-g.png" /><figcaption>Generated with DALL-E 3</figcaption></figure><p>As social media platforms heavily rely on AI to power key functions like content moderation, personalized recommendations, and targeted advertising, the <strong>EU AI Act</strong> will have significant implications for these platforms and their users.</p><h4>1. Risk-Based Classification of AI</h4><p>The <strong>EU AI Act</strong> categorizes AI systems based on the level of risk they pose, ranging from minimal to high-risk applications. Social media platforms, especially in the areas of content moderation and recommendation algorithms, could potentially fall into the “high-risk” category due to their influence on public discourse, mental health, and political outcomes. High-risk AI systems will face stricter requirements, including impact assessments, monitoring, and reporting to ensure compliance.</p><p>Popular platforms like X, TikTok, and Instagram may need to rethink how their AI models handle sensitive content. Content moderation tools, which rely on AI to flag or remove harmful content, could be subject to more rigorous standards to ensure they are not biased or censoring legitimate speech.</p><h4>2. Transparency Requirements</h4><p>One of the most important aspects of the EU AI Act is the increased demand for <strong>transparency</strong>. Under the new law, social media companies will be required to provide users with clearer information about how their AI systems operate. For example, recommendation algorithms, which determine what content appears in a user’s feed, will need to be more transparent in explaining why certain posts are promoted or demoted.</p><p>This shift toward transparency means that users will have more insight into how their data is being used and why they are being shown specific ads or content. It also offers an opportunity for users to better understand how AI shapes their social media experience, potentially fostering more trust in these platforms.</p><h4>3. Addressing Bias and Discrimination</h4><p>Algorithmic bias is a known issue in AI-driven social media platforms, where certain groups may be unfairly treated by AI systems, such as content moderation algorithms that disproportionately impact minority communities. The EU AI Act seeks to address this problem by enforcing stricter guidelines for detecting and mitigating bias in high-risk AI systems.</p><p>Social media platforms will need to ensure that their AI models do not propagate bias, whether through content moderation or targeted advertising. This could lead to the adoption of more sophisticated AI tools capable of better detecting context and reducing discriminatory practices in automated decision-making.</p><h4>4. Accountability and Governance</h4><p>The Act emphasizes the need for <strong>accountability</strong>, meaning that social media companies must ensure robust governance of their AI systems. Companies will be required to implement risk management systems, perform regular audits of their AI models, and keep detailed logs of their AI’s decision-making processes. This is intended to prevent AI systems from causing harm, either by mistake or through misuse.</p><p>For social media platforms, this will likely mean heavier compliance costs and more complex internal procedures to monitor the functioning of their AI systems. While this might slow down the rollout of new AI features, it could ultimately lead to safer and more user-friendly social media environments.</p><h4>5. User Protection and Privacy</h4><p>The Act also extends protections to users by regulating how AI systems handle personal data. Social media companies will need to comply with strict data protection standards, ensuring that AI-driven tools respect user privacy. In particular, AI systems that involve profiling or personalized advertising will be closely monitored to ensure they do not exploit personal data in harmful ways.</p><p>For users, this means enhanced privacy rights and the ability to better control how their data is used. Platforms will need to be more transparent about their data collection practices, which could help restore some of the trust that has been lost by privacy scandals that happened over years.</p><h3>Conclusion</h3><p>The EU AI Act represents a significant step toward regulating the fast-evolving field of artificial intelligence. For social media platforms, this legislation will bring both challenges and opportunities. On the one hand, compliance with the Act’s stringent requirements will require major changes to how platforms develop and deploy AI. On the other hand, the Act encourages a more transparent, accountable, and ethical approach to AI, which could foster greater trust and safety in online spaces.</p><p>With the EU AI Act, social media companies will need to rethink their AI strategies, ensuring that their technologies are not only innovative but also responsible and aligned with new regulatory expectations. The future of social media will be shaped not just by AI’s capabilities, but by how well it is governed in the interest of users.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=320c29376052" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Udacity Capstone Project: Customer Segmentation for Arvato Financial Solutions]]></title>
            <link>https://medium.com/@busra.oguzoglu/udacity-capstone-project-customer-segmentation-for-arvato-financial-solutions-6d13e4f83f11?source=rss-6bc4ddbdded0------2</link>
            <guid isPermaLink="false">https://medium.com/p/6d13e4f83f11</guid>
            <category><![CDATA[udacity]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[arvato]]></category>
            <category><![CDATA[capstone-project]]></category>
            <category><![CDATA[ml-engineering]]></category>
            <dc:creator><![CDATA[Busra Oguzoglu]]></dc:creator>
            <pubDate>Mon, 23 Sep 2024 08:04:18 GMT</pubDate>
            <atom:updated>2024-09-23T08:04:18.421Z</atom:updated>
            <content:encoded><![CDATA[<p>In this project, we analyze demographic data for a mail-order sales company in Germany and compare it against the general population’s demographics. The goal is to identify which parts of the population are most likely to become customers based on historical data. By applying machine learning algorithms and clustering techniques, we can uncover insights into customer behavior and predict potential customer segments for targeted marketing efforts.</p><p>The project consists of three main stages:</p><ol><li>Data Preprocessing and Cleaning</li><li>Unsupervised Learning for Customer Segmentation</li><li>Predictive Modeling for Targeting New Customers</li></ol><p>In this post, I will walk you through each stage, sharing the steps and results along the way. Let’s begin!</p><h3>Data Exploration and Cleaning</h3><p>Before diving into any modeling, it’s crucial to first understand the data and address any issues such as missing values, outliers, and inconsistencies. This step ensures that the data is prepared and suitable for further analysis.</p><h4>1. Data Exploration:</h4><p>We began by loading and exploring the two main datasets: <strong>AZDIAS</strong> (general population demographics) and <strong>CUSTOMERS</strong> (demographics of mail-order company customers). During this step, we checked for missing values, duplicates, and analyzed the distribution of each feature.</p><p>Key points during exploration:</p><ul><li><strong>Missing Values</strong>: Some columns had a high percentage of missing values (up to 98% in some cases).</li><li><strong>Data Types</strong>: A mix of categorical and numerical features.</li><li><strong>Outliers</strong>: Certain features contained outliers, which were identified through visualizations and summary statistics.</li></ul><p>Statistics:</p><pre>AZDIAS Missing Values Summary (Top 5 columns):<br>ALTER_KIND4 890016<br>ALTER_KIND3 885051<br>ALTER_KIND2 861722<br>ALTER_KIND1 810163<br>EXTSEL992 654153</pre><p>CUSTOMERS Missing Values Summary (Top 5 columns):</p><pre>ALTER_KIND4           191416<br>ALTER_KIND3           190377<br>ALTER_KIND2           186552<br>ALTER_KIND1           179886<br>KK_KUNDENTYP          111937</pre><h4>2. Handling Missing Values &amp; Data Cleaning:</h4><p>To clean the data, we implemented the following strategies:</p><ul><li><strong>Dropping Features</strong>: Columns with more than 50% missing values were dropped.</li><li><strong>Imputing Missing Values</strong>: For numerical columns, we imputed missing values using the mode (most frequent value) for each feature. For categorical columns, specific strategies were applied (e.g., imputing missing values with “Unknown” for categories).</li></ul><h4>3. Handling Categorical Data:</h4><p>Some columns had too many distinct values, making them unsuitable for modeling (especially for one-hot encoding). For example:</p><ul><li><strong>CAMEO_DEU_2015</strong>: 45 unique values</li><li><strong>CAMEO_INTL_2015</strong>: 43 unique values</li></ul><h4>4. Handling Highly Correlated Features:</h4><p>Using correlation analysis, we identified features that were highly correlated (correlation &gt; 0.9). Redundant features were removed to avoid multicollinearity. Below is a snippet of some of the highly correlated features:</p><pre>Feature 1          Feature 2          Correlation<br>PLZ8_ANTG4         KBA13_ANTG4        0.899595<br>KBA05_KRSHERST1    KBA05_HERST1       0.889293<br>D19_BANKEN_DATUM   D19_BANKEN_ONLINE_DATUM  0.887769</pre><h4>5. Data Normalization:</h4><p>Before applying dimensionality reduction and clustering, we normalized the numerical data. This ensures that each feature contributes equally to the analysis, especially in algorithms like PCA and KMeans, which are sensitive to the scale of input data.</p><h3>Dimensionality Reduction: Principal Component Analysis (PCA)</h3><p>Given the high dimensionality of the data, dimensionality reduction was essential to reduce the computational complexity and improve model performance. We used <strong>Principal Component Analysis (PCA)</strong> to project the data into a lower-dimensional space while preserving as much variance as possible.</p><ul><li><strong>PCA Output</strong>: We reduced the feature set from 366 columns to a more manageable number of components that captured around 95% of the variance.</li></ul><p>This step helped prepare the data for the clustering process, which we will explain in the next section.</p><h3>KMeans Clustering</h3><p>To better understand customer segmentation and identify which demographic clusters best describe the company’s customer base, we applied <strong>KMeans Clustering</strong> to both the general population (AZDIAS) and customer datasets. Clustering allows us to group similar individuals together based on shared characteristics, which can help in identifying patterns.</p><h4>Key Steps in Clustering:</h4><ol><li><strong>KMeans Algorithm</strong>: We started with KMeans and used the <strong>Elbow Method</strong> to determine the optimal number of clusters for segmentation. After evaluating the graph, we selected <strong>8 clusters</strong> as the optimal value for segmentation.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*BFzhH9RJ1aQCIyWesRlhHw.png" /></figure><p><strong>2. Cluster Analysis</strong>: After segmenting the population and customer datasets, we analyzed the characteristics of each cluster. Below is a summary of key features within the clusters. The analysis helped us to identify clusters that are overrepresented in the customer data compared to the general population.</p><h4>Cluster Analysis Table:</h4><p>This table displays mean values for key demographic features for each cluster:</p><pre>| Cluster | LNR       | AKT_DAT_KL | ALTER_HH | ANZ_KINDER | ANZ_PERSONEN | ARBEIT | D19_VERSICHERUNGEN |<br>|---------|-----------|------------|----------|------------|--------------|--------|--------------------|<br>| 0       | 651721.24 | 1.20       | 0.15     | 0.0015     | 1.01         | 3.99   | 0.0006             |<br>| 1       | 696480.18 | 5.37       | 8.84     | 0.0708     | 1.38         | 3.15   | 0.0009             |<br>| 2       | 290449.41 | 4.95       | 9.28     | 0.0660     | 1.43         | 4.03   | 0.0005             |<br>| 3       | 700135.98 | 6.56       | 11.16    | 0.1523     | 1.43         | 2.86   | 0.0010             |<br>| 4       | 695326.44 | 3.53       | 8.33     | 0.0402     | 1.55         | 2.56   | 0.0015             |<br>| 5       | 694169.31 | 4.90       | 7.15     | 0.0166     | 1.29         | 3.57   | 0.0004             |<br>| 6       | 642978.46 | 6.53       | 10.57    | 0.0953     | 1.32         | 3.75   | 0.0034             |<br>| 7       | 661329.10 | 2.66       | 15.64    | 0.4176     | 2.75         | 2.88   | 0.2458             |</pre><h4>Cluster Distributions:</h4><p>We then compared the distribution of clusters between the general population and the customer base. Some key insights:</p><ul><li><strong>Cluster 0</strong> is overrepresented in the customer data, with about <strong>39%</strong> of customers belonging to this cluster compared to <strong>12.5%</strong> in the general population.</li><li><strong>Clusters 4 and 7</strong> are also overrepresented, while clusters like <strong>3, 2, and 6</strong> are significantly underrepresented.</li></ul><h4>General Population Cluster Distribution:</h4><pre>Cluster 3: 15.1%<br>Cluster 4: 14.2%<br>Cluster 5: 14.1%<br>Cluster 6: 13.4%<br>Cluster 0: 12.5%<br>Cluster 7: 10.6%<br>Cluster 2: 10.4%<br>Cluster 1: 9.5%</pre><h4>Customer Cluster Distribution:</h4><pre>Cluster 0: 38.9%<br>Cluster 4: 25.3%<br>Cluster 7: 15.4%<br>Cluster 1: 9.5%<br>Cluster 5: 7.7%<br>Cluster 2: 1.7%<br>Cluster 3: 0.8%<br>Cluster 6: 0.5%</pre><h4>Overrepresented Clusters:</h4><ul><li><strong>Cluster 0</strong>: Customers in this cluster are <strong>1.6 times</strong> more likely to belong to this cluster compared to the general population.</li><li><strong>Cluster 4</strong>: Customers are <strong>2.85 times</strong> more likely to belong to this cluster.</li><li><strong>Cluster 7</strong>: Customers are <strong>3.49 times</strong> more likely to belong to this cluster.</li></ul><h4>Underrepresented Clusters:</h4><ul><li><strong>Cluster 3</strong>: Customers are <strong>91.53 times</strong> less likely to be part of this cluster compared to the general population.</li><li><strong>Cluster 6</strong>: This is the most underrepresented, with <strong>139.44 times</strong> fewer customers compared to the general population.</li></ul><p>The visualizations below shows the distribution of clusters in both the population and customer datasets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/989/1*zf5yEqYNQRD42Rnqnvb5Jg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/868/1*95jFr9X98cfaL43ovaC9cA.png" /></figure><h3>Observations from the Results:</h3><ul><li><strong>Cluster 0 and Cluster 4</strong>: These clusters show a significantly higher number of customers compared to other clusters, meaning that the individuals in these demographic clusters are more likely to convert into customers. This implies that features defining these clusters could be crucial for customer targeting.</li><li><strong>Cluster 1 and Cluster 7</strong>: These clusters also show overrepresentation but to a lesser extent compared to clusters 0 and 7. This suggests that while individuals in these clusters can still be potential customers, they may not be as strongly linked to conversion.</li><li><strong>Cluster 6 and Cluster 3</strong>: These clusters are underrepresented in customer data compared to the general population. Individuals in these clusters are less likely to become customers, and this could be due to specific demographic factors or behavioral differences.</li></ul><h4>General Population Summary for Overrepresented Clusters (Cluster 0, 4, 7)</h4><ul><li>Cluster 0: This group shows a lower number of people per household (ANZ_PERSONEN: 1.01) and relatively higher engagement in labor (ARBEIT: 3.99).</li><li>Cluster 4: Households in this cluster tend to have more children (ANZ_KINDER: 0.04) and more people (ANZ_PERSONEN: 1.55), suggesting that this cluster might be more family-oriented.</li><li>Cluster 7: This group has the highest number of people per household (ANZ_PERSONEN: 2.75) and is characterized by a significant amount of car ownership (BALLRAUM: 4.66) and engagement in car-related purchases like insurance (D19_LETZTER_KAUF_BRANCHE_D19_VERSICHERUNGEN).</li></ul><p>These observations point to the fact that different demographic characteristics strongly influence conversion rates. Knowing these traits, businesses can tailor their marketing strategies to target people from clusters that are overrepresented in the customer base, thus improving their conversion rates and marketing efficiency.</p><h3>Supervised Learning</h3><p>After the unsupervised clustering, we moved on to a supervised approach, specifically to predict which individuals in the <em>mailout</em> dataset would most likely become customers.</p><h4>XGBoost Model</h4><p>The XGBoost model is an ensemble-based gradient-boosting model, known for its ability to handle complex data. We chose XGBoost due to its robust nature and tendency to perform well on structured data like ours. However, the ROC-AUC score of 0.7143 indicated that while XGBoost captured some useful information, there was room for improvement.</p><h4>Logistic Regression Model</h4><p>We followed up with a Logistic Regression model and achieved a much better ROC-AUC score of 0.8270. Interestingly, logistic regression, which is a simpler model compared to XGBoost, performed better in this case.</p><h3>Discussion of Results</h3><p><strong>Why ROC-AUC as the Evaluation Metric?</strong></p><p>ROC-AUC (Receiver Operating Characteristic — Area Under Curve) is an appropriate metric because:</p><ol><li>It handles binary classification tasks well.</li><li>It is particularly useful when dealing with imbalanced datasets (which we had), as it provides a measure of how well the model distinguishes between the positive and negative classes, rather than relying solely on accuracy.</li><li>It shows the trade-off between sensitivity (true positive rate) and specificity (false positive rate), which gives a better understanding of the classifier’s performance.</li></ol><p><strong>Why did Logistic Regression Perform Better than XGBoost?</strong></p><p>Even though XGBoost is a more complex and powerful algorithm, Logistic Regression performed better for several reasons:</p><ul><li><strong>Imbalanced Dataset</strong>: Logistic Regression is often more stable with highly imbalanced datasets like ours. The XGBoost model might have overfitted or failed to properly balance the class distribution despite our efforts to address the imbalance.</li><li><strong>Feature Simplicity</strong>: Logistic Regression works well with simpler feature sets, and after dimensionality reduction and clustering, the features may have been more linear, making Logistic Regression more appropriate for this task.</li><li><strong>Regularization</strong>: Logistic Regression allows for effective regularization, preventing overfitting, especially in sparse or high-dimensional datasets like the one we worked with after encoding.</li></ul><p><strong>Comments on the Model Evaluation Results</strong></p><p>The logistic regression results were quite interesting:</p><ul><li>The <strong>recall for class 1</strong> (the customers) was very high (0.74), indicating that the model successfully identified a significant portion of the customers.</li><li>The <strong>precision for class 1</strong> was lower (0.12), meaning that the model classified a lot of non-customers as customers.</li><li>The model accuracy was 74%, but because of the imbalance, this number alone doesn’t give the full picture. The ROC-AUC score gives a better understanding of the model’s performance, especially with imbalanced data. A score of 0.8270 suggests that the logistic regression model was effective in distinguishing between customers and non-customers. This score is an improvement over the XGBoost model, which had a lower ROC-AUC of 0.7143.</li></ul><h3>Next Steps and Improvements</h3><ul><li><strong>Feature Engineering</strong>: Creating more meaningful features or transforming existing ones could further improve performance, especially by capturing more complex relationships between demographic variables and customer behavior.</li><li><strong>SMOTE or Over-Sampling</strong>: Instead of under-sampling, we could explore Synthetic Minority Over-sampling Technique (SMOTE) to generate synthetic samples of the minority class, allowing the model to learn from a more balanced dataset without losing valuable data.</li><li><strong>Hyperparameter Tuning for XGBoost</strong>: Given the complexity of XGBoost, more extensive hyperparameter tuning could potentially improve its performance, making it a more competitive model against logistic regression.</li><li><strong>Ensemble Methods</strong>: Another approach to improve performance could be to combine models (e.g., blending logistic regression and XGBoost) to leverage the strengths of both.</li></ul><p>In summary, the logistic regression model, despite its simplicity, provided better results on this imbalanced dataset. Its ability to generalize and correctly recall a higher proportion of customers made it a stronger candidate. However, there’s still room for improvement by further refining features, balancing techniques, and model tuning.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6d13e4f83f11" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Programming for Beginners 3: Methods (Java)]]></title>
            <link>https://medium.com/@busra.oguzoglu/programming-for-beginners-3-methods-java-84af71f1db9b?source=rss-6bc4ddbdded0------2</link>
            <guid isPermaLink="false">https://medium.com/p/84af71f1db9b</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[java-programming]]></category>
            <category><![CDATA[programming-languages]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[learning-to-code]]></category>
            <dc:creator><![CDATA[Busra Oguzoglu]]></dc:creator>
            <pubDate>Mon, 26 Aug 2024 11:57:31 GMT</pubDate>
            <atom:updated>2024-08-26T11:57:31.411Z</atom:updated>
            <content:encoded><![CDATA[<p>In this blog series, fundamental concepts in Java programming language will be explained easily and quickly for beginners. These posts can be used as quick notes for the subjects, as they will focus on essential points only and can be helpful in basic programming classes and for everyone who wants to learn and use Java fast. These posts should not be considered in-depth explanations; they are meant to be easy-to-understand notes. Please treat them as such, and if you want in-depth knowledge about programming topics (which I highly recommend if you want to learn more), use sources like books from experts.</p><p>All posts and exercises can also be found on my Github page: <a href="https://github.com/busraoguzoglu/Java-Study-Materials">https://github.com/busraoguzoglu/Java-Study-Materials</a></p><p>Feel free to use the visuals but please do reference the source when you do so.</p><p>A method in Java is a collection of statements that are grouped together to perform an operation, it has inputs (can be multiple) and a single output (the return value).</p><p>Structure of a method is as follows:</p><pre>private static double findAverage(double[] numbers) {<br>    // Method Body<br>    double sum = 0.0;<br>    for (double e : numbers)<br>        sum += e;<br>    return sum / numbers.length;<br>}</pre><ul><li>private static double findAverage(double[] numbers) is the method header.</li><li>doubleis the return type.</li><li>findAverage is the method name.</li><li>double[] numbers are the method parameters.</li><li>Methods may have a return statement, they do not need to have it if their return type is void.</li></ul><h3>Method Calls:</h3><pre>private static int max(int a, int b) {<br>    int result = a;<br>    if (b &gt; a) <br>    result = b;<br>    return result;<br>}</pre><pre>int input1 = 5;<br>int input2 = 8;<br><br>int o = max(input1,input2);</pre><p>When we call max with input1 and input2, they are Argument Values. They are passed to the method parameters int a and int b.</p><p>Result is passed to the output variable o.</p><h3>Activation Record and Call Stack:</h3><p>When a method is called, an activation record (or activation frame) is created. It has the parameters and other variables of the method.</p><p>When an activation record is created for a method, it is stored in an area of the memory, referred as call stack. Call stack can also be called as runtime stack, machine stack or just stack.</p><p>When a new method is called inside a method, the caller method’s activation record stays and a new activation method is created for the method that has been called.</p><p>When a method returns, its activation record is removed from the stack.</p><p><strong>Example:</strong></p><pre>public class AppMethods {<br>    public static void main(String[] args) {<br>        int input1 = 5;<br>        int input2 = 8;<br>        int o = max(input1,input2); <br>        System.out.println(&quot;Bigger number is: &quot; + o);<br>}<br>    private static int max(int a, int b) {<br>        int result = a;<br>        if (b &gt; a) <br>        result = b;<br>        foo(result);<br>        return result;<br>    }<br><br>    private static void foo(int result) {<br>        System.out.println(&quot;Foo works&quot;);<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pZVKNWwZpFwodgd80sBduA.png" /></figure><h3>Pass by Value vs Pass by Reference:</h3><p>The arguments are passed by value to parameters when invoking a method, but it is only applicable to primitive types: int, long, float, double, boolean (for example, not an array)</p><p>This means that variables in the caller method are not affected by changes made to the parameters inside the method, if they are primitive type.</p><p>How do we pass non primitive types? Pass by Reference. We can see how that works is an example:</p><pre>public class AppPassValueReference {<br>    public static void main(String[] args) {<br>        int age = 23; // primitive type<br>        int[] numbers = {8,5,3}; // array is a reference type<br>        System.out.println(&quot;Before: Age=&quot; + age + &quot;, Numbers=&quot; + Arrays.toString(numbers));<br>        modifyValues(age, numbers);<br>        System.out.println(&quot;After : Age=&quot; + age + &quot;, Numbers=&quot; + Arrays.toString(numbers));<br>    }<br>    <br>    private static void modifyValues(int age, int[] b) {<br>        age = 2;<br>        b[0] = 2;<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mKkQtcsAaP8L_GCBxOrXkw.png" /></figure><h3>Method Overloading:</h3><p>Two or more methods can have the same name but different parameter lists, this is called method overloading.</p><p>The Java compiler determines which method to use based on the method signature</p><pre>public static int max(int num1, int num2) { /** Return the max of two int values */<br>    if (num1 &gt; num2)<br>        return num1;<br>    else<br>        return num2;<br>}<br>public static double max(double num1, double num2) { /** Find the max of two double values */<br>    if (num1 &gt; num2)<br>        return num1;<br>    else<br>        return num2;<br>}<br>public static double max(double num1, double num2, double num3) { /** Return the max of three double values */<br>    return max(max(num1, num2), num3);<br>}</pre><h3>Variable Length Arguments:</h3><p>You can pass a variable number of arguments of the same type to a method.</p><p>Only one variable-length parameter may be specified in a method, and this parameter must be the last parameter</p><p>Java treats a variable-length parameter as an array</p><pre>public static void main(String[] args) {<br>    printMax(34, 3, 3, 2, 56.5); // printMax method can process variable number of arguments <br>    printMax(4,6); // printMax method can process variable number of arguments<br>    printMax(new double[]{1, 2, 3}); // You can give an array as an argument<br>}<br>public static void printMax(double... numbers) {<br>    if (numbers.length == 0) {<br>        System.out.println(&quot;No argument passed&quot;);<br>    return;<br>}</pre><h3>Variable Scope:</h3><p>The scope of a variable is the part of the program where the variable can be referenced</p><p>The scope of a local variable starts from its declaration and continues to the end of the block that contains that variable</p><p>As an example if we create a for loop, variable i cannot be referenced outside the loop.</p><pre>for (int i = 1; i &lt;= 4; i++) <br>{<br>   // Scope of i starts<br>   ....<br>   // Scope of i ends<br>}</pre><p>This code does not work:</p><pre>public static void main(String[] args) <br>{<br>    int a = 4;<br>    int b = 7;<br>    printValues();<br>}<br>private static void printValues() {<br>    System.out.println(&quot;a is &quot; + a + &quot;, b is : &quot; + b);<br>}</pre><p>Scope of a and b is only their block, they cannot be referenced outside the main method. (We could pass them as parameters to printValues function.)</p><p>Similary, if we create a new variable inside printValues() function and try to reach it in main method, we cannot do that.</p><p>A method parameter is also a local variable: The scope of a method parameter covers the entire method but cannot be reached outside.</p><pre>private static int computeSquare(int a) {<br>    // Scope of a starts<br>    System.out.println(&quot;input is: &quot; + a);<br>    System.out.println(&quot;square of the input is : &quot; + a * a);<br>    return a * a;<br>    // Scope of a ends<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=84af71f1db9b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Generative 3D Content Generation — Stability AI Models]]></title>
            <link>https://medium.com/@busra.oguzoglu/generative-3d-content-generation-stability-ai-models-3817094ef99a?source=rss-6bc4ddbdded0------2</link>
            <guid isPermaLink="false">https://medium.com/p/3817094ef99a</guid>
            <dc:creator><![CDATA[Busra Oguzoglu]]></dc:creator>
            <pubDate>Thu, 23 May 2024 06:34:03 GMT</pubDate>
            <atom:updated>2024-05-23T06:43:36.809Z</atom:updated>
            <content:encoded><![CDATA[<h3>Generative 3D Content Generation — Stability AI Models</h3><p>This post is about a general overview of a project that I worked on to explore advanced AI models for generating high-quality 3D content from 2D images, specifically focusing on Stability AI’s Stable Zero123 and TripoSR models. These models aim to automate the conversion of 2D designs into 3D meshes, enhancing productivity in many areas especially in gaming, VR technologies by overcoming traditional 3D modeling limitations.</p><h3>Introduction</h3><h4>Topic Overview</h4><p>The rapid expansion of digital and virtual realms necessitates a significant volume of diverse, high-quality 3D content. Traditional 3D modeling techniques are labor-intensive and lack scalability, presenting a bottleneck for content creators, especially in areas like industrial design.</p><h4>Project Objective</h4><p>I have investigated two state-of-the-art AI models, Stable Zero123 and TripoSR, to automate the generation of textured 3D meshes from 2D images. The project evaluates their computational efficiency and integration with popular 3D rendering tools like Blender.</p><h3>Literature Review</h3><h4>Scaling 3D Content Generation</h4><p>Recent advancements in AI have introduced models capable of generating 3D content from 2D images, addressing the scalability issue inherent in traditional 3D modeling methods.</p><h4>Existing Models and Limitations</h4><p>Previous models often lacked geometric detail and had limited mesh topology. Stability AI’s Stable Zero123 and TripoSR aim to address these limitations, offering improved integration with tools like Blender.</p><h4>Datasets</h4><p>Both models were trained on the Objaverse dataset and tested on curated versions of the GSO and OmniObject3D datasets, providing a robust foundation for evaluating model performance.</p><h3>Model Details</h3><p>A general overview of the models are given below. Both models have multiple components that needs deep understanding on their own, and upon request I may explain how they work in detail.</p><h4>Stable Zero123</h4><p><strong>Novel Multi-view Synthesis</strong></p><ul><li>Input: A single image of an object.</li><li>Output: A series of synthesized images from different camera angles.</li></ul><p>Process:</p><ul><li>CLIP Model: Processes the input image to obtain semantic embeddings.</li><li>Variational Autoencoder (VAE): Encodes the image to get a latent representation.</li><li>Camera Trajectory Encoding: Simulates different viewing angles.</li><li>U-Net Architecture: Uses spatial and temporal attention layers to ensure consistency between frames.</li></ul><p><strong>3D Generation</strong></p><ul><li>Input: Multi-view images generated in the previous step.</li><li>Output: A 3D mesh model of the object.</li></ul><p>Process:</p><ul><li>Neural Radiance Field (NeRF) Representation: Captures the general shape and texture of the object.</li><li>Mesh Optimization: Refines the shape and texture based on the multi-view images.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gs117eO9mATtmSLnOwMbvA.png" /><figcaption>Model overview from ‘<a href="https://arxiv.org/pdf/2403.12008">SV3D: Novel Multi-view Synthesis and 3D Generation from a Single Image using Latent Video Diffusion</a>’ paper</figcaption></figure><h4>TripoSR</h4><p><strong>Image Encoding</strong></p><ul><li>Input: A single image of an object.</li><li>Output: Latent vectors representing the image.</li></ul><p>Process:</p><ul><li>Image Encoder: Projects the image into latent vectors using a vision transformer.</li></ul><p>Image-to-Triplane Decoder</p><ul><li>Input: Latent vectors from the image encoder.</li><li>Output: Triplane representation of the object.</li></ul><p>Process:</p><ul><li>Triplane Representation: Decodes latent vectors into a triplane-based NeRF.</li></ul><p><strong>3D Mesh Generation</strong></p><ul><li>Input: Triplane representation from the decoder.</li><li>Output: 3D mesh model of the object.</li></ul><p>Process:</p><ul><li>Volumetric Rendering: Renders the triplane-based NeRF outputs into a 3D mesh.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HGKcm2L2192PAD4SamS0Kw.png" /><figcaption>Overview of LRM model. Please refer to the original paper for details: ‘<a href="https://arxiv.org/abs/2311.04400">LRM: Large Reconstruction Model for Single Image to 3D</a>’</figcaption></figure><h3>Comparison and Project Experiments</h3><h4>Model Deployment and Testing</h4><p>Both models were deployed and tested on a local computer to generate 3D meshes and multi-view images. (Apple Macbook Pro with Apple M2 Pro chip and 32GB memory)</p><h4>ComfyUI</h4><p><a href="https://github.com/comfyanonymous/ComfyUI">ComfyUI</a> is a modular and extensible interface designed to simplify the workflow for deploying and testing AI models, particularly those involved in generative tasks. It provides a user-friendly graphical interface that allows users to set up, run, and visualize complex AI workflows without deep technical knowledge.</p><p>ComfyUI has a huge community behind it and different workflows for different projects can be found from: <a href="https://openart.ai/workflows/home">https://openart.ai/workflows/home</a>, <a href="https://comfyworkflows.com/">https://comfyworkflows.com/</a> and other free resources.</p><p>Features of ComfyUI:</p><ul><li>Modular Design</li><li>User-Friendly Interface</li><li>Real-Time Monitoring</li><li>Integration Capabilities</li></ul><p>Usage in the Project:</p><ul><li>Workflow Setup</li><li>Parameter Tuning</li><li>Visualization</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r7RFT448-qKLz8wvhsmO3g.png" /><figcaption>Workflow for Stable Zero123: View Generation (First part of the 3D pipeline)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Uz1w8VtuDPaVsdCA5kK-kA.png" /><figcaption>Simple workflow for TripoSR: Mesh Generation</figcaption></figure><h3>Computational Requirements and System Properties</h3><p>Stable Zero123 requires significant computational resources for training, whereas TripoSR is designed for fast inference, making it more accessible for users with limited resources.</p><h3>Output Quality and Integration</h3><p>The outputs were evaluated for geometric detail, texture quality, and compatibility with Blender. Stable Zero123 provides higher quality but is more computationally demanding. TripoSR offers a balance between quality and efficiency.</p><h3>Challenges and Solutions</h3><p>Challenges included the loss of color attributes in TripoSR’s output meshes when opened in Blender and high computational costs. Adjusting ComfyUI parameters and exploring more efficient training can be explored.</p><h3>Results</h3><h4>TripoSR: Mesh Synthesis</h4><p>The model generates meshes in around 30 seconds (note the specs of my computer, and I have used MPS), with varying quality based on the input complexity. (With the default parameters: geometry resolution set to 512, threshold is set to 50 and chunk size being 8192.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bFjgZyKTTqxoO7ZBDf234w.png" /><figcaption>Input and output image example 1: Simple Chair</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5SEl4I8S-CqCT0MGxmdIjw.png" /><figcaption>Input and output image example 2: Washing Machine</figcaption></figure><h4>Stable Zero123: Multi-View Synthesis</h4><p>The model successfully generates multi-view images with high quality.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5UNn6HqaaxQUmT13wpn-JQ.png" /><figcaption>Multi-view images of the washing machine</figcaption></figure><h3>Conclusion</h3><p>The results demonstrate that advanced AI models like Stable Zero123 and TripoSR offer promising solutions for scalable 3D content generation. While Stable Zero123 provides higher quality outputs, as it seen from the results for multi-view generation, its computational demands are more substantial. TripoSR, on the other hand, balances quality and efficiency, making it a practical choice for quick 3D reconstructions. However, especially datasets that were used for training these datasets are lacking for different types of objects. Right now, these models can generate quality outputs for only a number of objects. Future research should focus on enhancing the detail of generated models and reducing inference times to make these technologies more accessible and practical for a broader range of applications..</p><h3>References</h3><ol><li>Voleti et al. [2024]. SV3D: <a href="https://sv3d.github.io/">Novel multi-view synthesis and 3D generation from a single image using latent video diffusion.</a></li><li>Tochilkin et al. [2024]. <a href="https://arxiv.org/abs/2403.02151">TripoSR: Fast 3D object reconstruction from a single image.</a></li><li>Hong et al. [2024]. <a href="https://arxiv.org/abs/2311.04400">LRM: Large reconstruction model for single image to 3D.</a></li><li>Hu et al. [2021]. <a href="https://arxiv.org/abs/2106.09685">LoRA: Low-rank adaptation of large language models.</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3817094ef99a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>