<?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 Defne Buse Çelik on Medium]]></title>
        <description><![CDATA[Stories by Defne Buse Çelik on Medium]]></description>
        <link>https://medium.com/@daphnebuse?source=rss-6620f796da84------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Zt1kdEy3YOIZp6M0xWHSAA.jpeg</url>
            <title>Stories by Defne Buse Çelik on Medium</title>
            <link>https://medium.com/@daphnebuse?source=rss-6620f796da84------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 15 Nov 2026 07:36:01 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@daphnebuse/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[LangChain Temelleri]]></title>
            <link>https://medium.com/global-ai-hub/langchain-temelleri-10963adefccd?source=rss-6620f796da84------2</link>
            <guid isPermaLink="false">https://medium.com/p/10963adefccd</guid>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[yapay-zeka]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Defne Buse Çelik]]></dc:creator>
            <pubDate>Mon, 14 Oct 2024 20:54:56 GMT</pubDate>
            <atom:updated>2024-10-14T20:54:56.785Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/764/0*302GbD5UHWPWHEyM.png" /></figure><h4><strong>LangChain Nedir?</strong></h4><p>LangChain, doğal dil işleme projelerinin esnekliğini ve gücünü artıran yenilikçi bir çerçevedir. Büyük dil modelleri (LLM) ile derin etkileşim sağlayarak metin oluşturma, sorgulama, analiz ve veri kaynaklarıyla entegrasyon gibi çok yönlü görevler için optimize edilmiştir.</p><p>LangChain, süreçleri modüler bir yapıya dönüştürmektedir ve geliştiricilerin adım adım zincirler oluşturmalarını sağlamaktadır. Bu sayede kullanıcıların karmaşık dil işleme görevlerini tek bir çerçeve içinde ve organize bir halde ölçeklenebilir çözümleri kolaylaştırmalarını sağlar.</p><p>LangChain, LLM uygulamalarının gelişimini hızlandırmak için tasarlanmıştır. LangChain, yazılım geliştiricilerinin harici bileşenler ve veri kaynaklarıyla LLM uygulamalarını entegre ederek hızlı bir şekilde oluşturulmalarını sağlar. Geliştiriciler LangChain uygulamalarını, Python veya JavaScript / TypeScript kullanarak oluşturabilir.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/764/0*-CQTWpiAau8Qoj5W.png" /><figcaption>LangChain Bileşenleri</figcaption></figure><p>LangChain birden fazla büyük dil modelini destekler ve modeli tek bir parametre değişikliği ile değiştirmenizi sağlar. Hızlı bir şekilde birden fazla dil modelini test edebilir ve farklı kullanım durumları için farklı modeller kullanabilirsiniz. LangChain’in esnekliği, farklı LLM sağlayıcılarını ve modellerini minimum kod değişiklikleriyle test etmenizi sağlamasıdır.</p><p>LangChain’deki “chain”, bir işleme hattı (pipeline) oluşturarak uygulanacak eylemleri bir araya getirme fikrini oluşturmaktadır. Her eylem veya zincir, genel hedefi tamamlamak için işleme hattında gerekli bir adımdır. RAG modeli, kullanıcının bir soru göndermesiyle başlar. Metinden bir gömme modeli oluşturulur, vektör veritabanında soru hakkında daha fazla bağlam kazanmak için bir arama yapılır, hem orijinal soru hem de geri kazanımın bağlamı kullanılarak bir istem(prompt) oluşturulur, büyük dil modeline gönderilir.</p><p>RAG modelinde tüm adımların başarılı bir şekilde gerçekleşmesi gerekmektedir. LangChain, belirli bir yapılandırma ile belirli bir şekilde adımları bir araya getirmek için zincir yapısı sunmaktadır. Tüm LangChain kütüphaneleri, adımları uygulamayı ve güçlü işlem hatları oluşturmayı kolaylaştırmak için zincir yapısını takip etmektedir.</p><h4>Nasıl Çalışmaktadır?</h4><p>LangChain uygulamaları, kullanıcılar ile büyük dil modelleri arasında köprü oluşturarak zincirler aracılığıyla ileri geri iletişim kurmayı sağlamaktadır.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/764/0*m2YkXazdi89Me3sO.png" /></figure><p>Bir LangChain uygulamasının temel bileşenleri şunlardır:</p><p><strong>Model Etkileşimi (Model I/O)</strong>: Dil modeliyle etkileşimi yöneten, girişleri beslemek ve çıktıları çıkarmak gibi görevleri denetleyen bileşenler.</p><p><strong>Verilerin Bağlantısı ve Bilgiye Erişim (Retrieval):</strong> Bilgiye erişim bileşenleri, verimli sorgular ve erişim işlemlerine olanak tanıyan verilere erişebilir, bdönüştürebilir ve depolayabilir. İndeksler, dil sorgularını işlerken ilgili verilerin verimli bir şekilde alınmasını sağlayan, bilgileri yapılandırılmış bir şekilde düzenleyen ve depolayan veritabanları olarak hizmet eder. Bilgiye erişim öğeleri, bu harici bağlamın kullanımına yardımcı olurken bir dil modeli tarafından bir yanıtın oluşturulmasına Almayla Artırılmış Üretim (RAG) denir.</p><pre><br>from langchain.chains import RetrievalQA<br>from langchain.document_loaders import TextLoader<br>from langchain.embeddings.openai import OpenAIEmbeddings<br>from langchain.llms import OpenAI<br>from langchain.text_splitter import CharacterTextSplitter<br>from langchain.vectorstores import Chroma<br>#Document loader<br>loader = TextLoader(&quot;defnebusecelik.txt&quot;)<br>documents = loader.load()<br>#Document Transformer<br>text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0)<br>texts = text_splitter.split_documents(documents)<br>#Embedding model<br>embeddings = OpenAIEmbeddings()<br>#Vector DB to store embeddings<br>docsearch = Chroma.from_documents(texts, embeddings)<br>#Retriever being used using parameter retriever<br>qa = RetrievalQA.from_chain_type(llm=OpenAI(), chain_type=&quot;stuff&quot;, retriever=docsearch.as_retriever())<br>query = &quot;What this document about? Summarize it in a paragraph&quot;<br>qa.run(query)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/0*yJ098FjWghsgu9HF.png" /><figcaption>RAG</figcaption></figure><p><strong>Zincirler (Chains) :</strong> Zincirler, bir isteme(prompt) dayalı bir talimatı yerine getirmenin en iyi yolunu belirleyen yeniden kullanılabilir bileşenlerdir. Bir sonraki dil modeli besleme çıkışıyla birden fazla dil modeli çağrılarını bir araya getirmenizi sağlar. Bu sayede çeşitli LLM işlevleri arasında karmaşık iş akışları ve bilgi çıkarmak yer alır.</p><pre># Import LLMChain and define chain with language model and prompt as arguments.<br>from langchain.chains import LLMChain<br>chain = LLMChain(llm=llm, prompt=prompt)<br># Run the chain only specifying the input variable.<br>print(chain.run(&quot;large language model&quot;))  </pre><p><strong>İstem(Prompt) Şablonları</strong>: LangChain, farklı dil modelleriyle nasıl etkileşime girdiğinizi standartlaştırmak için istem(prompt) şablonları kullanır. Bu şablonlar, temelde yer alan büyük dil modelinden bağımsız olarak istemlerin tutarlı biçimlendirilmesini ve ifade edilmesini sağlar.</p><p>HumanMessage : Kullanıcı tarafından verilen istem</p><p>AIMessage : LLM tarafından verilen yanıt</p><p>SystemMessage: Sohbet modeline rolü hakkında bilgi aktarabileceğimiz bağlam</p><pre>from langchain.prompts import ChatPromptTemplate<br>from langchain.prompts.chat import SystemMessage, HumanMessagePromptTemplate<br>from langchain.chat_models import ChatOpenAI<br>template = ChatPromptTemplate.from_messages(<br>    [<br>        SystemMessage(<br>            content=(&quot;You are a python coder AI that helps user with bugs <br>                and writing programs&quot;)),<br>        HumanMessagePromptTemplate.from_template(&quot;{text}&quot;),<br>    ]<br>)<br>llm = ChatOpenAI()<br>llm(template.format_messages(text=&#39;Check whether a number is prime or not&#39;))</pre><p><strong>Ajanlar:</strong> Ajanlar, büyük dil modellerine ve diğer araçlara yönelik komutları düzenler ve belirli görevleri yerine getirmelerini veya belirlenmiş sorunları çözmelerini sağlar.</p><pre># Import Python REPL tool and instantiate Python agent<br>from langchain.agents.agent_toolkits import create_python_agent<br>from langchain.tools.python.tool import PythonREPLTool<br>from langchain.python import PythonREPL<br>from langchain.llms.openai import OpenAI<br>agent_executor = create_python_agent(<br>    llm=OpenAI(temperature=0.6, max_tokens=1000),<br>    tool=PythonREPLTool(),<br>    verbose=True<br>)<br>agent_executor.run(&quot;What is the solution of this problem : A triangular array of squares has one square in the first row, two in the second, and in general, k squares in the kth row for 1 \leq k \leq 11.$ With the exception of the bottom row, each square rests on two squares in the row immediately below (illustrated in given diagram). In each square of the eleventh row, a 0$ or a $1$ is placed. Numbers are then placed into the other squares, with the entry for each square being the sum of the entries in the two squares below it. For how many initial distributions of $0$&#39;s and $1$&#39;s in the bottom row is the number in the top square a multiple of $3$??&quot;)</pre><p><strong>Bellek:</strong> Uygulamaların bağlamı korumasını sağlamak için kullanılır, örneğin bir konuşmadaki önceki mesajları hatırlamak. Birçok farklı bellek türü vardır. Hepsi farklı durumlarda faydalıdır ve farklı parametrelere ve dönüş türlerine sahiptir. Langchain’in Konuşma Arabellek Belleği, konuşma geçmişini depolayan temel bir bellek arabelleğidir. Sohbet belleğinden mesajların bir listesini döndüren bir arabellek özelliğine sahiptir. Bu bellek türü, bir tartışmanın en son geçmişini depolamak ve almak için önemlidir.</p><pre>from langchain.llms import OpenAI<br>from langchain.prompts import PromptTemplate<br>from langchain.chains import LLMChain<br>from langchain.memory import ConversationBufferMemory<br>llm = OpenAI(temperature=0)<br>template = &quot;&quot;&quot;You are a nice chatbot having a conversation with a human.<br>Previous conversation:<br>{chat_history}<br>New human question: {question}<br>Response:&quot;&quot;&quot;<br>prompt = PromptTemplate.from_template(template)<br>memory = ConversationBufferMemory(memory_key=&quot;chat_history&quot;)<br>conversation = LLMChain(<br>    llm=llm,<br>    prompt=prompt,<br>    verbose=True,<br>    memory=memory<br>)</pre><h4>LangChain Mimarisi</h4><p>LangChain’in mimarisi, geliştiricilerin özel çözümler oluşturmak için bileşenleri karıştırıp eşleştirmelerine olanak tanıyan modüler ve genişletilebilir şekilde tasarlanmıştır.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/0*Yz5NjFW73iESt_GS.png" /><figcaption>Langchain Mimarisi</figcaption></figure><ul><li>Bir modelin örneklenmesi— Codex, GPT-4 vb. için bir Python örneği oluşturun.</li><li>Mantığın tanımlanması — Python’da uygulama mantığı ve iş akışları yazın.</li><li>Zincirleme yürütme — Python kodunuzdan dil modelini çağırın.</li><li>Sonuçları önbelleğe alma — Yeniden hesaplamayı önlemek için model çıktılarını önbelleğe alın.</li><li>Önbelleklerin paylaşılması — Verimlilik için önbellek dağıtın.</li><li>Modelleri karşılaştırma— Farklı modelleri karşılaştırın</li><li>Ölçekte çalıştırma— Sunucusuz platformlardan yararlanın</li></ul><p>Temel mimari öğeler şunları içermektedir:</p><ul><li><strong>LangChain:</strong> LangChain, geliştiricilerin karmaşık görevleri yönetilebilir adımlara bölerek kolaylaştıran zincirler halinde birden fazla bileşeni birleştirmelerine olanak tanır. Bu modülerlik, hata ayıklamayı ve bakımı basitleştirir.</li><li><strong>LangGraph:</strong> LangGraph,büyük dil modellerini kullanarak durum bilgisi olan, çok aktörlü uygulamaların oluşturulmasını sağlar. Adımları bir grafikteki kenarlar ve düğümler olarak modeller ve uygulama akışının görsel bir temsilini sağlar.</li><li><strong>LangServe:</strong> LangServe, geliştiricilerin LangChain uygulamalarını REST API’leri olarak dağıtmalarına olanak tanır ve bunları mevcut sistemlere ve iş akışlarına entegre etmeyi kolaylaştırır.</li><li><strong>LangSmith:</strong> LangSmith, büyük dil modeli uygulamalarının hata ayıklama, test etme ve izleme araçlarını sağlayarak geliştiricilerin çözümlerini performans ve güvenilirlik açısından optimize edebilmelerini sağlar.</li></ul><h4>LangChain Kullanımın Faydaları</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/764/0*P0Q9KWwRBWU9UfvO.png" /></figure><ul><li><strong>Azaltılmış Geliştirme Süresi:</strong> Önceden oluşturulmuş bileşenler ve standartlaştırılmış arayüzler, sıfırdan büyük dil modeli uygulamaları oluşturmaya kıyasla geliştirme süresini önemli ölçüde azaltır.</li><li><strong>Modüler Tasarım: </strong>LangChain, geliştiricilerin dil modeli sağlayıcılarını kolayca değiştirmelerine veya tüm uygulamayı etkilemeden iş akışının belirli bölümlerini değiştirmelerine olanak tanıyan modülerliği teşvik eder.</li><li><strong>Gelişmiş Performans: </strong>LangChain, iletişimi kolaylaştırarak ve olası hataları ele alarak büyük dil modeli etkileşimlerini optimize eder. Daha hızlı yanıt sürelerine ve dil modeli kaynaklarının daha verimli kullanımına yol açabilir.</li><li><strong>Gelişmiş Yetenekler:</strong> LangChain, temel dil modeli etkileşiminin ötesinde işlevlerin kilidini açar. Bilgi entegrasyonu, vektör veritabanları ve özelleştirilebilir iş akışları, geliştiricilerin daha karmaşık ve bilgilendirici uygulamalar oluşturmasını sağlar.</li><li><strong>Aracılık İşlevselliği: </strong>LangChain, çeşitli dil modeli aramalarını, veri alma prosedürlerini ve işleme aşamalarını birleştirerek karmaşık görevleri yürütme yeteneğine sahip kendi kendini yöneten varlıklar olan “ajanlar” kavramını sunar. Ajanlar genişletilebilir ve özelleştirilebilirdir ve geliştiricilere karmaşık yapay zeka odaklı iş akışları tasarlama özgürlüğü sunar. Geliştiriciler, ajanları kullanarak çeşitli veri kaynaklarıyla akıllıca etkileşim kuran karmaşık süreçleri otomatikleştiren ve çok adımlı faaliyetleri gerçekleştiren dinamik uygulamalar oluşturabilir. Bu özellik sayesinde daha akıllı çözümler mümkün hale gelir ve uygulamaların kullanışlılığı ve verimliliği artar.</li></ul><h4>LangChain Kullanımı</h4><p>LangChain’i indirebilmek için:</p><pre>pip install langchain</pre><p>LangChain’i içe aktarmak ve OpenAI gibi bir model oluşturmak için:</p><pre>from langchain import OpenAI<br>ai = OpenAI()</pre><p>Modeli özelleştirmek için:</p><pre>ai = OpenAI(<br>    model_name=&quot;code-davinci-002&quot;, # Codex model<br>    temperature=0.7,               # Higher values mean more random<br>    max_tokens=100,               # Maximum output length<br>    frequency_penalty=0,          # Penalize repetitive text<br>    presence_penalty=0            # Penalize off-prompt wandering<br>)</pre><p>Sıcaklık parametresi (temperature), oluşturulan içerikteki yaratıcılık ve tutarlılık arasındaki dengeyi kontrol etmek için kullanılır.</p><p>Düşük sıcaklık (0,0–0,4): Gerçekçi ve kesin yanıtlar için.<br>Orta sıcaklık (0,5–0,7): Genel içerik oluşturma, yaratıcılık ve tutarlılığı dengeleme için.<br>Daha yüksek sıcaklık (0,8–1,0): Yenilikçi ve beklenmedik çıktılar üretir, beyin fırtınası kampanyaları, sosyal medya içeriği ve bir konu hakkında yeni bakış açıları için harikadır.</p><h4>Metin Üretimi</h4><pre>import langchain<br>ai = langchain.OpenAI()<br>def generate_post(title, author):<br>  prompt = f&quot;Generate a blog post on &#39;{title}&#39; by {author}:&quot;<br>  return ai.generate(prompt)print(generate_post(&quot;Using LangChain&quot;, &quot;Defne Buse Celik&quot;))image to grayscale</pre><p>Yalnızca bir başlık ve yazar verildiğinde tüm bir blog yazısı oluşturmak için Codex’i kullanır. Sonuç bir insan tarafından yazılmış gibi tutarlı bir şekilde okunan, çoklu paragraflı sentetik metindir. Bu üreteci, istenen uzunluk, ton, dahil edilecek anahtar kelimeler, gönderi kalitesini karşılayana kadar döngüsel oluşturma, harici bir bilgi tabanı kullanarak gerçekleri doğrulama, taslakların yinelemeli olarak iyileştirilmesine izin verme gibi daha fazla girdi parametresi ekleyerek geliştirebiliriz.</p><h4><strong>Arama ve Soru Cevaplama</strong></h4><pre>import langchain<br>codebase = load_codebase() <br>def semantic_search(query):  results = []  for func in codebase:    doc = func.__doc__<br>    <br>    prompt = f&quot;Query: {query}\nDoc: {doc}\nRelevance:&quot;<br>    score = ai.generate(prompt)<br>    <br>    results.append({<br>      &quot;function&quot;: func,<br>      &quot;relevance&quot;: score  <br>    })<br>  <br>  return sorted(results, key=lambda x: x[&quot;relevance&quot;], reverse=True)[:5]print(semantic_search(&quot;Convert &quot;))</pre><p>Sorgu ile her fonksiyonun doküman dizisi arasındaki anlamsal alaka düzeyini değerlendirmek için Codex’i kullanır. En alakalı ilk 5 fonksiyonu döndürür. Önbellek dekoratörü, sonuçları yeniden kullanarak pahalı model sorgularını en aza indirir. Diğer arama ve QA uygulamaları arasında belge alma motorları, akıllı ürün önericisi, müşteri desteği için sohbet robotları, bilgi tabanları ve uzman sistem bulunur. Büyük dil modelleri birçok arama ve soru cevaplama alanı için akıl yürütme yetenekleri sağlar.</p><h4>Veri İşleme ve Analizi</h4><pre>resumes_db = []<br>ai = OpenAI()@ai.cache<br>def extract_resume(resume_text)<br>  name_prompt = f&quot;Extract the candidate name from this resume:\n{resume_text}\nName:&quot;<br>  email_prompt = f&quot;Extract the candidate email from this resume:\n{resume_text}\nEmail:&quot; <br>  email = ai.generate(email_prompt)<br>  <br>  return {<br>    &quot;name&quot;: name,<br>    &quot;email&quot;: email <br>  }<br>for path in resume_paths:<br>  text = open(path).read()<br>  <br>  data = extract_resume(text)  <br>  resumes_db.append(data)print(resumes_db)</pre><p>Özgeçmiş metnini ayrıştırmak ve yapılandırılmış alanları çıkarmak için Codex’i kullanır. Diğer veri işleme yetenekleri arasında belgeleri kategorilere ayırma, metinden varlıkları çıkarma, hakkında soruları yanıtlama, uzun raporları özetleme yer alır.</p><h4><strong>Akıllı Ajanlar</strong></h4><p>LangChain, Codex gibi modeller kullanarak sanal asistanlar, sohbet robotları ve müşteri hizmetleri temsilcileri oluşturmayı mümkün kılar.</p><pre>histories = {} # Track conversation history<br>ai = OpenAI()  def converse(message, history=[]):<br>  <br>  history.append(message)    prompt = f&quot;The conversation history is:\n\n{history}\n\nHuman: {message}\nAgent:&quot;  response = ai.generate(prompt)  history.append(response)  return responsewhile True:  input = get_user_message()<br>  <br>  response = converse(input, histories[user_id])  print(response)  histories[user_id] = histories[user_id]</pre><p>Codex’ten daha alakalı yanıtlar üretmek için konuşma geçmişi bağlamı kullanılır. Dil modelleri, istekleri anlayan ve doğal konuşmalar yapan asistanlar sağlar.</p><h4>Performans İçin Önbelleğe Alma</h4><p>Büyük dil modellerini sorgulamak zaman alıcı ve yoğun kaynak kullanımına sebep olabilir. LangChain, model çıktılarını kalıcı hale getirmek ve bunların yeniden hesaplanmasını önlemek için çıktıları yerleşik önbelleğe alma sağlar.</p><pre>@ai.cache<br>def generate_summary(text):<br>  return ai.generate(&quot;Summarize this: &quot; + text)<br>print(generate_summary(&quot;Some text&quot;)) <br>print(generate_summary(&quot;Some text&quot;)) </pre><p>Bu, tekrarlanan çağrılarda pahalı model sorgularını atlayarak zamandan ve paradan tasarruf sağlar. Bazı yapılandırılabilir önbelleğe alma parametreleri; önbellek depolama seçeneği — Yerel dosya, Redis veya SQLite, özel önbellek anahtarları ve manuel önbelleğe alma, önbellek boyutu sınırları ve LRU çıkarma, zamana dayalı önbellek süresi sonu, geliştirme sırasında önbelleği yok sayma. Önbelleğe alma, dil modelleri uygulamalarında performansı ve maliyetleri optimize etmeye yardımcı olur.</p><h4>Model Karşılaştırması</h4><pre>from langchain.benchmark import Benchmark<br>benchmark = Benchmark(<br>    openai=OpenAI(),<br>    parti=Parti(), <br>    jurassic=Jurassic()   <br>)outputs = benchmark.run(&quot;What is LangChain?&quot;, n=1)print(outputs)</pre><p>İstemi 3 modelin hepsinde çalıştırır ve yanıtlarını bir sözlükte döndürür. Daha sonra; çıktı doğruluğu ve semantiği, gereken belirteç sayısı, API çağrısı başına maliyet, genel sonuç kalitesi gibi farklılıkları programatik olarak analiz edebilebilir. Karşılaştırmalı değerlendirme, uygulamanın işlevsel ve ekonomik ihtiyaçları için doğru modeli belirlemeye yardımcı olacaktır.</p><h4>LangChain Kullanım Alanları Örnekleri</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/0*FS54RisCh-ptt0oO.png" /><figcaption>Langchain Kullanım Alanları Örnekleri</figcaption></figure><p><strong>Sohbet Robotları:</strong> Geliştiriciler, kullanıcılarla doğal olarak etkileşim kuran, müşteri desteği sağlayan, soruları yanıtlayan ve işlemleri kolaylaştıran akıllı sohbet robotları oluşturabilir.</p><p><strong>Üretken Soru-Cevaplama (GQA): </strong>LangChain, mevcut en güncel verilere dayalı yanıtlar üreten sistemler oluşturmak için kullanılabilir ve yanıtların doğruluğunu ve alakalılığını artırır.</p><p><strong>Belge Analizi ve Özetleme: </strong>Büyük miktarda metni analiz edip özetleyebilen araçların geliştirilmesini sağlayarak önemli içgörülerin çıkarılmasını kolaylaştırır.</p><p><strong>Kod Analizi: </strong>LangChain, olası hatalar veya güvenlik açıkları için kodu analiz etmek ve yazılım kalitesini artırmak için kullanılabilir.</p><p><strong>Veri Artırma: </strong>Makine öğrenimi modellerini eğitmek için yararlı olan mevcut veri kümelerine benzer yeni veriler üretebilir.</p><h4>Sonuç</h4><p>Sonuç olarak, LangChain büyük dil modelleri (LLM) ile entegre uygulamaların geliştirilmesinde önemli bir rol oynar. Sağlam ve esnek mimarisiyle LangChain, geliştiricilerin dil modelleriyle karmaşık zincirler oluşturmasına ve çeşitli görevleri daha verimli bir şekilde çözmesine olanak tanır. Ayrıca, LangSmith entegrasyonuyla bu zincirlerin izlenmesi ve optimize edilmesi daha kolay hale gelir.Almayla Artırılmış Üretim (RAG) gibi teknikler, yalnızca dil modellerine dayanmayan, aynı zamanda harici bilgi kaynaklarına erişen ve daha doğru ve güncel sonuçlar sunan sistemlerin oluşturulmasını sağlar. LangChain tarafından sunulan bu esneklik ve ölçeklenebilirlik, özellikle müşteri desteği, arama motorları, bilgi tabanlı asistanlar ve içerik yönetimi gibi alanlarda önemli avantajlar sağlar. Geliştiriciler, LangChain kullanarak daha dinamik, kullanıcı dostu ve özelleştirilebilir LLM tabanlı çözümler oluşturabilir.</p><h4>Referanslar</h4><p>LangChain Documentation. Available at: <a href="https://python.langchain.com/">https://python.langchain.com</a></p><p>Sakamoto, A. (2023, July 24). LangChain Chains: What is LangChain. Kanaries. Available at: <a href="https://docs.kanaries.net/articles/langchain-chains-what-is-langchain">https://docs.kanaries.net/articles/langchain-chains-what-is-langchain</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=10963adefccd" width="1" height="1" alt=""><hr><p><a href="https://medium.com/global-ai-hub/langchain-temelleri-10963adefccd">LangChain Temelleri</a> was originally published in <a href="https://medium.com/global-ai-hub">Global AI Hub</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Quick Look At LangChain]]></title>
            <link>https://medium.com/global-ai-hub/a-quick-look-at-langchain-d1155491fdee?source=rss-6620f796da84------2</link>
            <guid isPermaLink="false">https://medium.com/p/d1155491fdee</guid>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[langchain]]></category>
            <dc:creator><![CDATA[Defne Buse Çelik]]></dc:creator>
            <pubDate>Wed, 02 Oct 2024 12:19:51 GMT</pubDate>
            <atom:updated>2024-10-02T12:19:51.566Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lLJskZXwfgOvUYd7.png" /></figure><h4><strong>What is LangChain?</strong></h4><p>LangChain is an innovative framework that enhances the flexibility and power of natural language processing projects. By enabling deep interaction with large language models (LLMs), it is optimized for versatile tasks such as text generation, querying, analysis and integration with data sources.</p><p>LangChain transforms processes into a modular structure, allowing developers to create step-by-step chains. This enables users to handle complex language processing tasks within a single framework efficiently and in an organized manner, facilitating scalable solutions.</p><p>LangChain is designed to accelerate the development of LLM applications. LangChain enables software developers to quickly build LLM applications by integrating with external components and data sources. Developers can build LangChain applications with Python or JavaScript/TypeScript.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/819/1*c5y9rdhRc8568an-O_IdhQ.png" /><figcaption>LangChain Components</figcaption></figure><p>LangChain supports multiple LLMs and allows you to replace one with another with a single parameter change. You can quickly test multiple LLMs for compatibility and use different models for different use cases. LangChain’s flexibility allows you to test different LLM providers and models with minimal code changes.</p><p>The “chain” in LangChain brings the idea of putting AI actions together in order to create a processing pipeline. Each action or chain is a needed step in the pipeline to complete the overall goal. Thinking about the RAG pattern, it starts with the user submitting a question. An embedding is created from that text, a lookup is done on a vector database to gain more context about the question, then a prompt is created using both the original question and the context from the retrieval. The prompt is submitted to the LLM which responds with an intelligent completion of the prompt.</p><p>All the steps in the RAG pattern need to happen in succession. If there are any errors along the way, the processing should stop. LangChain offers the chain construct to attach steps together in a specific way with a specific configuration. All LangChain libraries follow this chain construct to make it very easy to move steps around and create powerful processing pipelines.</p><h4>How does it work?</h4><p>LangChain applications bridge users and LLMs, communicating back and forth with the LLM through chains.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xABhzWI0xooumza7.png" /></figure><p>The key components of a LangChain application are:</p><ul><li><strong>Model Interaction (Model I/O)</strong>: Components that manage the interaction with the language model, overseeing tasks like feeding inputs and extracting outputs.</li><li><strong>Data Connection and Retrieval:</strong> Retrieval components can access, transform and store data allowing for efficient queries and retrieval. Indexes serve as databases that organize and store information in a structured manner, enabling efficient retrieval of relevant data when processing language queries. Retrieval elements help in the usage of this external context while the generation of a response by an LLM is called the Retrieval Augmented Generation (RAG).</li></ul><pre><br>from langchain.chains import RetrievalQA<br>from langchain.document_loaders import TextLoader<br>from langchain.embeddings.openai import OpenAIEmbeddings<br>from langchain.llms import OpenAI<br>from langchain.text_splitter import CharacterTextSplitter<br>from langchain.vectorstores import Chroma<br>#Document loader<br>loader = TextLoader(&quot;defnebusecelik.txt&quot;)<br>documents = loader.load()<br>#Document Transformer<br>text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0)<br>texts = text_splitter.split_documents(documents)<br>#Embedding model<br>embeddings = OpenAIEmbeddings()<br>#Vector DB to store embeddings<br>docsearch = Chroma.from_documents(texts, embeddings)<br>#Retriever being used using parameter retriever<br>qa = RetrievalQA.from_chain_type(llm=OpenAI(), chain_type=&quot;stuff&quot;, retriever=docsearch.as_retriever())<br>query = &quot;What this document about? Summarize it in a paragraph&quot;<br>qa.run(query)<br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*_34xzzT3hJ2S5FM3zWe6mQ.png" /><figcaption>RAG</figcaption></figure><ul><li><strong>Chains:</strong> Chains are reusable components that determine the best way to fulfill an instruction based on a prompt. It allows you to chain together multiple LLM calls with the output of one LLM feeding into the next. This enables complex workflows and information extraction across various LLM functionalities.</li></ul><pre># Import LLMChain and define chain with language model and prompt as arguments.<br>from langchain.chains import LLMChain<br>chain = LLMChain(llm=llm, prompt=prompt)<br># Run the chain only specifying the input variable.<br>print(chain.run(&quot;large language model&quot;))  </pre><ul><li><strong>Prompt Templates</strong>: LangChain utilizes prompt templates to standardize how you interact with different LLMs. These templates ensure consistent formatting and phrasing of prompts, regardless of the underlying LLM.</li></ul><p>HumanMessage : The prompt given by the user</p><p>AIMessage : The response given by the LLM</p><p>SystemMessage: Its a context that we can pass to the chatmodel about its role.</p><pre>from langchain.prompts import ChatPromptTemplate<br>from langchain.prompts.chat import SystemMessage, HumanMessagePromptTemplate<br>from langchain.chat_models import ChatOpenAI<br>template = ChatPromptTemplate.from_messages(<br>    [<br>        SystemMessage(<br>            content=(&quot;You are a python coder AI that helps user with bugs <br>                and writing programs&quot;)),<br>        HumanMessagePromptTemplate.from_template(&quot;{text}&quot;),<br>    ]<br>)<br>llm = ChatOpenAI()<br>llm(template.format_messages(text=&#39;Check whether a number is prime or not&#39;))</pre><ul><li><strong>Agents:</strong> Agents orchestrate commands directed at LLMs and other tools, enabling them to perform specific tasks or solve designated problems.</li></ul><pre># Import Python REPL tool and instantiate Python agent<br>from langchain.agents.agent_toolkits import create_python_agent<br>from langchain.tools.python.tool import PythonREPLTool<br>from langchain.python import PythonREPL<br>from langchain.llms.openai import OpenAI<br>agent_executor = create_python_agent(<br>    llm=OpenAI(temperature=0.6, max_tokens=1000),<br>    tool=PythonREPLTool(),<br>    verbose=True<br>)<br>agent_executor.run(&quot;What is the solution of this problem : A triangular array of squares has one square in the first row, two in the second, and in general, k squares in the kth row for 1 \leq k \leq 11.$ With the exception of the bottom row, each square rests on two squares in the row immediately below (illustrated in given diagram). In each square of the eleventh row, a 0$ or a $1$ is placed. Numbers are then placed into the other squares, with the entry for each square being the sum of the entries in the two squares below it. For how many initial distributions of $0$&#39;s and $1$&#39;s in the bottom row is the number in the top square a multiple of $3$??&quot;)</pre><ul><li><strong>Memory:</strong> Allow applications to retain context, for example remembering the previous messages in a conversation. There are many different types of memory. They are all helpful in different situations and have different parameters and return types. Langchain’s Conversation Buffer Memory is a basic memory buffer that stores the conversation history. It has a buffer property that returns a list of messages from the chat memory. This type of memory is important for storing and retrieving the most recent history of a discussion.</li></ul><pre>from langchain.llms import OpenAI<br>from langchain.prompts import PromptTemplate<br>from langchain.chains import LLMChain<br>from langchain.memory import ConversationBufferMemory<br>llm = OpenAI(temperature=0)<br>template = &quot;&quot;&quot;You are a nice chatbot having a conversation with a human.<br>Previous conversation:<br>{chat_history}<br>New human question: {question}<br>Response:&quot;&quot;&quot;<br>prompt = PromptTemplate.from_template(template)<br>memory = ConversationBufferMemory(memory_key=&quot;chat_history&quot;)<br>conversation = LLMChain(<br>    llm=llm,<br>    prompt=prompt,<br>    verbose=True,<br>    memory=memory<br>)</pre><h4>LangChain Architecture</h4><p>The architecture of LangChain is designed to be modular and extensible, allowing developers to mix and match components to create tailored solutions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*tAXmlyTORIQP9PA4J4y99g.png" /><figcaption>LangChain Architecture</figcaption></figure><ul><li>Instantiating a model — Create a Python instance for Codex, GPT-4, etc.</li><li>Defining logic — Write application logic and workflows in Python</li><li>Chaining execution — Invoke the LLM from your Python code</li><li>Caching results — Cache model outputs to avoid recomputing</li><li>Sharing caches — Distribute caches for efficiency</li><li>Benchmarking models — Compare different models</li><li>Running at scale — Leverage Serverless platforms</li></ul><p>Key architectural elements include:</p><ul><li><strong>LangChain: </strong>LangChain allows developers to combine multiple components into chains which facilitate complex tasks by breaking them down into manageable steps. This modularity simplifies debugging and maintenance.</li><li><strong>LangGraph:</strong> This component enables the construction of stateful, multi-actor applications using LLMs. It models steps as edges and nodes in a graph, providing a visual representation of the application flow.</li><li><strong>LangServe:</strong> LangServe allows developers to deploy LangChain applications as REST APIs, making it easier to integrate them into existing systems and workflows.</li><li><strong>LangSmith:</strong> This platform provides tools for debugging, testing and monitoring LLM applications, ensuring that developers can optimize their solutions for performance and reliability.</li></ul><h4>Benefits of using LangChain</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Rtco9S5oXneSWBVn.png" /></figure><ul><li><strong>Reduced Development Time:</strong> Pre-built components and standardized interfaces significantly reduce development time compared to building LLM applications from scratch.</li><li><strong>Modular Design: </strong>LangChain promotes modularity, allowing developers to easily swap LLM providers or modify specific parts of the workflow without affecting the entire application.</li><li><strong>Improved Performance:</strong> LangChain optimizes LLM interactions by streamlining communication and handling potential errors. This can lead to faster response times and more efficient use of LLM resources.</li><li><strong>Enhanced Capabilities:</strong> LangChain unlocks functionalities beyond basic LLM interaction. Knowledge integration, vector databases and customizable workflows empower developers to build more sophisticated and informative applications.</li><li><strong>Agentic Functionality: </strong>LangChain presents the notion of “agents,” which are self-governing entities that possess the ability to carry out intricate tasks by combining several LLM searches, data retrieval procedures, and processing stages. These agents are extensible and customizable and offer developers the freedom to design complex AI-driven workflows. By utilizing agents, developers can create dynamic applications that interact intelligently with several data sources, automate complex processes, and carry out multi-step activities. More sophisticated and intelligent solutions are made possible by this feature, which improves the usefulness and efficiency of applications.</li></ul><h4><strong>Using LangChain</strong></h4><p>For install LangChain:</p><pre>pip install langchain</pre><p>Then import LangChain and instantiate a model like OpenAI:</p><pre>from langchain import OpenAI<br>ai = OpenAI()</pre><p>Some ways to customize the model:</p><pre>ai = OpenAI(<br>    model_name=&quot;code-davinci-002&quot;, # Codex model<br>    temperature=0.7,               # Higher values mean more random<br>    max_tokens=100,               # Maximum output length<br>    frequency_penalty=0,          # Penalize repetitive text<br>    presence_penalty=0            # Penalize off-prompt wandering<br>)</pre><p>The temperature parameter is used to control the balance between creativity and consistency the generated content.</p><ul><li>Lower temperature (0.0–0.4): For factual and precise responses.</li><li>Moderate temperature (0.5–0.7): Ideal for general content creation, balancing creativity and consistency.</li><li>Higher temperature (0.8–1.0): Generate innovative and unexpected outputs, great for brainstorming campaigns, social media content and fresh perspectives on a topic.</li></ul><h4>Text Generation</h4><pre>import langchain<br>ai = langchain.OpenAI()<br>def generate_post(title, author):<br>  prompt = f&quot;Generate a blog post on &#39;{title}&#39; by {author}:&quot;<br>  return ai.generate(prompt)print(generate_post(&quot;Using LangChain&quot;, &quot;Defne Buse Celik&quot;))image to grayscale</pre><p>This uses Codex to generate an entire blog post given just a title and author. The result is multi-paragraph synthetic text that reads coherently like a human wrote it. We can evolve this generator by accepting more input parameters like desired length, tone, keywords to include, looping generation until post meets quality thresholds, validating facts using an external knowledge base, allowing iterative refinement of drafts.</p><h4>Search and Question Answering</h4><pre>import langchain<br>codebase = load_codebase() <br>def semantic_search(query):  results = []  for func in codebase:    doc = func.__doc__<br>    <br>    prompt = f&quot;Query: {query}\nDoc: {doc}\nRelevance:&quot;<br>    score = ai.generate(prompt)<br>    <br>    results.append({<br>      &quot;function&quot;: func,<br>      &quot;relevance&quot;: score  <br>    })<br>  <br>  return sorted(results, key=lambda x: x[&quot;relevance&quot;], reverse=True)[:5]print(semantic_search(&quot;Convert &quot;))</pre><p>This leverages Codex to assess semantic relevance between the query and each function’s docstring. It returns the top 5 most relevant functions. The cache decorator minimizes expensive model queries by reusing results. Other search and QA applications include document retrieval engines, intelligent product recommender, chatbots for customer support, knowledge bases and expert system LLMs provide reasoning capabilities perfect for many search and question answering domains.</p><h4>Data Processing and Analytics</h4><pre>resumes_db = []<br>ai = OpenAI()@ai.cache<br>def extract_resume(resume_text)<br>  name_prompt = f&quot;Extract the candidate name from this resume:\n{resume_text}\nName:&quot;<br>  email_prompt = f&quot;Extract the candidate email from this resume:\n{resume_text}\nEmail:&quot; <br>  email = ai.generate(email_prompt)<br>  <br>  return {<br>    &quot;name&quot;: name,<br>    &quot;email&quot;: email <br>  }<br>for path in resume_paths:<br>  text = open(path).read()<br>  <br>  data = extract_resume(text)  <br>  resumes_db.append(data)print(resumes_db)</pre><p>This uses Codex to parse resume text and extract structured fields. Other data manipulation capabilities include classifying documents into categories, extracting entities from text, answering questions about , summarizing long reports into key insights Intelligent Agents</p><p>LangChain makes creating virtual assistants, chatbots, and customer service agents possible using models like Codex.</p><pre>histories = {} # Track conversation history<br>ai = OpenAI()  def converse(message, history=[]):<br>  <br>  history.append(message)    prompt = f&quot;The conversation history is:\n\n{history}\n\nHuman: {message}\nAgent:&quot;  response = ai.generate(prompt)  history.append(response)  return responsewhile True:  input = get_user_message()<br>  <br>  response = converse(input, histories[user_id])  print(response)  histories[user_id] = histories[user_id]</pre><p>This uses the conversation history context to generate more relevant responses from Codex. LLMs enable delightful assistants that understand requests and hold natural conversations.</p><h4>Caching for Performance</h4><p>Querying large language models can be time-consuming and resource intensive. LangChain provides built-in caching to persist model outputs and avoid recomputing them.</p><pre>@ai.cache<br>def generate_summary(text):<br>  return ai.generate(&quot;Summarize this: &quot; + text)<br>print(generate_summary(&quot;Some text&quot;)) <br>print(generate_summary(&quot;Some text&quot;)) </pre><p>This saves time and money by skipping expensive model queries on repeated calls. Some configurable caching parameters; choice of cache storage — Local file, Redis, or SQLite, custom cache keys and manual caching, cache size limits and LRU eviction,time-based cache expiry, ignoring cache during development. Caching helps optimize performance and costs in production LLM applications.</p><h4>Benchmarking Models</h4><pre>from langchain.benchmark import Benchmark<br>benchmark = Benchmark(<br>    openai=OpenAI(),<br>    parti=Parti(), <br>    jurassic=Jurassic()   <br>)outputs = benchmark.run(&quot;What is LangChain?&quot;, n=1)print(outputs)</pre><p>This runs the prompt on all 3 models and returns their responses in a dictionary. You can then programmatically analyze differences in; output accuracy and semantics, number of tokens required, cost per API call, overall resultant quality.</p><p>Benchmarking helps determine the right model for your application’s functional and economic needs.</p><h4>Use Cases of LangChain</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*WH0uvkO2gbOqcdfz5mEeYQ.png" /><figcaption>LangChain Use Cases</figcaption></figure><p><strong>Chatbots:</strong> Developers can create intelligent chatbots that interact with users naturally, providing customer support, answering queries and facilitating transactions.</p><p><strong>Generative Question-Answering (GQA): </strong>LangChain can be used to build systems that generate answers based on the most up-to-date data available, enhancing the accuracy and relevance of responses.</p><p><strong>Document Analysis and Summarization: </strong>The framework enables the development of tools that can analyze and summarize large volumes of text, making it easier to extract key insights.</p><p><strong>Code Analysis: </strong>LangChain can be employed to analyze code for potential bugs or security vulnerabilities, improving software quality.</p><p><strong>Data Augmentation: </strong>The framework can generate new data that is similar to existing datasets, which is useful for training machine learning models.</p><h4>Conclusion</h4><p>In conclusion, LangChain plays a crucial role in the development of applications integrated with large language models (LLMs). With its robust and flexible architecture, LangChain allows developers to build complex chains with LLMs, solving various tasks more efficiently. Additionally, with LangSmith integration, monitoring and optimizing these chains becomes easier. Techniques like Retrieval-Augmented Generation (RAG) enable the creation of systems that not only rely on language models but also access external information sources, delivering more accurate and up-to-date results. This flexibility and scalability offered by LangChain provide significant advantages, particularly in areas like customer support, search engines,knowledge-based assistants and content management. Developers can create more dynamic, user-friendly and customizable LLM-based solutions using LangChain.</p><p>References</p><p>LangChain Documentation. Available at: <a href="https://python.langchain.com/">https://python.langchain.com</a></p><p>Sakamoto, A. (2023, July 24). LangChain Chains: What is LangChain. Kanaries. Available at: <a href="https://docs.kanaries.net/articles/langchain-chains-what-is-langchain">https://docs.kanaries.net/articles/langchain-chains-what-is-langchain</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d1155491fdee" width="1" height="1" alt=""><hr><p><a href="https://medium.com/global-ai-hub/a-quick-look-at-langchain-d1155491fdee">A Quick Look At LangChain</a> was originally published in <a href="https://medium.com/global-ai-hub">Global AI Hub</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Quick Look At The Principal Component Analysis (PCA)]]></title>
            <link>https://medium.com/@daphnebuse/a-quick-look-at-the-principal-component-analysis-pca-9c955f638eea?source=rss-6620f796da84------2</link>
            <guid isPermaLink="false">https://medium.com/p/9c955f638eea</guid>
            <dc:creator><![CDATA[Defne Buse Çelik]]></dc:creator>
            <pubDate>Wed, 02 Oct 2024 11:59:51 GMT</pubDate>
            <atom:updated>2024-10-02T11:59:51.685Z</atom:updated>
            <content:encoded><![CDATA[<p>Here you will learn what the Principal Component Analysis (PCA) is, its advantages/disadvantages and its implementation in Python. I hope you like!</p><h4>1. What is the Principal Component Analysis?</h4><p>Principal Component Analysis (PCA) is a commonly used statistical technique for dimensionality reduction and data compression. PCA aims to transform a set of correlated variables into a smaller set of uncorrelated variables, known as principal components, while still preserving as much of the original variation as possible. PCA has widespread applications in various fields, including image and speech recognition, finance, genetics, and social sciences. It can also be used to find hidden patterns if the data has high dimensions. In finance, PCA is often used for portfolio optimization and risk management, where it can be used to identify the underlying risk factors and to construct portfolios that are diversified across these factors. In image and speech recognition, PCA is used to extract the most important features from high-dimensional data sets, which can then be used for classification and clustering. In genetics, PCA is used to identify the genetic variation that underlies complex traits and diseases, and to identify the populations that are most genetically similar or dissimilar to each other.</p><p>PCA is based on the notion of variance. The principal components are chosen in such a way that they account for the maximum amount of variance in the data set. In other words, the first principal component represents the direction of maximum variance in the data, the second principal component represents the direction of the second-highest variance, and so on. The principal components are orthogonal, which means that they are uncorrelated and independent of each other. This is how it can be interpreted.</p><p>The interpretation of the principal components can be challenging, especially when there are many variables involved. However, some general guidelines can be used to interpret the loadings of the principal components. Loadings represent the correlation between each variable and the principal component. Large positive loadings indicate that a variable has a strong positive relationship with the principal component, while large negative loadings indicate that a variable has a strong negative relationship with the principal component. Loadings close to zero indicate that a variable is not strongly related to the principal component.</p><p>Technically, PCA works when data in a higher dimensional space is mapped to data in a lower dimensional space, provided that the variance of data in a lower dimensional space is maximum. It includes a series of steps such as constructing the covariance matrix of the data, calculating the eigenvectors of this matrix, and determining the eigenvectors corresponding to the largest eigenvalue.</p><p>PCA can also be seen as a projection of the data onto a lower-dimensional space. The first principal component represents the direction of maximum variance in the data, and subsequent principal components represent the direction of maximum variance that is orthogonal to the previous components. This means that the principal components capture the most important information in the data while discarding the least important information.</p><h4>2. What is the PCA working principle?</h4><p><strong>2.1 Standardize the data</strong></p><p>PCA assumes that the data is standardized, which means that each variable has a mean of zero and a standard deviation of one. This step is necessary to ensure that all variables are on the same scale.</p><p><strong>2.2 Calculate the covariance matrix</strong></p><p>The covariance matrix measures the relationship between each pair of variables. It shows how much two variables vary together. The diagonal elements of the covariance matrix represent the variance of each variable.</p><p><strong>2.3 Calculate the eigenvectors and eigenvalues</strong></p><p>The eigenvectors and eigenvalues of the covariance matrix represent the principal components and their associated variance. The eigenvectors represent the direction of the principal components, and the eigenvalues represent the amount of variance explained by each principal component.</p><p><strong>2.4 Choose the number of principal components</strong></p><p>The number of principal components to retain depends on the amount of variance that needs to be preserved. A common rule of thumb is to retain the principal components that explain at least 70–80% of the total variance.</p><p><strong>2.5 Transform the data</strong></p><p>The data is transformed by multiplying the standardized data by the matrix of eigenvectors. This results in a new set of variables, which are the principal components.</p><h4><strong>3. Several Variants of PCA</strong></h4><p>PCA is a versatile technique that can be applied to various types of data, including numerical, categorical, and mixed data. For numerical data, PCA is based on the correlation matrix, which measures the linear relationship between each pair of variables. For categorical data, PCA is based on the contingency table, which measures the association between each pair of categories. For mixed data, PCA can be based on the correlation matrix of the numerical variables and the contingency table of the categorical variables.</p><p><strong>3.1 Kernel PCA</strong></p><p>This is a nonlinear version of PCA that uses a kernel function to map the data into a higher-dimensional space, where linear separation is easier to achieve.</p><p><strong>3.2 Incremental PCA</strong></p><p>This is a variant of PCA that can handle large data sets by processing the data in small batches.</p><p><strong>3.3 Sparse PCA</strong></p><p>This is a variant of PCA that encourages sparsity in the loadings, which means that only a small subset of the variables are used in each principal component.</p><p><strong>3.4 Robust PCA</strong></p><p>This is a variant of PCA that is less sensitive to outliers and can handle data with missing values.</p><h4>4. Advantages and Disadvantages</h4><p><strong>4.1 Advantages</strong></p><p>· It reduces the dimensionality of the data, which makes it easier to visualize and analyze.</p><p>· It helps to identify the underlying structure of the data, which can be useful in identifying patterns and relationships between variables.</p><p>· It can be used to remove noise and redundant information from the data.</p><p>· Another important property of PCA is that the eigenvalues of the covariance matrix represent the amount of variance explained by each principal component. The sum of the eigenvalues is equal to the total variance of the data. This allows us to calculate the proportion of variance explained by each principal component, and to choose the number of principal components to retain based on a desired level of variance preservation.</p><p><strong>4.2 Disadvantages</strong></p><p>· It assumes that the data is linear and normally distributed, which may not be true in all cases.</p><p>· It can be sensitive to outliers, which can affect the principal components and their associated variance.</p><p>· It can be difficult to interpret the principal components, especially if there are many variables involved.</p><h4>5. Coding with Python</h4><pre>import pandas as pd<br>import numpy as np<br>import matplotlib.pyplot as plt<br>from sklearn.decomposition import PCA<br>from sklearn.preprocessing import StandardScaler<br>from sklearn.datasets import load_iris<br><br>#import data<br>iris = load_iris()<br>data = pd.DataFrame(data=iris.data, columns=iris.feature_names)<br>print(data.head())<br><br>#standardization<br>scaler = StandardScaler()<br>data_scaled = scaler.fit_transform(data)<br><br>iris_scaled = pd.DataFrame(data=data_scaled, columns=iris.feature_names)<br>print(iris_scaled.head())</pre><pre>#fit and transform the data using the PCA object<br>pca = PCA(n_components=2)<br>PCA= pca.fit_transform(data_scaled)<br><br>prop_var = pca.explained_variance_ratio_<br>eigenvalues = pca.explained_variance_<br><br>pca_iris = pd.DataFrame(data = PCA, columns = [&#39;PC1&#39;, &#39;PC2&#39;])<br>print(pca_iris.head())</pre><pre><br>def plot(score,coef,labels=None):<br> <br>    xs = score[:,0]<br>    ys = score[:,1]<br>    n = coef.shape[0]<br>    scalex = 1.0/(xs.max() - xs.min())<br>    scaley = 1.0/(ys.max() - ys.min())<br>    plt.scatter(xs * scalex,ys * scaley,<br>                s=5, <br>                color=&#39;purple&#39;)<br> <br>    for i in range(n):<br>        plt.arrow(0, 0, coef[i,0], <br>                  coef[i,1],color = &#39;blue&#39;,<br>                  alpha = 0.5)<br>        plt.text(coef[i,0]* 1.15, <br>                 coef[i,1] * 1.15, <br>                 labels[i], <br>                 color = &#39;orange&#39;, <br>                 ha = &#39;center&#39;, <br>                 va = &#39;center&#39;)<br> <br>    plt.xlabel(&quot;PC{}&quot;.format(1))<br>    plt.ylabel(&quot;PC{}&quot;.format(2))    <br>    plt.figure()<br><br><br>plt.title(&#39;Biplot of PCA&#39;)<br>plot(PCA, np.transpose(pca.components_), list(iris.feature_names))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/446/1*IPTXZ5vCKW8XIJf5QFVXFQ.png" /></figure><h4>6- Conclusion</h4><p>In conclusion, PCA is a powerful tool for dimensionality reduction and data compression. Understanding the steps involved in performing PCA and its limitations is important for ensuring that it is used appropriately and effectively.</p><p>References</p><p><a href="https://www.turing.com/kb/guide-to-principal-component-analysis">Step-By-Step Guide to Principal Component Analysis With Example</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9c955f638eea" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Quick Look At Linear Regression]]></title>
            <link>https://medium.com/@daphnebuse/a-quick-look-at-linear-regression-79332421544a?source=rss-6620f796da84------2</link>
            <guid isPermaLink="false">https://medium.com/p/79332421544a</guid>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[regression]]></category>
            <category><![CDATA[supervised-learning]]></category>
            <category><![CDATA[linear-regression]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Defne Buse Çelik]]></dc:creator>
            <pubDate>Thu, 31 Aug 2023 11:05:53 GMT</pubDate>
            <atom:updated>2023-08-31T11:05:53.835Z</atom:updated>
            <content:encoded><![CDATA[<p>Here you will learn what Linear Regression algorithm is. I hope you like my writing!</p><h4><strong>Content</strong></h4><ul><li>What is Linear Regression?</li><li>Types of Linear Regression</li><li>Types of Linear Regression Line</li><li>Assumption for Linear Regression Model</li><li>Simple Linear Regression Formula</li><li>Multiple Linear Regression Formula</li><li>Understanding the Slope and Intercept</li><li>Key Ideas of Linear Regression</li><li>What is Loss function?</li><li>What is Cost function?</li><li>Linear Regression with Gradient Descent</li><li>Linear Regression Model Performance</li></ul><h4>What is Linear Regression?</h4><p>Linear regression is an algorithm that provides a linear relationship between an independent variable and a dependent variable to predict the outcome of future events. It is a statistical method used in data science and machine learning for predictive analysis.</p><p>The dependent features are called the <strong>dependent variables</strong>, <strong>outputs</strong> or <strong>responses</strong>. The independent features are called the <strong>independent variables</strong>, <strong>inputs</strong>, <strong>regressors</strong> or <strong>predictors</strong>.</p><p>The independent variable is also the predictor or explanatory variable that remains unchanged due to the change in other variables. However, the dependent variable changes with fluctuations in the independent variable. The regression model predicts the value of the dependent variable, which is the response or outcome variable being analyzed or studied.</p><p>Thus, linear regression is a supervised learning algorithm that simulates a mathematical relationship between variables and makes predictions for continuous or numeric variables such as sales, salary, age, product price, etc.</p><p>It helps determine; if a independent variable does a good job in predicting the dependent variable or which independent variable plays a significant role in predicting the dependent variable.</p><h4>Types of Linear Regression</h4><p><strong>Simple Linear Regression: </strong>If a single independent variable is used to predict the value of a numerical dependent variable, then such a Linear Regression algorithm is called Simple Linear Regression.</p><p>You can use simple linear regression when you want to know:</p><ol><li>How strong the relationship is between two variables.</li><li>The value of the dependent variable at a certain value of the independent variable.</li></ol><p><strong>Multiple Linear Regression:</strong> If more than one independent variable is used to predict the value of a numerical dependent variable, then such a Linear Regression algorithm is called Multiple Linear Regression. The independent variables can be continuous or categorical.</p><h4><strong>Types of Linear Regression Line</strong></h4><p>A linear line showing the relationship between the dependent and independent variables is called a <strong>regression line</strong>.</p><p><strong>Positive Linear Relationship: </strong>If the dependent variable increases on the Y-axis and independent variable increases on X-axis, then such a relationship is termed as a Positive linear relationship.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/328/1*DAIc65UlCnoham68Eynmjg.png" /></figure><p><strong>Negative Linear Relationship: </strong>If the dependent variable decreases on the Y-axis and independent variable increases on the X-axis, then such a relationship is called a negative linear relationship.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/352/1*M5ZOAVsceiXWrFsepw0zbA.png" /></figure><h4>Assumption for Linear Regression Model</h4><p>Linear regression is a powerful tool for understanding and predicting the behavior of a variable, however, it needs to meet a few conditions in order to be accurate and dependable solutions.</p><p>1. <strong>Linearity</strong>: The independent and dependent variables have a linear relationship with one another. This implies that changes in the dependent variable follow those in the independent variable(s) in a linear fashion.</p><p>2. <strong>Independence</strong>: The observations in the dataset are independent of each other. This means that the value of the dependent variable for one observation doesn’t depend on the value of the dependent variable for another observation.</p><p>3. <strong>Homoscedasticity</strong>: Across all levels of the independent variable(s), the variance of the errors is constant. This indicates that the amount of the independent variable(s) has no impact on the variance of the errors.</p><p>4. <strong>Normality</strong>: The errors in the model are normally distributed.</p><p>5. <strong>No multicollinearity</strong>: There is no high correlation between the independent variables. This indicates that there is little or no correlation between the independent variables.</p><h4>Simple Linear Regression Formula</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/143/1*TETOCRIUSDZnCJUhlG6GlQ.png" /><figcaption>Simple Linear Regression formula</figcaption></figure><ul><li><strong>y</strong> is the predicted value of the dependent variable (y) for any given value of the independent variable (x).</li><li><strong>B0</strong> is the intercept, the predicted value of y when the x is 0.</li><li><strong>B1</strong> is the regression coefficient — how much we expect y to change as x increases.</li><li><strong>x</strong> is the independent variable.</li><li><strong>e</strong> is the error of the estimate, or how much variation there is in our estimate of the regression coefficient.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*Naz_PjUcqr5vBZ3i-cIa-w.jpeg" /></figure><pre> from sklearn.linear_model import LinearRegression  <br> regressor= LinearRegression()  <br> regressor.fit(x_train, y_train)  <br> y_pred= regressor.predict(x_test)  <br> x_pred= regressor.predict(x_train)<br><br># Finding Intercept and Coefficient for Our Model<br> lr.intercept_<br> lr.coef_[0]<br><br># Visualizing the Training set results<br> mtp.scatter(x_train, y_train, color=&quot;green&quot;)   <br> mtp.plot(x_train, x_pred, color=&quot;red&quot;)    <br> mtp.title(&quot;Training Dataset&quot;)  <br> mtp.xlabel(&quot;X_train&quot;)  <br> mtp.ylabel(&quot;Y_train&quot;)  <br> mtp.show()<br><br># Visualizing the Test set results<br> mtp.scatter(x_test, y_test, color=&quot;blue&quot;)   <br> mtp.plot(x_train, x_pred, color=&quot;red&quot;)    <br> mtp.title(&quot;Test Dataset&quot;)  <br> mtp.xlabel(&quot;X_test&quot;)  <br> mtp.ylabel(&quot;Y_test&quot;)  <br> mtp.show()<br></pre><h4>Multiple Linear Regression Formula</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*0fQaW38s-OUoX8O6YoTF0Q.jpeg" /></figure><pre> x= data_set.iloc[:, :-1].values  <br> y= data_set.iloc[:, 4].values  <br><br> from sklearn.model_selection import train_test_split  <br> x_train, x_test, y_train, y_test= train_test_split(x, y, test_size= 0.2, random_state=0)  <br> <br> from sklearn.linear_model import LinearRegression  <br> regressor= LinearRegression()  <br> regressor.fit(x_train, y_train)  <br> y_pred= regressor.predict(x_test)  <br><br> print(&#39;Train Score: &#39;, regressor.score(x_train, y_train))  <br> print(&#39;Test Score: &#39;, regressor.score(x_test, y_test))</pre><h4>Understanding the Slope and Intercept</h4><p>When working with linear regression, our main goal is to find the best fit line that means the error between predicted values and actual values should be minimized. The best fit line will have the least error. The different values for weights or the coefficient of lines (b0, b1) gives a different line of regression, so we need to calculate the best values for b0 and b1 to find the best fit line.</p><p><strong>Slope: </strong>In a linear regression model, the slope is very important in the equation because it tells you how much you can expect<em> Y </em>to change as<em> X </em>increases.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/288/1*kaMegC_ddCIhvTqKZHCkhw.jpeg" /></figure><p>It can also be calculated by the formula;</p><blockquote><em>m = r*(Sy/Sx)</em></blockquote><p>Where r is the correlation co-efficient, Sy and Sx is the standard deviation of x and y. And r can be calculated as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/463/1*98AYurpkw4SELuORvpZJ_g.gif" /></figure><p><strong>Intercept:</strong> The <em>y-</em>intercept is the place where the regression line<em> y = b1x + b0</em> crosses the <em>y</em>-axis (where <em>x</em> = 0), and is denoted by <em>b. </em>Formula to calculate the intercept is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/390/1*4XQPSy3ncTm0mGa04G2NgQ.jpeg" /></figure><p>We can put this slope and intercept into the formula (y = b1x +b0) and you have the description of the best fit line.</p><p><strong>Residuals:</strong> The distance between the actual value and predicted values is called residual. If the observed points are far from the regression line, then the residual will be high, and so cost function will high. If the scatter points are close to the regression line, then the residual will be small and hence the cost function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IjsTPrTQ0igtUR8G0BRfIw.png" /></figure><h4>Key Ideas of Linear Regression</h4><p>· Correlation explains the interrelation between variables within the data.</p><p>· Variance is the degree of the spread of the data.</p><p>· Standard deviation is the dispersion of mean from a data set by studying the variance’s square root.</p><p>· Residual is the actual value found within the dataset minus the expected value that is predicted in linear regression.</p><h4>What is Loss function?</h4><p>The loss function is the function that computes the distance between the current output of the algorithm and the expected output. It’s a method to evaluate how your algorithm models the data. It can be categorized into two groups. One for classification (discrete values, 0,1,2…) and the other for regression (continuous values).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/486/1*9Cc0YEWQMyhmYZ5CeG6crw.jpeg" /></figure><p>The cost function is calculated as an average of the loss function. The loss function is a value which is calculated at every instance. So, for a single training cycle loss is calculated numerous times, but the cost function is only calculated once.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*UbyrHBcES54sqJpKZw8FNw.jpeg" /></figure><h4>What is Cost function?</h4><p>The different values for weights or coefficient of lines (b0, b1) gives the different line of regression, and the cost function is used to estimate the values of the coefficient for the best fit line.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*heAJdk5xhr71dnsR4Lmgeg.jpeg" /></figure><p>Cost function optimizes the regression coefficients or weights. It measures how a linear regression model is performing.</p><p>Cost function is basically the calculation of the error between predicted values and expected values and presents it in the form of a single real number.</p><p>We can use the cost function to find the accuracy of the mapping function, which maps the input variable to the output variable. This mapping function is also known as Hypothesis function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/944/1*3HBJ3P5c8PUL0hjZtCAUyg.png" /></figure><p>For Linear Regression, we use the Mean Squared Error (MSE) cost function, which is the average of squared error occurred between the predicted values and actual values. It may also take Root Mean Square Error.</p><p>We want the Cost function to be 0 or close to zero,which is the best possible outcome one can get.</p><h4>Linear Regression with Gradient Descent</h4><p>Gradient descent is an optimization algorithm used to find the values of parameters of a function that minimizes a cost function. Gradient descent is used to minimize the MSE by calculating the gradient of the cost function. It is done by a random selection of values of coefficient and then iteratively update the values to reach the minimum cost function.</p><p>Based on the slope, gradient descent updates the values for the set of weights and the bias and re-iterates the training loop over new values . This iterative approach is repeated until a minimum error is reached and gradient descent cannot minimize the cost function any further, it depends on various hyperparameters in which one of the crucial ones is the Learning Rate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*wkadeEbaSoXOYmOQR9Ec8w.jpeg" /></figure><p>The learning rate refers to how much the parameters are changed at each iteration. If the learning rate is too high, the model fails to converge and jumps from good to bad cost optimizations. If the learning rate is too low, the model will take too long to converge to the minimum error.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*ZT2qBrZZ4LySeFaNQ-W87Q.jpeg" /></figure><p><strong>Steps followed by the Gradient Descent to obtain lower cost function: </strong>Initially, the values of b0 and b1 will be 0 and the learning rate(α) will be introduced to the function. The value of learning rate(α) is taken very small,something between 0.01 or 0.0001.</p><p>Then the partial derivative is calculate for the cost function equation in terms of slope and also derivatives are calculated with respect to the intercept. After calculation the equation acheived will be.</p><blockquote>After the derivatives are calculated, the slope(b0) and intercept(b1) are updated with the help of the following equation.<br> b0= b0+α*derivative of b0<br> b1 = b1+α*derivative of b1</blockquote><p>The process of updating the values of b0 and b1 continues until the cost function reaches the ideal value of 0 or close to 0. The values of b0 and b1 now will be the optimum value to describe the best fit line.</p><h4>Linear Regression Model Performance</h4><p><strong>Mean Squared Error (MSE): </strong>MSE is computed as RSS divided by the total number of data points, i.e. the total number of observations or examples in our given dataset. MSE tells us what the average RSS is per data point.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cV8l0ej_8CY8GEjTf6-SMw.png" /></figure><p><strong>Root Mean Squared Error (RMSE): </strong>RMSE takes the MSE value and applies a square root over it. RMSE can be directly used to interpret the ‘average error’ that our prediction model makes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*7TMoQc0nZ0-Kyjx9mF7NpA.jpeg" /></figure><p><strong>R-Squared Method: </strong>R-squared is a statistical method that determines the goodness of fit. It measures the strength of the relationship between the dependent and independent variables on a scale of 0–100%. The high value of R-square determines the less difference between the predicted values and actual values and hence represents a good model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*tvlw_pLY6Tt58-Loh3C6hw.jpeg" /></figure><h4>Conclusion</h4><p>In summary, linear regression serves as a foundational technique for modeling relationships between variables. Its simplicity and interpretability make it valuable across diverse fields. However, its assumptions, like linearity and homoscedasticity, should be considered. As data science evolves, linear regression maintains its significance alongside more advanced methods, showcasing its enduring relevance in statistical analysis and prediction.</p><p>References</p><p><a href="https://www.geeksforgeeks.org/ml-linear-regression/">Linear Regression in Machine learning - GeeksforGeeks</a></p><p><a href="https://www.javatpoint.com/linear-regression-in-machine-learning">https://www.javatpoint.com/linear-regression-in-machine-learning</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=79332421544a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Quick Look At Classification]]></title>
            <link>https://medium.com/@daphnebuse/a-quick-look-at-classification-571ddc2a3911?source=rss-6620f796da84------2</link>
            <guid isPermaLink="false">https://medium.com/p/571ddc2a3911</guid>
            <category><![CDATA[supervised-learning]]></category>
            <category><![CDATA[classification]]></category>
            <category><![CDATA[classification-algorithms]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Defne Buse Çelik]]></dc:creator>
            <pubDate>Tue, 29 Aug 2023 11:13:24 GMT</pubDate>
            <atom:updated>2023-08-29T11:13:24.187Z</atom:updated>
            <content:encoded><![CDATA[<p>Here you will learn what Classification is and Classification algorithms. I hope you like my writing!</p><h4><strong>What is Classification?</strong></h4><p>Classification is the process of recognizing, understanding, and grouping ideas and objects into preset categories or subpopulations. Using precategorized training datasets, machine learning programs use a variety of algorithms to classify future datasets into categories.</p><p>Classification algorithms in machine learning use input training data to predict the likelihood that subsequent data will fall into one of the predetermined categories.</p><p>In machine learning and statistics, classification is a supervised learning approach in which the computer program learns from the input data and then uses this learning to classify new observations. This dataset may simply be binary class (like identifying whether the person is male or female or that the mail is spam or non-spam) or it may be multiclass. Some practical examples of classification problems are: speech recognition, handwriting recognition, biometric identification, document classification etc.</p><p>Binary classifiers works with only two classes or possible outcomes (example: positive or negative sentiment) and Multiclass classifiers work with multiple classes (example: to which country a flag belongs). Multiclass assumes that each sample is assigned to one and only one label.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mI603iWjHqWnw_X2S9I4Xg.png" /><figcaption>Binary / Multi-class Classification</figcaption></figure><h4><strong>Classification Algorithms</strong></h4><ul><li>Logistic Regression</li><li>Naive Bayes Classifier</li><li>K-Nearest Neighbors</li><li>Support Vector Machines</li><li>Decision Trees</li><li>Random Forest</li><li>Gradient Boost Classifier</li><li>Stochastic Gradient Descent Algorithm</li><li>Linear Discriminant Analysis (LDA)</li><li>Quadratic Discriminant Analysis (QDA)</li></ul><h4>1. Logistic Regression Algorithm</h4><p>Logistic regression is a supervised learning classification algorithm want to predict the probability of a target variable. It’s one among the only machine learning algorithms which will be used for various classification problems like spam detection, diabetes prediction, cancer detection etc.</p><p>Logistic regression is simpler to implement, interpret and really efficient to coach. Logistic Regression tries to find the best line that separates the two classes. If the amount of observations is lesser than the amount of features, Logistic Regression shouldn’t be used, otherwise it’s going to cause overfitting.</p><p>We use logistic regression for the binary classification of data points. We perform categorical classification such that an output belongs to either of the two classes (1 or 0). This is a disadvantage for logistic regression algorithm.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/683/1*xu7DQ3B4CF-Pm_puZuz0mg.jpeg" /></figure><p>Two of the important parts of logistic regression are Hypothesis and Sigmoid Curve. The data generated from this hypothesis can fit into the log function that creates an S-shaped curve known as “sigmoid”. Using this log function, we can further predict the category of class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/410/1*GfU0AaNUx_rIgChHLb-wGg.png" /><figcaption>Logistic Regression Model</figcaption></figure><h4>2. Naïve Bayes Algorithm</h4><p>Naive Bayes algorithm is one of the powerful machine learning algorithms that is used for classification. It is an extension of the Bayes theorem where in each feature assumes independence. It is used for a variety of tasks such as spam filtering and other areas of text classification.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/461/1*l2ORKnDBglpIXH6uSPzb6w.jpeg" /></figure><p>Naïve Bayes Classifier is one among the straightforward and best classification algorithms which helps in building the fast machine learning models which will make quick predictions. When the assumption of independence is valid, Naive Bayes is much more capable than the other algorithms like logistic regression.</p><p>Naive Bayes is known to be a bad estimator. If the categorical variable belongs to a category that wasn’t followed up in the training set, then the model will give it a probability of 0 which will inhibit it from making any prediction. It’s a bad new for algorithm.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/337/1*3359N1ZLJfI3xI-P0teObQ.png" /><figcaption>Naive Bayes Model</figcaption></figure><h4>3. K-Nearest Neighbors Algorithm</h4><p>K-nearest neighbors is one of the important classification algorithms in machine learning. KNNs belong to the supervised learning domain and have several applications in pattern recognition, data mining, and intrusion detection. This algorithm is simple to implement, robust to noisy training data, and effective if training data is large.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/1*uiL4g2nY1U9yCPNiu-QrPQ.jpeg" /></figure><p>These KNNs are used in real life scenarios where non-parametric algorithms are required. These algorithms don’t make any assumptions about how the data is distributed.</p><p>KNN makes predictions according to the class density of the nearest neighbors of the vector formed by the independent variables of the value to be predicted. The distance of the point to be predicted to other points is calculated. The Minkowski distance calculation function is used for this.</p><p>These are the disadvantages for algorithm; need to determine the value of K and the computation cost is high as it needs to compute the distance of each instance to all the training samples.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/396/1*sxGbJZi3mw9qG5Flm9BRPA.png" /><figcaption>K-Nearest Neighbors Model</figcaption></figure><h4>4. Support Vector Machine Algorithm</h4><p>Support Vector Machines are a type of supervised machine learning algorithm that provides analysis of data for classification and regression. The algorithm is effective in high dimensional spaces and it uses subset of training points in the decision function so it is also have memory efficient.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/417/1*zxkmj1Rrk-36XqpO7QlGuQ.jpeg" /></figure><p>We carry out plotting in the n-dimensional space. The value of each feature is also the value of the specified coordinate. We find the ideal hyperplane that differentiates between the two classes. These support vectors are the coordinate representations of individual observation. It is a frontier method for segregating the two classes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/413/1*rPMQnOc3qcdA3HopF_FgJA.png" /><figcaption>Support Vector Machine Model</figcaption></figure><h4>5. Decision Tree Algorithm</h4><p>Decision Tree algorithms are used for both predictions as well as classification in machine learning. Using the decision tree with a given set of inputs, one can map the various outcomes that are a result of the consequences or decisions. Decision Tree is simple to understand and visualise, requires little data preparation and can handle both numerical and categorical data.</p><p>Decision tree is a result of various hierarchical steps that will help you to reach certain decisions. In order to build this tree, there are two steps — Induction and Pruning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*IjnJzYue1lE5IMZr8hOVZw.jpeg" /></figure><p>Decision tree can create complex trees that don’t generalise well and decision trees can be unstable because small variations in the data might result in a completely different tree being generated. It’s a disadvantage for algorithm.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*v8YOG850u4jiO7Oj1FHJKA.png" /><figcaption>Decision Tree Model</figcaption></figure><h4>6. Random Forest Algorithm</h4><p>Random Forest classifiers are a type of ensemble learning method that is used for classification, regression.</p><p>Random Forest Classifiers facilitate the reduction in the overfitting of the model and these classifiers are more accurate than the decision trees in several cases.</p><p>Random forests exhibit real time prediction but that is slow. They are also difficult to implement and have a complex algorithm.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/710/1*dbNbfsC9V_HzPRdesbmlzg.png" /><figcaption>Random Forest Model</figcaption></figure><h4>7. Gradient Boost Classifier</h4><p>Gradient Boosting= Gradient Descent+Boosting. It uses gradient descent algorithm which can optimize any differentiable loss function. An ensemble of trees are built one by one and individual trees are summed sequentially.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/497/1*-IqG8yp2nH8X-1cOW-QKaA.jpeg" /></figure><h4>8. Stochastic Gradient Descent Algorithm</h4><p>Stochastic Gradient Descent (SGD) is a class of machine learning algorithms for large scale learning. It is an efficient approach towards discriminative learning of linear classifiers under the convex loss function which is linear (SVM) and logistic regression.</p><p>We apply SGD to the large scale machine learning problems that are present in text classification and other areas of Natural Language Processing.</p><p>The SGD algorithm requires a number of hyperparameters such has regularization and a number of iterations. It is also quite sensitive to feature scaling, which is one of the most important steps under data-preprocessing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/581/1*LokVI3DAEBaH2DwIjZjYVg.png" /><figcaption>Stochastic Gradient Descent Model</figcaption></figure><h4>9. Linear Discriminant Analysis (LDA)</h4><p>Linear Discriminant Analysis (LDA) is a classification algorithm that projects your data onto a linear decision boundary, which separates your training data into different classes.</p><p>It does this by finding the optimal hyperplane that maximizes the distance between different classes while minimizing the within class variance. This is useful for multi-class classification problems where we want to group our data into different classes based on some shared characteristics.</p><h4>10. Quadratic Discriminant Analysis (QDA)</h4><p>Quadratic Discriminant Analysis (QDA) is a variant of LDA that allows for non-linear seperation of data. This is achieved by fitting a quadratic curve to your data instead of a linear boundary.</p><p>QDA is more computationally expensive because it has to compute the within class variance for each class, which is a quadratic operation.</p><p>However, QDA may be a better choice than LDA if you have a lot of training data and you believe that the classes in your data aren’t linearly separable.</p><h4>Conclusion</h4><p>Classification algorithms are essential tools in the realm of machine learning, allowing us to categorize data and make informed decisions based on patterns and features. It’s crucial to select the appropriate classification algorithm based on the characteristics of the dataset, the complexity of the problem, and the desired interpretability.</p><p>References</p><p><a href="https://data-flair.training/blogs/machine-learning-classification-algorithms/">https://data-flair.training/blogs/machine-learning-classification-algorithms/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=571ddc2a3911" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Quick Look At The Local Outlier Factor (LOF)]]></title>
            <link>https://medium.com/@daphnebuse/a-quick-look-at-the-local-outlier-factor-lof-f6a4f5116dab?source=rss-6620f796da84------2</link>
            <guid isPermaLink="false">https://medium.com/p/f6a4f5116dab</guid>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[local-outlier-factor]]></category>
            <dc:creator><![CDATA[Defne Buse Çelik]]></dc:creator>
            <pubDate>Mon, 13 Mar 2023 16:16:38 GMT</pubDate>
            <atom:updated>2023-03-13T16:16:38.579Z</atom:updated>
            <content:encoded><![CDATA[<p>Here you will learn what the Local Outlier Factor (LOF) is, its advantages/disadvantages and its implementation in Python. I hope you like my first writing!</p><h4><strong>1. What is the Local Outlier Factor?</strong></h4><p>Local Outlier Factor (LOF) is a popular unsupervised machine learning algorithm used for outlier detection in data mining.</p><p>The algorithm is designed to identify anomalies in the data set based on their local density rather than on global characteristics of the data. The LOF algorithm is a powerful tool for detecting anomalies in data that don’t conform to the overall pattern of the data set.</p><h4><strong>2. What is the LOF working principle?</strong></h4><p>The LOF algorithm works by comparing the density of a data point to the density of its surrounding neighbors. It does this by measuring the distance between a data point and its k-nearest neighbors. The LOF of a data point is defined as the ratio of the average density of its k-nearest neighbors to its own density. Data points with a low LOF value are considered normal, while those with a high LOF value are considered outliers.</p><p><strong>2.1 K-Distance and K-Neighbors</strong></p><p>In order to find the distance between observations, it is necessary to determine the hyperparameter k. The k value determines how many neighbors we’re looking at. K-distances are calculated according to this k value. For example, if k=4, the distance to the nearest fourth neighbor is looked at. If we give a very small value to k, the algorithm becomes sensitive to noise and if we give a large value, it may not recognize local anomalies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/349/1*V6ygkq2dRVJswYVUUfIHzA.png" /><figcaption>k-distance</figcaption></figure><p><strong>2.2 Reachability Distance</strong></p><p>It can be defined as the maximum distance between the two desired points( A and B ). Measuring the distance between the two points given here is specific to the problem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*bGc9dP180M0IQCUn98QyVA.png" /></figure><p><strong>2.3</strong> <strong>Local Reachability Density (LRD)</strong></p><p>It refers to how far we need to go from the point we are at to reach the next point or set of points. The calculated reachability distances are used to calculate the local accessibility density. For all k closest neighbors of a, the reachability distances are calculated and the values found are summed and divided by the value of k. When the inverse of this value is taken, we calculate the density we are looking for.</p><p>The local reachability density of an object A is defined by</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/412/1*488HsQCyzrk1zAWi3h6TRQ.png" /></figure><p>which is the inverse of the average reachability distance of the object A from its neighbors.</p><p><strong>2.4</strong> <strong>Local Outlier Factor (LOF)</strong></p><p>The calculation of Local outlier factor (LOR) is done by taking the ratio of the average of the lrds of k number of neighbors of a point and the lrd of that point.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/399/1*rwpC6OFthYJ9N464RdQ32w.png" /></figure><p>So in the equation,</p><p>· if the density of the neighbors and the point are almost equal we can say that they are quite similar;</p><p>· if the density of the neighbors is lesser than the density of the point we can say that the point is an inlier,</p><p>· if the density of the neighbors is more than the density of the point we can say that the point is an outlier.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/370/1*_katKp06-kQZ-BM7XI_LMA.png" /><figcaption>example</figcaption></figure><p>—&gt; LOF(k) ~ 1 means Similar density as neighbors,</p><p>— &gt; LOF(k) &lt; 1 means Higher density than neighbors (Inlier),</p><p>—&gt; LOF(k) &gt; 1 means Lower density than neighbors (Outlier)</p><h4><strong>3. Advantages and Disadvantages</strong></h4><p><strong>3.1 Advantages</strong></p><p>The LOF algorithm has several advantages over other outlier detection methods:</p><p>· It is able to detect outliers that are not necessarily distant from the rest of the data set, but rather have a lower local density than their neighbors.</p><p>· LOF is relatively robust to noise and can handle data sets with irregular or complex structures.(mixed numeric and categorical features.)</p><p>· LOF is computationally efficient and can handle large data sets with a reasonable amount of memory and processing power.</p><p>· One of the key strengths of LOF is its ability to handle high-dimensional data, which is common in many real world applications. However, the curse of dimensionality can pose a challenge for outlier detection, as the distance metric used to compute local densities becomes less informative as the number of dimensions increases. To address this issue, several methods have been proposed to reduce the dimensionality of the data set before applying LOF.</p><p><strong>3.2 Disadvantages</strong></p><p>· It is not always the same LOF score that determines whether a point is an outlier or not. It might vary for different data sets.</p><p>· As LOF score can be any number that the ratio produces, it might be a little inconvenient to understand the distinguishing of inliers and outliers based on it.</p><h4><strong>4. Coding with Python</strong></h4><pre>from sklearn.neighbors import LocalOutlierFactor<br>from sklearn.datasets import make_blobs<br>from numpy import quantile, where, random<br>import matplotlib.pyplot as plt<br><br>random.seed(1)<br>x, _ = make_blobs(n_samples=300, centers=1, cluster_std=.3, center_box=(10,10))<br><br>plt.scatter(x[:,0], x[:,1])<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/384/1*zt4ct0xepJs-Rp5Rp6M1rA.png" /></figure><pre>model = LocalOutlierFactor(n_neighbors=40) <br>print(model)  <br>model.fit_predict(x) <br> <br>lof = model.negative_outlier_factor_<br>thresh = quantile(lof, .05)<br>print(thresh) <br> <br>index = where(lof&lt;=thresh)<br>values = x[index]<br><br>plt.scatter(x[:,0], x[:,1])<br>plt.scatter(values[:,0],values[:,1], color=&#39;purple&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/384/1*WXdh6PT9oeTIiMAlCjpSnw.png" /></figure><h4><strong>5- Conclusion</strong></h4><p>In summary, Local Outlier Factor (LOF) is a powerful and widely used algorithm for outlier detection in data mining. Its ability to identify outliers based on local density makes it well-suited to handle complex and irregular data sets, and its computational efficiency makes it a practical choice for large-scale data analysis. The selection of an appropriate value for the parameter k is an important consideration when using LOF, and several variations of the algorithm have been proposed to address specific challenges in outlier detection. Note that the choice of the_neighbors and contamination parameters can have a significant impact on the performance of the LOF algorithm. These parameters should be tuned carefully based on the characteristics of the data set and the desired sensitivity to outliers.</p><p>References</p><ul><li><a href="https://en.wikipedia.org/wiki/Local_outlier_factor">Local outlier factor - Wikipedia</a></li><li><a href="https://scikit-learn.org/stable/auto_examples/neighbors/plot_lof_outlier_detection.html">Outlier detection with Local Outlier Factor (LOF)</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f6a4f5116dab" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>