<?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 AI應用顧問Andy on Medium]]></title>
        <description><![CDATA[Stories by AI應用顧問Andy on Medium]]></description>
        <link>https://medium.com/@Andy30808?source=rss-54b4617b5170------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*7FhBy_SRD7q7YtqxfHGyFQ.jpeg</url>
            <title>Stories by AI應用顧問Andy on Medium</title>
            <link>https://medium.com/@Andy30808?source=rss-54b4617b5170------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 15:09:05 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@Andy30808/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[打造你自己的 AI Agent！從零開始自建一套 MCP 系統教學]]></title>
            <link>https://medium.com/@Andy30808/%E6%89%93%E9%80%A0%E4%BD%A0%E8%87%AA%E5%B7%B1%E7%9A%84-ai-agent-%E5%BE%9E%E9%9B%B6%E9%96%8B%E5%A7%8B%E8%87%AA%E5%BB%BA%E4%B8%80%E5%A5%97-mcp-%E7%B3%BB%E7%B5%B1%E6%95%99%E5%AD%B8-c2bedec118ac?source=rss-54b4617b5170------2</link>
            <guid isPermaLink="false">https://medium.com/p/c2bedec118ac</guid>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[mcp-server]]></category>
            <category><![CDATA[llm-applications]]></category>
            <dc:creator><![CDATA[AI應用顧問Andy]]></dc:creator>
            <pubDate>Mon, 18 Aug 2025 15:44:44 GMT</pubDate>
            <atom:updated>2025-08-18T15:44:44.192Z</atom:updated>
            <content:encoded><![CDATA[<h3>一、MCP 是什麼？為什麼選它？</h3><p><strong>MCP</strong> 全名為Model Context Protocol，中文為<strong>「</strong>模型上下文協議<strong>」。</strong>是一個輕量級、模組化的 Agent 框架，由開發Claude模型的美國新創公司Anthropic推出。你可以把它想像成：</p><p><strong>一個幫你把「語言模型」包裝成「智慧助理」的開發工具箱。</strong></p><p>允許你註冊任意自定義工具（Tool），這些工具可以是查資料庫、抓 API、讀內部文件，甚至是控制你內部系統的操作流程。LLM 負責理解語意、做任務規劃與串接這些工具，實現一種「語意驅動的程式執行」邏輯。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*ROo590oQF5cWJJTx" /><figcaption>圖片來源：<a href="https://www.descope.com/learn/post/mcp">https://www.descope.com/learn/post/mcp</a></figcaption></figure><h4>組成MCP有哪些架構與角色？</h4><p>Model Context Protocol（MCP）採用「客戶端–主機–伺服器」的架構設計，整體系統具備<strong>模組化與組合性</strong>，每個 MCP Server 都能專注處理特定領域的任務，例如檔案存取、網頁搜尋或資料庫操作等。</p><h3>二、MCP 架構角色說明：</h3><ul><li><strong>MCP Host（主機）</strong>：像是 Claude Desktop、整合式開發環境（IDE），或是你的 Python 應用程式 — — 這些應用會透過 MCP 存取資料。</li><li><strong>MCP Client（客戶端）</strong>：協定的實作端，負責與 MCP Server 建立 1 對 1 的連線，傳遞指令與接收結果。</li><li><strong>MCP Server（伺服器）</strong>：每個 MCP Server 是一個輕量程式，透過標準化的 MCP 協定，提供特定能力（例如工具調用、資源存取、Prompt 模組化等）。</li><li><strong>Local Data Sources（本地資料來源）</strong>：指你的電腦上的檔案、資料庫或本地服務。MCP Server 可安全地存取這些資源。</li><li><strong>Remote Services（遠端服務）</strong>：指透過網路可用的外部系統，例如公開 API 或企業內部 API，MCP Server 可連線與之互動。</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KSKsn3UfRjw6NY4SC94naQ.png" /></figure><h3>三、快速開始：建立一個最小可運作的MCP專案</h3><p>要快速實作一個簡易的MCP專案，可分為以下步驟</p><blockquote>第一步：建立 MCP Server</blockquote><blockquote>第二步：建立MCP Client</blockquote><blockquote>第三步：串接LLM，實現自然語言調用</blockquote><blockquote>Final：連結前端，用Streamlit打造互動介面</blockquote><h4><strong>第一步：建立 MCP Server</strong></h4><p>以下示範建立一個基於MCP協議的伺服器，並且定義一個簡單的加法工具API</p><p>首先，匯入必要模組，需先下載 Python模組 mcp[cli]，使用pip下載</p><pre>pip install mcp[cli]==1.10.1</pre><pre>from mcp.server.fastmcp import FastMCP<br>from dotenv import load_dotenv<br>from mcp import StdioServerParameters<br>from mcp.client.stdio import stdio_client</pre><p>接著，定義一個MCP server，需定義</p><ul><li>伺服器名稱：&quot;Knowledge&quot;。</li><li>host=&quot;0.0.0.0&quot;：伺服器會綁定所有網路介面（僅用於 SSE 傳輸）。</li><li>port=8050：設定 SSE 模式的伺服器埠號。</li><li>stateless_http=True：允許 stateless HTTP 模式（例如 streamable-http 傳輸）。</li></ul><pre>mcp = FastMCP(<br>    name=&quot;Knowledge Base&quot;,<br>    host=&quot;0.0.0.0&quot;,  # only used for SSE transport (localhost)<br>    port=8050,  # only used for SSE transport (set this to any port)<br>)</pre><p>下一步：使用mcp decorator @mcp_tool()定義可呼叫工具</p><p>在這一步中，自行定義可供mcp調用的工具，可以是調用某特定API取得資料，也可以是某檔案文件操作的程式。</p><p>舉例來說，我有某特定用途的文件，當我需要問到其中內容實再調用，我就可以定義以下函式</p><pre>@mcp.tool()<br>def get_knowledge_base() -&gt; str:<br>    &quot;&quot;&quot;Retrieve the entire knowledge base as a formatted string.<br><br>    Returns:<br>        A formatted string containing all Q&amp;A pairs from the knowledge base.<br>    &quot;&quot;&quot;<br>    try:<br>        kb_path = os.path.join(os.path.dirname(__file__), &quot;data&quot;, &quot;kb.json&quot;)<br>        with open(kb_path, &quot;r&quot;) as f:<br>            kb_data = json.load(f)<br><br>        # Format the knowledge base as a string<br>        kb_text = &quot;Here is the retrieved knowledge base:\n\n&quot;<br><br>        if isinstance(kb_data, list):<br>            for i, item in enumerate(kb_data, 1):<br>                if isinstance(item, dict):<br>                    question = item.get(&quot;question&quot;, &quot;Unknown question&quot;)<br>                    answer = item.get(&quot;answer&quot;, &quot;Unknown answer&quot;)<br>                else:<br>                    question = f&quot;Item {i}&quot;<br>                    answer = str(item)<br><br>                kb_text += f&quot;Q{i}: {question}\n&quot;<br>                kb_text += f&quot;A{i}: {answer}\n\n&quot;<br>        else:<br>            kb_text += f&quot;Knowledge base content: {json.dumps(kb_data, indent=2)}\n\n&quot;<br><br>        return kb_text<br>    except FileNotFoundError:<br>        return &quot;Error: Knowledge base file not found&quot;<br>    except json.JSONDecodeError:<br>        return &quot;Error: Invalid JSON in knowledge base file&quot;<br>    except Exception as e:<br>        return f&quot;Error: {str(e)}&quot;</pre><h4>第二步：建立 MCP client</h4><p>在上一步中，我們已經啟動了一個 MCP Server，現在我們要撰寫一個 MCP Client，若Client與server互為不同主機的話，即需透過 SSE（Server-Sent Events）協定與 Server 建立連線，呼叫其中註冊的工具。</p><p>這個步驟中，我們會完成以下幾件事：</p><ol><li>連接到 MCP Server（本例使用 <a href="http://localhost:8050/sse%EF%BC%89">http://localhost:8050/sse）</a></li><li>初始化 session</li><li>列出伺服器上所有可用工具</li><li>從server.py呼叫一個名為 get_knowledge的工具</li></ol><pre>async def main():<br>    &quot;&quot;&quot;Main entry point for the client.&quot;&quot;&quot;<br>    await connect_to_server(&quot;server.py&quot;)<br><br>    # 範例 詢問公司假期相關規定<br>    query = &quot;What is our company&#39;s vacation policy?&quot;<br>    print(f&quot;\nQuery: {query}&quot;)<br><br>    response = await process_query(query)<br>    print(f&quot;\nResponse: {response}&quot;)<br><br>    await cleanup()# 清理資源<br><br><br>if __name__ == &quot;__main__&quot;:<br>    asyncio.run(main())</pre><pre>async def connect_to_server(server_script_path: str = &quot;server.py&quot;):<br>    &quot;&quot;&quot;Connect to an MCP server.<br><br>    Args:<br>        server_script_path: Path to the server script.<br>    &quot;&quot;&quot;<br>    global session, stdio, write, exit_stack<br><br>    # 配置<br>    server_params = StdioServerParameters(<br>        command=&quot;python&quot;,<br>        args=[server_script_path],<br>    )<br><br>    # 連接到伺服器<br>    stdio_transport = await exit_stack.enter_async_context(stdio_client(server_params))<br>    stdio, write = stdio_transport<br>    session = await exit_stack.enter_async_context(ClientSession(stdio, write))<br>    # 如果為sse連線<br>    # sse_url = &quot;http://localhost:8050/sse&quot;<br><br>    # sse_transport = await exit_stack.enter_async_context(sse_client(sse_url))<br>    # read_stream, write_stream = sse_transport<br>    # session = await exit_stack.enter_async_context(ClientSession(read_stream, write_stream))<br><br>    # Initialize the connection<br>    await session.initialize()<br><br>    # List available tools<br>    tools_result = await session.list_tools()<br>    print(&quot;\nConnected to server with tools:&quot;)<br>    for tool in tools_result.tools:<br>        print(f&quot;  - {tool.name}: {tool.description}&quot;)<br><br><br>async def get_mcp_tools() -&gt; List[Dict[str, Any]]:<br>    &quot;&quot;&quot;Get available tools from the MCP server in OpenAI format.<br><br>    Returns:<br>        A list of tools in OpenAI format.<br>    &quot;&quot;&quot;<br>    global session<br><br>    tools_result = await session.list_tools()<br>    return [<br>        {<br>            &quot;type&quot;: &quot;function&quot;,<br>            &quot;function&quot;: {<br>                &quot;name&quot;: tool.name,<br>                &quot;description&quot;: tool.description,<br>                &quot;parameters&quot;: tool.inputSchema,<br>            },<br>        }<br>        for tool in tools_result.tools<br>    ]</pre><h4>第三步：串接OpenAI API(or 其他LLM API)</h4><p>在這一步中，我們會使用OpenAI所定義的function calling格式，實現LLM calling tool</p><p>首先，定義process_query函式，此函式會藉由輸入的問題或需求， 決定是否要調用相關的mcp tool。如果有相應的mcp tool可調用， 則執行該工具；如果沒有，則透過LLM進行回應。</p><pre><br>async def process_query(query: str) -&gt; str:<br>    &quot;&quot;&quot;Process a query using OpenAI and available MCP tools.<br><br>    Args:<br>        query: The user query.<br><br>    Returns:<br>        The response from OpenAI.<br>    &quot;&quot;&quot;<br>    global session, openai_client, model<br><br>    # Get available tools<br>    tools = await get_mcp_tools()<br><br>    # Initial OpenAI API call<br>    response = await openai_client.chat.completions.create(<br>        model=model,<br>        messages=[{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: query}],<br>        tools=tools,<br>        tool_choice=&quot;auto&quot;,<br>    )<br><br>    # Get assistant&#39;s response<br>    assistant_message = response.choices[0].message<br><br>    # Initialize conversation with user query and assistant response<br>    messages = [<br>        {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: query},<br>        assistant_message,<br>    ]<br><br>    # Handle tool calls if present<br>    if assistant_message.tool_calls:<br>        # Process each tool call<br>        for tool_call in assistant_message.tool_calls:<br>            # Execute tool call<br>            result = await session.call_tool(<br>                tool_call.function.name,<br>                arguments=json.loads(tool_call.function.arguments),<br>            )<br><br>            # Add tool response to conversation<br>            messages.append(<br>                {<br>                    &quot;role&quot;: &quot;tool&quot;,<br>                    &quot;tool_call_id&quot;: tool_call.id,<br>                    &quot;content&quot;: result.content[0].text,<br>                }<br>            )<br><br>        # Get final response from OpenAI with tool results<br>        final_response = await openai_client.chat.completions.create(<br>            model=model,<br>            messages=messages,<br>            tools=tools,<br>            tool_choice=&quot;none&quot;,  # Don&#39;t allow more tool calls<br>        )<br><br>        return final_response.choices[0].message.content<br><br>    # No tool calls, just return the direct response<br>    return assistant_message.content</pre><h4><strong>Final：連結前端，用Streamlit打造互動介面</strong></h4><p>應用最後，使用streamlit打造前端互動介面來執行自建的MCP server</p><pre>import streamlit as st<br>import asyncio<br>from mcp import ClientSession<br>from mcp.client.sse import sse_client<br><br>MCP_SERVER_URL = &quot;http://localhost:8050/sse&quot;  # 替換成你的 MCP Server URL<br><br>st.set_page_config(page_title=&quot;🧠 MCP 應用看板&quot;, layout=&quot;wide&quot;)<br>st.title(&quot;🧠 MCP Agent 看板&quot;)<br><br># 選單欄<br>menu = st.sidebar.selectbox(&quot;功能選單&quot;, [&quot;Agent 對話&quot;, &quot;工具清單&quot;])<br><br># 初始化狀態<br>if &quot;chat_history&quot; not in st.session_state:<br>    st.session_state.chat_history = []<br><br># Async 函數包裝器<br>def async_run(coro):<br>    return asyncio.run(coro)<br><br># 顯示 Agent 對話頁面<br>if menu == &quot;Agent 對話&quot;:<br>    with st.form(&quot;chat_form&quot;):<br>        user_input = st.text_input(&quot;請輸入你的問題：&quot;, &quot;&quot;)<br>        submitted = st.form_submit_button(&quot;送出&quot;)<br><br>    if submitted and user_input.strip():<br>        st.session_state.chat_history.append({&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: user_input})<br>        st.markdown(&quot;⏳ 回應中...&quot;)<br><br>        async def call_agent():<br>            async with sse_client(MCP_SERVER_URL) as (read_stream, write_stream):<br>                async with ClientSession(read_stream, write_stream) as session:<br>                    await session.initialize()<br>                    response = await session.run(user_input)<br>                    return response<br><br>        result = async_run(call_agent())<br>        reply = result if isinstance(result, str) else str(result)<br>        st.session_state.chat_history.append({&quot;role&quot;: &quot;assistant&quot;, &quot;content&quot;: reply})<br><br>    # 顯示聊天記錄<br>    for msg in st.session_state.chat_history:<br>        role = &quot;🙋‍♂️ 你：&quot; if msg[&quot;role&quot;] == &quot;user&quot; else &quot;🤖 Agent：&quot;<br>        st.markdown(f&quot;**{role}** {msg[&#39;content&#39;]}&quot;)<br><br># 顯示工具清單頁面<br>elif menu == &quot;工具清單&quot;:<br>    st.subheader(&quot;🔧 可用工具列表&quot;)<br><br>    async def list_tools():<br>        async with sse_client(MCP_SERVER_URL) as (read_stream, write_stream):<br>            async with ClientSession(read_stream, write_stream) as session:<br>                await session.initialize()<br>                result = await session.list_tools()<br>                return result.tools<br><br>    tools = async_run(list_tools())<br><br>    for tool in tools:<br>        st.markdown(f&quot;### {tool.name}&quot;)<br>        st.markdown(f&quot;{tool.description}&quot;)<br>        st.markdown(&quot;---&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Df8efhmX83hPgc0XpgpGTg.png" /></figure><h4>結語</h4><p>網路上已有許多連結外部工具或對特定系統操作的mcp package，但如果有特殊需求，自建一些小工具並結合LLM執行也相當有趣，若有特定想完成的MCP tool不妨在留言處告訴我，有其他想討論的也歡迎在底下留言。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c2bedec118ac" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LINE 蔬果菜價預測平台：預測市場趨勢，掌握最佳採購時機！]]></title>
            <link>https://medium.com/@Andy30808/line-%E8%94%AC%E6%9E%9C%E8%8F%9C%E5%83%B9%E9%A0%90%E6%B8%AC%E5%B9%B3%E5%8F%B0-%E9%A0%90%E6%B8%AC%E5%B8%82%E5%A0%B4%E8%B6%A8%E5%8B%A2-%E6%8E%8C%E6%8F%A1%E6%9C%80%E4%BD%B3%E6%8E%A1%E8%B3%BC%E6%99%82%E6%A9%9F-94c4eafacdf6?source=rss-54b4617b5170------2</link>
            <guid isPermaLink="false">https://medium.com/p/94c4eafacdf6</guid>
            <category><![CDATA[time-series-analysis]]></category>
            <category><![CDATA[lstm]]></category>
            <category><![CDATA[line]]></category>
            <category><![CDATA[line-bot]]></category>
            <dc:creator><![CDATA[AI應用顧問Andy]]></dc:creator>
            <pubDate>Wed, 18 Sep 2024 14:07:04 GMT</pubDate>
            <atom:updated>2024-09-18T14:08:22.778Z</atom:updated>
            <content:encoded><![CDATA[<h4>為何需要線上價格平台</h4><p>不管是股價、蛋價、肉價、菜價等等，這類商品價格會隨市場變化而波動的商品往往讓採購者傷透腦筋。不僅要考慮合適的訂購量以避免出現過多囤貨，也要考慮利潤的估算。過去幾大蔬果批發商經常發生訂購太多的蔬果導致最終只好報廢作收，造成的浪費與損失十分可觀。</p><p>如果可以事前得知大致的交易價格，依此決定採購數量，是否就能有效減少不必要的浪費？若能有統一的價格平台能夠查詢過去的蔬果交易價格並給出相對應的價格預測，採購者就能對訂購量有事前的參考依據</p><h4>合作企業： 正暘農產股份有限公司</h4><p>本次專案接到正暘農產的需求，期望得到十種日常消耗量最大的蔬果價格預測，讓正暘同仁可掌握未來三天、一週、與一個月的蔬果價格，以作為購買時的參考依據。</p><blockquote><strong><em>達成效益 蔬果廚餘庫存量減少30%，減碳120頓</em></strong></blockquote><p>透過未來的蔬果價格，正暘同仁更能掌握購買進貨量， 避免購買過多蔬果導致剩餘庫存過量，造成浪費。在導入蔬果價格預測平台後，正暘農產的整體廚餘庫存量減少了30%， 帶動五家合作企業共同使用，總計減碳120頓碳排放。</p><h4>平台工具：LINE OA 官方帳號</h4><p>LINEOA 作為線上平台給予使用者與開發者非常高的自由度，除了作為與客人的交流管道，保持與顧客的聯繫外；也可以當作企業內部互相交換情報，宣傳公司政策的交流平台。</p><p>LINE OA針對使用者設計貼標、群發、預約等多種功能，更重要的是可以串接自己訓練的AI預測模型，提供使用者落地即用AI服務。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-wKCnSECwScHlf4O-0Puuw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kNdRGYWDMeZdLe0-Gv1ygg.jpeg" /><figcaption>LINE BOT串接AI模型</figcaption></figure><h4><strong>蔬果價格預測模型：長短期記憶模型(LSTM)</strong></h4><p>蔬菜價格為時序型資料， 除了季節性、週期性的波動外，也會因為天氣、天災因素導致價格出現巨大變動。考慮到使用單純的時間序列模型無法考慮到環境因素，因此我決定使用長短期記憶模型(Long short-term Memory，簡稱LSTM) 作為本次專案的模型訓練主要架構</p><p>LSTM 由單元(cell) 、 輸入門(input gate)、輸出門(output gate)、遺忘門(forget gate) 所組成。 LSTM以向量方式計算每個門的輸入輸出， 及該保留多少，使得我們可以納入多個影響變數去更好的訓練出結果</p><p>詳細的運作原理在本文就不予以贅述，感興趣的朋友可按讚留言告訴我，之後再單獨出教學文章。 範例程式碼如下圖。</p><pre>import numpy as np<br>from keras.wrappers.scikit_learn import KerasRegressor<br>from keras.wrappers.scikit_learn import KerasRegressor<br>from sklearn.model_selection import GridSearchCV<br>from keras.models import Sequential<br>from keras.layers import LSTM<br>from keras.layers import Dense,Dropout<br>import pandas as pd<br><br>from sklearn.preprocessing import MinMaxScaler,LabelEncoder<br><br><br>data = pd.read_excel(&quot;菜價旬/蔬菜產品交易價量走勢圖資料花胡瓜.xls&quot;)</pre><pre>grid_model = KerasRegressor(build_fn=build_model,verbose=1,validation_data=(testX,testY))<br>parameters = {&#39;batch_size&#39; : [16,20],<br>              &#39;epochs&#39; : [8,10],<br>              &#39;optimizer&#39; : [&#39;adam&#39;,&#39;Adadelta&#39;] }<br>grid_search  = GridSearchCV(estimator = grid_model,<br>                            param_grid = parameters,<br>                            cv = 2)<br><br>grid_search = grid_search.fit(trainX,trainY)</pre><h4>AI預測模型串接LINE OA：webhook</h4><p>當你的服務是由某項事件觸發時， webhook 即很適合作為資料源傳遞架構。 而LINEBOT webhook為客戶端與伺服器端搭建一座橋樑，每當用戶發出訊息時，LINE會依照訊息內容、種類傳遞事件到服務端， 服務端依照訊息觸發流程或發送訊息回給LINE webhook。</p><p>此次專案我用LINE BOT搭建三個啟動事件，一為查看過去一週蔬菜價格；二為取得未來三天、一週、一個月的預測價格；最後為啟用颱風模式調整預測</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IsELJlTRi5lIAa8CIBE22A.png" /><figcaption>LINE Webhook運作示意圖</figcaption></figure><h4>菜價預測準確度</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y9TM-PKjfdarPPVORlRwuQ.png" /></figure><p>本次專案採用108年~112年共五年的訓練資料，實際上線測試113年1月~6月總計六個月，平均誤差百分比約在12%。結果上達客戶預期要求，並且後台持續監控預測準確率，隨時在偏移時重新訓練。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*nC1ag54LZuQlv7iy9zXwIQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*fTxiTDLtc5M_-HGZarzPuA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*D8fGo5Kj2kk-v08Fbkj6oA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*KX6V_Ah5T5Cz3ynewM_YkA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*xolrjYAC9lzXtu7DQj9iSg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*ZWIpgp8134djyCMTsMLOYw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*sezUa1aQ3yRlgMNBds8udg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*WTiO0twlF5kUyuTjtikYqA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*GbCMOYo-Sux9qiOeihc7lA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*9J-smKaBFLlcDMTx2Yc1jA.png" /><figcaption>十種蔬菜價格預測Actual-predicted plot</figcaption></figure><h4>菜價資料來源</h4><pre>headers = {<br>        &#39;Content-Type&#39;: &#39;application/json&#39;,<br>    }<br><br>    url = f&quot;https://data.moa.gov.tw/api/v1/AgriProductsTransType/?Start_time={lasttwomonth}&amp;End_time={current_time}&amp;CropCode={crop}&amp;MarketName=%E5%8F%B0%E5%8C%97%E4%B8%80&quot;<br><br>    req = requests.get(url,headers=headers)<br><br><br>    crawl_data = req.json()</pre><p>各市場的蔬菜價格與交易量都有開放API可以取得，只要有開市的日子，即可取得交易日時的高、低、中、均價， 本次專案即是用過去三十天的高低中均價、是否有颱風警報作為特徵，來預測今天開市的平均價格，結果也顯示Lstm AI 模型在抓取時間趨勢上確實有不錯的效果。</p><h4>總結</h4><p>總結此次專案，完全使用免費開源的工具即完成客戶的需求，並且資料也是使用政府開放API資料，因此對於獨立開發者來說，上手難度與成本非常低。</p><p>同時本專案的概念可以復用在漁貨、 肉類、雞蛋等其他農產品價格預測上， 只要有開放API資料可取得，剩餘訓練模型與伺服器運行成本對於個人接案或小型公司也是完全可負擔的。</p><p>對於缺乏實作經驗的學生或剛起步的工程師來說，也是非常好的專案學習經驗。對於客戶來說，冷冰冰的AI模型跟是否準確可能並非最關切的事，整體服務是否有達成客戶預期以及是否有降低客戶訂購成本會是優先考量。AI模型會是服務的一部份，但絕不會是全部，如何讓AI輔助、 節省、降低客戶人工、庫存、 維護成本才是客戶買單的關鍵。在前期思考軟體服務架構及提案時，一定能有所幫助。</p><p>聯絡方式</p><p>信箱：skps30808@gmail.com</p><p>Line：260391760</p><p>IG：cfp_andy</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=94c4eafacdf6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[自動生成資料報告！用ChatGpt、PowerAutomate、PowerBI自動生成資料報告]]></title>
            <link>https://medium.com/@Andy30808/%E8%87%AA%E5%8B%95%E7%94%9F%E6%88%90%E8%B3%87%E6%96%99%E5%A0%B1%E5%91%8A-%E7%94%A8chatgpt-powerautomate-powerbi%E8%87%AA%E5%8B%95%E7%94%9F%E6%88%90%E8%B3%87%E6%96%99%E5%A0%B1%E5%91%8A-84dfd6bf7c96?source=rss-54b4617b5170------2</link>
            <guid isPermaLink="false">https://medium.com/p/84dfd6bf7c96</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[rpa-tools]]></category>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[power-bi]]></category>
            <dc:creator><![CDATA[AI應用顧問Andy]]></dc:creator>
            <pubDate>Sun, 14 Jan 2024 19:09:56 GMT</pubDate>
            <atom:updated>2024-01-14T19:09:56.262Z</atom:updated>
            <content:encoded><![CDATA[<p>不知道各位在做資料分析的時侯，是否常遇到分析完資料，做完圖表，甚而預測出機率，卻不知如何寫出相對應的敘述、報告？或者下筆時不知從何而起，能不能請ChatGpt幫忙我們寫出資料報告呢？</p><p>今天要介紹如何介接ChatGpt、PowerBI、PowerAutomate三大工具，來幫我們完成從視覺化、資料闡述、儀表板等等工作。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aAuTXVowMEU5fFdC15xOuA.png" /></figure><h4>匯入資料</h4><p>首先，第一步進入PowerBI，選擇你要分析的資料集匯入至報表內，這次我們作範例的資料是一份員工離職分析的資料表，其中有每位員工的職稱、調薪幅度、工時等等資訊</p><p>並且我們套用預測模型，得到了每位員工潛在的離職機率，並且我們想知道高離職員工有甚麼樣的特徵。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wwqqmNkL1gFnxdjSB1BAgg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AuP4rNqYr5HGm0SYjxDVeA.png" /></figure><h4>資料視覺化</h4><p>第二步，我們使用視覺化的方法，看出了一些Insight。比如說未調薪、主任階級、未獲額外加給的員工為最有可能離職。</p><p>接下來我們來看看，如果我餵給ChatGpt同樣的資料集，ChatGpt是否會給我差不多，甚至一樣的Insight，並且寫成一份資料報告給我</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MbZkem2Z-LgeBGcKzzCtEA.png" /></figure><h4>PowerAutomate&amp;ChatGpt</h4><p>第三步，我們需要介接OpenAI API至PowerBI中，怎麼做到呢？這時候就需要PowerAutomate來幫助我們。</p><p>我們可以在視覺效果中找到PowerAutomate的Icon，點擊後就可以在報表中新增一個PowerAutomate流程。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/515/1*il8isu6ucuJr0uXX97arFQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qfCqx97YoF78hA1B7j165g.png" /></figure><p>我們可以直接新增一個範本流程(Trigger a Power BI button with a custom action)，點擊後就會進到右邊畫面</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Uu7sl3y5_2qfS4avLkffVg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YuklsP_3iIlDSMUnUlII0g.png" /></figure><p>按下新步驟，選擇HTTP ，方法選擇POST，接著在Authorization處填上Bearer “openai api key”</p><p>本文選擇你要的model，以及我們要問ChatGpt的事，比如說我要求他根據PowerBI上的資料，給我離職機率高的原因並給出資料分析報告</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a9NKp-56NB7f8SK7hO7nVg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qo_TQuHRiSuVdVp76jnwTg.png" /></figure><h4>Result</h4><p>我們可以將ChatGpt的回應直接顯示在PowerBI的儀表板上，從ChatGpt的回應告訴我說，職稱、薪資調整比例、獎金最大值、年資是影響員工離職的主要原因。跟我們分析的結果是不是幾乎一樣呢！</p><p>完善流程後，分析資料不用像在大海撈針，可以先給AI進行初步分析，我們再依據AI的分析進一步完成後續的視覺化應用，做起事來就快了許多！</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s3r4g1Z5h8Pr2Skra-30Aw.png" /></figure><h4>小結</h4><p>未來一定還有許多好用的工具來幫助我們做資料分析，掌握這些工具就已經比別人厲害許多囉！</p><p>今天介紹PowerBI、PowerAutomate、ChatGpt的串接應用，若喜歡以上內容再幫忙按個拍手、追蹤，我會持續更新相關內容，感謝！</p><blockquote><em>延伸閱讀</em></blockquote><p><a href="https://medium.com/@Andy30808/%E5%AF%A6%E6%89%93%E5%AF%A6%E8%B3%BC%E7%89%A9%E7%B1%83%E5%88%86%E6%9E%90-%E4%BD%BF%E7%94%A8%E5%9B%A0%E7%B4%A0%E5%88%86%E6%9E%90-factor-analysis-%E6%89%BE%E5%87%BA%E9%A1%A7%E5%AE%A2%E6%B6%88%E8%B2%BB%E7%B5%84%E5%90%88-411a2be93659">實打實購物籃分析！ 使用因素分析(Factor Analysis)找出顧客消費組合</a></p><blockquote><a href="https://medium.com/@Andy30808/%E4%BD%BF%E7%94%A8llm-agent-%E8%87%AA%E5%8B%95%E5%BD%99%E6%95%B4%E9%97%9C%E9%8D%B5%E5%AD%97%E8%88%87%E6%AD%B8%E7%B4%8Dgoogle-search-%E6%90%9C%E5%B0%8B%E7%B5%90%E6%9E%9C-f73433ace375"><em>使用LLM Agent 自動彙整關鍵字與歸納Google Search 搜尋結果</em></a></blockquote><p><a href="https://medium.com/@Andy30808/%E5%A6%82%E4%BD%95%E5%BE%97%E7%9F%A5%E5%93%81%E7%89%8C%E5%AE%9A%E4%BD%8D-%E4%BB%A5%E5%93%81%E7%89%8C%E7%9F%A5%E8%A6%BA%E5%AE%9A%E4%BD%8D%E5%9C%96%E8%A6%96%E8%A6%BA%E5%8C%96%E6%B6%88%E8%B2%BB%E8%80%85%E5%85%A7%E5%BF%83-4321cd1cc67c">如何得知品牌定位？以品牌知覺定位圖視覺化消費者內心</a></p><p><a href="https://medium.com/@Andy30808/%E7%94%A8power-bi%E5%BB%BA%E7%AB%8B%E5%8D%B3%E6%99%82%E8%B3%87%E6%96%99%E4%B8%B2%E6%B5%81%E8%A6%96%E8%A6%BA%E5%8C%96-%E5%8D%B3%E6%99%82%E7%9B%A3%E6%8E%A7%E7%9C%8B%E6%9D%BF-c0ebffbfbbac">用Power BI建立即時資料串流視覺化/即時監控看板！</a></p><blockquote><em>聯絡方式</em></blockquote><blockquote><em>信箱：skps30808@gmail.com</em></blockquote><blockquote><em>Line：260391760</em></blockquote><blockquote><em>IG：cfp_andy</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=84dfd6bf7c96" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[手把手用Autogen自動開發軟體、自動生成圖表、自動寫報告]]></title>
            <link>https://medium.com/@Andy30808/%E6%89%8B%E6%8A%8A%E6%89%8B%E7%94%A8autogen%E8%87%AA%E5%8B%95%E9%96%8B%E7%99%BC%E8%BB%9F%E9%AB%94-%E8%87%AA%E5%8B%95%E7%94%9F%E6%88%90%E5%9C%96%E8%A1%A8-%E8%87%AA%E5%8B%95%E5%AF%AB%E5%A0%B1%E5%91%8A-4dda531a5a91?source=rss-54b4617b5170------2</link>
            <guid isPermaLink="false">https://medium.com/p/4dda531a5a91</guid>
            <category><![CDATA[autogen]]></category>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[AI應用顧問Andy]]></dc:creator>
            <pubDate>Fri, 12 Jan 2024 18:22:14 GMT</pubDate>
            <atom:updated>2024-01-13T12:54:07.065Z</atom:updated>
            <content:encoded><![CDATA[<p>上一篇文章中我們使用了AI agent爬取網路資訊並歸納關鍵字，然而當我們要執行多個工作以完成一項專案時，能不能用AI的力量幫助我們完成任務。</p><p>舉例來說，我想要設計一款APP來管理我的日常行程，可以把要完成的任務分解成分析需求、撰寫程式、測試、除錯等等工作。能不能做到將這幾項任務分別交由不同的AI Agent來實現，並且又可以互相協作，完成我們提出的需求？</p><p>接下來要介紹的是由微軟開發的大語言模型框架Autogen，不僅能夠實現多代理人互相溝通協作、客製化，在實作上可以說是最接地氣的開發框架！我們直接來看如何使用吧</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*I3eP99FvKiX6X6Up.png" /></figure><p>首先，第一步先安裝Autogen套件，Python版本要在3.8以上</p><pre>pip install pyautogen</pre><p>第二步，創建一個環境檔，裡面有使用的模型與API key</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jDoik6iafO_NBdnvLSuO6w.png" /></figure><pre>[<br>    {<br>        &quot;model&quot;: &quot;gpt-4&quot;,<br>        &quot;api_key&quot;: &quot;sk-70Mm2StIbyV353qb1ZTPT3BlbkFJNvnUZ623Cxk4so5xxxxx&quot;<br>    }<br>]</pre><p>第三步，創建一個py檔，我們會需要兩個Agent分別是聽取我們需求的UserProxyAgent，以及負責實作開發的AssistantAgent。</p><p>最後，我們將要做的事情以message方式傳達給UserProxyAgent，比如說，我這邊想實作一款股票追蹤網站，請畫出NVDA AAPL TSLA股價以及交易量</p><pre>from autogen import AssistantAgent,UserProxyAgent,config_list_from_json<br><br>#Import openapi key<br>config_list = config_list_from_json(env_or_file=&quot;OAI_CONFIG_LIST&quot;)<br><br>assistant = AssistantAgent(name=&quot;assistant&quot;,llm_config={&quot;config_list&quot;:config_list})<br><br>user_proxy = UserProxyAgent(name=&quot;user_proxy&quot;,code_execution_config={&quot;work_dir&quot;:&quot;coding&quot;})<br><br><br>user_proxy.initiate_chat(assistant,message=&quot;use streamlit to create stock pricing app that contain NVDA AAPL TSLA stock pricing and trading volume&quot;)</pre><p>執行以後，若沒有額外新增需求，Autogen即會自動找到需要的套件、安裝、程式撰寫、執行一次搞定</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*20blHXAEL1Xu9lK9FpyNkA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fMzK4voBN2euXhMvrhwvkQ.png" /></figure><p>結果如以下畫面，真的省下許多查找，除錯的時間，可以專心在思考使用者需求與如何藉由更精準的prompt來達到我們想要的成果</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*75NPGwxHN_OSsadfE84YzA.png" /></figure><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FfcGhcbnzdWk%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DfcGhcbnzdWk&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/87fd24e543175b7318630503baf8205a/href">https://medium.com/media/87fd24e543175b7318630503baf8205a/href</a></iframe><p>今天只介紹Autogen的基礎使用方式，未來對這類文章有興趣的話，可以按讚分享，並留言告訴我你想看到甚麼內容！</p><blockquote><em>延伸閱讀</em></blockquote><p><a href="https://medium.com/@Andy30808/%E5%AF%A6%E6%89%93%E5%AF%A6%E8%B3%BC%E7%89%A9%E7%B1%83%E5%88%86%E6%9E%90-%E4%BD%BF%E7%94%A8%E5%9B%A0%E7%B4%A0%E5%88%86%E6%9E%90-factor-analysis-%E6%89%BE%E5%87%BA%E9%A1%A7%E5%AE%A2%E6%B6%88%E8%B2%BB%E7%B5%84%E5%90%88-411a2be93659">實打實購物籃分析！ 使用因素分析(Factor Analysis)找出顧客消費組合</a></p><blockquote><a href="https://medium.com/@Andy30808/%E4%BD%BF%E7%94%A8llm-agent-%E8%87%AA%E5%8B%95%E5%BD%99%E6%95%B4%E9%97%9C%E9%8D%B5%E5%AD%97%E8%88%87%E6%AD%B8%E7%B4%8Dgoogle-search-%E6%90%9C%E5%B0%8B%E7%B5%90%E6%9E%9C-f73433ace375?source=your_stories_page-------------------------------------">使用LLM Agent 自動彙整關鍵字與歸納Google Search 搜尋結果</a></blockquote><p><a href="https://medium.com/@Andy30808/%E5%A6%82%E4%BD%95%E5%BE%97%E7%9F%A5%E5%93%81%E7%89%8C%E5%AE%9A%E4%BD%8D-%E4%BB%A5%E5%93%81%E7%89%8C%E7%9F%A5%E8%A6%BA%E5%AE%9A%E4%BD%8D%E5%9C%96%E8%A6%96%E8%A6%BA%E5%8C%96%E6%B6%88%E8%B2%BB%E8%80%85%E5%85%A7%E5%BF%83-4321cd1cc67c">如何得知品牌定位？以品牌知覺定位圖視覺化消費者內心</a></p><p><a href="https://medium.com/@Andy30808/%E7%94%A8power-bi%E5%BB%BA%E7%AB%8B%E5%8D%B3%E6%99%82%E8%B3%87%E6%96%99%E4%B8%B2%E6%B5%81%E8%A6%96%E8%A6%BA%E5%8C%96-%E5%8D%B3%E6%99%82%E7%9B%A3%E6%8E%A7%E7%9C%8B%E6%9D%BF-c0ebffbfbbac">用Power BI建立即時資料串流視覺化/即時監控看板！</a></p><blockquote><em>聯絡方式</em></blockquote><blockquote><em>信箱：skps30808@gmail.com</em></blockquote><blockquote><em>Line：260391760</em></blockquote><blockquote><em>IG：cfp_andy</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4dda531a5a91" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[使用LLM Agent 自動彙整關鍵字與歸納Google Search 搜尋結果]]></title>
            <link>https://medium.com/@Andy30808/%E4%BD%BF%E7%94%A8llm-agent-%E8%87%AA%E5%8B%95%E5%BD%99%E6%95%B4%E9%97%9C%E9%8D%B5%E5%AD%97%E8%88%87%E6%AD%B8%E7%B4%8Dgoogle-search-%E6%90%9C%E5%B0%8B%E7%B5%90%E6%9E%9C-f73433ace375?source=rss-54b4617b5170------2</link>
            <guid isPermaLink="false">https://medium.com/p/f73433ace375</guid>
            <category><![CDATA[search-engine-optimizati]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[large-language-models]]></category>
            <dc:creator><![CDATA[AI應用顧問Andy]]></dc:creator>
            <pubDate>Tue, 24 Oct 2023 19:53:45 GMT</pubDate>
            <atom:updated>2023-10-24T19:53:45.087Z</atom:updated>
            <content:encoded><![CDATA[<p>相信每個人在搜尋資料時都需要耗費大量時間爬文、爬資料，並還要把搜尋結果消化、整理、吸收，能不能利用大型語言模型結合AI 代理人來幫我們自動將我們需要的搜尋結果快速歸納、整理，並將其記錄成文件建檔。</p><p>Langchain Agent 結合客製化搜尋設計、爬蟲、摘要彙整等功能，可依據自身需求打造專屬個人的搜尋引擎，來看看是怎麼做到的吧！</p><h4>Google Serp api</h4><p><a href="https://serpapi.com/search-api">https://serpapi.com/search-api</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2EVpoBny5mYkG5BA_VE_Hw.png" /></figure><p>google針對其搜尋引擎開方大量API可供查詢使用，例如一般的搜尋引擎Google Search API、針對地圖搜索的Google Map API、或是針對職缺搜尋或金融資訊相關的Google job API與Google Finance API，使用申請帳號，得到serp API key，免費方案可每月執行100次搜索，對於一般使用者已經相當夠用！</p><h4>Browserless</h4><p><a href="https://www.browserless.io/scraping-automation/">Browserless - The #1 Best Free Open Source Web Scraping Tool For Devs</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UnvGMlBLIOC1q9IIjX3hgw.png" /></figure><p>當我們有了搜尋結果後，你可能會想說該怎麼進到網頁中並把網頁資訊自動爬蟲下來，難道還要一個一個網頁寫爬蟲程式嗎？</p><p>那當然是不用啦！現在已經有非常方便的自動化網頁爬蟲Browserless可以想網頁資訊給爬取下來，同樣送出相對應的網址進行request，BrowserlessAPI即可將網頁資訊回傳，之後再用Beautiful Soup解析萃取文字檔，即可輕鬆獲取想對應的網站內容囉</p><h4>Langchain Prompt and Agent</h4><p>最後就是我們主角，Langchain的登場時間！</p><p>Langchain為簡化使用大型語言模型使用門檻的應用程式框架，你可以把它想像成使用大型語言模型來搭建應用程式的武器庫，其中包含非常多的LLM應用可做使用，例如調用自有資料的檢索增強生成(RAG)、SQL產生器、external API互動等等，在Langchain都用相應的函式可供使用</p><p>此次我們要用到的為Summarization 與 Agent，summarization很好理解就是用於摘要我們的網站內容的，而Agent是可根據自身使用需求，建立起基於LLM的應用，比如說我需要一個自動搜尋並摘要網頁的工具，在Agent設計裡，你只需要告訴他期望達成的結果，即可完成一個客製搜尋引擎</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dvX3tfXsm0MlnRMubM5fHQ.png" /></figure><p>接下來只要把相應的input流程設計好，一個LLM Agent就設計完成囉</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/550/1*n5ZJ6yJXE3d5T_C5WcSPSw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jgV0Nd64Zp8jImYxCDAb_w.png" /></figure><h4>Streamlit UI</h4><p>最後我們用Streamlit搭建一個UI畫面，實際測試結果如何</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FEI1iC4GwCWs%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DEI1iC4GwCWs&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FEI1iC4GwCWs%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/439d0e5c56f0704cc95f600b872ebbcb/href">https://medium.com/media/439d0e5c56f0704cc95f600b872ebbcb/href</a></iframe><p>實際結果非常不錯！LLM如實的將我的需求實現，以後要爬旅遊資訊、餐廳、搜尋論文資料，都不用一頁一頁的翻Google囉，是不是很方便呢！</p><p>若喜歡以上內容再幫忙按個拍手、追蹤，我會持續更新相關內容，感謝！</p><blockquote><em>聯絡方式</em></blockquote><blockquote><em>信箱：skps30808@gmail.com</em></blockquote><blockquote><em>Line：260391760</em></blockquote><blockquote><em>IG：cfp_andy</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f73433ace375" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Shopping Basket Analysis! Using Factor Analysis to find customer consumption combinations.]]></title>
            <link>https://medium.com/@Andy30808/shopping-basket-analysis-using-factor-analysis-to-find-customer-consumption-combinations-936fdccad895?source=rss-54b4617b5170------2</link>
            <guid isPermaLink="false">https://medium.com/p/936fdccad895</guid>
            <category><![CDATA[market-basket-analysis]]></category>
            <category><![CDATA[dimensionality-reduction]]></category>
            <category><![CDATA[factor-analysis]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[AI應用顧問Andy]]></dc:creator>
            <pubDate>Mon, 16 Jan 2023 14:45:49 GMT</pubDate>
            <atom:updated>2023-01-16T14:45:49.153Z</atom:updated>
            <content:encoded><![CDATA[<p>When people shop and consume, they definitely have habitual consumption combinations. Finding those consumption combinations can actively mine potential demand and expand consumer purchasing amounts through strategies such as recommendations and cross-selling.</p><h4>Data Preparation</h4><p>This analysis focuses on the consumption records of female customers. Before analyzing the shopping basket, it’s better to group them according to several purchase roles, such as housewives, single women, men, students, etc., to avoid too much noise affecting the relationship of consumption.</p><p>Integrate the consumption records into each customer, observing the number of times each consumed during the observation period. If there are frequent shopping records consumed together, it is easier to form a shopping basket.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YGy_YevbHguw6yJ5M3jeQw.png" /></figure><h4>Exploratory Factor Analysis</h4><p>The concept of Factor Analysis is similar to Principal Component Analysis (PCA), the difference is that PCA reduces multi-dimensional data to a few dimensions in the direction of maximum data variation, while Factor Analysis reduces data to a specific number of dimensions based on the correlation between data, such as reducing 10 columns of data to 3 columns and presenting the correlation of these 10 columns in 3 columns through coefficients.</p><p>Using the concept of a shopping basket, there are 1000 products in the mall. When the cashier at the checkout counter finds that everyone always buys food , furniture , and stationery together, the 1000 products can be reduced to 3 shopping baskets. <strong>When promoting, you can target one product in the shopping basket to promote and drive the sales of other products.</strong></p><h4>Selecting the Number of Factors</h4><p>Before doing Factor Analysis, you need to set the target number of factors. The way to set it is based on the Eigenvalue of each factor. The Eigenvalue simply means the explanatory variance. Think of it as a shopping basket. If there is only one product in the shopping basket, it loses the meaning of the shopping basket, right? So we only need to select the number of factors with Eigenvalues greater than one.</p><p>Additionally, the larger the Eigenvalue, the more the factor can explain the correlation of the data, which means the more frequently the shopping basket appears. The larger the Eigenvalue will be, the more we can trust that this consumption combination is the customer’s preferred combination.</p><p>The following program can quickly produce 12 factors and special values for each factor, and the Eigenvalue greater than 1 is selected as the number of factors:”</p><pre>import pandas as pd<br>import matplotlib.pyplot as plt<br>from factor_analyzer import FactorAnalyzer<br><br>data = pd.read_csv(&quot;購物籃ver1.csv&quot;)<br>data = data.drop(columns=&quot;刷卡日期 年/月/日&quot;)<br><br>data.columns = [&quot;Education_fee&quot;, &quot;Insurance&quot;, &quot;Donation&quot;, &quot;Public&quot;, &quot;Grocery&quot;, &quot;Quality goods&quot;, &quot;Food&quot;,<br>                &quot;Pharmacy&quot;, &quot;Consumer Electronic&quot;, &quot;SuperMarket&quot;, &quot;Transportation&quot;, &quot;Travel&quot;, &quot;Casual&quot;, &quot;Other&quot;]<br><br>print(data.head())<br>fa = FactorAnalyzer(12, rotation=&quot;varimax&quot;) #依據資料有幾個欄位設定<br>fa.fit(data)<br><br>ev, v = fa.get_eigenvalues()<br><br><br>plt.scatter(range(1, data.shape[1]+1), ev)<br>plt.plot(range(1, data.shape[1]+1), ev)<br>plt.title(&#39;Scree Plot&#39;)<br>plt.xlabel(&#39;Factors&#39;)<br>plt.ylabel(&#39;Eigenvalue&#39;)<br>plt.grid()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/861/1*Sw1hfwhrMs_uwuVutMIQqA.png" /><figcaption>“Selecting the number of factors with Eigenvalues greater than 1</figcaption></figure><h4>Factor Analysis</h4><p>After determining the number of shopping baskets, you can directly run Factor Analysis. The following code can be directly applied. After running, use a heatmap to observe the meaning represented by each factor (shopping basket).</p><pre>import seaborn as sns<br>import numpy as np<br>import pandas as pd<br>import matplotlib.pyplot as plt<br>from factor_analyzer import FactorAnalyzer<br><br>data = pd.read_csv(&quot;購物籃ver1.csv&quot;)<br>data = data.drop(columns=&quot;刷卡日期 年/月/日&quot;)<br><br>data.columns = [&quot;Education_fee&quot;, &quot;Insurance&quot;, &quot;Donation&quot;, &quot;Public&quot;, &quot;Grocery&quot;, &quot;Quality goods&quot;, &quot;Food&quot;,<br>                &quot;Pharmacy&quot;, &quot;Consumer Electronic&quot;, &quot;SuperMarket&quot;, &quot;Transportation&quot;, &quot;Travel&quot;, &quot;Casual&quot;, &quot;Other&quot;]<br><br>print(data.head())<br><br>fa = FactorAnalyzer(4, rotation=&quot;varimax&quot;) #因子個數 <br>fa.fit(data)<br><br><br>df_cm = pd.DataFrame(np.abs(fa.loadings_), index=data.columns)<br>fig, ax = plt.subplots(figsize=(12, 10))<br><br>sns.heatmap(df_cm, ax=ax, annot=True, cmap=&#39;BuPu&#39;)<br>ax.tick_params(axis=&#39;x&#39;, labelsize=15)<br>ax.set_title(&quot;Factor Analysis&quot;, fontsize=12)<br>ax.set_ylabel(&quot;consume_type&quot;)<br>plt.show()</pre><p>The X-axis represents 4 shopping baskets, and the Y-axis represents the original products or services consumed. From the first shopping basket, we can see that the consumption coefficients of Quality goods, Food, and Casual are the highest, which should represent the shopping consumption during vacation; the second shopping basket is Grocery, Supermarket, and Transportation with the highest coefficients, which should represent family shopping consumption; the third shopping basket is Pharmacy and Transportation; the fourth shopping basket is Other and Consumer Electronics.</p><p>Combined with the previous Scree Plot, these four shopping baskets are sorted according to the strength of the Eigenvalue, which means that female consumers are more inclined to use credit cards for quality leisure consumption and bulk shopping consumption, and are less inclined to consume pharmacy and consumer electronics. When recommending shopping baskets, it is recommended to use the first two shopping baskets for better results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ghqCftJJ8ESGydE6Asn-hw.png" /></figure><h4>Shopping Basket Strength</h4><p>Each shopping basket is a combination of different consumption, so we can simplify the original consumption data to the strength score of the shopping basket. The strength score is the standardized data (0 represents the average level), the higher it is, the more this customer prefers this shopping basket consumption combination. The following code can compare the transformed shopping basket strength score with the original consumption data.</p><pre>factor = pd.DataFrame(fa.transform(df))<br>df[&quot;客戶&quot;] = data[&quot;客戶id&quot;]<br><br>final_data = pd.concat([df, factor], axis=1, ignore_index=True)<br><br>final_data.columns = [&quot;Insurance&quot;, &quot;Public&quot;, &quot;Grocery&quot;, &quot;Quality goods&quot;, &quot;Food&quot;,<br>                      &quot;Pharmacy&quot;, &quot;Consumer Electronic&quot;, &quot;SuperMarket&quot;, &quot;Transportation&quot;, &quot;Travel&quot;, &quot;Casual&quot;, &quot;Other&quot;, &quot;客戶&quot;, &quot;購物籃0&quot;, &quot;購物籃1&quot;, &quot;購物籃2&quot;, &quot;購物籃3&quot;]<br>print(final_data.head())<br><br>final_data.to_csv(&quot;轉換後.csv&quot;)</pre><h4>Preference for Quality Goods, Food, and Casual</h4><p>By sorting the strength score of the first shopping basket from high to low, and listing customers above the average level. It can be seen that the top customers are far ahead in terms of consumption of quality goods,casual, and food.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fvg02t8oGyFYsr6g1xkBqA.png" /></figure><h4>Preference for Grocery, SuperMarket, and Transportation</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EzSbbXmvX7bbUs2Be2ELNA.png" /></figure><h4>Summary</h4><p>There are lots of theoretical methods for basket analysis, this article provides a method for dimensionality reduction based on product service relevance. In addition, there are methods such as customer similarity-based recommendations and Apriori algorithms for basket analysis.</p><p>After analysis, it is still necessary to evaluate the results based on the market segmentation of the data, to be able to explain them well and to go back to the data repeatedly to check for logical inconsistencies.</p><p>If you like the above content, please help with a clap and follow, I will continue to update relevant content, thank you!</p><blockquote>Contact Information:</blockquote><blockquote>Email: <a href="/service/mailto:skps30808@gmail.com">skps30808@gmail.com</a></blockquote><blockquote>Line: 260391760</blockquote><blockquote>IG: cfp_andy</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=936fdccad895" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[了解企業顧客價值！以ARFM模型定義高價值顧客]]></title>
            <link>https://medium.com/@Andy30808/%E4%BA%86%E8%A7%A3%E4%BC%81%E6%A5%AD%E9%A1%A7%E5%AE%A2%E5%83%B9%E5%80%BC-%E4%BB%A5arfm%E6%A8%A1%E5%9E%8B%E5%AE%9A%E7%BE%A9%E9%AB%98%E5%83%B9%E5%80%BC%E9%A1%A7%E5%AE%A2-aec7b63f236d?source=rss-54b4617b5170------2</link>
            <guid isPermaLink="false">https://medium.com/p/aec7b63f236d</guid>
            <category><![CDATA[rfm-analysis]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[customer-experience]]></category>
            <category><![CDATA[marketing]]></category>
            <dc:creator><![CDATA[AI應用顧問Andy]]></dc:creator>
            <pubDate>Sat, 14 Jan 2023 16:32:58 GMT</pubDate>
            <atom:updated>2023-01-15T11:29:06.148Z</atom:updated>
            <content:encoded><![CDATA[<h4>定義顧客價值：RFM</h4><p>行銷學界講述的顧客價值有兩個面向，第一種是企業提供給客戶，由客戶感知產品、服務帶給自身的價值，又稱顧客知覺價值(Customer Perceived Value)；另一種為顧客帶給企業，由企業自行定義其帶給企業本身利益，由企業立場出發的高價值、低價值客戶，RFM指標為最常見使用來定義顧客價值的指標。</p><p>對企業來說，定義高價值顧客離不開三個問題，<strong>這個顧客上次何時購買？這個顧客多經常購買？這個顧客花多少錢購買？</strong></p><p>以數據方法回答即以最近購買期間(Recency)、購買次數(Frequency)、平均消費金額(Monetary)三個指標，並稱為RFM指標，用以衡量誰是企業高價值顧客，應將資源優先投入。</p><h4><strong>RFM計算方式</strong></h4><p>計算RFM所需的資料為客戶ID、消費日期、消費金額，交易序號，範例資料如下</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VWvEN1ebxAWTLYKZDoYn6A.png" /><figcaption>這裡的序號、ID用以代表某位客戶與某筆交易，數值本身無大小意義</figcaption></figure><p>RFM的計算層級，通常以每個客戶為基準，我們可以決定一個時間區段，計算每位客戶距今為止的購買天數、消費頻率、平均消費金額，以Tableau的計算欄位公式如下</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/841/1*ePN27rh0a5BN_H0lE2c3qQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/1*Okt1sYZz3zXIA617bXnyFA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/834/1*k9W1y9WqmVtd7kPyptaqwg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/988/1*jqLaABXyRuLvT4RtpI1OLA.png" /></figure><h4>RFM評分</h4><p>計算完RFM後，可以依人數比例依序給予1~5分評分，並將其加總為RFM Score，依照RFM Score為客戶排名，就可以知道企業高價值客戶分別是哪些人，需要將資源優先投入。</p><p>評分方式可以依據產業特性自由調整，如果消費金額對企業來說為首要價值考量，可以將M評分加權，得出的RFM Score就會偏重以消費金額為分數差異大小。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9uy2tGwwfvpmIs28msEUaA.png" /><figcaption>將R、F、M由大至小(R由小至大)分為五份，給予5~1的評分，加總後進行排名</figcaption></figure><h4>RFM的缺點</h4><p>RFM為描述目前客戶消費狀況提供簡單直覺的價值評判依據，但對於每位客戶在觀察期間內消費行為的變化，甚至對未來行為的預測，未能提供企業明確的行動方針。</p><p>針對RFM的缺點，我們要創造一個新指標名為消費者活躍度(Customer Activity Index)，來衡量每位客戶交易型態的變化</p><h4>消費者活躍度(Customer Activity Index)</h4><p>以三位客戶的消費行為為例，橫軸為時間，縱軸為購買金額，第一位客戶(藍色線)可以看到明顯有越來越頻繁消費的趨勢；第二位客戶(橘色線)明顯越來越不消費；第三位客戶(綠色線)較有固定的消費習慣。</p><p>用Recency跟Frequency並無法看出這三位客戶在觀察期間內消費頻率的變化，因此需要創造一項指標顯示出消費頻率的變化，<strong>活躍性指標(CAI，Customer Activity Index)</strong>即是用來量化活躍程度的抽象概念。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*umvw8bTs-kEswBRSxjG9xQ.png" /><figcaption>相較2010~2011年，2012年的消費頻率明顯增加</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LjtDOxKPgWHfknjfp_ERiw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4WUJrdwWk60YnZX5KYSsAg.png" /><figcaption>(橘色)相較2010~2011年，2012年的消費頻率明顯減少。(綠色)一直維持穩定的消費習慣</figcaption></figure><p>原本的消費頻率(Frequency)，假定是觀察期間中每固定一段時間即消費一次，比如2022年總共消費12次，平均下來1個月消費一次。平均消費期間(Interpurchase Time)為一個月。</p><p>然而從上圖可以看到購買期間是不固定的，如何將購買期間的變化數據萃取出來？</p><p>首先，從活躍度的角度，我們可以知道<strong>越近期資料越重要</strong>， 所以針對較靠近現在的消費期間給予較大的權重，較過去的消費期間給予較小的權重，將簡單平均消費期間減去加權後的平均消費期間，除以簡單平均消費期間，就可得出此位客戶的活躍度。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/505/1*aDIXwRygnBUUnkCnI1gj7A.png" /><figcaption>活躍度計算公式(CAI)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*joruJaNIqci303cgexsRRw.png" /><figcaption>計算範例</figcaption></figure><h4>應用ARFM模型</h4><p>有了顧客活躍度後，即可以用簡單的四象限圖區分潛力客戶與流失客戶，位於第四象限，消費頻率高但活躍度低的客戶，企業應優先保持聯絡，詢問不與企業來往的原因，制定挽救方案。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WoGNX5vQGb8oAOGqteLTFQ.png" /><figcaption>活躍度與消費頻率象限圖(原點為全體平均)</figcaption></figure><h4>資料、指標的意義</h4><p>總結針對顧客消費紀錄所做的ARFM分析，需要注意資料是幫助分析人員更好理解現實情況的工具，了解資料背後的故事背景，消費者行為，才能做出更有意義的分析結果。</p><p>ARFM從最基本的三個問題出發，再探討購買期間變化所代表的意涵。另外還有百百種購買行為如價格敏感度、品牌忠誠度能夠用來定義顧客價值，制定策略。</p><p>若喜歡以上內容再幫忙按個拍手、追蹤，我會持續更新相關內容，感謝！</p><blockquote>延伸閱讀</blockquote><p><a href="https://medium.com/@Andy30808/%E5%AF%A6%E6%89%93%E5%AF%A6%E8%B3%BC%E7%89%A9%E7%B1%83%E5%88%86%E6%9E%90-%E4%BD%BF%E7%94%A8%E5%9B%A0%E7%B4%A0%E5%88%86%E6%9E%90-factor-analysis-%E6%89%BE%E5%87%BA%E9%A1%A7%E5%AE%A2%E6%B6%88%E8%B2%BB%E7%B5%84%E5%90%88-411a2be93659">實打實購物籃分析！ 使用因素分析(Factor Analysis)找出顧客消費組合</a></p><p><a href="https://medium.com/@Andy30808/%E5%88%86%E6%9E%90%E6%B6%88%E8%B2%BB%E8%80%85%E8%A1%8C%E7%82%BA-%E6%89%BE%E5%87%BA%E5%88%A9%E5%9F%BA%E5%B8%82%E5%A0%B4-%E7%94%A8k-means%E9%80%B2%E8%A1%8C%E5%B8%82%E5%A0%B4%E5%8D%80%E9%9A%94-stp-%E5%88%86%E6%9E%90-a1f400c4b77">分析消費者行為，找出利基市場！用K-means進行市場區隔(STP)分析</a></p><p><a href="https://medium.com/@Andy30808/%E5%A6%82%E4%BD%95%E5%BE%97%E7%9F%A5%E5%93%81%E7%89%8C%E5%AE%9A%E4%BD%8D-%E4%BB%A5%E5%93%81%E7%89%8C%E7%9F%A5%E8%A6%BA%E5%AE%9A%E4%BD%8D%E5%9C%96%E8%A6%96%E8%A6%BA%E5%8C%96%E6%B6%88%E8%B2%BB%E8%80%85%E5%85%A7%E5%BF%83-4321cd1cc67c">如何得知品牌定位？以品牌知覺定位圖視覺化消費者內心</a></p><p><a href="https://medium.com/@Andy30808/%E7%94%A8power-bi%E5%BB%BA%E7%AB%8B%E5%8D%B3%E6%99%82%E8%B3%87%E6%96%99%E4%B8%B2%E6%B5%81%E8%A6%96%E8%A6%BA%E5%8C%96-%E5%8D%B3%E6%99%82%E7%9B%A3%E6%8E%A7%E7%9C%8B%E6%9D%BF-c0ebffbfbbac">用Power BI建立即時資料串流視覺化/即時監控看板！</a></p><blockquote>聯絡方式</blockquote><blockquote>信箱：skps30808@gmail.com</blockquote><blockquote>Line：260391760</blockquote><blockquote>IG：cfp_andy</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aec7b63f236d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[實打實購物籃分析！ 使用因素分析(Factor Analysis)找出顧客消費組合]]></title>
            <link>https://medium.com/@Andy30808/%E5%AF%A6%E6%89%93%E5%AF%A6%E8%B3%BC%E7%89%A9%E7%B1%83%E5%88%86%E6%9E%90-%E4%BD%BF%E7%94%A8%E5%9B%A0%E7%B4%A0%E5%88%86%E6%9E%90-factor-analysis-%E6%89%BE%E5%87%BA%E9%A1%A7%E5%AE%A2%E6%B6%88%E8%B2%BB%E7%B5%84%E5%90%88-411a2be93659?source=rss-54b4617b5170------2</link>
            <guid isPermaLink="false">https://medium.com/p/411a2be93659</guid>
            <category><![CDATA[factor-analysis]]></category>
            <category><![CDATA[market-basket-analysis]]></category>
            <category><![CDATA[marketing]]></category>
            <category><![CDATA[marketing-strategies]]></category>
            <dc:creator><![CDATA[AI應用顧問Andy]]></dc:creator>
            <pubDate>Tue, 27 Dec 2022 21:06:46 GMT</pubDate>
            <atom:updated>2022-12-27T21:06:46.877Z</atom:updated>
            <content:encoded><![CDATA[<p>每個人在購物消費的時候，一定都有習慣的消費組合，找出那些消費組合就能主動挖掘潛在需求，並透過推薦、交叉銷售等策略來擴大消費者購買金額。</p><p>購物籃分析(Market Basket Analysis)，泛指根據交易紀錄探索產品關聯性的所有方法。今天介紹用探索性因素分析(Exploratory Factor Analysis)來找出前幾名的購物籃組合。</p><h4>資料準備</h4><p>這次分析，專注在女性消費者的消費紀錄上。在分析購物籃之前，最好可以根據幾個購買角色，如家庭主婦、單身女性、男性、學生等等先進行分群，以免太多雜訊影響消費的關聯性。</p><p>將消費紀錄整合成每位客戶，在觀察期間內各消費的消費次數，如果有經常在一起消費的購物紀錄的話，就比較容易形成購物籃。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YGy_YevbHguw6yJ5M3jeQw.png" /></figure><h4>探索性因素分析</h4><p>因素分析的概念與主成分分析(PCA)很相似，差別在於主成分分析是以資料變異最大的方向將多維數遽降至少數幾維；因素分析則是以資料之間的關聯性將資料降至特定數量的維度，例如10個欄位的資料降至3個欄位，並以係數的方式呈現這10個欄位在3個欄位中的關聯性。</p><p>以購物籃的概念來解釋，商場上有1000種商品，這麼多的商品到了收銀台中收銀員發現大家固定會將食物種類一起購買、家具類一起購買、文具類一起購買，這時侯就可以將1000種產品縮減為3個購物籃，在促銷時就可以針對購物籃中某一商品促銷，帶動其餘商品的買氣。</p><h4>挑選因子個數</h4><p>在做因素分析前需要先設定目標的因子數量，設定的方式可依每因子的特徵值(Eigenvalue)設定。特徵值的意思簡單來說就是解釋變異量，大家把它想成購物籃中如果只有一個商品那就失去購物籃的意義了對吧，所以我們只需挑選特徵值大於1的因子數量即可。另外，特徵值越大表示此因子越能解釋資料的相關性程度，意思就是此購物籃出現的頻率越多次，越能相信此消費組合是客戶偏好的組合，特徵值就會越大</p><p>以下程式可以快速產出12個因子與特徵值，選擇4個因子做購物籃分析。</p><pre>import pandas as pd<br>import matplotlib.pyplot as plt<br>from factor_analyzer import FactorAnalyzer<br><br>data = pd.read_csv(&quot;購物籃ver1.csv&quot;)<br>data = data.drop(columns=&quot;刷卡日期 年/月/日&quot;)<br><br>data.columns = [&quot;Education_fee&quot;, &quot;Insurance&quot;, &quot;Donation&quot;, &quot;Public&quot;, &quot;Grocery&quot;, &quot;Quality goods&quot;, &quot;Food&quot;,<br>                &quot;Pharmacy&quot;, &quot;Consumer Electronic&quot;, &quot;SuperMarket&quot;, &quot;Transportation&quot;, &quot;Travel&quot;, &quot;Casual&quot;, &quot;Other&quot;]<br><br>print(data.head())<br>fa = FactorAnalyzer(12, rotation=&quot;varimax&quot;) #依據資料有幾個欄位設定<br>fa.fit(data)<br><br>ev, v = fa.get_eigenvalues()<br><br><br>plt.scatter(range(1, data.shape[1]+1), ev)<br>plt.plot(range(1, data.shape[1]+1), ev)<br>plt.title(&#39;Scree Plot&#39;)<br>plt.xlabel(&#39;Factors&#39;)<br>plt.ylabel(&#39;Eigenvalue&#39;)<br>plt.grid()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/861/1*Sw1hfwhrMs_uwuVutMIQqA.png" /><figcaption>選擇特徵值(eigenvalue)大於1的因子個數</figcaption></figure><h4>因素分析</h4><p>決定好購物籃個數後，就可以直接跑因素分析，以下程式碼可以直接套用。跑完後，用熱力圖(heatmap)來觀察一下每個因子(購物籃)所代表的含意</p><pre>import seaborn as sns<br>import numpy as np<br>import pandas as pd<br>import matplotlib.pyplot as plt<br>from factor_analyzer import FactorAnalyzer<br><br>data = pd.read_csv(&quot;購物籃ver1.csv&quot;)<br>data = data.drop(columns=&quot;刷卡日期 年/月/日&quot;)<br><br>data.columns = [&quot;Education_fee&quot;, &quot;Insurance&quot;, &quot;Donation&quot;, &quot;Public&quot;, &quot;Grocery&quot;, &quot;Quality goods&quot;, &quot;Food&quot;,<br>                &quot;Pharmacy&quot;, &quot;Consumer Electronic&quot;, &quot;SuperMarket&quot;, &quot;Transportation&quot;, &quot;Travel&quot;, &quot;Casual&quot;, &quot;Other&quot;]<br><br>print(data.head())<br><br>fa = FactorAnalyzer(4, rotation=&quot;varimax&quot;) #因子個數 <br>fa.fit(data)<br><br><br>df_cm = pd.DataFrame(np.abs(fa.loadings_), index=data.columns)<br>fig, ax = plt.subplots(figsize=(12, 10))<br><br>sns.heatmap(df_cm, ax=ax, annot=True, cmap=&#39;BuPu&#39;)<br>ax.tick_params(axis=&#39;x&#39;, labelsize=15)<br>ax.set_title(&quot;Factor Analysis&quot;, fontsize=12)<br>ax.set_ylabel(&quot;consume_type&quot;)<br>plt.show()</pre><p>X軸代表4個購物籃，Y軸代表原始的商品或消費的服務。從第一個購物籃可以看到精品消費(Quality goods)、食物(Food)、休閒消費(Casual)三個消費係數最高，應為代表休假出遊時的購物消費；第二個購物籃為百貨購物(Grocery)、量販(SuperMarket)、交通(Transportation)係數最高，應為家庭購物消費；第三個購物籃為藥妝(Pharmacy)、交通(Transportation)；第四個購物籃為其它(Other)、居家電信(Consumer Eletronic)。</p><p>結合上一張Scree Plot，這四個購物籃的強度是依照特徵值大小排序的，代表女性更傾向以信用卡進行精品休閒消費與量販購物消費，較不傾向進行藥妝消費與居家電信消費，在進行購物籃推薦時建議以前兩名購物欄進行推薦效果會更顯著。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ghqCftJJ8ESGydE6Asn-hw.png" /></figure><h4>購物籃強度</h4><p>每個購物籃皆為不同消費的組合，因此我們可以將原始的消費數據精簡至購物籃的強度分數，強度分數為標準化後的數據(0表示平均水準)，越高表示此客戶越偏好此購物籃的消費組合，以下程式碼可將轉換後的購物籃強度分數與原始消費數據做一個比較。</p><pre>factor = pd.DataFrame(fa.transform(df))<br>df[&quot;客戶&quot;] = data[&quot;客戶id&quot;]<br><br>final_data = pd.concat([df, factor], axis=1, ignore_index=True)<br><br>final_data.columns = [&quot;Insurance&quot;, &quot;Public&quot;, &quot;Grocery&quot;, &quot;Quality goods&quot;, &quot;Food&quot;,<br>                      &quot;Pharmacy&quot;, &quot;Consumer Electronic&quot;, &quot;SuperMarket&quot;, &quot;Transportation&quot;, &quot;Travel&quot;, &quot;Casual&quot;, &quot;Other&quot;, &quot;客戶&quot;, &quot;購物籃0&quot;, &quot;購物籃1&quot;, &quot;購物籃2&quot;, &quot;購物籃3&quot;]<br>print(final_data.head())<br><br>final_data.to_csv(&quot;轉換後.csv&quot;)</pre><h4>偏好精品、食物、休閒客戶</h4><p>將第一個購物籃強度分數由高排至低，並列出高於平均水準的客戶。可以看到的確前幾名客戶在精品、休閒、食物的消費次數遙遙領先</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fvg02t8oGyFYsr6g1xkBqA.png" /></figure><h4>偏好百貨、量販、交通客戶</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EzSbbXmvX7bbUs2Be2ELNA.png" /></figure><h4>小結</h4><p>購物籃分析的理論方法有很多種，此提供依據商品服務相關性進行數據降維的方法。另外有根據客戶相似性進行推薦、Apriori演算法等等購物籃分析方法。在分析完後還是要根據資料的市場區隔評估結果是否恰當，能解釋得通，並回到資料面反覆檢查，才不會出現不合邏輯的結果。</p><p>若喜歡以上內容再幫忙按個拍手、追蹤，我會持續更新相關內容，感謝！</p><blockquote>延伸閱讀</blockquote><p><a href="https://medium.com/@Andy30808/%E5%88%86%E6%9E%90%E6%B6%88%E8%B2%BB%E8%80%85%E8%A1%8C%E7%82%BA-%E6%89%BE%E5%87%BA%E5%88%A9%E5%9F%BA%E5%B8%82%E5%A0%B4-%E7%94%A8k-means%E9%80%B2%E8%A1%8C%E5%B8%82%E5%A0%B4%E5%8D%80%E9%9A%94-stp-%E5%88%86%E6%9E%90-a1f400c4b77">分析消費者行為，找出利基市場！用K-means進行市場區隔(STP)分析</a></p><p><a href="https://medium.com/@Andy30808/%E5%A6%82%E4%BD%95%E5%BE%97%E7%9F%A5%E5%93%81%E7%89%8C%E5%AE%9A%E4%BD%8D-%E4%BB%A5%E5%93%81%E7%89%8C%E7%9F%A5%E8%A6%BA%E5%AE%9A%E4%BD%8D%E5%9C%96%E8%A6%96%E8%A6%BA%E5%8C%96%E6%B6%88%E8%B2%BB%E8%80%85%E5%85%A7%E5%BF%83-4321cd1cc67c">如何得知品牌定位？以品牌知覺定位圖視覺化消費者內心</a></p><p><a href="https://medium.com/@Andy30808/%E7%94%A8power-bi%E5%BB%BA%E7%AB%8B%E5%8D%B3%E6%99%82%E8%B3%87%E6%96%99%E4%B8%B2%E6%B5%81%E8%A6%96%E8%A6%BA%E5%8C%96-%E5%8D%B3%E6%99%82%E7%9B%A3%E6%8E%A7%E7%9C%8B%E6%9D%BF-c0ebffbfbbac">用Power BI建立即時資料串流視覺化/即時監控看板！</a></p><blockquote>聯絡方式</blockquote><blockquote>信箱：skps30808@gmail.com</blockquote><blockquote>Line：260391760</blockquote><blockquote>IG：cfp_andy</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=411a2be93659" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[分析消費者行為，找出利基市場！用K-means進行市場區隔(STP)分析]]></title>
            <link>https://medium.com/@Andy30808/%E5%88%86%E6%9E%90%E6%B6%88%E8%B2%BB%E8%80%85%E8%A1%8C%E7%82%BA-%E6%89%BE%E5%87%BA%E5%88%A9%E5%9F%BA%E5%B8%82%E5%A0%B4-%E7%94%A8k-means%E9%80%B2%E8%A1%8C%E5%B8%82%E5%A0%B4%E5%8D%80%E9%9A%94-stp-%E5%88%86%E6%9E%90-a1f400c4b77?source=rss-54b4617b5170------2</link>
            <guid isPermaLink="false">https://medium.com/p/a1f400c4b77</guid>
            <category><![CDATA[marketing-strategies]]></category>
            <category><![CDATA[segmentation]]></category>
            <category><![CDATA[marketing]]></category>
            <category><![CDATA[k-means]]></category>
            <category><![CDATA[stp]]></category>
            <dc:creator><![CDATA[AI應用顧問Andy]]></dc:creator>
            <pubDate>Wed, 14 Dec 2022 19:38:50 GMT</pubDate>
            <atom:updated>2022-12-14T19:38:50.540Z</atom:updated>
            <content:encoded><![CDATA[<h4>市場區隔分析</h4><p>市場上有各式各樣的行為，消費者有不同行為、特質，了解市場上有哪些人，這些人有什麼消費動機、行為特質，能幫助企業設定目標市場，制定行銷策略。</p><p>市場區隔的方式有很多種，大致可分為<strong>事前區隔法</strong>與<strong>事後區隔法</strong>。事前區隔法通常依據性別、地區、年齡等等變數做區分，事前區隔法的優點是區分容易、所需資訊少；缺點為難以覺察消費者的消費動機、行為特質的差異性，不易做出具行銷意義的市場區隔。事後區隔法則是以消費者的特質、行為進行區分，優點是能夠真正了解消費者的消費動機與行為特點；缺點是需要蒐集足夠時間的數據才能得到有意義的結果。</p><p>而究竟該如何利用客戶消費數據，以資料分析、AI演算法對客戶進行標記、分類，並定義客戶喜好呢？</p><p>今天要跟各位分享如何以簡單的演算法─K平均法，來區分出不同行為的消費者，並從中得出有意義的行銷資訊！</p><h4>資料準備</h4><p>本次示範以某家信用卡公司的消費紀錄資料為例，一般來說，原始資料會記錄消費者使用信用卡的日期、金額、刷卡類型與客戶的基本資料等，資料範例如下圖</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8joLXbzJlDaMvI726N98Zg.png" /></figure><p>但這份資料想看出有意義的資訊顯然是有困難的，因此需要做一些處理，最常使用的為RFM分析、活躍度指標(CAI)、穩定度指標(CRI)，這些指標是怎麼產生的之後再出文章詳細解說(再請大家按讚追蹤！)。</p><p>最近購買期間(Recency)為消費者距離上次消費間隔的天數；消費次數(Frequency)為期間內的總消費次數；平均消費金額(Monetary value)為期間內的平均消費金額；客戶活躍度(CAI)為衡量期間內客戶是否有越來越常消費，越高表示此客戶有越常消費的趨勢；客戶穩定度(CRI)比較複雜，可以理解成此客戶的消費行為是否穩定，若無穩定的消費型態，CRI即越低，反之則越高。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/946/1*-n75nZJKrmXQmgEfnyWWxw.png" /></figure><h4>K平均法(K-means Clustering Algorithm)</h4><p>先來聊聊將消費者分群的目的與目標，<strong>分群的目的在於找出消費者間的異質性</strong>，並針對不同群體、或價值最高的群體執行不同策略或推薦。</p><p>因此分群的<strong>目標即是群體間的差異最大、群內差異最小，</strong>在分群後要注意每一群是否都有別具其他群沒有的特色，以及群體內的變異是否足夠小使得我們可以認為他們是具有相似特質的消費者，兩者都符合才是好的分群。</p><p>有關K平均法的細節，未來再跟大家詳細介紹。這裡我們只需思考要設定多少個&quot;K&quot;，K代表要分的群數，分得太少，群內的變異過大，不具代表性；分得太多，群體間沒有區別，失去分群的意義。因此分群設定需要一定程度的試誤，並搭配視覺化觀察分群後的結果，才可以得到合適的群數。</p><p>這次示範就簡單用sciki-learn中的k-mean套件來完成，K設定為3</p><p>程式碼範例如下</p><pre>from sklearn.cluster import KMeans<br>import pandas as pd<br><br>data = pd.read_csv(&quot;大數據行銷實作練習_集群分析.xlsx - RFM.csv&quot;)<br><br>data = data.loc[:, [&quot;客戶Id&quot;, &quot;Recency&quot;, &quot;Frequcency&quot;,<br>                    &quot;Monetary value(average)&quot;, &quot;CAI&quot;, &quot;CRI&quot;]]<br><br>data = data.dropna()<br><br>kmeans = KMeans(n_clusters=4)<br><br>kmeans.fit(data)<br><br>data[&quot;分類結果&quot;] = kmeans.predict(data)<br><br>print(data.tail())<br><br>data.to_csv(&quot;分類結果.csv&quot;)</pre><h4>結果解釋</h4><p>我們可以從每一群的資料平均值來判斷該如何描述市場區隔，從消費次數(96.97次)可以看到，第一群(藍色)是最常消費的族群，但從CAI(2.55)與最近購買期間(94.2天)來看，此族群沒有越來越頻繁消費的趨勢，且已有一段時間未使用信用卡；第二群(橘色)是平均消費金額最高的一群，且有越來越頻繁消費的趨勢，惟此群人數最少(3人)、消費次數最低，應是習慣以信用卡進行高消費行為的客戶。第三、四群屬於最穩定消費的族群，CRI分別為一、二名，其他數值也較為平均。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6mW6e3MLEOPI2_afGxU8YQ.png" /></figure><h4>策略擬定</h4><p>以信用卡公司的角度來說，消費紀錄最大價值在於獲取客戶喜好數據，以行銷發卡公司的金融商品。因此可以針對消費能力最高的第二群(橘色)，研究消費喜好，提供其財富管理方案與金融商品；也可以提供刷卡消費紅利，增加其購買次數，得到更多消費數據。</p><p>在選定策略對象時，需針對不同產業性質，定義其價值較高的群體。例如對便利超商來說，消費次數與活躍度指標會是更重要的特質。在得出結果後，還是要回頭思考對企業價值最高的行動，並思考是否需要添加新變數，來回分析數次後，才能得到具有價值的結論。</p><blockquote><em>聯絡方式</em></blockquote><blockquote><em>信箱：skps30808@gmail.com</em></blockquote><blockquote><em>Line：260391760</em></blockquote><blockquote><em>IG：cfp_andy</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a1f400c4b77" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[如何以人工智慧打造企業韌性供應鍊]]></title>
            <link>https://medium.com/@Andy30808/%E5%A6%82%E4%BD%95%E4%BB%A5%E4%BA%BA%E5%B7%A5%E6%99%BA%E6%85%A7%E6%89%93%E9%80%A0%E4%BC%81%E6%A5%AD%E9%9F%8C%E6%80%A7%E4%BE%9B%E6%87%89%E9%8D%8A-27d0a82cb1f1?source=rss-54b4617b5170------2</link>
            <guid isPermaLink="false">https://medium.com/p/27d0a82cb1f1</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[predictions]]></category>
            <category><![CDATA[inventory-management]]></category>
            <dc:creator><![CDATA[AI應用顧問Andy]]></dc:creator>
            <pubDate>Sat, 03 Dec 2022 16:57:38 GMT</pubDate>
            <atom:updated>2022-12-04T14:13:33.385Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>過去企業倡導及時生產(JIT)的生產方式，強調在需要的時候，按需要的量，生產需要的產品。</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5Pw6WPjtdSSnjK-t7Xld9g.png" /></figure><p>及時生產的優勢在降低庫存、流動性風險低、效率高。然而自2018年以來，中美貿易戰、新冠肺炎疫情、俄烏戰爭等等黑天鵝事件愈發頻繁，市場景氣的變化速度相較過去快上不少，讓奉行及時生產的企業在近幾年吃上不少苦頭。</p><p>最知名的例子莫過於幾大車廠(豐田、福特、福斯)在疫情期間因車輛需求的減少降低車用晶片的訂單，但在疫情趨緩，車市復甦，晶片需求暴增導致供不應求，車廠無車可賣，預計影響至2023年底。</p><p>由豐田(Toyota)提出的生產方式，讓汽車產業蓬勃發展，卻也讓他們面臨21世紀以來最大危機。面對如今動盪不安的局勢，無論是汽車產業、零售業、製造業，<strong>需要的是能夠面對風險，處理緊急事件的韌性能力</strong></p><h3>如何以人工智慧打造韌性供應鏈？</h3><p>在不額外增加產線，加大產能的情況下，企業能不能做到提前預警，並有能力監控、預測上下游產線狀況、需求狀況，進而做到即時調度、供應不斷鍊。</p><p>而人工智慧又能如何幫助企業，主要反映在三個面向</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u7AR2GSyaXvUgvWB5RCtkg.png" /></figure><p><strong>可視化</strong></p><p>蒐集必要供應鏈資訊，打下高品質的資訊基礎，是人工智慧能發揮功效的第一件事。除了基本的訂單量、銷貨量、庫存量，供應商供貨情況、客戶的需求狀況、市場情資，紀錄越全面的資訊對提前預警調度越有幫助！</p><p>有資料之後，以視覺化、戰情看板的方式呈現更能夠讓決策者了解目前的市場情況與企業內部的整體資訊，並可以調整參數模擬不同情況。</p><p><strong>可預測性</strong></p><p>市場的狀況變化多端，人腦的算力有限，依靠機器學習的工具幫助建立預測模型可以納入多方資訊，並以非線性、複雜的演算法擬和資料。</p><p>模型除了給出預測結果外，還會告訴你市場情資重要程度(feature importance)、變數與目標預測曲線(Partial Dependence Plot)、情境模擬分析(scenario analysis)，來幫助你面對未來不同情況，該如何做決策應對。</p><p><strong>可調適性</strong></p><p>做到上述兩點，基本上已做好動態調整的準備。面對突發狀況能夠依據模擬分析的結果做出應對，做到供應不斷鍊，極小化損失。</p><h3>建立銷售預測模型</h3><p>根據企業的產品線，整理出銷售預測數據的特徵與目標。如前一期訂單、月份、前兩期訂單、前兩期訂單平均</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*N5DgJ8VXVruTMHgS" /></figure><p>以過去五年數據訓練資料，以最近一年(2021年)進行測試，選出表現最佳、穩定的模型。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3821WImot9ivTt_M" /></figure><p>2021年的測試結果可以看到，模型成功預測訂單量的上下波動，並且以95%信賴區間估計，90%的訂單都落在預測區間內。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*96WyksCnL2fRS2VQ" /><figcaption>2021年預測訂單與實際訂單量</figcaption></figure><h3>庫存管理看板</h3><p>在每月、季初，模型根據預測訂單量，推薦安全庫存水位。採購人員即可檢視目前品號的庫存狀況是否低於安全庫存，決定是否採購或清倉。並且時時根據目前市場消息，調整預測數據，給予庫存調配建議。</p><p><strong>以人工智慧技術可檢視企業內部的庫存是否有高低估情況，將庫存調整至最適庫存</strong>。並以風險值告知決策者緊急程度，讓決策者能夠優先處理高風險缺料品號，避免無法達交，影響商譽。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jMJQ-IEg1AoT5Sva" /></figure><h4>小結</h4><p>根據筆者服務的客戶，往往都依照經驗設定庫存水位，少了就補，累積不少呆料囤積，甚至有貨物囤積了數年都沒賣出去。</p><p>本次個案用訂單預測模型設定標準庫存，根據訂單趨勢、多寡、插單量來建立安全庫存水位，不僅將<strong>整體庫存降低25%</strong>，<strong>增加四百萬新台幣的流動資金</strong>；也將採購流程變得更智慧、更有效率！</p><blockquote><em>聯絡方式</em></blockquote><blockquote><em>信箱：skps30808@gmail.com</em></blockquote><blockquote><em>Line：260391760</em></blockquote><blockquote><em>IG：cfp_andy</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=27d0a82cb1f1" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>