<?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 CW Lin on Medium]]></title>
        <description><![CDATA[Stories by CW Lin on Medium]]></description>
        <link>https://medium.com/@peaceful0907?source=rss-d2d57a7d3dc9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*BxEJd-7n0iJa1AB-v2j0tg.jpeg</url>
            <title>Stories by CW Lin on Medium</title>
            <link>https://medium.com/@peaceful0907?source=rss-d2d57a7d3dc9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 02:32:46 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@peaceful0907/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[Build your customized Chatbot with RAG and LangChain agent]]></title>
            <link>https://peaceful0907.medium.com/build-your-customized-chatbot-with-rag-and-langchain-agent-0eae1923702e?source=rss-d2d57a7d3dc9------2</link>
            <guid isPermaLink="false">https://medium.com/p/0eae1923702e</guid>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[chatbots]]></category>
            <category><![CDATA[langchain]]></category>
            <dc:creator><![CDATA[CW Lin]]></dc:creator>
            <pubDate>Sun, 25 Aug 2024 17:14:26 GMT</pubDate>
            <atom:updated>2024-08-25T17:14:26.904Z</atom:updated>
            <content:encoded><![CDATA[<p>Since ChatGPT became popular, many companies have started wanting to create their own chatbots to serve customers. The job market has also seen positions like LLM engineer, chatbot engineer/trainer/manager, and others.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iGdFJTHMIG79N2HChWaooQ.gif" /><figcaption><a href="https://miro.medium.com/v2/resize:fit:1400/1*iGdFJTHMIG79N2HChWaooQ.gif">https://miro.medium.com/v2/resize:fit:1400/1*iGdFJTHMIG79N2HChWaooQ.gif</a></figcaption></figure><p>Using LLM to build up a chatbot and letting LLM be able to answer questions like internal knowledge of the enterprise is not just inserting information and calling LLM API but also needs lots of preprocess and post-process measures that require custom development. (your source data might include lots of images, videos, or databases which is not easy to understand by LLM)</p><p>However, aside from the complex preprocessing and postprocessing, building a customized chatbot that can update information in real-time can essentially be achieved through RAG and agent.</p><p>This article will introduce how to build a chatbot with retrieval and Google search functions through Langchain agent.</p><h3>Retrieval Augmented Generation(RAG)</h3><p>When we want LLM to learn additional knowledge(e.g. internal enterprise information, FAQ, …) but the content is too long to fit into the prompt (due to input token limit), we need RAG to help us retrieve documents.</p><p>The following figure elaborates RAG concept very well:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lQeBio-CovQ8FNRw9zR10g.png" /><figcaption>Retrieval-Augmented Generation for Large Language Models: A Survey</figcaption></figure><p>Let’s start by looking at the indexing section in the top right corner. <br>First, we prepare the documents containing the knowledge we want the LLM to have, then we break down this long text into many chunks and convert them into embeddings, which are stored in the vectorstore.</p><p>Then, while User Query sentence input, we convert the query sentence into embedding, too. Then calculate the vector similarity between query embedding and embedding in the vectorstore to find out the most similar k chunks. <br>Finally, we insert the original sentences of chunks into the prompt to let LLM have relative knowledge to answer the User Query.</p><p>Although the idea is pretty intuitive, there are serval ways to further improve the retrieval performance. The article <a href="https://arxiv.org/abs/2312.10997">Retrieval-Augmented Generation for Large Language Models: A Survey</a> has stated serval methods. If the basic RAG can’t fit your scenario, you may refer to it.</p><p>Now, let’s see how to use Langchain to create a RAG. The document I’m going to retrieve is this paper: <a href="https://arxiv.org/abs/2312.10997">Retrieval-Augmented Generation for Large Language Models: A Survey</a>.</p><p>Without further ado, let’s see the code:</p><pre>from langchain.document_loaders import PyPDFLoader<br>from langchain.text_splitter import RecursiveCharacterTextSplitter<br>from langchain.vectorstores import FAISS<br>from langchain.embeddings import OpenAIEmbeddings<br>from langchain.chains import RetrievalQA, create_retrieval_chain<br>from langchain.chat_models import ChatOpenAI<br>from langchain_core.prompts import ChatPromptTemplate<br>from langchain.chains.combine_documents import create_stuff_documents_chain<br><br><br>system_prompt = (<br>    &quot;You are an assistant for question-answering tasks. &quot;<br>    &quot;Use the following pieces of retrieved context to answer &quot;<br>    &quot;the question. If you don&#39;t know the answer, say that you &quot;<br>    &quot;don&#39;t know. Use three sentences maximum and keep the &quot;<br>    &quot;answer concise.&quot;<br>    &quot;\n\n&quot;<br>    &quot;{context}&quot;<br>)<br><br>rag_prompt = ChatPromptTemplate.from_messages(<br>    [<br>        (&quot;system&quot;, system_prompt),<br>        (&quot;human&quot;, &quot;{input}&quot;),<br>    ]<br>)<br><br>def get_qa_chain(pdf_path):<br>    # read file<br>    loader = PyPDFLoader(pdf_path)<br>    documents = loader.load()<br>    <br>    # split your docs into texts chunks<br>    text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=100)<br>    texts = text_splitter.split_documents(documents)<br>    <br>    # embed the chunks into vectorstore (FAISS)<br>    embeddings = OpenAIEmbeddings()<br>    vectorstore = FAISS.from_documents(texts, embeddings)<br>    <br>    # create retriever and rag chain<br>    retriever = vectorstore.as_retriever(search_kwargs={&quot;k&quot;: 3})<br>    question_answer_chain = create_stuff_documents_chain(llm=ChatOpenAI(model_name=&#39;gpt-4o-mini&#39;, temperature=0),<br>                                                         prompt=rag_prompt)<br>    rag_chain = create_retrieval_chain(retriever, question_answer_chain)<br>    <br>    return rag_chain<br>    <br>rag_chain = get_qa_chain(&#39;RAG.pdf&#39;)</pre><p>Basically, I just copied and pasted from the <a href="https://python.langchain.com/v0.2/docs/tutorials/pdf_qa/">official tutorials</a>. You can see that Langchain has already packaged a lot of things, including loading PDFs, embedding, vector stores, vector search, and connecting to the LLM. Just thinking about coding all of this from scratch is exhausting 💦</p><p>Here, I’m using OpenAI’s GPT-4, so remember to set your token in the environment variables.</p><p>Now, let’s take a look at the conversation with the RAG chain:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lOTGPiJZzVyBAP4_A1Ck-g.png" /></figure><p>It looks not bad. Although the LLM may already have relative knowledge about RAG, the answer of rag_chain is based on <em>rag.pdf.</em></p><p>In addition, you can use <em>result[‘context’] </em>to see the most similar k chunks that RAG retrieves.</p><p>However, you’ll notice that no matter what question you ask, it will perform a search and generate a response, even if you just say “hello”.</p><p>At this point, you might think, what if it could decide on its own whether a question needs a search, and execute different functions based on different questions? That’s the concept of an agent.</p><h3>Agent</h3><p>Now, we have a goal that letting LLM decide whether to retrieve or not for client’s question, and according to different questions it will execute different functions.</p><p>We can build an LLM like below figure. We use two LLMs to achieve it.</p><p>The green LLM determines which tool (RAG, Google Search, or No Need) to use for the client question, then executes the tool to retrieve information.<br>The retrieved information is then inserted into the prompt of the blue LLM, instructing it to use this information to generate a response for the client.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E0xlm8z6ZHFm52dPnLaiGw.png" /></figure><p>We can also achieve this using Langchain’s agent. I believe there are pros and cons to each approach.</p><p>If it’s not too complicated, you can use prompt engineering to let the LLM decide which tool to use. Using the Langchain agent requires less effort but can be more complex, harder to debug, and the Langchain version is constantly updating, with commands and applications being continuously revised.</p><p>But I’m a bit too lazy to write everything out, so let’s just implement the agent using Langchain directly. 😅</p><p>Besides rag_chain described in the previous paragraph, I also wanna give the ability of Google search to agent. In other words, I will provide the agent with two tools: RAG for retrieving pdf and Google search.</p><p>We have already finish rag_chain, and we can achieve the function of Google search via searchAPI. Here, I use <strong>Serper</strong>.</p><p>You can go to Serper website and register a free account to get a token, which has 2500 free queries. Langchain also has GooleSerperAPIWrapperto help us implement it in just one line code!</p><pre>from langchain_community.utilities import GoogleSerperAPIWrapper<br>search = GoogleSerperAPIWrapper()</pre><p>Let’s do a simple test of the search functionality:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mJQfJvto10o8WTsboXpeMg.png" /></figure><p>ok, now, we can use search to do google search and return search results with string.</p><p>Let’s wrap rag_chain and search into tool:</p><pre>from langchain.agents import Tool, AgentExecutor, create_react_agent<br><br>tools = [<br>    Tool(<br>        name=&quot;RAG&quot;,<br>        func=rag_chain.invoke,<br>        description=&quot;Useful when you&#39;re asked Retrieval Augmented Generation(RAG) related questions&quot;<br>    ),<br>    Tool(<br>        name=&quot;Google Search&quot;,<br>        description=&quot;For answering questions that are not related to legal or when you don&#39;t know the answer, use Google search to find the answer&quot;,<br>        func=search.run,<br>    )<br>]</pre><p>The description in the tools is used to let LLM know which tool should be used, hence, based on your requirements, write the description as clearly as possible.</p><p>Now, we design a prompt to restrict the way that agent thought and then output the response what we want.</p><pre>character_prompt = &quot;&quot;&quot;Answer the following questions as best you can. You have access to the following tools:<br>{tools}<br><br>For any questions requiring tools, you should first search the provided knowledge base. If you don&#39;t find relevant information from provided knowledge base, then use Google search to find related information.<br><br>To use a tool, you MUST use the following format:<br>1. Thought: Do I need to use a tool? Yes<br>2. Action: the action to take, should be one of [{tool_names}]<br>3. Action Input: the input to the action<br>4. Observation: the result of the action<br><br>When you have a response to say to the Human, or if you do not need to use a tool, you MUST use the following format:<br>1. Thought: Do I need to use a tool? No<br>2. Final Answer: [your response here]<br><br>It&#39;s very important to always include the &#39;Thought&#39; before any &#39;Action&#39; or &#39;Final Answer&#39;. Ensure your output strictly follows the formats above.<br><br>Begin!<br><br>Previous conversation history:<br>{chat_history}<br><br>Question: {input}<br>Thought: {agent_scratchpad}<br>&quot;&quot;&quot;</pre><p>You might think how can I write out such a long prompt. You can see prompt hub of langchain to find some example then do some adjustment.</p><pre>from langchain import hub<br>hub.pull(&quot;hwchase17/react&quot;)</pre><p>Next, use create_react_agent to package the tool and prompt into an agent, and then use AgentExecutor to run the agent and generate a response. I also took the opportunity to add the memory mechanism here.</p><pre>from langchain.prompts.prompt import PromptTemplate<br>from langchain.chains.conversation.memory import ConversationBufferWindowMemory<br><br>chat_model = ChatOpenAI(model_name=&#39;gpt-4&#39;,<br>                        temperature=0,<br>                        streaming=True,<br>                        verbose=True,<br>                        max_tokens=1024,<br>                        )<br><br>prompt = PromptTemplate.from_template(character_prompt)<br>agent = create_react_agent(chat_model, tools, prompt)<br><br>memory = ConversationBufferWindowMemory(memory_key=&#39;chat_history&#39;, k=5, return_messages=True, output_key=&quot;output&quot;)<br>agent_chain = AgentExecutor(agent=agent,<br>                            tools=tools,<br>                            memory=memory,<br>                            max_iterations=5,<br>                            handle_parsing_errors=True,<br>                            verbose=True,<br>                            )</pre><p>This agent_chain can be used for conversations. When the user inputs a question, it will determine whether to use a tool, which tool to use, and execute actions to get the tool&#39;s response. <br>It then checks if there is enough information. If there is, it generates a reply based on the collected information. If not, it will continue executing actions until the maximum iteration is reached.</p><p>Note that, it may suffer an issue: LLM doesn’t follow our instructions in prompt to response, which will result in LLM parse error. You’ll find that it has already collected enough information to answer the question, but it reply Sorry, I don&#39;t have enough information to answer your question...</p><p>So, here I try to use prompt engineer to alleviate that. You can see that I repeatedly emphasized you MUST use the following format、It’s very important to always include the ‘Thought’ before any ‘Action’ or ‘Final Answer’. Ensure your output strictly follows the formats above.</p><p>and I also use the powerful model <strong>gpt-4. </strong>Because I found that larger models are better at following our prompt instructions</p><p>Now, let’s see the performance of agent_chain:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZOSLDegCMGoyQ4I2PLhslw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nN3CXopTInXeTDkc_3kcbg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-xeM9oAXOEZSY0n3NbL4BA.png" /></figure><p>It seems to response very well~ by adding some front-end development, you can interact with this chatbot on a webpage.</p><p>In the end, I organized this agent into the following flowchart. <br>I believe it’s a chatbot architecture that can be used in many scenarios; you just need to replace the RAG retrieval knowledge base with your own content.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xoXAcQnvvUmGjZ6X85AhRg.png" /></figure><h3>Reference</h3><p><a href="https://medium.com/@cch.chichieh/rag-retrieval-augmented-generation-%E7%82%BA%E8%87%AA%E7%84%B6%E8%AA%9E%E8%A8%80%E8%99%95%E7%90%86%E6%8F%AD%E9%96%8B%E6%96%B0%E7%AF%87%E7%AB%A0-fced76fdb8b9">RAG (Retrieval Augmented Generation): 為自然語言處理揭開新篇</a></p><p><a href="https://arxiv.org/abs/2312.10997">Retrieval-Augmented Generation for Large Language Models: A Survey</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0eae1923702e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Develop a large language model application using Langchain]]></title>
            <link>https://blog.gopenai.com/develop-a-large-language-model-application-using-langchain-aca380a22122?source=rss-d2d57a7d3dc9------2</link>
            <guid isPermaLink="false">https://medium.com/p/aca380a22122</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[chatgpt]]></category>
            <dc:creator><![CDATA[CW Lin]]></dc:creator>
            <pubDate>Thu, 21 Sep 2023 16:50:53 GMT</pubDate>
            <atom:updated>2023-09-23T09:48:05.333Z</atom:updated>
            <content:encoded><![CDATA[<p>You may have heard of or used ChatGPT, the large language model (LLM) chatbot developed by OpenAI, on the web and been amazed by what it can do. If you are a developer, you must wanna build up your own application power by LLM.</p><p>I would use this article to record how to use <strong>Openai’s API</strong> and how to utilize <strong>Langchain</strong>, an open framework that can connect LLM with external sources, to let your LLM be able to answer questions such as current time or information from your own documents(may from your data, book or PDF,…).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vk9B_zWpYHDUEL-L" /><figcaption>Photo by <a href="https://unsplash.com/@stanleydai?utm_source=medium&amp;utm_medium=referral">Stanley Dai</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Outline</h3><ul><li><strong>Access to LLM from openai<br></strong>1. Using LLM from python<br>2. Chat completions<br>3. Completions</li><li><strong>Langchain<br></strong>1. ConversationChain<br> — Conversation Buffer Window<br> — Conversation Summary<br>2. add customized variable into prompt template<br>3. agents</li></ul><h3>Access to LLM from openai</h3><p>Before anything else, we need to get your own OpenAI API key:</p><ol><li>Go to <a href="https://openai.com/">https://openai.com/</a></li><li>login then choose API</li><li>Click on your Profile image (top right) &gt; View API keys</li><li>Click on + Create new secret key</li></ol><h3>Using LLM from python</h3><p>First, install the package openai by pypi</p><p>pip install openai</p><p>Then, we can import openai and start to chat!</p><p>I would go through <strong>Chat completions </strong>and<strong> completions </strong>in openai.</p><blockquote><strong>completions</strong> provides the completion for a single prompt and takes a single string as an input, whereas the <strong>chat completions</strong> provides the responses for a given dialog and requires the input in a specific format corresponding to the message history.</blockquote><h4><strong>Chat completions</strong></h4><pre>import openai<br>import os<br>OPENAI_KEY = os.environ[&#39;OPENAI_KEY&#39;]<br><br>completion = openai.ChatCompletion.create(model=&quot;gpt-3.5-turbo&quot;, <br>                                          max_tokens=128,<br>                                          temperature=0.9,<br>                                          messages=[{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: &quot;Hello world&quot;}])<br><br>print(completion.choices[0].message.content)<br># Hello! How can I assist you today?</pre><p>If you want to have a multi-turn interactive conversation, you’ll need to append each round of dialogue and feed it into the next round.</p><pre>messages = []<br>for i in range(3):<br>    msg = input(&#39;human: &#39;)<br>    messages.append({&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: msg})<br>    response = openai.ChatCompletion.create(<br>        model=&quot;gpt-3.5-turbo&quot;,<br>        max_tokens=128,<br>        temperature=0.9,<br>        messages=messages<br>    )<br>    ai_response = response.choices[0].message.content.replace(&#39;\n&#39;, &#39;&#39;)<br>    messages.append({&quot;role&quot;:&quot;assistant&quot;,&quot;content&quot;: ai_response})<br>    print(f&#39;ai: {ai_response}&#39;)<br>    print(&#39;\n&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NN6YR2VFese93rHZvcOoiQ.png" /></figure><p>The capable model can be found at <a href="https://platform.openai.com/docs/models/overview">https://platform.openai.com/docs/models/overview</a>.</p><p>Note that for each round, we append all of the preview’s conversation history into the messages list and it’ll lead number of tokens growing linearly. So make sure that you only retain the lasted k rounds of conversation history in the messages list. (or it will exceed the token limit and also charge more money😅)</p><p>Later on, we’ll use Langchain’s memory mechanism to make multi-round conversation easier to implement.</p><h4><strong>Completions</strong></h4><p>completion provides the completion for a single prompt and takes a single string as an input.</p><p>Imagine that, your boss asks you to build a sentence classification model to know if the restaurant’s reviews from customs are positive or negative.</p><p>Basically, you have to collect an amount of review data and label it positive or negative so that you can train a binary classification model no matter using LSTM or fine-tuning BERT.</p><p>With LLM’s completions, you don’t have to label lots of data. You even don’t need to collect training data. You only have to give a few examples to LLM and ask it to classify the given sentence!</p><p>First, we input a few examples as prompt and the API will return a text completion that attempts to match whatever instructions or context you gave it.</p><pre>def generate_prompt(sentence):<br>    return &quot;&quot;&quot;You have to determine whether the given restaurant review is positive or negative..<br>content: I had an amazing dining experience at this restaurant.<br>Answer: positive<br>Content: The ambiance of this restaurant is wonderful, and the food is consistently flavorful.<br>Answer: positive<br>Content: The service was a bit slow, and it took a while for our orders to arrive.<br>Answer: negative<br>content: I had a terrible experience at this restaurant. The food was cold when it arrived at our table.<br>Answer: negative<br>Content: {}<br>Answer:<br>&quot;&quot;&quot;.format(<br>       sentence.capitalize()<br>   )</pre><p>Here, I list a few examples as prompt to AI.</p><p>If you are too lazy to think out a couple of examples, you can also ask chatGPT to give you some examples.😂</p><p>Then we can ask LLM to classify the new content:</p><pre>query_sentence = &quot;The food is just run of mill.&quot;<br><br>response = openai.Completion.create(<br>    model=&quot;text-davinci-003&quot;,<br>    prompt=generate_prompt(query_sentence),<br>    temperature=0.9<br>)<br>print(response.choices[0].text)  # --&gt; negative</pre><p>see, pretty easy!! You can tell your boss that you need a week to build up the model and then finish this task in just 1 hour 🥳</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zFheLakTtYJozcQ6" /><figcaption>Photo by <a href="https://unsplash.com/@dan__burton?utm_source=medium&amp;utm_medium=referral">Dan Burton</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Langchain</h3><p>Langchain is an open framework that can connect LLM with external sources. Langchain is offered as python and javascript package.</p><p>Generally, LangChain is a framework for developing applications powered by language models (e.g. GPT4, Llama, PaLM2,…), it makes the complicated parts of working &amp; building with AI models easier.</p><p>This <a href="https://github.com/gkamradt/langchain-tutorials/blob/main/LangChain%20Cookbook%20Part%201%20-%20Fundamentals.ipynb">Langchain cookbook</a> elaborates Langchain very well.</p><h4>install</h4><p>pip install langchai</p><h4>use LLM in langchain</h4><pre>import os<br>from langchain.llms import OpenAI<br><br>OPENAI_KEY = os.environ[&#39;OPENAI_KEY&#39;]<br>llm = OpenAI(model_name=&quot;gpt-3.5-turbo&quot;, openai_api_key=OPENAI_KEY)<br>llm(&quot;hello, how are you?&quot;)<br># &quot;Hello! I&#39;m an AI language model, so I don&#39;t experience emotions like humans do. But I&#39;m here to help you. How can I assist you today?&quot;</pre><p>We can see that it just imports openai from Langchain and call LLM in an easier way!</p><p>Now let us re-build a chat conversation chatbot and few-shot learning as the above chapter by Langchain.</p><h4>ConversationChain</h4><p>To build a multi-turn interactive conversation, we will use ConversationChain and <a href="https://python.langchain.com/docs/modules/memory/">the memory unit in Langchain</a>.</p><p>Langchain has many different kinds of memory mechanisms. I think the Conversation Buffer Windowand Conversation Summary<strong> </strong>are two of the most useful kinds of memory.</p><p><strong>Conversation Buffer Window</strong></p><p>ConversationBufferWindowMemory keeps a list of the interactions of the conversation over time. It only uses the last K interactions. This can be useful for keeping a sliding window of the most recent interactions, so the buffer will not get too large.</p><pre>from langchain.chains import ConversationChain<br>from langchain.memory import ConversationBufferWindowMemory<br><br>memory = ConversationBufferWindowMemory(k=10, input_key=&#39;history&#39;)<br>chain = ConversationChain(memory=memory, llm=llm, verbose=True)<br>chain(&#39;hello, i am henry. how are you?&#39;)<br>chain(&#39;1+2+3+...+100=?&#39;)<br>chain(&#39;do you remember my name?&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YdERkDFUvFhHQIrm61_ouw.png" /></figure><p>Compared to the last chapter, we append chat history by ourselves. With Langchain, we can easily do multi-turn conversations.</p><p>In fact, ConversationChain has auto-given a default prompt into chain. We can see prompt by chain.prompt.template :</p><pre>The following is a friendly conversation between a human and an AI. The AI is talkative and provides lots of specific details from its context. If the AI does not know the answer to a question, it truthfully says it does not know.<br><br>Current conversation:<br>{history}<br>Human: {input}<br>AI:</pre><p>We can design our own prompt ourselves by PromptTemplate.</p><p>For example, if we want to build an English tutor, we might design prompt as:</p><pre>prompt_template = &quot;&quot;&quot;<br>Your name is Lisa, and you are 28 years old.<br>You are a professional English teacher, and your task is to engage in English conversation practice with students.<br>If students make grammar or vocabulary mistakes, you have to correct student and provide the correct usage.&quot;<br><br>Current conversation:<br>{history}<br><br>student:{input}<br>Lisa:<br>&quot;&quot;&quot;</pre><p>then create prompt template and ConversationChain:</p><pre>from langchain import PromptTemplate<br><br>prompt = PromptTemplate(input_variables=[&quot;history&quot;, &quot;input&quot;], template=prompt_template)<br>memory = ConversationBufferWindowMemory(k=10, input_key=&#39;history&#39;)<br>chain = ConversationChain(prompt=prompt, memory=memory, llm=llm, verbose=True)</pre><p>Under this prompt, the conversation will go like:</p><pre>chain(&quot;hello, what&#39;s your name?&quot;)  <br># Hi! My name is Lisa. Nice to meet you!<br><br>chain(&quot;I name are Henry&quot;)  <br># Hi Henry! Nice to meet you too. Just so you know, the correct way to say your name is &quot;My name is Henry&quot;.<br><br>chain(&quot;where is you come from?&quot;)<br># Hi there! It&#39;s nice to meet you. The correct way to ask that question is &quot;Where do you come from?&quot;. I&#39;m from the United States.<br><br>chain(&quot;thanks for your correction!&quot;)<br># You&#39;re welcome! It&#39;s my pleasure to help. If you ever need help with grammar or vocabulary, don&#39;t hesitate to ask!</pre><p>and we can see current memory by <br>memory.load_memory_variables({})[‘history’] or memory.buffer</p><p><strong>Conversation Summary</strong></p><p>conversation summary creates a “running summary” by feeding current conversation history into another LLM and requiring it to summary the conversation into a sentence then feed this summary into the prompt.</p><p>just like the above example, but we switch memory from bufferwindow to ConversationSummaryMemory</p><pre>from langchain import PromptTemplate<br>from langchain.chains import ConversationChain<br>from langchain.memory import ConversationSummaryMemory<br><br>prompt_template = &quot;&quot;&quot;<br>Your name is Lisa, and you are 28 years old.<br>You are a professional English teacher, and your task is to engage in English conversation practice with students.<br>If students make grammar or vocabulary mistakes, you have to correct student and provide the correct usage.&quot;<br><br>Current conversation:<br>{history}<br><br>student:{input}<br>Lisa:<br>&quot;&quot;&quot;<br>prompt = PromptTemplate(input_variables=[&quot;history&quot;, &quot;input&quot;], template=prompt_template)<br>memory = ConversationSummaryMemory(llm=llm, input_key=&#39;history&#39;)<br>chain = ConversationChain(prompt=prompt, memory=memory, llm=llm, verbose=True)</pre><p>You can see that there is one more llm in the memory object. Let us dive into this llm. We can see the prompt of memory’s llm by memory.prompt.template:</p><pre>Progressively summarize the lines of conversation provided, adding onto the previous summary returning a new summary.<br><br>EXAMPLE<br>Current summary:<br>The human asks what the AI thinks of artificial intelligence. The AI thinks artificial intelligence is a force for good.<br><br>New lines of conversation:<br>Human: Why do you think artificial intelligence is a force for good?<br>AI: Because artificial intelligence will help humans reach their full potential.<br><br>New summary:<br>The human asks what the AI thinks of artificial intelligence. The AI thinks artificial intelligence is a force for good because it will help humans reach their full potential.<br>END OF EXAMPLE<br><br>Current summary:<br>{summary}<br><br>New lines of conversation:<br>{new_lines}<br><br>New summary:</pre><p>ConversationSummaryMemory is an LLM that summarizes the current conversation (new summary) and then feeds the summary result into the original LLM’s prompt_template {history}.</p><p>we can also use memory.load_memory_variables({})[‘history’] to see the memory of LLM in each round.</p><p>It would go like this:</p><p><em>The human asks what the AI thinks of artificial intelligence. The AI introduces itself as Lisa and expresses pleasure at meeting the human before asking how it can help them with their English conversation practice. The AI expresses appreciation for the question and then inquires further about the human’s English conversation practice.</em></p><h4>add customized variable into prompt template</h4><p>It is well known that ChatGPT’s training data does not include the most recent information, and, of course, it cannot be aware of the current time.</p><p>If you ask Lisa: chain(&quot;do you know what time is it&quot;). She may respond to you: <em>I’m sorry, I don’t know what time it is. However, it’s important to use the correct verb tense when speaking English. In this case, you should have said &quot;Do you know what time it is?&quot;</em></p><p>Hence, we need to feed the current time to Lisa as a variable in the prompt.</p><p>Whereas, as I know, ConversationChain does not support customized variables other than <em>input</em> and <em>history. </em>So, we need to change to use <strong>LLMChain, </strong>which<strong> </strong>is more of a base interface.</p><p><a href="http://LLMChain and ConversationChain">LLMChain v.s. ConversationChain</a></p><p>We can add an additional variable in the prompt, that is dynamically changed from each round of conversation.</p><p>For example:</p><pre>from langchain.memory import ConversationBufferWindowMemory, ConversationSummaryMemory<br>from langchain import PromptTemplate, LLMChain<br>from datetime import datetime<br><br>prompt_template = &quot;&quot;&quot;<br>Your name is Lisa, and you are 28 years old.<br>You are a professional English teacher, and your task is to engage in English conversation practice with students.<br>If students make grammar or vocabulary mistakes, you have to correct student and provide the correct usage.&quot;<br><br>Current time is {current_time}<br><br>Current conversation:<br>{history}<br><br>student:{input}<br>Lisa:<br>&quot;&quot;&quot;<br><br>prompt = PromptTemplate(input_variables=[&quot;current_time&quot;, &quot;history&quot;, &quot;input&quot;], template=prompt_template)<br>memory = ConversationSummaryMemory(llm=llm, input_key=&#39;history&#39;)<br>chain = LLMChain(prompt=prompt, memory=memory, llm=llm)<br><br>human_sentence = &quot;can you tell me what time it is?&quot;<br>current_time = datetime.now()<br>time_str = current_time.strftime(&quot;%Y-%m-%d %H:%M&quot;)<br>chain.predict(input=human_sentence, current_time=time_str)<br><br># --&gt; Yes, it is currently September 17th, 2023 at 11:55 PM. Is there anything else I can help you with?</pre><p>A tricky thing is that when you wanna add a customized variable in the input_variables, you must specify the <em>input_key</em> in memory (it’s input_key=’history’ in the above example) [<a href="https://github.com/langchain-ai/langchain/issues/8710">reference</a>]</p><h3>agents</h3><p>If the information you want to tell LLM can be just expressed as a couple of sentences, then you can set a variable in the prompt just like the above example.</p><p>However, if the information you want to let LLM know is an article, database, or webpage, then you will need <strong>agents</strong>.</p><p><strong>Agent</strong> takes in an input and returns a response corresponding to an action to take along with an action input. There are many types of agents (which are better for different use cases) <a href="https://python.langchain.com/docs/modules/agents/agent_types.html">here</a>.</p><p><strong>Tool</strong> is “capability” of an agent. This is an abstraction on top of a function that makes it easy for LLMs (and agents) to interact with it. e.g. Google search.</p><p>Now, let us try to create a conversation chatbot with the capability to answer questions about yolov8.</p><pre>from langchain.llms import OpenAI<br>from langchain.document_loaders import PyPDFLoader<br>from langchain.text_splitter import RecursiveCharacterTextSplitter<br>from langchain.vectorstores import FAISS<br>from langchain.embeddings import OpenAIEmbeddings<br>from langchain.chains import RetrievalQA<br><br>from langchain.chains.conversation.memory import ConversationBufferWindowMemory<br>from langchain.agents import Tool, initialize_agent<br>from langchain.agents import AgentType<br><br>llm = OpenAI(model_name=&quot;text-davinci-003&quot;, openai_api_key=OPENAI_KEY)</pre><p>Actually, most of the things we need to do are wrapped in Langchain’s command. So, you might already know the thing we’re going to do with a glimpse at the import package!</p><p>First, load <a href="https://arxiv.org/abs/2305.09972">yolov8 paper pdf</a> and feed into LLM</p><pre># read pdf<br>loader = PyPDFLoader(&quot;./yolov8.pdf&quot;)<br>documents = loader.load()<br><br># get your splitter ready<br>text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=10)<br><br># split your docs into texts chunks<br>texts = text_splitter.split_documents(documents)<br><br># get embedding engine then embedd your texts<br>embeddings = OpenAIEmbeddings(openai_api_key=OPENAI_KEY)<br>vectorstore = FAISS.from_documents(texts, embeddings)<br><br># create the retriever<br>retriever = vectorstore.as_retriever()<br><br># create qa chain<br>qa = RetrievalQA.from_chain_type(llm=llm, chain_type=&quot;map_reduce&quot;, retriever=retriever)</pre><p>We load the pdf first, then split the whole file into chunks, which is easier to embed. Then, embed each text chunk and store it in the vectorstore.</p><p>finally, create a retriver to find information from vectorstore based on FAISS.</p><p>Basically, <strong>qa </strong>already<strong> </strong>is an LLM that can answer the question based on pdf.</p><pre>qa.run(&quot;what&#39;s new in yolov8&quot;)<br># --&gt; YOLOv8 is the latest version of YOLO, and it contains several new features such as improved neural architecture search capabilities, the ability to run on mobile devices, and faster inference times. It also has more accurate detections and a larger model size compared to YOLOv7</pre><p>However, qa only can answer the question about the pdf. We want a chatbot that is not only able to answer questions about pdf but also can chat with people as well.</p><pre>qa.run(&quot;who are you?&quot;)  # --&gt; I don&#39;t know.<br>qa.run(&quot;what can you do for me?&quot;)  # --&gt; I don&#39;t know.</pre><p>Here is a way to achieve our goal. Take <strong>qa</strong> as a function to create a <a href="https://python.langchain.com/docs/modules/agents/how_to/custom_llm_chat_agent">custom LLM agent</a>.</p><p>Let’s refer to the <a href="https://python.langchain.com/docs/modules/agents/agent_types/chat_conversation_agent">conversational agent</a> and add the stuff we have learned so far:</p><pre># create a custom tool<br>tools = [<br>    Tool(<br>        name=&quot;Knowledge from doc&quot;,<br>        func=qa.run,<br>        description=&quot;useful for when you need to answer questions about computer vision.&quot;,<br>    )<br>]<br><br>agent_chain = initialize_agent(tools, llm, agent=AgentType.CONVERSATIONAL_REACT_DESCRIPTION,<br>                               verbose=True, memory=memory)</pre><p>create memory and agent chain</p><pre>memory = ConversationSummaryMemory(llm=llm, memory_key=&#39;chat_history&#39;, input_key=&#39;input&#39;)<br>agent_chain = initialize_agent(tools, llm,<br>                               agent=AgentType.CONVERSATIONAL_REACT_DESCRIPTION,<br>                               verbose=True, memory=memory)</pre><p>we can see the prompt behind the agent_chain</p><p>print(agent_chain.agent.llm_chain.prompt.template)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/996/1*76pdXvTd5qBD5lsvT5-TqA.png" /></figure><p>You can see that Langchain has helped us to create a prompt behind the agent to achieve our goal(create a chatbot that can answer questions based on PDF).</p><p>agent_chain.run(input=”what can you do?”)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1004/1*SsxTzoqrlFUxbg8nyUdjTg.png" /></figure><p>agent_chain.run(input=&quot;what’s different between yolov8 and yolov5&quot;)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/998/1*VdYKBJlL9T8Dw2uxkT7Jxw.png" /></figure><p>and of course, we can modify this prompt to give personality to the agent and also add additional input variables!</p><p>for example, I set up a personality and added a {current_time} variable to let Lisa be able to answer the current time like below:</p><pre>my_prompt = &quot;&quot;&quot;<br>Your name is Lisa, you are a 20 years old girl and is a data scientist.<br>You are a Japanese-American mix, graduated from UCLA, and currently work at Google.<br>Overall, you are a powerful assistant that can help with a wide range of tasks and provide valuable insights and information on a wide range of topics.<br>Whether you need help with a specific question or just want to have a conversation about a particular topic, Assistant is here to assist.<br><br>Current time is: {current_time}<br><br>TOOLS:<br>------<br>Assistant has access to the following tools:<br>&gt; Knowledge from doc: useful for when you need to answer questions about the most recent state of the union address. Input should be a fully formed question.<br>To use a tool, please use the following format:<br>```<br>Thought: Do I need to use a tool? Yes<br>Action: the action to take, should be one of [Knowledge from doc]<br>Action Input: the input to the action<br>Observation: the result of the action<br>```<br>When you have a response to say to the Human, or if you do not need to use a tool, you MUST use the format:<br>```<br>Thought: Do I need to use a tool? No<br>AI: [your response here]<br>```<br><br>Begin!<br><br>Previous conversation history:<br>{chat_history}<br><br>New input: {input}<br>{agent_scratchpad}<br>&quot;&quot;&quot;<br><br>prompt = PromptTemplate(input_variables=[&quot;current_time&quot;, &quot;chat_history&quot;, &quot;input&quot;, &quot;agent_scratchpad&quot;], template=my_prompt)</pre><p>then we can just overwrite the prompt of agent_chain:</p><p>agent_chain.agent.llm_chain.prompt = prompt</p><p>the results will like:</p><pre>agent_chain.run(input=&quot;what&#39;s your name&quot;, current_time=&quot;2023-09-20 15:45:30&quot;)<br># --&gt; &#39;My name is Lisa. Nice to meet you!&#39;<br><br>agent_chain.run(input=&quot;where are you from&quot;, current_time=&quot;2023-09-20 15:45:30&quot;)<br># --&gt; I&#39;m from a mix of Japanese and American backgrounds. I graduated from UCLA and currently work at Google.<br><br>agent_chain.run(input=&quot;what time it is?&quot;, current_time=&quot;2023-09-20 15:45:30&quot;)<br># --&gt; The current time is 2023-09-20 15:45:30.</pre><p>Lisa also can use tool to answer the question about yolov8:</p><p>agent_chain.run(input=”what’s backbone of yolov8&quot;, current_time=”2023–09–20 15:45:30&quot;)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/492/1*jeBJX4f6_9a1gz5kLA5MSg.png" /></figure><p>agent_chain.run(input=”what’s new in yolov8&quot;, current_time=”2023–09–20 15:45:30&quot;)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*J2xeMytfNrzOReCw3sKpCw.png" /></figure><p>If the questions are beyond the scope of the PDF, it will not be able to answer:</p><p>agent_chain.run(input=&quot;what’s the weather tomorrow?&quot;, current_time=”2023–09–20 15:45:30&quot;)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/996/1*uvyYzl6ELr0dt6Fzrd90Qw.png" /></figure><p>Langchain has wrapped lots of tools and various agent type that you can use. I think the most useful tool is <a href="https://python.langchain.com/docs/integrations/tools/google_search">google search</a>.</p><p>You can search for tools and methods that suit your needs in <a href="https://python.langchain.com/docs/get_started/introduction">Langchain doc</a>. I believe that for the most part, you can simply import them and start using them!</p><h3>Reference</h3><p><a href="https://medium.com/data-professor/beginners-guide-to-openai-api-a0420bc58ee5">https://medium.com/data-professor/beginners-guide-to-openai-api-a0420bc58ee5</a></p><ul><li><a href="https://zhuanlan.zhihu.com/p/640240974">LangChain Memory 结合LLMs：让你的聊天机器人拥有记忆力</a></li><li><a href="https://github.com/GoogleCloudPlatform/solutions-genai-llm-workshop/blob/main/LAB001-1-Langchain-Basis/0-run.py">solutions-genai-llm-workshop/LAB001-1-Langchain-Basis/0-run.py at main · GoogleCloudPlatform/solutions-genai-llm-workshop</a></li><li><a href="https://www.pinecone.io/learn/series/langchain/langchain-prompt-templates/">Prompt Engineering and LLMs with Langchain | Pinecone</a></li><li><a href="https://github.com/gkamradt/langchain-tutorials/blob/main/LangChain%20Cookbook%20Part%201%20-%20Fundamentals.ipynb">langchain-tutorials/LangChain Cookbook Part 1 - Fundamentals.ipynb at main · gkamradt/langchain-tutorials</a></li></ul><p><a href="https://python.langchain.com/docs/modules/agents/agent_types/chat_conversation_agent">conversational agent type</a></p><p><a href="https://github.com/langchain-ai/langchain/issues/1322">modify the prompt of an agent</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aca380a22122" width="1" height="1" alt=""><hr><p><a href="https://blog.gopenai.com/develop-a-large-language-model-application-using-langchain-aca380a22122">Develop a large language model application using Langchain</a> was originally published in <a href="https://blog.gopenai.com/">GoPenAI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sentence Embedding by BERT and Sentence Similarity]]></title>
            <link>https://peaceful0907.medium.com/sentence-embedding-by-bert-and-sentence-similarity-759f7beccbf1?source=rss-d2d57a7d3dc9------2</link>
            <guid isPermaLink="false">https://medium.com/p/759f7beccbf1</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[natural-language-process]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[CW Lin]]></dc:creator>
            <pubDate>Tue, 24 Jan 2023 15:11:01 GMT</pubDate>
            <atom:updated>2023-01-24T15:16:32.244Z</atom:updated>
            <content:encoded><![CDATA[<p>This article will introduce how to use BERT to get sentence embedding and use this embedding to fine-tune downstream tasks. I will also talk about Sentence Similarity for sentence clustering or intention matching.</p><p>I will only go through a few details of BERT in this article since there are already tons of excellent articles and tutorials on the internet talking about it.</p><p>OK, that start it!</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*g0trzlwLX7Hg-MSM.png" /><figcaption><a href="https://www.codemotion.com/magazine/ai-ml/bert-how-google-changed-nlp-and-how-to-benefit-from-this/">https://www.codemotion.com/magazine/ai-ml/bert-how-google-changed-nlp-and-how-to-benefit-from-this/</a></figcaption></figure><h3>BERT sentence embedding for downstream task</h3><p>The concept is to transform the sentence (i.e. sequence of text) into a numerical vector and then come up with a linear layer to do the downstream task (classification or regression)</p><p>BERT offers the following 4 down-stream task examples:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*Kj51FTTX_4ndOsre.jpg" /></figure><p>To use BERT, you need to prepare the input stuffs for BERT.</p><ol><li><strong>token id</strong>: The index of each text in BERT corpus.</li><li><strong>attention mask</strong>: Because we will padding every sentence to the same length, it needs attention mask to let self-attention layer know which words are padding words and mask them.</li><li><strong>segment id</strong>: If your downstream task need input two sentences (e.g. sentence pair classification, question answering), segment id is used to distinguish first and second sentence. If your task only have one sentence as input, you only need to create a constant array with any index.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*fbSGn2IPabfNRWVU.png" /></figure><p>Let us create these input tensors step by step then you will be clear on that.</p><ol><li><strong>import package &amp; download tokenizer and model:</strong></li></ol><pre>import torch  <br>from transformers import BertTokenizer,BertModel<br><br>tokenizer = BertTokenizer.from_pretrained(&#39;bert-base-uncased&#39;) <br>model = BertModel.from_pretrained(&quot;bert-base-uncased&quot;)<br><br># models: https://huggingface.co/models?sort=downloads</pre><p><strong>2. tokenize the sequence</strong></p><pre>sentence = &#39;I really enjoyed this movie a lot.&#39;<br><br>tokens = tokenizer.tokenize(sentence)<br>print(tokens)<br># [&#39;i&#39;, &#39;really&#39;, &#39;enjoyed&#39;, &#39;this&#39;, &#39;movie&#39;, &#39;a&#39;, &#39;lot&#39;, &#39;.&#39;]</pre><p><strong>3. Add [CLS] and [SEP] tokens</strong></p><pre>tokens = [&#39;[CLS]&#39;] + tokens + [&#39;[SEP]&#39;]<br>tokens<br># [&#39;[CLS]&#39;, &#39;i&#39;, &#39;really&#39;, &#39;enjoyed&#39;, &#39;this&#39;, &#39;movie&#39;, &#39;a&#39;, &#39;lot&#39;, &#39;.&#39;, &#39;[SEP]&#39;]</pre><p><strong>4. Padding the input</strong></p><pre>T=15<br>padded_tokens = tokens + [&#39;[PAD]&#39; for _ in range(T-len(tokens))]<br>print(&quot;Padded tokens are \n {} &quot;.format(padded_tokens))<br>attn_mask = [ 1 if token != &#39;[PAD]&#39; else 0 for token in padded_tokens  ]<br>print(&quot;Attention Mask are \n {} &quot;.format(attn_mask))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*274xOecSRApOYsWfk5rpcQ.png" /></figure><p><strong>5. Create a list of segment tokens</strong></p><pre>seg_ids = [0 for _ in range(len(padded_tokens))]</pre><p><strong>6. Create input tensor for all of this stuff</strong></p><pre>sent_ids = tokenizer.convert_tokens_to_ids(padded_tokens)<br>token_ids = torch.tensor(sent_ids).unsqueeze(0) <br>attn_mask = torch.tensor(attn_mask).unsqueeze(0) <br>seg_ids   = torch.tensor(seg_ids).unsqueeze(0)<br><br>print(token_ids)<br>print(attn_mask)<br>print(seg_ids)<br><br># tensor([[ 101, 1045, 2428, 5632, 2023, 3185, 1037, 2843, 1012, 102, 0, 0, 0, 0, 0]])<br># tensor([[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0]])<br># tensor([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]])</pre><p><strong>7. model inference</strong></p><p>So far, we’ve already prepared the input BERT need, we are ready to feed all this stuffs into model then get the sentence embedding.</p><pre>output = model(token_ids, attention_mask=attn_mask,token_type_ids=seg_ids)<br>last_hidden_state, pooler_output = output[0], output[1]<br><br>print(last_hidden_state.shape) #hidden states of each token<br>print(pooler_output.shape) #hidden states of [cls] (forward one linear layer and Tanh activation)</pre><p>Basically, pooler_output is what we want. We only need to add some linear layer to create output layer for our downstream task to fine-tune the neural network. For example:</p><pre>from transformers import BertTokenizer,BertModel<br><br>class BERT_classifier(nn.Module):<br>    def __init__(self, bertmodel, num_label):<br>        super(BERT_classifier, self).__init__()<br>        self.bertmodel = bertmodel<br>        self.classifier = nn.Linear(bertmodel.config.hidden_size, num_label)<br><br>    def forward(self, wrapped_input):<br>        hidden = self.bertmodel(**wrapped_input)<br>        last_hidden_state, pooler_output = hidden[0], hidden[1]<br>        logits = self.classifier(pooler_output)<br><br>        return logits<br><br>bert = BertModel.from_pretrained(&quot;bert-base-uncased&quot;)<br>model = BERT_classifier(bert, 2)</pre><p>you also can just use the build in model structure in Huggingface, e.g. BertForSequenceClassification, BertForQuestionAnswering</p><pre>from transformers import BertForSequenceClassification<br>model = BertForSequenceClassification.from_pretrained(&#39;bert-base-uncased&#39;, num_labels=2)<br><br># this has same model structure as above</pre><p>You might have noticed that it’s very easy to inference with BERT, the main effort is to create the input tensor of BERT.</p><p>In the real situation, we don’t need to construct input tensor step by step like in the above described. The tokenizer has already wrapped all this work into a single command.</p><p>We can just use the below command to replace the step 2,3,4,5.</p><pre>wrapped_input = tokenizer(sentence, max_length=15, add_special_tokens=True, truncation=True, <br>                          padding=&#39;max_length&#39;, return_tensors=&quot;pt&quot;)<br>                          <br>wrapped_input<br>#{&#39;input_ids&#39;: tensor([[ 101, 1045, 2428, 5632, 2023, 3185, 1037, 2843, 1012, 102, 0, 0, 0, 0, 0]]), <br>  &#39;token_type_ids&#39;: tensor([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]), <br>  &#39;attention_mask&#39;: tensor([[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0]])}</pre><blockquote>Note: <em>padding=True</em> will padding to the longest setence length,<br>on the other hand, if padding=‘max_length’ then it will padding to the length “max_length”</blockquote><p>unpack this dict and feed it into the model then we’ll get the embedding</p><pre>output = model(**wrapped_input)<br>last_hidden_state, pooler_output = output[0], output[1]</pre><h3>Exercise</h3><p>I take IMDb movie review as an example (BERTforSequenceClassification). The goal is to classify whether the movie review is positive or negative.</p><p>Basically, it’s just PyTorch training pipeline so I’m not going to talk too much in this article. I put jupyter notebook in <a href="https://github.com/henry16lin/BERTforSequenceClassification">this github repo</a> you can refer to it.</p><p>The val acc ~92.5% and test set acc = 23084 / 25000(92.336%)</p><pre>[epoch 1]train on 24000 data......<br>100%|██████████| 1500/1500 [09:24&lt;00:00,  2.66it/s]<br>training set: average loss: 0.0168, acc: 21350/24000(88.958%)<br>validation on 1000 data......<br>Val set:Average loss:0.0120, acc:928/1000(92.800%)<br>elapse: 575.06s<br><br>[epoch 2]train on 24000 data......<br>100%|██████████| 1500/1500 [09:15&lt;00:00,  2.70it/s]<br>training set: average loss: 0.0094, acc: 22685/24000(94.521%)<br>validation on 1000 data......<br>Val set:Average loss:0.0126, acc:936/1000(93.600%)<br>elapse: 566.25s<br><br>[epoch 3]train on 24000 data......<br>100%|██████████| 1500/1500 [09:19&lt;00:00,  2.68it/s]<br>training set: average loss: 0.0054, acc: 23321/24000(97.171%)<br>validation on 1000 data......<br>Val set:Average loss:0.0166, acc:925/1000(92.500%)<br>elapse: 569.87s <br><br>[epoch 4]train on 24000 data......<br>100%|██████████| 1500/1500 [09:18&lt;00:00,  2.69it/s]<br>training set: average loss: 0.0032, acc: 23621/24000(98.421%)<br>validation on 1000 data......<br>Val set:Average loss:0.0196, acc:925/1000(92.500%)<br>elapse: 568.86s <br><br>[epoch 5]train on 24000 data......<br>100%|██████████| 1500/1500 [09:21&lt;00:00,  2.67it/s]<br>training set: average loss: 0.0021, acc: 23743/24000(98.929%)<br>validation on 1000 data......<br>Val set:Average loss:0.0180, acc:925/1000(92.500%)<br>elapse: 572.23s</pre><h3>Sentence Similarity</h3><p>When you are trying to do sentence/doc clustering or intention matching, you will need to do sentence similarity.</p><p>You might think about using BERT embedding we got from the above section and then calculate Euclidean distance or cosine similarity between two sentence embeddings. However, it’s not a good solution.</p><p>Reminding that BERT pre-train was trained by <em>MaskedLM</em>, <em>NextSentencePrediction,</em> hence the original purpose of BERT is not to create a meaningful embedding of the sentence but for some specific downstream task.</p><blockquote><strong>Jacob Devlin’s comment:</strong> I’m not sure what these vectors are, since BERT does not generate meaningful sentence vectors. It seems that this is is doing average pooling over the word tokens to get a sentence vector, but we never suggested that this will generate meaningful sentence representations. And even if they are decent representations when fed into a DNN trained for a downstream task, it doesn’t mean that they will be meaningful in terms of cosine distance. (Since cosine distance is a linear space where all dimensions are weighted equally). (<a href="https://github.com/google-research/bert/issues/164#issuecomment-441324222">https://github.com/google-research/bert/issues/164#issuecomment-441324222</a>)</blockquote><p>If you want to use BERT to do sentence similarity, the closest task should be <em>sentence pair classification.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bm9U94KnHVLMT5kr1MtCMg.png" /></figure><p>input is two sentences that you want to compare with and the target is whether these two sentences have the same meaning or not.</p><p>However, this method is not efficient. Imagine that you have 100 sentences and you want to know the similarity of each pair of sentences, then you need to feedforward BERT C(100, 2) = 4950 times.</p><p>The straightforward way is to train a meaningful embedding, then the embedding vector will contain the “meaning” of the sentence. You only need to calculate the similarity of the embedding vector to get the sentence similarity.</p><p><strong>Siamese Networks</strong> might come to your mind. Feedforward two BERT layers separately, then use <em>Contrastive loss</em> or <em>Triplet loss</em> to train the embedding.</p><p>This is a good idea and of course, it has been published in paper and developed into a well-used package.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*pRundV0Wns38EAohkG-0_A.png" /></figure><p>You can refer to <a href="https://arxiv.org/abs/1908.10084">Sentence-BERT: Sentence Embeddings using Siamese BERT-Networks</a>. The core idea is just to use BERT to train Siamese Network.</p><p>The authors consider three ways in the pooling strategies,: Using the output of the CLS-token, computing the mean of all output vectors (MEANstrategy), and computing a max-over-time of the output vectors (MAX-strategy), and finally choosing MEAN strategy as the default option.</p><p>The most important part is that they developed <a href="https://www.sbert.net/">sentence-transformers</a> and it offers the pretrain model which saves you the biggest effort: data collection and labeling!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/566/1*zlXcILWBUNcmNRmKWDBtLA.png" /></figure><h3>Exercise</h3><p>Suppose we are going to develop a chatbot and we need to do intention matching. Let us do a simple experiment.</p><p>First, import package and load model.</p><pre>from sentence_transformers import SentenceTransformer, util<br><br>model = SentenceTransformer(&#39;paraphrase-multilingual-MiniLM-L12-v2&#39;)  # multi-language model<br><br>sentences = [<br>    &#39;what is the weather tomorrow&#39;,<br>    &#39;will it rain tomorrow&#39;,<br>    &#39;Will the weather be hot in the future&#39;,<br>    &#39;what time is it&#39;,<br>    &#39;could you help me translate this setence&#39;,<br>    &#39;play some jazz music&#39;<br>]</pre><p>use this model to get the embedding of each sentence:</p><pre>embedding = model.encode(sentences, convert_to_tensor=False)<br>embedding.shape<br>#(6, 384)</pre><p>We can see the six sentences have been transformed into 384d embedding vectors.</p><p>Then we calculate cosine similarity pairwise and observe the result.</p><pre>cosine_scores = util.cos_sim(embedding, embedding)<br><br>d = {}<br>for i, v1 in enumerate(sentences):<br>    for j, v2 in enumerate(sentences):<br>        if i &gt;= j:<br>            continue<br>        d[v1 + &#39; vs. &#39; + v2] = cosine_scores[i][j].item()<br><br># sort by score<br>d_sorted = dict(sorted(d.items(), key=lambda x: x[1], reverse=True))<br>d_sorted<br><br>{&#39;what is the weather tomorrow vs. will it rain tomorrow&#39;: 0.8252906203269958,<br> &#39;what is the weather tomorrow vs. Will the weather be hot in the future&#39;: 0.6635355949401855,<br> &#39;will it rain tomorrow vs. Will the weather be hot in the future&#39;: 0.5936063528060913,<br> &#39;what is the weather tomorrow vs. what time is it&#39;: 0.47494661808013916,<br> &#39;will it rain tomorrow vs. what time is it&#39;: 0.4440332055091858,<br> &#39;Will the weather be hot in the future vs. what time is it&#39;: 0.33612486720085144,<br> &#39;could you help me translate this setence vs. play some jazz music&#39;: 0.1588955670595169,<br> &#39;what is the weather tomorrow vs. play some jazz music&#39;: 0.11192889511585236,<br> &#39;will it rain tomorrow vs. play some jazz music&#39;: 0.09996305406093597,<br> &#39;will it rain tomorrow vs. could you help me translate this setence&#39;: 0.09915214776992798,<br> &#39;what time is it vs. could you help me translate this setence&#39;: 0.09021759033203125,<br> &#39;what is the weather tomorrow vs. could you help me translate this setence&#39;: 0.08801298588514328,<br> &#39;Will the weather be hot in the future vs. could you help me translate this setence&#39;: 0.07638849318027496,<br> &#39;what time is it vs. play some jazz music&#39;: 0.054117172956466675,<br> &#39;Will the weather be hot in the future vs. play some jazz music&#39;: 0.027871515601873398}</pre><p>The score seems to be quite reasonable!</p><h3>Reference</h3><p><a href="https://blog.csdn.net/qq_40990057/article/details/119888442">NLP之Transformers：BERT的应用、训练和优化</a></p><p><a href="https://towardsdatascience.com/bert-for-measuring-text-similarity-eec91c6bf9e1">BERT setence similarity</a></p><p><a href="https://www.sbert.net/">SentenceTransformers</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=759f7beccbf1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sentence Embedding by BERT and Sentence Similarity (中文)]]></title>
            <link>https://peaceful0907.medium.com/sentence-embedding-by-bert-and-sentence-similarity-%E4%B8%AD%E6%96%87-9eddef28dc79?source=rss-d2d57a7d3dc9------2</link>
            <guid isPermaLink="false">https://medium.com/p/9eddef28dc79</guid>
            <category><![CDATA[natural-language-process]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[CW Lin]]></dc:creator>
            <pubDate>Tue, 24 Jan 2023 15:09:52 GMT</pubDate>
            <atom:updated>2023-01-24T15:09:52.532Z</atom:updated>
            <content:encoded><![CDATA[<p>BERT 的原理就不贅述了，網路上很多教學，我也在 <a href="https://medium.com/@peaceful0907/%E4%BE%86%E7%8E%A9%E9%BB%9Enlp-lstm-vs-bert-on-imdb-dataset-4aa18ecd65e2">來玩點NLP — LSTM vs. BERT on IMDb dataset</a> 這篇有大概介紹，有興趣可以去看看，只是我發現我在那篇裡使用了比較麻煩的方式來 fine-tune BERT 做文本分類，可能最近 BERT 發展得越來越方便使用，或是當時我沒發現比較方便的用法🤢</p><p>總之 這篇來記錄一下如何用 BERT 取得 sentence embedding 來 fine-tune downstream task 以及額外多寫一個 sentence similarity 的 task。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/896/0*g0trzlwLX7Hg-MSM.png" /><figcaption><a href="https://www.codemotion.com/magazine/ai-ml/bert-how-google-changed-nlp-and-how-to-benefit-from-this/">https://www.codemotion.com/magazine/ai-ml/bert-how-google-changed-nlp-and-how-to-benefit-from-this/</a></figcaption></figure><h3>BERT sentence embedding for downstream task</h3><p>基本上，概念就是把 sentence (i.e. sequence of text) 轉換成 vector 然後再接linear layer 做 downstream task。</p><p>BERT 提供下列四種 downstream task 的使用範例:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/784/0*pBfhtVlQn8E9bhGJ.png" /></figure><p>要使用BERT 必須先準備好 BERT 所需要的 input:</p><ol><li><strong>token id</strong>: 每個單字在字典裡對應的一個 index</li><li><strong>attention mask</strong>: 每個句子會padding成一樣長度，attention mask 讓self-attention layer 知道哪些是padding 把他mask 起來讓它不會去關注padding的特殊字 ([PAD])</li><li><strong>segment id</strong>: 針對一次要 input 兩個句子的任務用來區分第一個句子和第二個句子的 index，若 input 只有一個句子則隨便給一個一致的index 即可。</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/833/0*fbSGn2IPabfNRWVU.png" /></figure><p>我們來一步一步做一遍就很清楚了:</p><ol><li><strong>import 相關套件 &amp; download tokenizer and model:</strong></li></ol><pre>import torch  <br>from transformers import BertTokenizer,BertModel<br><br>tokenizer = BertTokenizer.from_pretrained(&#39;bert-base-uncased&#39;) <br>model = BertModel.from_pretrained(&quot;bert-base-uncased&quot;)<br><br># models: https://huggingface.co/models?sort=downloads</pre><p><strong>2. tokenize the sequence</strong></p><pre>sentence = &#39;I really enjoyed this movie a lot.&#39;<br><br>tokens = tokenizer.tokenize(sentence)<br>print(tokens)<br># [&#39;i&#39;, &#39;really&#39;, &#39;enjoyed&#39;, &#39;this&#39;, &#39;movie&#39;, &#39;a&#39;, &#39;lot&#39;, &#39;.&#39;]</pre><p><strong>3. Add [CLS] and [SEP] tokens</strong></p><pre>tokens = [&#39;[CLS]&#39;] + tokens + [&#39;[SEP]&#39;]<br>tokens<br># [&#39;[CLS]&#39;, &#39;i&#39;, &#39;really&#39;, &#39;enjoyed&#39;, &#39;this&#39;, &#39;movie&#39;, &#39;a&#39;, &#39;lot&#39;, &#39;.&#39;, &#39;[SEP]&#39;] </pre><p><strong>4. Padding the input</strong></p><pre>T=15<br>padded_tokens = tokens + [&#39;[PAD]&#39; for _ in range(T-len(tokens))]<br>print(&quot;Padded tokens are \n {} &quot;.format(padded_tokens))<br>attn_mask = [ 1 if token != &#39;[PAD]&#39; else 0 for token in padded_tokens  ]<br>print(&quot;Attention Mask are \n {} &quot;.format(attn_mask))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*274xOecSRApOYsWfk5rpcQ.png" /></figure><p><strong>5. Create a list of segment tokens</strong></p><pre>seg_ids = [0 for _ in range(len(padded_tokens))]</pre><p><strong>6. Create input tensor for all of this stuff</strong></p><pre>sent_ids = tokenizer.convert_tokens_to_ids(padded_tokens)<br>token_ids = torch.tensor(sent_ids).unsqueeze(0) <br>attn_mask = torch.tensor(attn_mask).unsqueeze(0) <br>seg_ids   = torch.tensor(seg_ids).unsqueeze(0)<br><br>print(token_ids)<br>print(attn_mask)<br>print(seg_ids)<br><br># tensor([[ 101, 1045, 2428, 5632, 2023, 3185, 1037, 2843, 1012, 102, 0, 0, 0, 0, 0]])<br># tensor([[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0]])<br># tensor([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]])</pre><p><strong>7. model inference</strong></p><p>到目前為止我們已經準備好BERT所需要的東西了 把這堆 tensor 餵進去model 就能得到embedding了～</p><pre>output = model(token_ids, attention_mask=attn_mask,token_type_ids=seg_ids)<br>last_hidden_state, pooler_output = output[0], output[1]<br><br>print(last_hidden_state.shape) #hidden states of each token<br>print(pooler_output.shape) #hidden states of [cls] (forward one linear layer and Tanh activation)</pre><p>(<a href="https://blog.csdn.net/zhaohongfei_358/article/details/127960742">這篇文章</a>有關於 last_hidden_state, pooler_output 的介紹)</p><p>基本上 pooler_output 就是我們想要的 sentence embedding，使用上 後面再串幾層 layer 組成我們要解決的 task 就能直接fine tune了。 如果懶得自己接layer組網路架構的話 也能直接用BERT提供的幾個網路架構 e.g. BertForSequenceClassification, BertForQuestionAnswering</p><blockquote><strong>基本款：</strong><br> — bertModel<br> — bertTokenizer<br><strong>預訓練階段:</strong><br> — bertForMaskedLM<br> — bertForNextSentencePrediction<br> — bertForPreTraining<br><strong>Fine-tuning 階段</strong><br> — bertForSequenceClassification<br> — bertForTokenClassification<br> — bertForQuestionAnswering<br> — bertForMultipleChoice</blockquote><p>看到這邊可以發現，要做 sentence embedding 主要的功都是花在組 BERT 的 input tensor。上面做過一遍應該也能比較清楚這些 tensor 是幹什麼的以及如何得到。<br>但其實 tokenizer 已經都把這些東西給封裝好了 (不論是AutoTokenizer or BertTokenizer)<br>上面的 2,3,4,5,6 步驟其實都可以被省略為以下這個做法</p><pre>wrapped_input = tokenizer(sentence, max_length=15, add_special_tokens=True, truncation=True, <br>                          padding=&#39;max_length&#39;, return_tensors=&quot;pt&quot;)<br>                          <br>wrapped_input<br>#{&#39;input_ids&#39;: tensor([[ 101, 1045, 2428, 5632, 2023, 3185, 1037, 2843, 1012, 102, 0, 0, 0, 0, 0]]), <br>  &#39;token_type_ids&#39;: tensor([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]), <br>  &#39;attention_mask&#39;: tensor([[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0]])}</pre><p>一下就得到 token_ids, attn_mask, seg_ids 了，背後也都已經做了padding~ (前面到底在辛苦什麼 XDD)</p><blockquote>Note: padding=True will padding to the longest setence length,<br>on the other hand, if padding=‘max_length’ then it will padding to the length “max_length”</blockquote><p>直接把這個 dict 丟給 model 就可以得到embedding 結果</p><pre>output = model(**wrapped_input)<br>last_hidden_state, pooler_output = output[0], output[1]</pre><h4><strong>小試身手</strong></h4><p>一樣使用 imdb 電影影評來實作文本分類 (BERTforSequenceClassification) 基本上就是 pytorch 的 training pipeline 我直接把 notebook 放到<a href="https://github.com/henry16lin/BERTforSequenceClassification">這個repo</a> ，有興趣參考就去看看吧～</p><p>訓練時 val acc ~92.5% , 最後 test set acc = 23084 / 25000(92.336%)</p><pre>[epoch 1]train on 24000 data......<br>100%|██████████| 1500/1500 [09:24&lt;00:00,  2.66it/s]<br>training set: average loss: 0.0168, acc: 21350/24000(88.958%)<br>validation on 1000 data......<br>Val set:Average loss:0.0120, acc:928/1000(92.800%)<br>elapse: 575.06s <br><br>[epoch 2]train on 24000 data......<br>100%|██████████| 1500/1500 [09:15&lt;00:00,  2.70it/s]<br>training set: average loss: 0.0094, acc: 22685/24000(94.521%)<br>validation on 1000 data......<br>Val set:Average loss:0.0126, acc:936/1000(93.600%)<br>elapse: 566.25s <br><br>[epoch 3]train on 24000 data......<br>100%|██████████| 1500/1500 [09:19&lt;00:00,  2.68it/s]<br>training set: average loss: 0.0054, acc: 23321/24000(97.171%)<br>validation on 1000 data......<br>Val set:Average loss:0.0166, acc:925/1000(92.500%)<br>elapse: 569.87s <br><br>[epoch 4]train on 24000 data......<br>100%|██████████| 1500/1500 [09:18&lt;00:00,  2.69it/s]<br>training set: average loss: 0.0032, acc: 23621/24000(98.421%)<br>validation on 1000 data......<br>Val set:Average loss:0.0196, acc:925/1000(92.500%)<br>elapse: 568.86s <br><br>[epoch 5]train on 24000 data......<br>100%|██████████| 1500/1500 [09:21&lt;00:00,  2.67it/s]<br>training set: average loss: 0.0021, acc: 23743/24000(98.929%)<br>validation on 1000 data......<br>Val set:Average loss:0.0180, acc:925/1000(92.500%)<br>elapse: 572.23s</pre><h3>Sentence Similarity</h3><p>當我想要做一些語句的 clustering 或是想要比對語句的相似度時(如在語音機器人裡，針對同一個需求但不同的問法, <em>i.e. intention matching</em>)，可能會需要用到 sentence similarity。</p><p>你可能會想到直接套用上面的BERT embedding 來直接算一下歐氏距離或cosine similarity，但其實這樣做是不好的。想想 這個 BERT的 pre-train 是透過 <em>MaskedLM</em>, <em>NextSentencePrediction </em>這兩個 task 來訓練得到的，所以 BERT 原始用法並不是用來產生 一個 meaningful 的 embedding 。</p><blockquote><strong>Jacob Devlin’s comment:</strong> I’m not sure what these vectors are, since BERT does not generate meaningful sentence vectors. It seems that this is is doing average pooling over the word tokens to get a sentence vector, but we never suggested that this will generate meaningful sentence representations. And even if they are decent representations when fed into a DNN trained for a downstream task, it doesn’t mean that they will be meaningful in terms of cosine distance. (Since cosine distance is a linear space where all dimensions are weighted equally). (<a href="https://github.com/google-research/bert/issues/164#issuecomment-441324222">https://github.com/google-research/bert/issues/164#issuecomment-441324222</a>)</blockquote><p>如果想用 BERT 來做 sentence similarity 比較接近的 task 應該是 <em>bertForSequenceClassification 的 成對句子分類任務</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/365/1*ruk-zL8-aZLBml8P90-_HA.png" /></figure><p>輸入兩個句子，然後 label 為是否為同一個意思。但這種做法如果你有100個句子要算兩兩的相似度的話，你就必須將這個網路 feedforward C(100, 2) = 4950 次。</p><p>比較直接的做法是訓練一個 meaningful 的 embedding，將來要是有任何要做sentence 比對的問題時就可以直接透過embedding 來計算相似度就好。</p><p>那你可能會聯想到 <strong>Siamese Network (</strong><a href="https://medium.com/@peaceful0907/few-shot-learning-siamese-network-73bc0a98c6fa">Few Shot Learning — Siamese Network</a> 我在這篇有介紹<strong>) </strong>串兩個 BERT 得到 embedding 後使用<strong> </strong>Contrastive loss or Triplet loss 來訓練 embedding。</p><p>沒錯 這個想法已經被發成 paper，並且也都開發成非常好用的工具了</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pRundV0Wns38EAohkG-0_A.png" /></figure><p>大家可以看這篇<a href="https://arxiv.org/abs/1908.10084"> Sentence-BERT: Sentence Embeddings using Siamese BERT-Networks</a> 其實就是 BERT 的 Siamese Network。</p><p>在 pooling strategies，paper 考慮了三種做法: Using the output of the CLS-token, computing the mean of all output vectors (MEANstrategy), and computing a max-over-time of the output vectors (MAX-strategy). 而最後選擇了使用 MEAN strategy.</p><p>最重要的是他們開發的 <a href="https://www.sbert.net/">sentence-transformers</a> 提供了 pretrain model，讓你省去最大的麻煩 — 搜集資料以及 labelling !</p><h4><strong>小試身手</strong></h4><p>我假設是一個要做語音助理的 intention matchin 來簡單做個實驗。</p><p>首先 import 套件並 load model.</p><pre>from sentence_transformers import SentenceTransformer, util<br><br>model = SentenceTransformer(&#39;paraphrase-multilingual-MiniLM-L12-v2&#39;)  # 多語言模型<br><br>sentences = [<br>    &#39;what is the weather tomorrow&#39;,<br>    &#39;will it rain tomorrow&#39;,<br>    &#39;Will the weather be hot in the future&#39;,<br>    &#39;what time is it&#39;,<br>    &#39;could you help me translate this setence&#39;,<br>    &#39;play some jazz music&#39;<br>]</pre><p>用這個 model 取得每個句子的 embedding</p><pre>embedding = model.encode(sentences, convert_to_tensor=False)<br>embedding.shape<br>#(6, 384)</pre><p>可以看到6個句子變成 6 個 384d 的 embedding vector</p><p>然後我們計算兩兩的 cosine similarity 來看看是否和直覺相符</p><pre>cosine_scores = util.cos_sim(embedding, embedding)<br><br>d = {}<br>for i, v1 in enumerate(sentences):<br>    for j, v2 in enumerate(sentences):<br>        if i &gt;= j:<br>            continue<br>        d[v1 + &#39; vs. &#39; + v2] = cosine_scores[i][j].item()<br><br># sort by score<br>d_sorted = dict(sorted(d.items(), key=lambda x: x[1], reverse=True))<br>d_sorted<br><br>{&#39;what is the weather tomorrow vs. will it rain tomorrow&#39;: 0.8252906203269958,<br> &#39;what is the weather tomorrow vs. Will the weather be hot in the future&#39;: 0.6635355949401855,<br> &#39;will it rain tomorrow vs. Will the weather be hot in the future&#39;: 0.5936063528060913,<br> &#39;what is the weather tomorrow vs. what time is it&#39;: 0.47494661808013916,<br> &#39;will it rain tomorrow vs. what time is it&#39;: 0.4440332055091858,<br> &#39;Will the weather be hot in the future vs. what time is it&#39;: 0.33612486720085144,<br> &#39;could you help me translate this setence vs. play some jazz music&#39;: 0.1588955670595169,<br> &#39;what is the weather tomorrow vs. play some jazz music&#39;: 0.11192889511585236,<br> &#39;will it rain tomorrow vs. play some jazz music&#39;: 0.09996305406093597,<br> &#39;will it rain tomorrow vs. could you help me translate this setence&#39;: 0.09915214776992798,<br> &#39;what time is it vs. could you help me translate this setence&#39;: 0.09021759033203125,<br> &#39;what is the weather tomorrow vs. could you help me translate this setence&#39;: 0.08801298588514328,<br> &#39;Will the weather be hot in the future vs. could you help me translate this setence&#39;: 0.07638849318027496,<br> &#39;what time is it vs. play some jazz music&#39;: 0.054117172956466675,<br> &#39;Will the weather be hot in the future vs. play some jazz music&#39;: 0.027871515601873398}</pre><p>看起來相似度是還跟直覺相符合的～</p><p>我也嘗試過繁體中文的 case，看起來也是蠻正確的，另外想想一般的中文可能簡體中文在網路上的量會遠大於繁體，所以查了一下發現我們中研院也有發佈繁體中文的 pre-train model 也有包含在 huggingface 裡(<a href="https://huggingface.co/ckiplab">https://huggingface.co/ckiplab</a>)，使用上非常方便！</p><h3>Reference</h3><p><a href="https://blog.csdn.net/qq_40990057/article/details/119888442">NLP之Transformers：BERT的应用、训练和优化</a></p><p><a href="https://towardsdatascience.com/bert-for-measuring-text-similarity-eec91c6bf9e1">BERT setence similarity</a></p><p><a href="https://ithelp.ithome.com.tw/articles/10304308?sc=iThelpR">Hugging Face 中文的文本生成 (中研院詞庫小組)</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9eddef28dc79" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Time series prediction — LSTM的各種用法]]></title>
            <link>https://peaceful0907.medium.com/time-series-prediction-lstm%E7%9A%84%E5%90%84%E7%A8%AE%E7%94%A8%E6%B3%95-ed36f0370204?source=rss-d2d57a7d3dc9------2</link>
            <guid isPermaLink="false">https://medium.com/p/ed36f0370204</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[time-series-forecasting]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[CW Lin]]></dc:creator>
            <pubDate>Thu, 16 Jun 2022 15:06:07 GMT</pubDate>
            <atom:updated>2022-06-16T15:06:07.562Z</atom:updated>
            <content:encoded><![CDATA[<h3>Time series prediction — LSTM的各種用法</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5JBKinMPftiGovQ4" /><figcaption>Photo by <a href="https://unsplash.com/@ismailhamzahk?utm_source=medium&amp;utm_medium=referral">Ismail Hamzah</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>前陣子剛好有機會碰到time series的題目，但在要使用 LSTM 時突然很猶豫到底該怎麼用比較好，於是便每種都使用看看，這篇以股價預測的資料作為範例紀錄以下這幾種做法:</p><ol><li>LSTM for multi-step prediction</li><li>LSTM auto encoder model</li><li>LSTM Seq2Seq model</li></ol><p>LSTM的原理就不贅述了，網路上很多教學，不過當然還是首推<a href="https://www.youtube.com/watch?v=xCGidAeyS4M">李宏毅老師的課程</a>，真的蠻仔細的 👍<br>另外會用 multi-step prediction 的原因是想說，如果有個模型可以輔助我去決定要不要買某檔股票，我應該不會只想知道隔天的預測，我可能會想知道未來一週(5天)的預測結果來做一個綜合的考量。</p><h3>data</h3><p>首先，我們要先準備一下實驗用的資料，就挑選2330 台積電近五年的資料來做實驗吧，可以在<a href="https://hk.finance.yahoo.com/quote/2330.TW/history/">奇摩財經這邊直接下載csv</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/918/1*OqyLGRjHm_jaXAeC1sZWpQ.png" /></figure><p>資料會長成像上面那樣，那我們這次的目標就是：</p><p><strong>透過前四週(20天) 的 (open, high, low, close, volume) 的數據去預測未來一週(五天) 的 close price</strong></p><p>也就是說我們每筆資料的input size是(seq_length, feature_dim) =(20, 5)</p><p>那接著就是把資料給整理成一個一個的 time windows 來做 model的 input:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Tyx0g9Lxd1pN71YmeKjlIA.png" /><figcaption>sliding windows 示意圖 (<a href="https://medium.com/towards-data-science/encoder-decoder-model-for-multistep-time-series-forecasting-using-pytorch-5d54c6af6e60">source</a>)</figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/afa157b54be605445b6aaa9f8a120ed0/href">https://medium.com/media/afa157b54be605445b6aaa9f8a120ed0/href</a></iframe><p>上面的程式碼做了四件事：</p><ol><li>normalization</li><li>切 validation set</li><li>create sequence windows</li><li>create train, val 的 dataloader</li></ol><p>設定train ratio = 0.8，看一下收盤價的 trend:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DQv8rJctIox-t4eklGL5Bw.png" /><figcaption>2330 close price</figcaption></figure><p>然後看一下切 window 後資料的形狀：</p><pre>print(X_train.shape) # torch.Size([624, 20, 5])<br>print(Y_train.shape) # torch.Size([624, 5])</pre><p>我們一共切了624個長度為20的windows，每個window 的dimension是 5，<br>ok 那這樣資料就準備好了～接著就是來準備模型吧</p><h3>LSTM for multi-step prediction</h3><p>這個情境下的模型相對另外兩種來說比較簡單，就是直接output一個要預測多久未來長度的向量，大架構如下圖:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aFXWrWGk9zxsPegdvP1y6A.png" /></figure><p>把他寫成 pytorch 程式碼:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5dd3ae3486d049c67fa64e094401e207/href">https://medium.com/media/5dd3ae3486d049c67fa64e094401e207/href</a></iframe><p>這個模型架構基本上就是兩層 LSTM 然後接一層linear 調整成output的形狀</p><pre>LSTM(<br>  (lstm): LSTM(5, 128, num_layers=2, batch_first=True, dropout=0.2)<br>  (linear): Linear(in_features=128, out_features=5, bias=True)<br>)</pre><p><em>Note1: LSTM layer 出來的 (batch_size, sequence length)和 input 相同，只有 feature dim 被改變了</em></p><p><em>Note2: LSTM layer 出來有兩個東西 output, (hn, cn) 其中<br> output: 保存了最後一層，每個 time step的輸出 h，如果是雙向 LSTM，每個time step的輸出 h = [h正向, h逆向] (同 time step的正向和逆向的 h連起來)。<br> hn保存了每一層，最後一個 time step 的 h，而 cn 保存的是 c 的值</em></p><p>上面的程式碼，LSTM 出來後取最後一層的最後一個time step 的 state 來丟到linear layer(如下圖的紅框)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hVS8J3QsZwqU_jzfR7m5cA.png" /></figure><p>那接下來就是把這個模型給訓練起來就好，loss function使用 nn.MSELoss()，optimizer 使用 <a href="https://github.com/lessw2020/Ranger-Deep-Learning-Optimizer">Ranger</a>，並且使用<a href="https://medium.com/ai-blog-tw/sharpness-aware-minimization-sam-%E7%B0%A1%E5%96%AE%E6%9C%89%E6%95%88%E5%9C%B0%E8%BF%BD%E6%B1%82%E6%A8%A1%E5%9E%8B%E6%B3%9B%E5%8C%96%E8%83%BD%E5%8A%9B-257613bb365"> SAM</a> 進行訓練。</p><p>我每個epoch 除了計算MSE loss 外，也把 input 和 target 換算回原來的scale(normalize的反運算)來比較直觀地看每個epoch 模型的誤差是多少</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/06812cf9594172e3e56fc145ce191031/href">https://medium.com/media/06812cf9594172e3e56fc145ce191031/href</a></iframe><p>一共訓練了200 epoch，結果如下:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VGyT0_4CgjNRlw2zAFtQDw.png" /></figure><p>可以看到，最後val set MAE在未來五天的整體平均誤差來到17.5左右，其實還蠻爛的，我不會相信這個模型去買股票XD</p><p>後來又想說，每過一天我們又有新的收盤資料，應該會用新的資料來更新對未來2~5天的預測結果，所以如果我每次預測都只看最近一天的預測結果，來看看預測的準確度會如何：</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/275b225744c9b0aaede7d0b9f5fb3129/href">https://medium.com/media/275b225744c9b0aaede7d0b9f5fb3129/href</a></iframe><p>得到的預測情形就會像這樣：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*3XTNZBr0kEP4zsQtoQIhZA.png" /></figure><p>也就是說，如果我們只看即將到來的那一天的預測值，那麼 MAE 誤差變成14.9，而誤差百分比 MAPE 則是2.5%</p><h3>LSTM Auto Encoder model</h3><p>這個模型的想法是由 encoder 來讀前20天的資料，並且將這20天資料的日月精華傳給decoder，再由decoder 轉成想要的output shape。和前面不一樣的是，decoder 重構出來的資料不只是未來五天的close price，我打算output每個 feature 的預測(感覺也不一定要這樣，只是這樣比較有和encoder對稱一點的感覺)，所以dimension 就是:</p><p>input: [batch_size, seq_length=20, feature_dim=5]<br>output: [batch_size, seq_length=5, feature_dim=5]</p><p>模型架構大概如下:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7x_g-TzA1Raoah5uO4szEA.png" /></figure><p>那來把這個架構給變成程式碼:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/acbb0588c413bf725c64dc24ad22e872/href">https://medium.com/media/acbb0588c413bf725c64dc24ad22e872/href</a></iframe><pre>LSTMAutoencoder(<br>  (encoder): LSTMEncoder(<br>    (lstm1): LSTM(5, 64, batch_first=True)<br>    (lstm2): LSTM(64, 36, batch_first=True)<br>  )<br>  (decoder): LSTMDecoder(<br>    (lstm1): LSTM(36, 36, batch_first=True)<br>    (lstm2): LSTM(36, 64, batch_first=True)<br>    (output_layer): Linear(in_features=64, out_features=5, bias=True)<br>  )<br>)</pre><p>接下來就是訓練這個模型，但這個架構下我對未來五個feature 都有進行預測(open, high, low, close, volume)，但其實我們只在意 close 的表現，所以對loss function 做了一下小修改：</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/af227f1c02a4a74fdedea5ec669c616a/href">https://medium.com/media/af227f1c02a4a74fdedea5ec669c616a/href</a></iframe><pre>loss_fn = weighted_MSE([0., 0., 0., 1., 0.]) #只看close price的維度</pre><p><em>Note: 這邊可以試一下也給其他feature loss，若只給 close price權重，也可以把output改成只有一個維度 (BTW 我試了之後結果也差不多)</em></p><p>另外在 rescale_MAE loss 的部分(將MAE反算回原本scale 比較直觀來觀察)，由於 output 多了一個維 [batch, seq, <strong>feature_dim</strong>] 所以這裡直接使用inverse transform 然後取close price 的dimension 的值:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/62f505b8f247fc6b5a559d42505c904c/href">https://medium.com/media/62f505b8f247fc6b5a559d42505c904c/href</a></iframe><p>接下來一樣使用ranger+SAM訓練200個epochs，結果如下:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4z09G2mELDVxaQUOTpdKvw.png" /></figure><p>最後val set MAE在未來五天的整體平均誤差來到 22.3 左右，比前一個模型直接做簡單預測的還爛 XD，不過auto-encoder 拿來進行預測，直觀來想也覺得好像怪怪的，AE一般來說是期望重構回和原始一樣的資料。</p><p>不管怎樣，也順便看一下只預測未來一天的話會是如何:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/992/1*mo3788bUaWLBqEh8tlQG3g.png" /></figure><p>恩…看不出來這個模型在預測什麼東東</p><p>或許AE架構的模型還是比較適合使用在anomaly detection 的task.</p><h3><strong>LSTM Seq2Seq model</strong></h3><p>最後來看LSTM seq2seq model，其實這個架構是我覺得最符合股價預測這個題目的做法(如果預測天數&gt;1天)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fD_n5XNtuteCZAFOPrz4KA.png" /><figcaption>seq2seq</figcaption></figure><p>跟AE一樣先一個encoder 濃縮input的資訊，但 seq2seq 的 decoder 是一個一個依序產出，而每一個產出會是下一個時間點的input。</p><p>來看一下程式：</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/03de1e610a826a5479c8707a018b2d4f/href">https://medium.com/media/03de1e610a826a5479c8707a018b2d4f/href</a></iframe><p>encoder 和之前一樣，就是一層LSTM而已，比較不一樣的是 decoder，因為<strong>decoder每一個 step 的 input 都只有一個時間點的資料，所以input size 變成 [batch_size, feature_size]，另外 input 還多了一個 hidden 和 cell 給 LSTM (encoder最後的hidden, cell state 拿來給decoder的 initial hidden , cell state，一般我們直接套LSTM時不會給，pytorch直接 default 設 0)</strong></p><p>decoder 經過一層 LSTM 後透過 linear 轉成 output size，而這個LSTM會在後面重複被調用(因為我們一次只預測一個，總共要預測未來五天，所以會調用5次，也就是下面seq2seq程式碼迴圈的部分)</p><p>把encoder 和decoder 組起來:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a3b1f0c03eb64c742ef7a70b78dca546/href">https://medium.com/media/a3b1f0c03eb64c742ef7a70b78dca546/href</a></iframe><p>上面的程式碼其實就是在組下面這張圖的網路架構：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2oYfrErgA-ylH2NzaKQ9Vg.png" /></figure><p>在decoder這邊會發現有一個teacher forcing，這是個訓練的小技巧，因為 decoder會把前一個時間點的輸出當成下一個時間點的輸入，如果我們在前個時間點做了錯誤的預測，那往後所有的時間點都會受到這個錯誤影響，也就是一步錯，步步錯的狀況</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FZSvD3m6F_LxNScY.png" /><figcaption>一步錯 步步錯</figcaption></figure><p>所以我們讓 teacher 介入去糾正預測出來的答案(input 正確答案)，但也不能每次都介入，到時模型拿來預測真的上戰場時，就沒有老師來告訴你正確答案了，所以我們設一個 random flag，老師偶爾出來糾正一下，避免一直訓練不起來。</p><p>好啦，那模型也組好了，再來就把他訓練起來就行，一樣用 Ranger+SAM 訓練 200 個 epoch</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IOVgvzJdAXk4zbzPOr--ew.png" /></figure><p>最後 val set MAE在未來五天的整體平均誤差來到 14.5左右</p><p>接著一樣來看看，如果只看最近一天的預測值，結果會是如何。 由於是對未來的預測，所以不會有正確答案來給我們 input，可以創一個 psedo的答案來input 然後設定 teacher_forcing_ratio=0 來完成預測:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/425f6e79b5ad189db19451b6b205a0fe/href">https://medium.com/media/425f6e79b5ad189db19451b6b205a0fe/href</a></iframe><p>最後就會得到:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/1*0KSTJFIFvV9W7SxxUTFHow.png" /></figure><p>平均誤差約 12.75，誤差率為2.1%，是目前表現最好的架構呢^^</p><h3>Conclusion</h3><p>這邊比較了LSTM的幾種用法:</p><p>multi-step prediction vs. Auto Encoder vs. Seq2Seq</p><p>這三種方法用在股價預測未來 5 天的表現，結果如下</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KCROKbqo9OH5rxgHlFHrAw.png" /></figure><p>以 MAE 的表現來看 seq2seq 的表現是最好的， MAPE 大概是 2.1%。</p><p>若一次預測未來一小段time series的命題下，seq2seq 應該是最適合的做法，若是對一段time series的資料做 classification 或 regression 可能一般的LSTM 直接做預測會比較好又簡單，如過是要做time series的anomaly detection 則 AutoEncoder 或許會是比較好的選擇～</p><p>最後，如果是資料量比較大的情況下，這三種做法都可以把 LSTM 換成transformer (self-attention) 計算應該會比較快也比較準。</p><h3>Reference</h3><p><a href="https://machinelearningmastery.com/how-to-develop-lstm-models-for-time-series-forecasting/">How to Develop LSTM Models for Time Series Forecasting</a></p><p><a href="http://zake7749.github.io/2017/09/28/Sequence-to-Sequence-tutorial/">從零開始的 Sequence to Sequence</a></p><p><a href="https://curow.github.io/blog/LSTM-Encoder-Decoder/">用Pytorch实现Encoder Decoder模型 (LSTM)</a></p><p><a href="https://towardsdatascience.com/how-to-make-a-pytorch-transformer-for-time-series-forecasting-69e073d4061e">How to make a Transformer for time series forecasting with PyTorch</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ed36f0370204" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Few Shot Learning - Siamese Network]]></title>
            <link>https://peaceful0907.medium.com/few-shot-learning-siamese-network-73bc0a98c6fa?source=rss-d2d57a7d3dc9------2</link>
            <guid isPermaLink="false">https://medium.com/p/73bc0a98c6fa</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[few-shot-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[CW Lin]]></dc:creator>
            <pubDate>Sun, 06 Jun 2021 15:34:09 GMT</pubDate>
            <atom:updated>2021-06-06T15:34:09.949Z</atom:updated>
            <content:encoded><![CDATA[<p>透過few shot learning 來打造生物識別(人臉、聲紋、手寫…)模型!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*AuZLKEVsQpsTD3Dt" /><figcaption>Photo by <a href="https://unsplash.com/@craftedbygc?utm_source=medium&amp;utm_medium=referral">Green Chameleon</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>由於疫情，近期都很少出門宅在家，就來記錄一下最近有用到的技術吧~</p><p>一般的分類問題往往都是屬於類別不多且每個類別資料量很多任務，比如MNIST 手寫資料集或 imagenet 的影像分類問題。但在生物識別的task 上我們往往沒辦法收集到那麼多資料，比如說我要建立一個人臉識別的模型，我應該不太可能跟每個我要識別的人都收集大量的照片，況且世界上的人那麽多，我也不大可能收集所有人的照片來建立分類模型。</p><p>Few shot learning 算是 meta-learning 的其中一塊，核心概念是讓模型學會學習(learn to learn)。這樣說有點懸，我們可以把它理解成: <strong><em>few shot learning 是要讓模型學會區分事物的差異。一個學會區分事物差異的模型，我們可以把它用在訓練集從未見過的新類別，並且可以只透過很少的樣本(few shot) 就學會區別此事物。</em></strong></p><h3>Siamese Network</h3><p>Siamese 這個詞是孿生、連體嬰的意思，表示兩個人身體相連且共享部分的器官。而siamese network 是只有兩個架構權重都相同的類神經網路組合在一起(如下右圖)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UytKxjgAGm94-w8h9fJb0Q.png" /></figure><p>可以看到這個網路的input 是一個image pairs，而我們的目標是要訓練一個能夠區分事物差異的網路。想必聰明的你已經想到要如何使用這個網路結構了！</p><p>首先我們要準備很多positive samples 以及 negative samples，分別表示相同類別的 image pairs 以及不同類別的 image pairs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XANYBG7jVGB6HN5zJOzYCg.png" /><figcaption><a href="https://www.youtube.com/watch?v=UkQ2FVpDxHg">https://www.youtube.com/watch?v=UkQ2FVpDxHg</a></figcaption></figure><p>而 siamese network 就是要預測 input 的 image pairs 是否為相同類別，所以說就是一個binary classification 的問題！</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/866/1*ESehqSnkxj50HnsLSZDgng.png" /></figure><p>實際要搭建siamese network 也非常的簡單，以pytorch 做一個範例:</p><pre>class siameseNet(nn.Module):<br>    def __init__(self, embedding_net):<br>        super(siameseNet, self).__init__()<br>        self.embedding_net = embedding_net</pre><pre>    def forward(self, x1, x2):<br>        output1 = self.embedding_net(x1)<br>        output2 = self.embedding_net(x2)<br>        return output1, output2</pre><pre>    def get_embedding(self, x):<br>        return self.embedding_net(x)</pre><p>其中 embedding_net 是任何你自己搭建的CNN 網路，最後再把output1, output2 喂給 loss function backward 即可。</p><p>預測時可以調用 get_embedding() 就不用每次都 forward 兩張image了~</p><p><strong>Contrastive loss</strong></p><p>目標: 使相同類別的embedding 越接近越好，不同類別的embedding 越遠越好，用這個觀點來看下面的式子就會非常直觀了</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xmSNfPsFTq5R89d1sccxfg.png" /><figcaption>Dw 表示兩embedding 之距離(歐式距離)</figcaption></figure><pre>class ContrastiveLoss(nn.Module):</pre><pre>   def __init__(self, margin):<br>        super(ContrastiveLoss, self).__init__()<br>        self.margin = margin<br>        self.eps = 1e-9</pre><pre>   def forward(self, output1, output2, target, size_average=True):<br>        distances = (output2 - output1).pow(2).sum(1)  # squared distances<br>        losses = 0.5 * (target.float() * distances +<br>                        (1 + -1 * target).float() * F.relu(self.margin - (distances + self.eps).sqrt()).pow(2))<br>        return losses.mean() if size_average else losses.sum()</pre><p><strong>Triplet loss</strong></p><p>Triplet Loss是Google 在 2015 年發表的 FaceNet 論文中提出。可視為Contrastive loss 的改良。</p><p>triplet loss 必須建構在三元的image pair 下才能計算，搭配的網路架構如下</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Xo2XMYGRZdXDYX5z" /></figure><p>可以看到triplet loss 的做法直接喂給模型一個positive 以及一個 negative sample 來訓練，目標一樣是期望positive 能越接近anchor 而 negative 能越遠離anchor:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Map0FG5iLesOF8BI" /><figcaption>triplet loss</figcaption></figure><pre>class TripletLoss(nn.Module):</pre><pre>   def __init__(self, margin):<br>        super(TripletLoss, self).__init__()<br>        self.margin = margin</pre><pre>   def forward(self, anchor, positive, negative, size_average=True):<br>        distance_positive = (anchor - positive).pow(2).sum(1)  <br>        distance_negative = (anchor - negative).pow(2).sum(1)  <br>        losses = F.relu(distance_positive - distance_negative + self.margin)<br>        return losses.mean() if size_average else losses.sum()</pre><p>要搭建triplet 的 network 其實和siamese 幾乎一模一樣，只是input, output 變成三個而已</p><pre>class TripletNet(nn.Module):<br>    def __init__(self, embedding_net):<br>        super(TripletNet, self).__init__()<br>        self.embedding_net = embedding_net</pre><pre>    def forward(self, x1, x2, x3):<br>        output1 = self.embedding_net(x1)<br>        output2 = self.embedding_net(x2)<br>        output3 = self.embedding_net(x3)<br>        return output1, output2, output3</pre><pre>    def get_embedding(self, x):<br>        return self.embedding_net(x)</pre><p>透過contrastive loss or triplet loss 訓練出來的 NN 已經學會了區分事物的差異，我們可以透過這個 NN 將影像embedding 到一個很具鑑別力的空間，在這個空間計算embedding 向量的距離來判斷是否為相同類別的事物。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*37VB61q9s7tc-Pq8x7PaJw.png" /></figure><p>所以不論人臉辨識，聲紋辨識，手寫辨識…等，我們首先需要大量資料來訓練這個embedding 的類神經網路；將來部署預測時每個類別只需要一筆資料把它轉換到這個embedding 的高維度空間中，便完成該類別的建模了。</p><p>以人臉為例，我們將要辨識的人臉forward到 embedding 空間，然後計算與之前已 ”註冊” 的人臉看看是否夠接近，若有超過門檻值則判為同一人:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B-zLdXmvEJz1sHfFgFIQvQ.png" /></figure><p>以 MNIST 手寫資料及為例來比較看看相同的網路架構以不同訓練方式所得到的embedding 空間:</p><pre># network structure<br>class embedding(nn.Module):<br>    def __init__(self, input_size, embed_dim=2):<br>        super(embedding, self).__init__()</pre><pre>self.embed_dim = embed_dim<br>        self.conv = nn.Sequential(<br>            nn.Conv2d(1, 32, 3, padding=1), nn.BatchNorm2d(32), nn.LeakyReLU(0.1,inplace=True),<br>            nn.Conv2d(32, 32, 3, padding=1, stride=2), nn.BatchNorm2d(32), nn.LeakyReLU(0.1,inplace=True),<br>            <br>            nn.Conv2d(32, 64, 3, padding=1), nn.BatchNorm2d(64), nn.LeakyReLU(0.1,inplace=True),<br>            nn.Conv2d(64, 64, 3, padding=1,stride=2), nn.BatchNorm2d(64), nn.LeakyReLU(0.1,inplace=True),<br>            )<br>        self.fc = nn.Linear(64*7*7, self.embed_dim)<br>        <br>    def forward(self, x):<br>        x = self.conv(x)<br>        x = x.view(x.size()[0], -1)<br>        x = self.fc(x)<br>        return x</pre><p>用上面的 siameseNet, TripletNet 訓練後使用get_embedding() 得到以下的結果:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vQ2vSVhxgzcgyUdPVUXuPw.png" /></figure><h3><strong>Margin Based Classification</strong></h3><p>以上的siamese network 算是一種 metric based learning的訓練方式，我們的目標其實是要讓類神經網路的embedding 空間更具鑑別力。</p><p>Margin Based Classficiation 不像在 feature 層直接計算損失的 Metric Learning 那樣，對 feature 加直觀的強限制，而是依然把人臉識別當 classification 任務進行訓練，通過對 softmax 公式的改進，實現了對 feature 層施加 margin 的限制，使網絡最後得到的 feature 更具鑑別力。訓練好的網路再把最後的classification layer 拿掉，只用前面的CNN做feature extraction</p><p>這一塊有些一系列的做法 sphereface, cosineface, arcface，分別在不同的地方對 softmax 加上margin 限制，具體細節有在 <a href="https://peaceful0907.medium.com/face-recognition-arcface-cf814fb5549e">人臉辨識, Face recognition (ArcFace)</a> 這篇文章裡描述。</p><h3>Conclusion</h3><p>metric learning 的概念直觀，直接針對verification的目的進行訓練，但其缺點是有時訓練很慢很難收斂，一方面是窮舉每種 image pair(or triplet pair) 會讓資料量變很多，另一方面是訓練的目標比單純分類問題還要困難，導致比較難收斂。因此有時候有人會先用分類模型先把模型訓練到一定程度後再用 triplet loss 來 fine tune。</p><h3>Reference</h3><p><a href="https://www.pyimagesearch.com/2020/12/07/comparing-images-for-similarity-using-siamese-networks-keras-and-tensorflow/">Comparing images for similarity using siamese networks</a></p><p><a href="https://www.gushiciku.cn/dc_hk/106546498">如何走近深度學習人臉識別？你需要這篇超長綜述</a></p><p><a href="https://www.youtube.com/watch?v=UkQ2FVpDxHg&amp;list=PLvOO0btloRnuGl5OJM37a8c6auebn-rH2">Few-Shot Learning</a></p><p><a href="https://arxiv.org/abs/1707.02131">SigNet: Convolutional Siamese Network for Writer Independent Offline Signature Verification</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=73bc0a98c6fa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Social Network Analysis — A preliminary exploration of graph and graph embedding(DeepWalk)]]></title>
            <link>https://peaceful0907.medium.com/social-network-analysis-a-preliminary-exploration-of-graph-and-graph-embedding-deepwalk-867747625904?source=rss-d2d57a7d3dc9------2</link>
            <guid isPermaLink="false">https://medium.com/p/867747625904</guid>
            <category><![CDATA[social-network-analysis]]></category>
            <category><![CDATA[graph]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[CW Lin]]></dc:creator>
            <pubDate>Fri, 07 Aug 2020 16:57:41 GMT</pubDate>
            <atom:updated>2021-01-16T16:23:55.413Z</atom:updated>
            <content:encoded><![CDATA[<h3>A preliminary exploration of graph, graph embedding(DeepWalk) and Graph Convolutional Networks(GCN)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y4u4ItBOml1MMGOBWh24Yg.jpeg" /><figcaption><a href="https://resilienteducator.com/lifestyle/teachers-online-network/">圖片來源</a></figcaption></figure><p>Machine learning 在結構化、影像、文字等類型的資料有許多發展外，以圖學(Graph)為基礎的社群網路資料(如 FB等社群網站互相follow的關係、電子信箱信件往來關係、論文間互相cite...等) 也是目前正在興起的一個方向，在推薦系統或用戶屬性分類以及文章引用建議等 有不少用途。</p><p>graph data 樣本間往往都存在著相關性，這違反了傳統 ML的 i.i.d.假設，使得演算法無法有效的利用此特徵來做預測。<br>最近讀了一些些相關的文章和教學，用這篇文章來稍為記錄一下。</p><blockquote>Outline:<br>1. graph<br>2. networkX<br>3. DeepWalk<br>4. Graph Convolutional Network<br>5. GCN on Cora dataset</blockquote><h3>Graph</h3><p>社群網路分析基本上是運用圖論(Graph theory)去從連結中研究關係與架構。Graph 是由&quot;節點&quot;(node or vertex) 和&quot;邊&quot; (edge)所組成，用 V 來代表node，E 代表 edge，一張 graph 的資料可以寫成 G = (V,E)，用以下方式表示:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/1*DbRZ7C-AZp_37p-ZIFzPFg.png" /></figure><p>graph 的架構經常使用 adjacency matrix 表示，並用degree 表示每一個node 有多少個node跟他相連。以上面舉的例子來說:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*EbVYrJMsGi8inCqmUZWh8A.png" /></figure><p>而每個node 可能會有自己的一些feature 和 label(可能是預測目標)，edge 也可能有不同權重(關連性的強度)，沒有的話就當作equal weight.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/361/1*kENeJWstnVZAQWtsAGyiMA.png" /><figcaption>node information example</figcaption></figure><h3>NetworkX</h3><p>networkx 是一款 Python 的package，用於創造、操作網絡。官網有基本操作的教學: <a href="https://networkx.github.io/documentation/stable/tutorial.html">https://networkx.github.io/documentation/stable/tutorial.html</a></p><p>用networkx 來建立上面的範例圖:</p><pre>import networkx as nx</pre><pre>G = nx.Graph() #initialize一張空圖<br>G.add_edges_from([(1,2),(1,3),(1,4),(2,3),(3,4)])<br>nx.draw(G,with_labels=True)</pre><pre>print(&#39;number of nodes:&#39;,G.number_of_nodes())<br>print(&#39;number of edges: &#39;,G.number_of_edges())</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/481/1*llFLxY7bWg_QRwJnTtFQbw.png" /></figure><p>使用 .add_node 和 .add_edge 新增 node 和edge:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/546/1*95uYFNR8uo7rrl2opZ2HhA.png" /></figure><p>使用 set_node_attributes 來給定 node 的label 或 feature</p><pre>## 隨機給每個 node A 或 B 兩種 label <br>import random</pre><pre>cat = [&#39;A&#39;,&#39;B&#39;]<br>node_cat_mapping = {<br>node:random.sample(cat,1)[0] for node in list(G.nodes)<br>}<br>node_cat_mapping</pre><pre>&gt;&gt;{1: &#39;B&#39;, 2: &#39;A&#39;, 3: &#39;B&#39;, 4: &#39;A&#39;, 5: &#39;A&#39;, 6: &#39;A&#39;}</pre><pre>## set node attribute by set_node_attributes<br>nx.set_node_attributes(G, node_cat_mapping, &#39;label&#39;)<br>G.nodes[1]</pre><pre>&gt;&gt;{&#39;label&#39;: &#39;B&#39;}<br></pre><pre>## we use different color to represent node label in graph. <br>cat_color_mapping = {&#39;A&#39;:&#39;green&#39;,&#39;B&#39;:&#39;yellow&#39;}</pre><pre>node_color_list = [cat_color_mapping[ G.nodes[node][&#39;label&#39;] ] for node in list(G.nodes) ]</pre><pre>node_color_list<br>&gt;&gt;[&#39;yellow&#39;, &#39;green&#39;, &#39;yellow&#39;, &#39;green&#39;, &#39;green&#39;]<br></pre><pre>## draw the graph<br>nx.draw(G,with_labels=True,node_color=node_color_list)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/428/1*OcspHIE9R8T1enK_gz25Hg.png" /></figure><h3>DeepWalk</h3><p>paper: <a href="https://arxiv.org/abs/1403.6652">https://arxiv.org/abs/1403.6652</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*XyyfQ6gXDBGYEksBfji_uQ.png" /></figure><p>一張graph 可能僅有一部分的node 有 label ，針對沒有label的node我們可能會想做一些像是 classification / anomaly detection 等等的事，而一般ML 模型是無法直接吃 graph 架構的。</p><p>Deepwalk是一種 graph embedding 的方法，它將graph 的拓樸架構映射到歐式空間，使每個 node轉換成一個低維度的向量表示。兩點在graph裡連結關係較強者在歐式空間中距離也會較接近。</p><p>embedding 的做法是利用word2vec ，在<a href="https://medium.com/@peaceful0907/%E7%B0%A1%E6%98%93%E8%AA%9E%E9%9F%B3%E5%8A%A9%E7%90%86%E5%AF%A6%E5%81%9A-5f6228937116">語音助理那篇</a>裡有稍微介紹到。但要套用skip-gram or CBOW 必須要有corpus呀，我只有graph又沒有sentences要怎麼做呢？</p><p>deepwalk的貢獻就是在graph的每個 node 上隨機遊走，將走過的路徑視為一句sentence，然後再透過word2vec得到 embeded function。</p><blockquote>Random Walk:</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/549/1*SAMTK32wH56p31uFb2v1cw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RW83DMj8rDPd2Vme236qjg.png" /><figcaption><a href="https://zhuanlan.zhihu.com/p/45167021">https://zhuanlan.zhihu.com/p/45167021</a></figcaption></figure><p>其實想想也蠻直觀的，node間的連結關係的確有點像單詞間前後文的關係。</p><p>演算法如下： 每個node為出發點各走 gamma 次 長度為 t 的路徑，把路徑收集起來當作語料庫來訓練word2vec，即可得到embedding</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/838/1*DIIFQJJMJQhzqWoZfAU3iQ.png" /><figcaption><a href="https://arxiv.org/pdf/1403.6652.pdf">https://arxiv.org/pdf/1403.6652.pdf</a></figcaption></figure><blockquote>DeepWalk 實做</blockquote><p>這裡我使用 karate_club_graph 數據集，Zachary’s Karate Club是一個描述大學空手道俱樂部成員社交關係的網路，由Wayne W. Zachary在論文 <a href="http://www1.ind.ku.dk/complexLearning/zachary1977.pdf">“An Information Flow Model for Conflict and Fission in Small Groups” </a>中提出，是一個常用的社交網路範例。這個俱樂部共包含34名成員，會長 John A 和教官 Mr. Hi (化名)之間因是否調漲價錢而產生衝突導致這個俱樂部一分為二，一半的成員跟著 Mr. Hi 成立了新的俱樂部，另一半成員要麼找了新的教練，要麼放棄空手道。</p><p>先來看一下數據集的樣子</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/78fcf7892dfc61791c94863f2d6934d5/href">https://medium.com/media/78fcf7892dfc61791c94863f2d6934d5/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/991/1*-yR-IQ7Ay3oLi5y-lITfeg.png" /></figure><p>稍為看一下degree 的資訊:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8ec4aba9a968c1b76c1539ebedb97de5/href">https://medium.com/media/8ec4aba9a968c1b76c1539ebedb97de5/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/636/1*fsgF5qWtaFBEYcCTMSpzAQ.png" /></figure><p>可以看到大部分的人都只有連接5個人以內，有兩個人的degree特別高，大概就是管理員和教官吧。</p><p>接著開始deepwalk的部分，這裡我是參考了<a href="https://www.twblogs.net/a/5c307a6ebd9eee35b3a4d3ff">這篇文章</a>，我把他的code稍微修改整理一下。</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/871e8f86269fcbb7a71fc48d96d91118/href">https://medium.com/media/871e8f86269fcbb7a71fc48d96d91118/href</a></iframe><p>來稍微看一下幾條random walk的路徑:</p><pre>for i in range(10):<br>    print(corpus[i])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/898/1*kQXyysAufWrie4Qf1YaaQA.png" /><figcaption>後面太長了截掉</figcaption></figure><p>可以看到前30條路徑皆為由0出發隨機走50步</p><p>接著把每個node 丟進train 好的 word2vec model 取得 embedding 並加入node attribute:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e9793b06cbbcfe19862c0ff4415def89/href">https://medium.com/media/e9793b06cbbcfe19862c0ff4415def89/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/417/1*lxxkcW8Pq_xLmwn9vCt6OQ.png" /><figcaption>node embedding vector</figcaption></figure><pre># set node attribute<br>nx.set_node_attributes(G, node_embedding_dic, &#39;embedding&#39;)</pre><pre>G.nodes[0]</pre><pre>&gt;&gt;{&#39;club&#39;: &#39;Mr. Hi&#39;, &#39;embedding&#39;: array([-0.655476 ,  0.7207127], dtype=float32)}</pre><p>可以看到node除了原本就有的 &#39;club&#39; 外多了embedding的attribute。接著把他畫出來看看:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/44ab71e277242fc1ca349af77cd39561/href">https://medium.com/media/44ab71e277242fc1ca349af77cd39561/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/380/1*Gi5j9VpiOdOylNVazLmgFA.png" /></figure><p>可以看到光用graph的架構資訊 (沒有用到任何node 的feature) 並只embedding 到2維空間就能用一個線性分類器把兩個類別給分的不錯了!</p><h3>Graph Convolutional Networks</h3><p>在CNN中convolution 能夠有效的提取 image 特徵同時又避免了過大的參數量而有許多表現很好的知名網路架構。然而CNN的 convolution 無法直接應用到圖學上，因此衍伸出了GCN。</p><p>對CNN熟的人大概都知道 convolution layer的運算就是把像素中鄰近的點給做 weighted sum，而GCN的概念其實也類似，它把與該node 有連結的node的feature給做weight sum。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/707/0*7YOWrsQglib6P8Eh.png" /></figure><p>找出每個node 鄰近的node 就是透過 adjacency matrix ，先定義幾個符號:</p><p>N: total node count<br>A: adjacency matrix(NxN)<br>X: node feature matrix (假設每個node 用 f 個 feature，那麼X為 NxF)<br>W: 權重矩陣 (假設第一層有 hidden_size個節點，那麼W為 F x hidden_size)</p><p>直接用例子來看，我延續前一篇的範例，並假設每個node 各有一個 2 維度的特徵:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/0*MaOyGjEZntQqaJnO.png" /></figure><pre>hidden_size = 10<br>A = np.matrix([[0,1,1,1],<br>               [1,0,1,0],<br>               [1,1,0,1],<br>               [1,0,1,0]])<br>X = np.matrix([[1,1],[2,2],[3,3],[4,4]]) #隨便假設每個node的feature<br>W = np.matrix(np.random.normal(loc=0,scale=1,size=(2, hidden_size)))#隨機給權重print(&#39;adjacency matrix size:&#39;,A.shape)<br>print(&#39;feature matrix size:&#39;,X.shape)<br>print(&#39;first layer weight matrix:&#39;,W.shape)&gt;&gt; adjacency matrix size: (4, 4) <br>&gt;&gt; feature matrix size: (4, 2) <br>&gt;&gt; weight matrix: (2, 10)</pre><p>那我們想要的是把node相鄰的點給做weighted sum 因此計算 A*X 便可得到</p><pre>A*X<br>&gt;&gt;matrix([[9., 9.],         <br>          [4., 4.],         <br>          [7., 7.],         <br>          [4., 4.]])</pre><p>手乘一次就會知道第一列的9 = 0*1+1*2+1*3+1*4，也就是和node ‘1’ 相臨的另外3個點的 feature 相加。因此呢，如果我們算的是A*X*W 就是有相鄰的這幾個node 的feature 做 weighted sum!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/386/0*UoNEQip_osH0aVn7.png" /></figure><p>然而這邊有兩個問題:</p><ol><li>沒用到自己的特徵</li><li>每個node 的degree不相同，在訓練的時候不公平，沒什麼人連接到的node可能gradient很小沒辦法訓練到，反之可能梯度爆炸</li></ol><p>因此做些調整: 把graph每個node 都加上自我連接，也就是 adjacency matrix 加上 identity matrix ，然後利用degree matrix 的反矩陣來對不同degree的node做標準化。</p><p>所以就變成:</p><pre>A_hat = A+np.eye(4)<br>D_hat = np.array(np.sum(A_hat, axis=1)).reshape(-1) #考慮自迴圈<br>D_hat = np.matrix(np.diag(D_hat))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/731/0*HomkKB9L-Qy3j0Lm.png" /></figure><p>可以看到當你degree越高(鄰居越多)，D 反矩陣對應的系數就會越小。<br>而標準化的方式直接取反矩陣算是一種算術平均:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/52/0*f8PihKuPu8b7Mv96.png" /></figure><p>但其實 GCN 幾乎都是用幾何平均的方式來標準化:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/130/0*bTE6q3yxrLmishxi.png" /></figure><p>最後再取個activation function 就變成:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/405/0*sJxv8SiMtNIZ7MfH.png" /><figcaption>(Hi代表第i 層的hidden layer 輸出，H0則為node feature 也就是上面的X)</figcaption></figure><p>GCN 到這邊看似直觀好理解，但其實背後有扎實的數學理論支持著，詳細可以看<a href="https://www.youtube.com/watch?v=M9ht8vsVEw8">李宏毅老師的助教課</a>了解一下。</p><h3>Example on Karate Club dataset</h3><p>這邊延用前一篇介紹的 Karate club 資料集來實做看看上面手刻的GCN</p><p>一樣先load 資料:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/164fca09923455ae32cf2f7b074fafcc/href">https://medium.com/media/164fca09923455ae32cf2f7b074fafcc/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/991/0*w-G1ND54e1WCQYei.png" /></figure><p>計算 A_hat 和 D_hat 以及初始化權重W，因為node其實沒有 feature 所以第一層的X 直接帶單位矩陣</p><p><a href="https://gist.github.com/henry16lin/e09c10a8efe69c917f7fbf655f221ca7#file-karaph_gcn_1-py">https://gist.github.com/henry16lin/e09c10a8efe69c917f7fbf655f221ca7#file-karaph_gcn_1-py</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/291/0*frizQ52NxoROfjVn.png" /></figure><p>然後就是計算GCN layer 並把softmax前的embedding拿來畫圖看看:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f4d3a42d5d86671c332b41716e26c993/href">https://medium.com/media/f4d3a42d5d86671c332b41716e26c993/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/463/0*UgYjZ5mLZ_GIuk5W.png" /></figure><p>到目前為止在完全沒有用到node feature 也沒有訓練直接使用隨機初始化的權重透過 GCN 出來的embedding 似乎就有點能分開的樣子!</p><p>接著我們找一組比較複雜一點的資料集來實際訓練GCN試試~</p><h3>GCN on Cora dataset</h3><p>要訓練類神經網路我們需要深度學習框架，這邊使用 pytorch geometric 簡稱pyG 是一個基於pytorch 建例來處理圖學相關資料的深度學習框架，使用過pytorch 基本上要操作pyG應該是可以無縫使用。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/271/0*kllIGsutw_f4Q3gL.png" /></figure><blockquote><em>Cora dataset</em></blockquote><p>cora dataset 是由機器學習論文所組成的，node 一共有七種論文類別:</p><ul><li>Case_Based</li><li>Genetic_Algorithms</li><li>Neural_Networks</li><li>Probabilistic_Methods</li><li>Reinforcement_Learning</li><li>Rule_Learning</li><li>Theory</li></ul><p>每一篇論文至少引用了數據集裡面另外一篇論文或者被另外一篇論文所引用，共有2708篇有label 的papers，而每篇paper 共有1433個feature，表示該篇paper是否有包含某個特殊的專有名詞(皆為0/1)</p><p>cora 數據集在pyG裡有內建 先把他load起來</p><pre>from torch_geometric.datasets import Planetoiddataset = Planetoid(root=&#39;/tmp/Cora&#39;, name=&#39;Cora&#39;)</pre><p>我們先把它轉成networkX 把graph 畫出來看看:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cde2a3812a6397398a670f3aef198fd5/href">https://medium.com/media/cde2a3812a6397398a670f3aef198fd5/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/547/0*SsyL8OoPnNvNU8to.png" /></figure><p>然後看一些graph的基本資訊:</p><pre>#some informationprint(dataset[0])<br>print(&#39;is directed:&#39;,dataset_x.is_directed())<br>print(&#39;num of nodes:&#39;,dataset_x.number_of_nodes())<br>print(&#39;num of edges:&#39;,dataset_x.number_of_edges())<br>print(&#39;num of classes:&#39;,len(set(y_np)))<br>print(&#39;degree distribution:&#39;)degree_sequence = [d for n, d in dataset_x.degree()]<br>plt.hist(degree_sequence,bins=&#39;auto&#39;)<br>plt.show()<br>print(&#39;average degree:&#39;,np.mean(degree_sequence))<br>&gt;&gt; Data(edge_index=[2, 10556], test_mask=[2708], train_mask=[2708],val_mask=[2708], x=[2708, 1433], y=[2708]) <br>&gt;&gt; is directed: False <br>&gt;&gt; num of nodes: 2708 <br>&gt;&gt; num of edges: 5278 <br>&gt;&gt; num of classes: 7 <br>&gt;&gt; average degree: 3.8980797636632203</pre><p>其中上面的 train/val/test mask 是有幫我們切分好的 true/false list</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/387/0*sXi7qXMp_4T6tHkd.png" /></figure><p>然後來建立GCN 的layer:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9e8c8e738f865077ba2ef1619484b256/href">https://medium.com/media/9e8c8e738f865077ba2ef1619484b256/href</a></iframe><p>可以看到完全和pytorch 一樣，只是引入了 pyG 的 layer!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/596/0*dRkY3EgQiRNROQOY.png" /></figure><p>最後開始訓練!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d9e237a9d310cfb43ea5df86170e8ac6/href">https://medium.com/media/d9e237a9d310cfb43ea5df86170e8ac6/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/615/0*oe5t5qNNzigVWj0j.png" /></figure><p>我們來看看GCN 把 cora data embedding 成什麼樣子來進行分類:<br>(使用t-SNE 降到2維呈現)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c303787af908fab0895dc31f75fcab0d/href">https://medium.com/media/c303787af908fab0895dc31f75fcab0d/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/0*j4kAS7mvmUtn0EYl.png" /></figure><p>可以看到把training set 分得很不錯，而test 似乎有點overfitting的現象，不過我覺得training set 的資料量這麼少(140筆)，應該也不容易了吧?!</p><p>順帶一提，基於好奇我用前一篇的 deepwalk 做一次cora dataset 把graph embedding到100維，然後將原本的node feature (1433維)給合併起來變成1533維的feature 並丟到XGBoost 跑跑看，最後得到 test acc~58%，所以GCN應該還是蠻有用的!</p><p>GCN 後來也有很多變型，如 <a href="https://arxiv.org/abs/1710.10903">GAT</a>(透過attention 學習edge間的比重) 以及 <a href="https://arxiv.org/abs/1905.07953">cluster-GCN</a>(解決graph太大時或layer較深時的計算問題)，這些在pytorch geometric裡都有提供可以直接使用!</p><h3>Reference:</h3><p><a href="https://www.twblogs.net/a/5b8c401f2b71771883319c75">社會網絡分析與挖掘 — -Python之networkx介紹</a></p><p><a href="https://zhuanlan.zhihu.com/p/45167021">【论文笔记】DeepWalk</a></p><p><a href="https://www.twblogs.net/a/5c307a6ebd9eee35b3a4d3ff">圖表示學習Graph Embedding：DeepWalk python實現</a></p><p><a href="https://mlelarge.github.io/dataflowr-slides/X/gnn.html#13">Graph Neural Networks [Marc Lelarge]</a></p><p><a href="https://medium.com/@yenhao0218/%E6%B7%B1%E5%BA%A6%E5%9C%96%E5%BD%A2%E5%8D%B7%E7%A9%8D%E7%B6%B2%E8%B7%AF-deep-learning-on-graphs-with-graph-convolutional-networks-part-1-69d98fe17995">深度圖形卷積網路 Deep Learning on Graphs with Graph Convolutional Networks</a></p><p><a href="https://purelyvivid.github.io/2019/07/07/GCN_1/">GCN(Graph Convolutional Network)的理解</a></p><p><a href="https://zhuanlan.zhihu.com/p/78452993">番外篇：PyG框架及Cora数据集简介</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=867747625904" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Generative Adversarial Network and Super Resolution GAN(SRGAN)]]></title>
            <link>https://peaceful0907.medium.com/generative-adversarial-network-and-super-resolution-gan-srgan-e2e7a4440066?source=rss-d2d57a7d3dc9------2</link>
            <guid isPermaLink="false">https://medium.com/p/e2e7a4440066</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[CW Lin]]></dc:creator>
            <pubDate>Fri, 24 Apr 2020 15:40:37 GMT</pubDate>
            <atom:updated>2020-04-26T05:42:26.608Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/981/1*E-JmUwv7zbwjzFm1hJLxPA.png" /></figure><p>Image super-resolution (SR) techniques reconstruct a higher-resolution image from the observed lower-resolution images. An intuitive method for this topic is interpolation, for which texture detail in the reconstructed images is typically absent.</p><p>Super-Resolution Generative Adversarial Network, or SRGAN, is a generative adversarial network (GAN) for image super-resolution that is more appealing to human perspective.</p><h3>Brief review of GAN</h3><p>GAN is comprised of two neural networks, Generator and Discriminator. GAN learns a probability distribution of a dataset by pitting these two neural networks against each other.</p><p>The structure is shown in below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y94btIuK3C2UQQV2jlLenQ.png" /></figure><blockquote>Notation</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*m-Sbpahn_BLzNUkcKtPuAA.png" /></figure><blockquote>Discriminator</blockquote><p><strong><em>Goal:</em></strong> discriminate whether the data were real or not.<br><strong><em>input:</em></strong> half real data + half generated from generator (fake data)<br><strong><em>loss function:</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/456/1*LGkqRh-lYubyosh1UTzT5w.png" /></figure><blockquote>Generator</blockquote><p><strong><em>Goal:</em> </strong>create data that look very similar to the real dataset to fool discriminator. It used the prediction of discriminator to feedback and update model.<br><strong><em>input:</em></strong> noise data<br><strong><em>loss function:</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/257/1*GM1D_Xya7G4AibSu42YijQ.png" /></figure><p>The optimization procedure is that fix G to update parameters of D(base on loss of discriminator) then fix D to update parameters of G(base on loss of generator).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/1*kHFILpErPcW0BWckcCWyhw.png" /><figcaption>GAN algorithm</figcaption></figure><p>This entire process is just like playing the following two-player minimax game with value function V(G,D).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/634/1*svJ9D1WeG2hN4ARh-PK6SA.png" /></figure><p>When generator can successfully fool discriminator, we can treat this generator as a distribution transformer to simulate the real data distribution.</p><h3>Generate random variable</h3><p>When we talk about generating random variable from any specific distribution, the standard method are <a href="https://en.wikipedia.org/wiki/Inverse_transform_sampling">inverse transform method</a>, <a href="https://en.wikipedia.org/wiki/Rejection_sampling">Accept-Reject sampling</a> or <a href="https://en.wikipedia.org/wiki/Metropolis%E2%80%93Hastings_algorithm">Metropolis-Hasting</a>… MCMC algorithms. However, if I want to generate image of dog from dog distribution, this is difficult to apply the traditional method mentioned above.</p><p>What is “probability distributions for images of dogs” means? This is an abstract idea. It’s hard to write down the density function of image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/1*Y7K9yJC7CzoC4wMUKLwj_w.png" /></figure><p>GAN treats neural network as a powerful black box that can learn directly from data how to generate data from any empirical distribution.</p><p>Given a density function which we can easily sample data from. We can use trained generator network in GAN to transform data into the other specific complicated data distribution. The original GAN paper also have proven that “if given enough capacity and training time, p_g will converge to p_data”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/811/1*Jl6-iX_qc3GYqSxql6QdNQ.png" /><figcaption><a href="https://arxiv.org/pdf/1406.2661.pdf">https://arxiv.org/pdf/1406.2661.pdf</a></figcaption></figure><p>For a simple example, assume that I can only generate data from uniform distribution and I have some observed data. I don’t know what is the ground-true distribution of observed data but I want to sample more data from the distribution behind the observed data(here we assume it’s normal distribution).</p><p>The idea is that training a generator network by GAN to transform uniform distribution(which we can generate) to empirical distribution of observed data(whose ground-true distribution is normal).</p><p>Refer to <a href="https://github.com/eriklindernoren/Keras-GAN">keras -GAN</a>, I use only one fully connected layer with 50 neurons in generator network and two fully connected layers with 128 neurons in discriminator network.</p><p>Sample 1000 data from normal distribution as our observed data, then train 30000 epochs. Let’s see some generator output during training:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/1*FEby3hOY666HP4Jw8hD8iA.png" /></figure><p>We can see that the data generated from generator is more and more like normal shape.</p><h3>Anomaly detection</h3><p>Generator also can be applied to do anomaly detection. <br>Assume that in common situation, we have data from uniform distribution and generator had learned how to transform uniform data to normal distribution. So, when generator outputs data which are not follow normal distribution, we can suspect that the original data may not follow uniform distribution anymore.</p><pre>import numpy as np<br>from keras.models import load_model<br>import matplotlib.pyplot as plt<br>from scipy import stats</pre><pre>generator_path = &#39;./models/generator_model_30000.hdf5&#39;<br>sample_size = 100</pre><pre>generator =  load_model(generator_path)<br>noise = np.random.uniform(0, 1, (sample_size, 1))#sample one dimensional uniform<br>batch_samples = generator.predict(noise)<br>samples = [i[0] for i in batch_samples]<br>statistic,p_value = stats.kstest(samples, &#39;norm&#39;,args=(0,1))</pre><pre>plt.hist(noise,density=True)<br>plt.show()<br>plt.hist(samples,density=True)<br>plt.title(&#39;p value is %.3f&#39;%p_value)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/781/1*7csab0vE1xXJpKFtGhB9vA.png" /></figure><p>We can see that the p-value of ks-test is 0.131 which is larger than 0.05. We can not reject null hypothesis and conclude that the data after transformed by generator are follow normal distribution.</p><p>Support that our data source suffer some issue such that data don’t follow uniform distribution anymore(e.g. beta distribution).</p><pre>## test other distribution<br>noise = np.random.beta(1,5,sample_size)<br>batch_samples = generator.predict(noise)<br>samples = [i[0] for i in batch_samples]<br>statistic,p_value = stats.kstest(samples, &#39;norm&#39;,args=(0,1))</pre><pre>plt.hist(noise)<br>plt.show()<br>plt.hist(samples)<br>plt.title(&#39;p value is %.3f&#39;%p_value)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/781/1*xiJvVqyYBaDKsC_MVLTqRg.png" /></figure><p>We can see that generator failed to transform data to normal distribution (p-value=0, reject H0) which implied that there are some problem from data source.</p><h3>Super Resolution GAN (SRGAN)</h3><p>With basic knowledge of GAN, we might image that how can we generate high resolution image(HR) from low resolution image(LR).</p><p><em>Let the real data of GAN be HR image, and noise data be LR image</em>, then let generator to learn how to generate super resolution image(transform LR image to HR) through GAN training procedure. If everything goes well, fake HR will eventually converge to HR. That is!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/734/1*2gElnwfVN_oTaKfDvrRBHA.png" /></figure><h4>Loss function</h4><p>The perceptual loss of SRGAN for the generator composes of content loss and adversarial loss.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/389/1*ac89ep32wNB3UJA6NfdGkg.png" /></figure><blockquote>Content loss:</blockquote><p>Extract feature map of HR image and fake HR image from VGG-19 and compute the MSE between these two features.The pixel-wise MSE loss is calculated as: (MSE between two feature map)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/454/1*snCRGACgc4pYkG0YaZEl0w.png" /></figure><p>Where φi,j indicate the feature map obtained by the j-th convolution (after activation) before the i-th maxpooling layer within the VGG19 network.</p><blockquote>Adversarial loss:</blockquote><p>Same as normal GAN generator loss</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*WFLJK-jYKfNHE0X15_vlug.png" /></figure><h4>Optimization</h4><p>For each batch update:</p><ol><li>Sample half batch of HR(real data) and downsampling to LR.</li><li>Sample another half batch of HR then feed it into generator network to get fake HR.</li><li>Feed HR and fake HR to discriminator and use typical GAN discriminator loss to update discriminator network</li><li>Feed LR into generator+discriminator(fixed) and use perceptual loss which described above to update generator network.</li></ol><h4>Network structure</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/826/1*p-zvIPupySW2c6MHc3OMEg.png" /><figcaption><a href="https://arxiv.org/pdf/1609.04802.pdf">https://arxiv.org/pdf/1609.04802.pdf</a></figcaption></figure><h4>Implement</h4><p>There are awesome GAN github we can apply(base on <a href="https://github.com/eriklindernoren/Keras-GAN">keras </a>and <a href="https://github.com/eriklindernoren/PyTorch-GAN">pytorch</a>)</p><p>I downloaded CelebFaces data from<a href="http://mmlab.ie.cuhk.edu.hk/projects/CelebA.html"> here</a> and train SRGAN with 30,000 epochs. Set LR resolution as 60*60 and HR resolution 240*240(4*upscaling).</p><p>I randomly took some images from internet to test the Generator network:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wcnhy3gD3dUskg6pz8RQfg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/961/1*ReGxpmBVE3RF1fcRliPWEA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/980/1*xbCPnsRFgBuvHzxfDZ_r3w.png" /></figure><p>It looks not bad, right? Nevertheless, I found that generator performs badly on eyes area especially when dealing with people with thick glasses. <br>It may due to this kind of image is less in training data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OeG1_jyNhoBEuC2wrGlLOg.png" /></figure><h3><strong>Reference</strong></h3><p><a href="https://arxiv.org/abs/1406.2661">Generative Adversarial Networks</a></p><p><a href="https://arxiv.org/pdf/1609.04802.pdf">Photo-Realistic Single Image Super-Resolution Using a Generative Adversarial Networ</a></p><p><a href="https://towardsdatascience.com/understanding-generative-adversarial-networks-gans-cd6e4651a29">Understanding Generative Adversarial Networks (GAN)</a></p><p><a href="https://medium.com/@jonathan_hui/gan-super-resolution-gan-srgan-b471da7270ec">GAN — Super Resolution GAN (SRGAN)</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e2e7a4440066" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Human Activity Recognition — SlowFast Network]]></title>
            <link>https://peaceful0907.medium.com/human-activity-recognition-slowfast-network-95c5d07246c?source=rss-d2d57a7d3dc9------2</link>
            <guid isPermaLink="false">https://medium.com/p/95c5d07246c</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[activity-recognition]]></category>
            <dc:creator><![CDATA[CW Lin]]></dc:creator>
            <pubDate>Tue, 24 Mar 2020 15:11:46 GMT</pubDate>
            <atom:updated>2020-03-24T15:15:38.177Z</atom:updated>
            <content:encoded><![CDATA[<h3>Human Activity Recognition — SlowFast Network</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OQHJ4OzDbf9bBCZX" /><figcaption>Photo by <a href="https://unsplash.com/@clearsky?utm_source=medium&amp;utm_medium=referral">Farsai Chaikulngamdee</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>影像分類、物件偵測等電腦視覺技術，隨著ImageNet、COCO數據集的挑戰發展出許多達到人類判斷水準的類神經網路。<br>而行為識別是個比影像的物件偵測難度更高的一個領域，他需要透過理解一段 video 做出預測，比一般影像(二維度空間)還要多了時間的維度。近年來儘管有些發展，但尚無法到達人類的理解層次。</p><p>如同 ImageNet，行為辨識也有個 benchmark: <a href="http://activity-net.org/">ActivityNet</a>，是個動作辨識相關之競賽，首次舉辦於CVPR2016年，他共有六種task的挑戰:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/264/1*DMQamtD-UlrYsLxidpKkmA.png" /></figure><p>Task 1: Temporal Action Proposals<br>Task 2: Temporal Action Localization<br>Task 3: Dense-Captioning Events in Videos<br>Task A: Trimmed Action Recognition<br>Task B: Spatio-temporal Action Localization<br>Task C: Trimmed Event Recognition</p><p>這邊我將 focus on task B，其餘的介紹可以參考<a href="http://cvfiasd.pixnet.net/blog/post/270823692-activitynet%E5%8B%95%E4%BD%9C%E8%BE%A8%E8%AD%98%E7%AB%B6%E8%B3%BD%E4%BB%8B%E7%B4%B9">這篇</a></p><h3>Spatio-temporal Action Localization</h3><p>這個task 需要判斷影片中哪個位置有人，並且判斷那個人在做什麼動作。使用的資料級是 AVA。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/286/1*dKbkFHgThEhaHTsTZ9rJfQ.png" /></figure><p>先來看AVA資料 :<a href="https://research.google.com/ava/index.html">https://research.google.com/ava/index.html</a><br>資料是 csv 檔，內容及欄位如下:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/943/1*YMWMBTxxkxqbANn6ay0Tng.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*11S96ydS4Q9mPFU2Dl5AGw.png" /></figure><p>所以呢 是一堆youtube的影片，要train的話還要有download 小工具才行，可以參考 <a href="https://github.com/facebookresearch/video-long-term-feature-banks/blob/master/DATASET.md">facebookresearch/video-long-term-feature-banks</a> (全部download並extract成 frame的話有大概有500G 且訓練似乎也不容易，自己玩的話還是建議不要train 直接拿pre-train好的model來試就好XD)<br>共有 430個 15-minute movie clips，每秒 label 包含每個人的位置及動作，train 共label約 83萬個動作，val 約 23萬個動作，共有 80 種動作類別。</p><p>這邊介紹這個task在去年表現最好由FAIR 發表的 SlowFast network</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x45M3_W1Q1mjvxLGyMS_AQ.png" /><figcaption><a href="https://research.google.com/ava/challenge.html">AVA challenge 2019</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5kPa5wnWb09vfwWAmNp9cQ.png" /><figcaption>action category</figcaption></figure><p>paper: <a href="https://arxiv.org/abs/1812.03982">https://arxiv.org/abs/1812.03982</a><br>github: <a href="https://github.com/facebookresearch/SlowFast">https://github.com/facebookresearch/SlowFast</a></p><h3>SlowFast network</h3><p>傳統影像處理只有空間上(x,y) 兩個維度，但對於video (x,y,t)多了時間的維度，而作者認為時間和空間的維度不應等同看待，空間信息較為緩慢，ex: 一個人在跑步，空間的信息不太發生變化，短時間內皆是”人”這個類別，但對於時間維度，變化是很快的(此人隨時可能是跑步或走路或著只是站著)。</p><p>受到生物學靈長類視覺系統中視網膜的啟發，在視網膜細胞中 80%是P-cell負責空間和顏色，20%是M-cell 負責響應運動變化。作者建立雙路的slowfast 網路來分別處理空間和時間的訊息。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/485/1*1WHtFwjDC0zuiAyaJ4Pp0A.png" /></figure><blockquote>Slow pathway</blockquote><p>負責捕捉空間的信息，架構可以試任何的3D convolutional network，主要特色是使用low frame rate input(large temporal stride)。</p><blockquote>fast pathway</blockquote><p>負責捕捉運動信息，使用 high frame rate input (low temporal stride)，並且使用較少的channel數 (經實驗後使用slow pathway的1/8 channel 數)。low channel數可以大幅降低運算量(因一般計算複雜度於channel為二次關係)使fast pathway的運算量大約變成slow pathway的 1/4(相當於P,M-cell的比例)，同時也可以把low channel看成對空間信息較不敏感。</p><p>兩個pathway都沒有 temporal downsampling(沒有大於1的 temporal stride，也沒有temporal pooling) 以保持時間保真度。</p><p>網路架構如下:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/451/1*3IarkvKrpJRqt_0k3fMOpg.png" /></figure><p>實作上讀取video的frame後sample部份給slow pathway 部份給fast pathway ，並且取一個frame做object detection 如下圖:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/669/1*p9aPiZOoQZM9rZex170DMw.png" /></figure><blockquote>側連結</blockquote><p>在pool1, res2, res3, res4 有側連結將fast pathway 連到 slow pathway。</p><p>對於兩個網路在時間維度不同shape 的問題提出了三種解決方案(如下)，並且經過實驗選擇了較佳的方案(time -strided convolution)作為default</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/774/1*uicsknvKY4AA2vJnMtMgXg.png" /></figure><h3>實測</h3><p>使用這個<a href="https://github.com/anhminh3105/SlowFast/tree/demo_app">fork</a> 來跑 (<a href="https://github.com/facebookresearch/SlowFast/issues/34">因官方好像還沒release</a>)</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FJ3xIp0x_6jA%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DJ3xIp0x_6jA&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FJ3xIp0x_6jA%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/57f5e540674665746df5c752df06d3dd/href">https://medium.com/media/57f5e540674665746df5c752df06d3dd/href</a></iframe><p>因為是每蒐集64個frame (~2秒) 才跑一次偵測，所以可以看到有點delay。但這個速度實在還差了一大截，每次推論要花到15 秒左右(1080ti)。</p><p>不過這篇paper 主要是提出一個雙向網路不同frame rate的概念來處理時間維度上的運動訊息，並證明了是有效的。讓我們繼續看看未來是否會研發出更方便好用的工具吧~</p><h3>Reference</h3><p><a href="https://arxiv.org/abs/1812.03982">https://arxiv.org/abs/1812.03982</a></p><p><a href="https://github.com/facebookresearch/SlowFast">https://github.com/facebookresearch/SlowFast</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=95c5d07246c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[來玩點NLP — LSTM vs. BERT on IMDb dataset]]></title>
            <link>https://peaceful0907.medium.com/%E4%BE%86%E7%8E%A9%E9%BB%9Enlp-lstm-vs-bert-on-imdb-dataset-4aa18ecd65e2?source=rss-d2d57a7d3dc9------2</link>
            <guid isPermaLink="false">https://medium.com/p/4aa18ecd65e2</guid>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[natural-language-process]]></category>
            <category><![CDATA[bert]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[CW Lin]]></dc:creator>
            <pubDate>Sat, 15 Feb 2020 15:34:36 GMT</pubDate>
            <atom:updated>2021-02-05T10:34:07.105Z</atom:updated>
            <content:encoded><![CDATA[<h3>來玩點NLP — LSTM vs. BERT on IMDb dataset</h3><p>在深度學習的領域裡，Computer Vision(CV)和Natural Language Process(NLP)為最熱絡的兩個領域。CV 玩了一段時間也想來碰一下NLP，就以基本的文本分類來踏入NLP 的世界吧~~</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dUmoKsXdfYSMlKqXs58KVA.jpeg" /><figcaption><a href="https://medium.com/voice-tech-podcast/python-tools-list-for-natural-language-processing-nlp-6c8109591b7c">圖片來源</a></figcaption></figure><p>在深度學習還沒發展起來前，大概是透過詞頻或TF-IDF來萃取文章特徵，然後套用像SVM 等的ML演算法。隨著 RNN 的發展使得NLP獲得許多突破，直到前幾年Transformer, BERT 的出現又往前跨出一大步。網路上有很多資源在講 RNN/LSTM 及BERT 再加上<a href="https://speech.ee.ntu.edu.tw/~tlkagk/courses.html">李宏毅老師</a>已經講的非常完美了，因此此篇文章只會稍微帶過方法，focus 在記錄以 pytorch 實現 LSTM and BERT。</p><p>初學NLP，網路上東看西看學來的，若有理解錯誤還請指教。</p><blockquote>Outline:<br>1. 資料前處理<br>2.方法概論 : RNN/LSTM、BERT<br>3. IMDb 影評分類 data overview<br>4. 實做</blockquote><h3>資料前處理</h3><p>要在文本資料使用ML演算法或類神經網路，首先必須要將文字給轉換成數字向量，電腦才能看得懂。最簡單的做法就是蒐集一大堆的文字，然後給每個不同的字詞一個 index，</p><ol><li><strong>建立語料庫(字典)，以及其對應關係(word_ind):</strong><br>比如說我們有語料庫(Corpus)只有兩個句子:[[&quot;i am happy&quot;],[“she is so cute”]]，那麼我們的辭彙(token)共有[“i”,”am”,”happy”,”she”,”is”,”so”,”cute”] 7個字，並且建立對應關係{i:1, am:2, happy:3, she:4, is:5, so:6, cute,7}。有了這樣的關係，一個句子就可以轉換成index的向量，例如 “she is happy” --&gt;[4,5,3]。 而不在語料庫的詞，都視為unknown。</li><li><strong>截長補短將句子補成一樣長度，將資料的維度統一方便後面丟入模型:<br></strong>使用的方法是zero padding，很簡單，就是過長的句子截掉，過短的補零。假設我們的資料就是上面的例子[[“i am happy”],[“she is so cute”]]，則可以轉成[[1,2,3,0],[4,5,6,7]]，變成長度一致的向量。</li></ol><p>現在我們能將每個字轉換成一個index，一個句子轉換成一個向量了。但是這個<strong><em>詞彙的 index沒有任何辭彙的意義在裡頭</em></strong>，因此有了所謂 word embedding的技術，他將每個字轉換到一個連續的高維歐氏空間中，而在這個空間裡，意思較相關的字詞在空間中也會比較接近，如下圖:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/394/1*2RaWtzDAPbQlGEknxhqOnw.png" /><figcaption><a href="https://www.youtube.com/watch?v=X7PH3NuYW0Q">https://www.youtube.com/watch?v=X7PH3NuYW0Q</a></figcaption></figure><p>而要如何得到 word embedding的轉換函數呢? 目前我知道的主要是<a href="https://zh.wikipedia.org/wiki/Word2vec">word2vec</a> 以及<a href="https://nlp.stanford.edu/projects/glove/">GloVe</a>兩種，分別為prediction base 及count base 的方法，都是蒐集大量文本資料集並以無監督的方式訓練而成。 word2vec 在 <a href="https://medium.com/@peaceful0907/%E7%B0%A1%E6%98%93%E8%AA%9E%E9%9F%B3%E5%8A%A9%E7%90%86%E5%AF%A6%E5%81%9A-5f6228937116">簡易語音助理實做</a> 裡有稍微的介紹到。embedding 這一步如果後面套用神經網路的話也可以讓他從頭 train 直接從你的 task 資料中學習。</p><p>好，假設我們已經能將詞透過 word embedding轉換成一組連續的向量了，到目前為止，我們的前處理大概是做了以下的流程:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uz7nac5mSN2d78XJG-c9EA.png" /><figcaption><a href="https://developers.google.com/machine-learning/guides/text-classification/step-3">https://developers.google.com/machine-learning/guides/text-classification/step-3</a></figcaption></figure><p>到這裡其實就可以套用一些ML的演算法做想做的事了，但如果只用字詞的組成來表達句子其實是有缺陷的， 我們<strong><em>沒有考慮到詞在句子中的位置資訊</em></strong>，而這對一段句子的意思有很大的影響。例如:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/662/1*eLGFPsZ1xfV-gW6KCPn3og.png" /><figcaption><a href="https://www.youtube.com/watch?v=X7PH3NuYW0Q">https://www.youtube.com/watch?v=X7PH3NuYW0Q</a></figcaption></figure><p>所以呢～大家會使用像 RNN, LSTM, attention 等的技術，將每個單詞上下文的文字也一起考慮進來，也就是一種具有記憶力的網路架構，能夠記得前面看過的資料。</p><h3><strong>Recurrent Neural Network(RNN) / Long Short-Term Memory (LSTM)</strong></h3><p>人在理解一個句子時，通常不是一個一個字逐字理解，而是從以往的知識以及上下文一起來理解文意，RNN 引入這種想法，讓機器模擬人類閱讀。而 LSTM 改善了一般RNN訓練時遇到梯度爆炸或消失的問題，同時也讓模型可以記住較長的資訊(記憶力較好)。</p><p>RNN 我是把他想成一個有自我遞迴的 layer ，他將讀過的東西會傳遞給下一個 input，如下圖:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/821/1*v1MS_RGe5QNKsY5_0MWhEw.png" /><figcaption><a href="https://colah.github.io/posts/2015-08-Understanding-LSTMs/">https://colah.github.io/posts/2015-08-Understanding-LSTMs/</a></figcaption></figure><p>所以用在剛剛那個例子，”white blood cells destroying an inflection”，當模型讀到 “destroying”這個字時，他會包含前面 ”white”,”blood”,”cells” 的資訊</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*1U8H9EZiDqfylJU7Im23Ag.gif" /><figcaption><a href="https://leemeng.tw/shortest-path-to-the-nlp-world-a-gentle-guide-of-natural-language-processing-and-deep-learning-for-everyone.html">圖片來源</a></figcaption></figure><p>而RNN 也有bidirectional 的版本，他在判斷一個字的輸入時，同時input (看過) 他的前文以及後文，如下圖:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/513/1*CqhLhnYU34HsQEBVhxSl6w.png" /><figcaption>v<a href="https://www.youtube.com/watch?v=xCGidAeyS4M">https://www.youtube.com/watch?v=xCGidAeyS4M</a></figcaption></figure><p>RNN在訓練的時候由於其目標函數非常的陡峭崎嶇(因 recurrent 的 weight每次input 都不斷連乘，輸入的序列長度指數成長的影響了output)，訓練時容易遇到gradient explode 以及gradient vanish 的問題，導致很難訓練，因此後來出現了LSTM。</p><p>根據 <a href="https://pytorch.org/docs/stable/nn.html">pytorch </a>的LSTM 公式搭配下面的圖即可以知道LSTM是怎樣運算的:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dyl5Lli9qAHqM-hLtzPC5w.png" /></figure><p>不要看到這麼多複雜的運算就嚇到，直接把他想成一個neural的運算，在keras 或 pytorch 都是一個指令就能建立 LSTM layer!</p><p>LSTM 不僅改善了RNN的訓練問題，在許多應用上也大幅改善了RNN的成果，也因此現在一般人在講RNN 通常就是指LSTM，若要表達原始的RNN 要稱 &quot;SimpleRNN&quot;。</p><h3>BERT (Bidirectional Encoder Representation from Transformer)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/958/1*LzkLcdwXc6shgP1XSISvlg.png" /><figcaption><a href="https://www.seroundtable.com/google-curriculum-optimizing-bert-28964.html">https://www.seroundtable.com/google-curriculum-optimizing-bert-28964.html</a></figcaption></figure><p>近年來，自從2017年底 Google 發表了Transformer的經典論文 <a href="https://arxiv.org/abs/1706.03762">”Attention Is All You Need”</a> 後，各種NLP task 都被transformer, self-attention 給洗榜過一遍，開啟了&quot;大注意時代&quot;。</p><p><a href="https://arxiv.org/abs/1810.04805">BERT</a> 是 2019年 Google 以無監督的方式利用大量無標註文本訓練出來的語言代表模型，其架構為 Transformer 中的 Encoder。BERT 提供了一個 pre-trained 的 fine-tuning based language representation。</p><p>如同computer vision 領域裡有 ImageNet 的各種知名pre-trained 好的網路給大家可以站在巨人的肩膀上 fine-tune 自己的 task。<br>而BERT 是 Google研究團隊使用大量資料集 BooksCorpus(800M words)以及 English Wikipedia(2500M words) 總共33億個字來做pre-train，BERT-base使用4個TPU花費了4天才跑完(google暴力美學阿!)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/586/1*_ao4sZ0OCoUv7KgYYROi5g.png" /><figcaption><a href="https://www.youtube.com/watch?v=UYPa347-DdE">https://www.youtube.com/watch?v=UYPa347-DdE</a></figcaption></figure><p>BERT提供了一個對人類語言有一定認知的一個 pre-train model，並提供了四種 fine-tune BERT 的 NLP應用範例，因此使用上我們只要把BERT當做一個~magic~ 的 layer，套上自己對應的 task 來fine tune就好 !</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/784/1*uGc-HbjEmMDtvo7GMlZ8fg.png" /></figure><p>那什麼是self-attention? 什麼是transformer? 這實在說來話長，大家可以去看<a href="https://www.youtube.com/watch?v=ugWDIIOHtPA">李宏毅老師的教學影片</a>，講的無敵清楚，看過後再去看paper或網路上其他人的教學就容易許多。</p><p>好了！ 說了那麼多，要是coding不出來就只是在空談阿!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/521/1*P-ic74oB0YngIkB-_cxk3A.png" /></figure><p>不要急~先找個資料集來瞧瞧~</p><h3>IMDb 影評分類 data overview</h3><p>資料載點:<a href="http://ai.stanford.edu/~amaas/data/sentiment/aclImdb_v1.tar.gz">http://ai.stanford.edu/~amaas/data/sentiment/aclImdb_v1.tar.gz</a></p><p>此資料蒐集50000筆電影影評的文字資料，切分成25000筆 train, 25000筆 test。而在train &amp; test 裡各自有neg 及pos 各12500筆負雷和好雷的影評資料，可以說是非常親人的入們款資料集!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*_30WBNWjGDVH8jj2zWuAGQ.png" /></figure><p>來看一篇資料:</p><p>train&gt;neg&gt;1_1.txt: <a href="https://www.imdb.com/review/rw0288449/?ref_=tt_urv">影評ur</a>l <br>Robert DeNiro plays the most unbelievably intelligent illiterate of all time. This movie is so wasteful of talent, it is truly disgusting. The script is unbelievable. The dialog is unbelievable. Jane Fonda’s character is a caricature of herself, and not a funny one. The movie moves at a snail’s pace, is photographed in an ill-advised manner, and is insufferably preachy. It also plugs in every cliche in the book. Swoozie Kurtz is excellent in a supporting role, but so what?&lt;br /&gt;&lt;br /&gt;Equally annoying is this new IMDB rule of requiring ten lines for every review. When a movie is this worthless, it doesn’t require ten lines of text to let other readers know that it is a waste of time and tape. Avoid this movie.</p><p>ok~憑我拙劣的英文能力也能看出這的確是一篇負評</p><p>接著我們就以 LSTM 以及 BERT 分別來實作電影影評分類，看看各自的表現如何~</p><h3><strong>實作 — LSTM</strong></h3><p>這部分我參考<a href="https://samaelchen.github.io/pytorch_lstm_sentiment/"> PyTorch实现LSTM情感分析</a> 這篇做一些修改來實做。 訓練的框架是用 pytorch，另外有使用到<a href="https://pypi.org/project/gensim/"> gensim</a>來load embedding 的pretrain weight(optional)</p><p>首先 load 資料並做前處理:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/112958e1e2dbee6d75cab556fb9127bb/href">https://medium.com/media/112958e1e2dbee6d75cab556fb9127bb/href</a></iframe><p>到這邊我們已經把資料都給 load 進來並且去除一些html tag, 標點符號, 換行符號的前處理。</p><p>train_data 是一個list 存放每一篇影評而train_tokenize是一個list 將上述的train_data依照空個切開:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/647/1*-DVj3Nj6shFJ1Lat2FQtcA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/656/1*n0vPNTko2e5QWXqH5hYywg.png" /><figcaption>train_data &amp; train_tokenize</figcaption></figure><p>接著將單辭轉換成 index →zero-padding →切出validation set →轉成 pytorch tensor 最後創建dataloader:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9fc096e24f5bb78437539786eeedaa43/href">https://medium.com/media/9fc096e24f5bb78437539786eeedaa43/href</a></iframe><p>到這裡我們已經把文章轉換成 index 的tensor 如下:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/331/1*xQeFsa07bhdUXbmGQ34VgQ.png" /><figcaption>train_features</figcaption></figure><p>可以看到長度較短的文章後面都被zero-padding 成 0，而長度較長的也被截成相同長度的tensor。</p><p>來看個preprocess 的結果，比如一個句子: &quot;an apple a day, keeps the doctor away&quot;:</p><pre>### let us see some preprocess result ###<br>text = &quot;an apple a day, keeps the doctor away&quot;<br>token = tokenizer(text)<br>print(&#39;text: &#39;+text)<br>print(&#39;token: &#39;+ str(token))<br>print(&#39;encode to index: &#39;+str(encode_samples([token])))</pre><pre>text: an apple a day, keeps the doctor away<br>token: [&#39;an&#39;, &#39;apple&#39;, &#39;a&#39;, &#39;day,&#39;, &#39;keeps&#39;, &#39;the&#39;, &#39;doctor&#39;, &#39;away&#39;]<br>encode to index: [[23314, 28267, 26943, 0, 49709, 27809, 29103, 70204]]</pre><p>可以看到每個字都被截出來轉成一個index，其中因為我在建置辭庫時已經前處理過將標點符號都濾除了，所以逗號 &quot;，&quot;並沒有在我的辭庫裡，而在上面的”an apple a day, keeps the doctor away” 裡的逗號就被視為unknown 給予index: 0</p><p>接著我導入了pre-train好的 word-embedding weight，透過 genism 讀取GloVe官方提供的pre-train word vector，這步也可以不做，直接讓模型從頭學習embedding layer。</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/45283ef996732672b71d6d594edb2b9c/href">https://medium.com/media/45283ef996732672b71d6d594edb2b9c/href</a></iframe><p>然後繼承 nn.Module 來建立網路架構:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7013eb5f7c7ebab68a361a58c0f8bb4f/href">https://medium.com/media/7013eb5f7c7ebab68a361a58c0f8bb4f/href</a></iframe><p>架構很簡單就是 embedding(from pre-train weight) →兩層LSTM → Linear <br><a href="https://zhuanlan.zhihu.com/p/39191116">(pytorch LSTM layer 講解)</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/668/1*EE2l2e2X6qdMoGScwsrpjA.png" /></figure><p>最後終於要來訓練模型啦~</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/21cecb4edcbde7674cfd5d57da365f62/href">https://medium.com/media/21cecb4edcbde7674cfd5d57da365f62/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/1*-6MCh_HMMqCC9kQIfrV6aw.png" /></figure><p>在1080ti 上花不到10分鐘就train完了，最後 testing set 的準確率達到88% !</p><h3>實作 — BERT</h3><p>這邊參考 <a href="https://leemeng.tw/attack_on_bert_transfer_learning_in_nlp.html">進擊的 BERT：NLP 界的巨人之力與遷移學習</a> ，這篇裡頭的任務是成對句子的分類任務(判斷兩個句子是否是相同來源)，而我把它改成單一句子的分類任務。</p><p>所需套建除了pytorch 外套用了<a href="https://github.com/huggingface/transformers">HuggingFace 團隊的 GitHub 專案</a>來實現BERT。直接安裝:</p><pre>pip install transformers</pre><p>首先import 相關模組:</p><pre>import torch<br>import torch.nn as nn<br>from torch.autograd import Variable<br>import torch.nn.functional as F</pre><pre>import time<br>import os<br>import re<br>from itertools import chain<br>from transformers import BertTokenizer</pre><pre>PRETRAINED_MODEL_NAME = &quot;bert-base-uncased&quot; #英文pretrain(不區分大小寫)<br>print(torch.__version__)</pre><pre>#1.3.1</pre><p>載入BERT token:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6c42ebd254ddd53838173ff06e65879e/href">https://medium.com/media/6c42ebd254ddd53838173ff06e65879e/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/247/1*8pTh9NrCDYMbZbTzPwt2sg.png" /></figure><p>可以看到bert-base-uncase 約有3萬多個token。<br>接著要讀取IMDb的影評文字資料並且透過 BERT 的tokenizer 轉換成對應的index，並且創建進入BERT 需要的 tensor 如下圖，paper 上的範例，但我們的task只有一個句子，所以segments_tensor的部分會全部給1</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/833/1*e0-kHJ-J2RU5KkBpzE644Q.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ff20c609ce0c4e633d303bb53925a8fb/href">https://medium.com/media/ff20c609ce0c4e633d303bb53925a8fb/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/171/1*MnrxGebqdp19WnrpdLHZ8Q.png" /></figure><p>來看一下到目前為止做的事情:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/da0202b5b82f3c34b6c773e702d25e14/href">https://medium.com/media/da0202b5b82f3c34b6c773e702d25e14/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/996/1*qx1xvhoEW6yVM2W4d-YLig.png" /><figcaption>怕版面太長，我把字的數量減少一些來呈現</figcaption></figure><p>接著建立pytorch dataloader 來一次取一個batch的資料放到GPU訓練:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5dd891b459ca2ba769de78b6154dea20/href">https://medium.com/media/5dd891b459ca2ba769de78b6154dea20/href</a></iframe><p>這邊記得在train 的dataset shuffle要寄得給true，因為我們的資料很整齊，前面都是pos 後面都是neg，這樣train 的時候一個batch會完全都是相同label，模型會train到奇怪的地方去。</p><p>接下來 load BERT pre-train model，單一句子分類的FINETUNE_TASK是歸類在 bertForSequenceClassification</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a4a2ffdf8ae3885eadfbaa9fc05b1d86/href">https://medium.com/media/a4a2ffdf8ae3885eadfbaa9fc05b1d86/href</a></iframe><p>這邊可以看到load進來的架構:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/491/1*cD2G2tsFJGKwS1t9d4Vh2g.png" /></figure><p>沒錯! 搞那麼久，這邊一行BertForSequenceClassification.from_pretraine就建好模型架構了!!</p><p>我們可以透過 <em>model.config</em> 來查看或調整模型參數。</p><p>最後來fine-tune BERT:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/74615f10bd8ce2ea6ea2622029b3b865/href">https://medium.com/media/74615f10bd8ce2ea6ea2622029b3b865/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/594/1*PUJbdqrrufUbL9OUfF62kw.png" /></figure><p>可以看到train的越多好像也沒什麼改進，且val loss甚至還一直上升，可能有些sample 錯的比較誇張導致 loss拉高，anyway validation acc 達到92%，讓我們來看看testing set的預測結果:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a745ccd59097c13c4d30bac12befc709/href">https://medium.com/media/a745ccd59097c13c4d30bac12befc709/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/146/1*YXLq5u3w1lEp3ucNIxOv2A.png" /></figure><p>準確率也達到了92%耶~開心^^</p><p>其實在paper上fine tune的例子幾乎都只用了3~5個epoch，在加上剛剛上面的training 過程，我便直接使用train 一個epoch的模型來跑test，結果第一個epoch 在testing set也有92%的準確率......所以BERT本身就對語言已經有一定的認知，把training data看過一遍就大概能做出不錯的分類了。</p><h3><strong>Reference</strong></h3><p><a href="https://leemeng.tw/shortest-path-to-the-nlp-world-a-gentle-guide-of-natural-language-processing-and-deep-learning-for-everyone.html">進入 NLP 世界的最佳橋樑：寫給所有人的自然語言處理與深度學習入門指南</a></p><p><a href="https://speech.ee.ntu.edu.tw/~tlkagk/courses.html">台大李宏毅老師課程</a></p><p><a href="https://colah.github.io/posts/2015-08-Understanding-LSTMs/">Understanding LSTM Networks</a></p><p><a href="https://samaelchen.github.io/pytorch_lstm_sentiment/">PyTorch实现LSTM情感分析</a></p><p><a href="https://leemeng.tw/attack_on_bert_transfer_learning_in_nlp.html">進擊的 BERT：NLP 界的巨人之力與遷移學習</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4aa18ecd65e2" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>