<?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 Byoung Jin Yu on Medium]]></title>
        <description><![CDATA[Stories by Byoung Jin Yu on Medium]]></description>
        <link>https://medium.com/@nanturtle?source=rss-c44163a35787------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*3BzpWqQPoiSEAVWu.jpg</url>
            <title>Stories by Byoung Jin Yu on Medium</title>
            <link>https://medium.com/@nanturtle?source=rss-c44163a35787------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 21:26:53 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nanturtle/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[Fine Tuning 모험기 Part 1]]></title>
            <link>https://medium.com/@nanturtle/fine-tuning-%EB%AA%A8%ED%97%98%EA%B8%B0-part-1-fb6d1fb738fd?source=rss-c44163a35787------2</link>
            <guid isPermaLink="false">https://medium.com/p/fb6d1fb738fd</guid>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[realreport]]></category>
            <category><![CDATA[fine-tuning]]></category>
            <dc:creator><![CDATA[Byoung Jin Yu]]></dc:creator>
            <pubDate>Thu, 06 Nov 2025 05:13:56 GMT</pubDate>
            <atom:updated>2025-11-13T01:14:30.394Z</atom:updated>
            <content:encoded><![CDATA[<h3>RAG (Retrieval-Augmented Generation)</h3><p>GPT가 이미 상당 수준의 일반 지식을 가지고 있지만, 잘 알려지지 않은 특정 분야의 지식은 알지 못한다. RAG는 이런 단점을 보완하기 위해 GPT에 필요한 지식을 제공해서 새로운 지식에 대한 답변도 가능하게 만드는 시스템이다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/665/1*6_f8mK5MoHWthVxGJauZYw.png" /></figure><p>우리테크는 개발자들이 Real* 제품군들을 보다 쉽게 사용할 수 있도록 RAG서비스를 제공하려고 연구개발중이다. 아래 구성도 처럼 주요 프롬프트와 Vector DB 자료를 검색해 덧붙이는 RAG의 일반적인 구조와 크게 다르지 않다.</p><p>먼저 사용자 요청에 따라 RealChart config를 출력하도록 시도해봤는데, Chart 같이 잘 알려진 분야는 이를 잘 이해하고 RealChart 모델을 어느정도 만들어내었다. 더욱 다양한 질문을 소화하고 정교한 결과를 만들려면 가이드 문서의 품질을 향상 시켜야 할 것으로 예상하고 있다.</p><h3>RealReport r2 JSON</h3><p>이어서 RealReport 양식도 생성할 수 있도록 시도하고자 했다. 그런데 RealChart에 비해 별도 디자이너로 양식을 만드는 RealReport r2 JSON 구조가 config 성격과는 거리가 있어서 생성형 AI 로 어떻게 입출력을 정의해야할지 고민스러웠다. 게다가 RealChart config에 비해 자유로운 포맷으로 config 구성이 복잡하고 비대했다. 보통 20kb정도의 크기를 갖는 샘플을 몇개만 추가해도 길이가 길다보니 OpenAI api 에서 TPM(Token per minute) 초과 오류가 발생했다. TPM은 OpenAI 계정 Tier별로 다른 제약이 있다. GPT 모델별로 token 수에 제약이 있는데 전체 token수, 출력 token수, 그리고 TPM 이 있다.</p><p>일단은 전체 token에서 여러 리포트 샘플들의 문자열 길이 때문에 입력이 차지하는 토큰이 너무 크다는 문제가 있었다. 이 문제를 해결려면 모델에 샘플을 미리 학습시키는 방법이 있는데, OpenAI Fine-tuning이 대책이 될 수 있을 것 같았다. 프롬프트에 예제를 많이 줄일 수 있는데다 학습비용 외에 추론 비용이 차이가 거의 없어서 유리할 것으로 보았다.</p><h3>Supervised? Reinforcement?</h3><p>막상 <a href="https://platform.openai.com/docs/guides/model-optimization">Fine-tuning 문서</a>를 살펴보았더니 종류가 많았다.</p><ul><li><strong>Supervised fine-tuning (SFT)</strong>: 입력-출력 쌍을 주고 “이런 질문엔 이런 답”으로 모델을 학습</li><li><strong>Direct preference optimization (DPO)</strong>: 같은 질문에 대해 “좋은 답 vs 덜 좋은 답”을 보여주고, 모델이 좋은 답을 더 자주 선택하도록 학습</li><li><strong>Reinforcement fine-tuning (RFT)</strong>: 모델이 답을 내면 평가(보상)를 주고, 반복해서 더 나은 행동을 하도록 학습</li><li><strong>Vision fine-tuning</strong>: 텍스트뿐 아니라 이미지(또는 이미지+텍스트)를 입력으로 넣어, 시각 정보까지 다루는 모델로 훈련</li></ul><p>Supervised fine-tuning 이 가장 단순한 것 같아서 시도해보기로 했다.</p><h3>RAG 처럼 때려넣으면 되나?</h3><p>처음에는 RAG 벡터 DB 구성처럼 문서 원문을 그대로 추가하면 될 것으로 생각했으나, 질문과 대답 쌍으로 구성된 JSONL 포맷을 준비해야 했다. 질문을 user role, 응답을 assistant role로 구성해 작성하는 구조다. 지침을 system role에 작성할 수도 있다.</p><pre>{&quot;messages&quot;: [{&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: &quot;Marv is a factual chatbot that is also sarcastic.&quot;}, {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: &quot;What&#39;s the capital of France?&quot;}, {&quot;role&quot;: &quot;assistant&quot;, &quot;content&quot;: &quot;Paris&quot;, &quot;weight&quot;: 0}, {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: &quot;Can you be more sarcastic?&quot;}, {&quot;role&quot;: &quot;assistant&quot;, &quot;content&quot;: &quot;Paris, as if everyone doesn&#39;t know that already.&quot;, &quot;weight&quot;: 1}]}<br>{&quot;messages&quot;: [{&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: &quot;Marv is a factual chatbot that is also sarcastic.&quot;}, {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: &quot;Who wrote &#39;Romeo and Juliet&#39;?&quot;}, {&quot;role&quot;: &quot;assistant&quot;, &quot;content&quot;: &quot;William Shakespeare&quot;, &quot;weight&quot;: 0}, {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: &quot;Can you be more sarcastic?&quot;}, {&quot;role&quot;: &quot;assistant&quot;, &quot;content&quot;: &quot;Oh, just some guy named William Shakespeare. Ever heard of him?&quot;, &quot;weight&quot;: 1}]}</pre><h3>샘플 설명을 상세히 쓰면 될까?</h3><p>질문, 응답 쌍으로 준비를 해야하다보니 샘플에 대한 상세 설명을 쓰면 실제 사용자는 상세하게 요청하지 않을테니 괴리가 있을 것 같았다. 우선 시험삼아 사용자가 요청할 만한 짧은 질의와 샘플로 구성했다.</p><h3>샘플이 부족하다고?</h3><p>단순한 샘플이 몇개 없어서 6개 정도의 JSONL 라인을 구성했는데, 예제가 부족하다는 오류가 발생했다.</p><pre>Training file has 6 example(s), but must have at least 10 examples</pre><h3>잔액이 부족하다고? 5만원 넘게 든다고?</h3><p>OpenAI dashboard Fine-tuning에서 Base Model 을 gpt-4.1 로 하고 Training data를 업로드해 생성해보았더니 잔액이 부족하다는 오류가 발생했다. 그런데 비용이 샘플 크기에 비해 만만치 않았다.</p><pre>Creating this fine-tuning job would exceed your hard limit, please check your plan and billing details. Cost of job ftjob-XXX: USD 46.73. Quota remaining for your project proj_YYY: USD 4.77.</pre><h3>어떤 모델을 써야할까?</h3><p>2025년 11월 기준 Fine-tuning을 지원하는 모델은 3.5, 4o, 4.1 정도였다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/579/1*114dp_A-1ETVzVxPBm50HA.png" /></figure><p>학습, 추론 비용이 비교적 저렴한 것 같은 gpt-4o-mini를 학습시켜보았다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*OrDWaUbVPDUE7FxZmMgkag.png" /></figure><p>학습 파일이 작긴 하지만 매우 잘 fitting 된 것 같았다. OpenAI Fine-tuning에서는 overfitting 이슈를 해결하기 위해 학습된 모델의 학습 step별 모델을 별도로 사용할 수 있도록 지원하고 있다.</p><h3>출력 토큰이 많이 부족한 것 같은데?</h3><p>학습된 모델에 RealReport json을 출력하도록 요청했는데, json 구성이 완성되지 않고 끊기는 문제가 발생했다. 모델이 지원하는 최대 토큰수는 입력+출력 토큰 수이고, 최대 출력 토큰 수 제약이 있었다. Fine-tuning 용 모델을 더 제약적이었다.</p><p>gpt-4.1 모델들이 훤씬 더 큰 토큰을 지원해서 gpt-4.1-mini로 다시 시도해보았다. Fine-tuning에서 gpt-4.1-mini 최대 출력 토큰 수는 16,384 이다. 초과설정하면 오류가 발생한다.</p><p>max_completion_tokens: 16_384 // OpenAI chat.completions.create max tokens config</p><h3>JSON을 잘 못만들어내는데?</h3><p>gpt-4.1-mini 로 학습한 후, 마찬가지로 RealReport 양식을 요청했는데, 이번에는 json을 제대로 만들어내지 못했다. jsonrepair 라는 라이브러리가 있어서 잘못된 구조를 고치도록 시도해보았지만 잘 고쳐주지 못했다. 경량화 모델의 한계로 보였다. 잘못된 json 구조를 직접 수정해서 살펴보았다. RealReport이 갖추어야할 구조를 제대로 생성해내지 못하고 있었다. 동일한 질문에 대한 결과도 잘 출력해주지 못했는데, AI 학습이라는 것은 패턴을 학습하는 것이지 벡터 DB 처럼 지식을 검색해서 가져오는 것이 아니기 때문이다. 충분한 샘플로 패턴을 학습시켜야 한다.</p><h3>코드는 잘 이해하겠지?</h3><p>가이드 문서 초안이 부실하기도 해서 결국 다시 원점으로 돌아가 핵심 가이드 문서를 보완하기로 했다. MVC 구조에서 RealReport Item별 상속구조에 따라 중복되거나 달라지는 조건들과 속성들이 있었다. Input token을 줄이려면 중복적인 내용을 줄이고, 리포트 구성 규칙을 일일이 설명하는 것이 적합해보이지 않았다. GPT가 코드를 잘 이해할 것이라고 가정하고 모델별 클래스 상속구조를 전달해보기로 했다. 리포트 구성의 논리적 제약을 판단할 수 있도록 관련 함수들도 추가해주었다.</p><pre>/** @type text */<br>class TextItem extends TextItemBase {<br>    text: string;<br>    rich: boolean;<br>}<br>/** @type space */<br>class SpaceItem extends ReportItem {<br>    override canAddTo(parent: ReportGroupItem): boolean {<br>        return parent instanceof BoxContainer || parent instanceof  ItemAddSection;<br>    }<br>}</pre><p>Item의 속성 접근이나 Box Container 에 포함가능한 검증 정도가 약간 개선된 것 같았다. 하지만 여전히 GPT 가 생성해내는 구조는 가이드 설명이 부족하다는 생각이 들었다. 상세한 규칙에 대한 내용이 필요해보였다. 코드는 추론 강화에는 좋지만 규칙 강제에는 약하다는 답변을 힌트로 접근해보았다.</p><h3>어떤 설명이 부족한거지?</h3><p>일반 ChatGPT 모델로 가이드문서를 업로드하고 리포트를 만들도록 요청하고 잘못된 부분은 왜 그렇게 판단했는지 물었다. 그리고 문서를 보완해나갔다. 특정 요소에 대한 Structural rule과 테이블 헤더 스타일링 같은 Design rule로 크게 두 가지 종류의 Rule을 명시했다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/718/1*1J251G4Zlrq1537oa7uSKQ.png" /></figure><p>여러번 핑퐁을 해보며 문서를 보완한 결과, gpt-5 일반 모델에서 핵심 가이드 문서만으로 만족할만한 결과를 내기 시작했다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FLt_ArSTQAyGFZH_RXr_zA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yYyEV2rSgFGWIrmqc3rVVA.png" /></figure><p>더 많은 양식을 시도해보고 개선해야하지만, 결국 프롬프트 엔지니어링이 중요한 부분이었다.</p><h3>다시 Fine-tuning</h3><p>Fine-tuning은 여전히 시도해볼 만한 기술이다. Report 양식은 사실상 자유도가 높은 문서 구조이기 때문에 RealReport 리포트 양식을 디자인하는 패턴 학습이 되면 더 다양한 요구사항을 만족시킬 수 있을 것이다. 다음 모험에서는 처음 시도했던 것 처럼 양식 하나를 통째로 학습하는 것이 아니라, 각 영역별, 기능별, 레이아웃별 등으로 쪼개어 학습 데이터셋을 준비해서 패턴을 학습시키는 방향으로 나아가보기로 한다.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fb6d1fb738fd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RealChart로 그려본 2023 Mckinsey 데이터 시각화 — Part 2]]></title>
            <link>https://medium.com/realgrid/realchart%EB%A1%9C-%EA%B7%B8%EB%A0%A4%EB%B3%B8-2023-mckinsey-%EB%8D%B0%EC%9D%B4%ED%84%B0-%EC%8B%9C%EA%B0%81%ED%99%94-part-2-b0d8c65523b9?source=rss-c44163a35787------2</link>
            <guid isPermaLink="false">https://medium.com/p/b0d8c65523b9</guid>
            <category><![CDATA[realchart]]></category>
            <category><![CDATA[charts]]></category>
            <category><![CDATA[realgrid]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[mckinsey]]></category>
            <dc:creator><![CDATA[Byoung Jin Yu]]></dc:creator>
            <pubDate>Sun, 28 Apr 2024 10:21:16 GMT</pubDate>
            <atom:updated>2024-05-12T09:29:17.734Z</atom:updated>
            <content:encoded><![CDATA[<h3>RealChart로 그려본 2023 Mckinsey 데이터 시각화 — Part 2</h3><p><a href="https://blog.realgrid.com/realchart%EB%A1%9C-%EA%B7%B8%EB%A0%A4%EB%B3%B8-2023-mckinsey-%EB%8D%B0%EC%9D%B4%ED%84%B0-%EC%8B%9C%EA%B0%81%ED%99%94-bc9c1ed0b63c">지난 포스트</a>에 이어서 Mckinsey에 소개된 2023년 가장 인기 있는 데이터 시각화 중 일부를 소개합니다. 데이터가 복잡한 정보를 설득력 있는 스토리로 변환하는 데 어떻게 도움이 되는지 알아보세요.</p><h3>성평등 노력</h3><p>모두가 기회에 접근할 수 있을 때 지역사회와 경제는 더욱 강력해집니다. 전 세계의 조직은 지속 가능하고 포용적인 성장을 달성하기 위한 의미 있는 진전을 위해 계속해서 노력하고 있습니다.</p><ul><li>여성들은 최고 경영진으로 올라가는 데 상당한 진전을 이루었지만 힘들게 얻은 성과는 미미합니다. 기업이 성평등을 달성 하려면 갈 길이 멉니다. 올해 직장 내 여성(Women in the Workplace) 보고서에 따르면 여성의 최고 경영진 대표성은 2015년 이후 11%포인트 증가해 소폭 증가했습니다. 그러나 관리자와 이사 수준에서는 각각 3%포인트와 4%포인트만 증가했습니다. 유색인종 여성의 발전은 동료에 비해 뒤떨어져 있습니다 . 기업 내 거의 모든 단계에서 유색인종 여성의 대표성은 백인 여성 및 남성에 비해 떨어집니다.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*57lj-qw207ObFsKSFXHfhQ.png" /><figcaption><a href="https://jsfiddle.net/gh/get/library/pure/realgrid/realchart-demo/tree/master/blog/gender-race">Try RealChart on jsfiddle</a></figcaption></figure><ul><li>많은 기업 지도자들이 성 다양성을 개선하기 위한 노력에 착수했지만 민간 시장과 같은 일부 영역에서는 글로벌 성 평등을 달성하는 데 수십 년이 걸릴 수 있습니다. 다른 기업 부문과 마찬가지로 사모펀드 회사에서도 대표성의 다양성 문제는 고위직에서 가장 두드러집니다. 현재 속도로 보면 투자 역할에 있어 상무이사 수준에서 성평등을 달성하는 데 60년이 걸릴 수 있습니다. 그러나 미래 리더의 인재 풀에는 더 많은 희망이 있습니다. 분석가 및 연구원과 같은 입사 수준의 역할에서는, 10년 안에 성평등을 달성할 수 있을 것으로 기대됩니다.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eyAfVFQLJBGV3TN970blAA.png" /><figcaption><a href="https://jsfiddle.net/gh/get/library/pure/realgrid/realchart-demo/tree/master/blog/gender-equality">Try RealChart on jsfiddle</a></figcaption></figure><p>출처: <a href="https://www.mckinsey.com/featured-insights/2023-year-in-review/2023-the-year-in-charts">https://www.mckinsey.com/featured-insights/2023-year-in-review/2023-the-year-in-charts</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b0d8c65523b9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/realgrid/realchart%EB%A1%9C-%EA%B7%B8%EB%A0%A4%EB%B3%B8-2023-mckinsey-%EB%8D%B0%EC%9D%B4%ED%84%B0-%EC%8B%9C%EA%B0%81%ED%99%94-part-2-b0d8c65523b9">RealChart로 그려본 2023 Mckinsey 데이터 시각화 — Part 2</a> was originally published in <a href="https://medium.com/realgrid">RealGrid Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RealChart로 그려본 2023 Mckinsey 데이터 시각화]]></title>
            <link>https://medium.com/realgrid/realchart%EB%A1%9C-%EA%B7%B8%EB%A0%A4%EB%B3%B8-2023-mckinsey-%EB%8D%B0%EC%9D%B4%ED%84%B0-%EC%8B%9C%EA%B0%81%ED%99%94-bc9c1ed0b63c?source=rss-c44163a35787------2</link>
            <guid isPermaLink="false">https://medium.com/p/bc9c1ed0b63c</guid>
            <category><![CDATA[mckinsey]]></category>
            <category><![CDATA[realchart]]></category>
            <category><![CDATA[charts]]></category>
            <category><![CDATA[realgrid]]></category>
            <category><![CDATA[data-visualization]]></category>
            <dc:creator><![CDATA[Byoung Jin Yu]]></dc:creator>
            <pubDate>Sun, 21 Apr 2024 09:59:26 GMT</pubDate>
            <atom:updated>2024-05-12T09:20:21.246Z</atom:updated>
            <content:encoded><![CDATA[<p>이번 포스트는 Mckinsey에 소개된 2023년 가장 인기 있는 데이터 시각화 중 일부를 소개합니다. 데이터가 복잡한 정보를 설득력 있는 스토리로 변환하는 데 어떻게 도움이 되는지 알아보세요.</p><h3>AI가 무대 중심에 서다</h3><p>생성형 AI(Generative AI)는 2023년 엄청난 주목을 받았습니다.</p><p>이미지, 텍스트, 비디오 등을 생성하는 애플리케이션이 대중에게 널리 제공 되면서 2023년 생성형 AI(Generative AI)가 전 세계의 관심을 끌었습니다 . 다양한 분야의 기업들이 이 기술을 빠르게 채택했으며, 이미 SaaS 개발로 전환하기 시작했습니다. 오늘날 업무의 최대 40%가 자연어 이해와 관련되어 있으므로 의사소통 및 문서화와 관련된 업무는 생성 AI 도구를 통해 상당한 자동화 잠재력을 갖고 있습니다. 이 기술은 교육 및 사무 지원과 같은 분야에서 업무 변화를 가속화 할 수 있습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k3lKG0V7qtWQMXcrT_zdyg.png" /><figcaption><a href="https://jsfiddle.net/gh/get/library/pure/realgrid/realchart-demo/tree/master/blog/generative-ai">Try RealChart on jsfiddle</a></figcaption></figure><h3>넷 제로(Net Zero) 임계점 도달</h3><p>넷제로 전환이 진행되고 있지만 충분히 빠르게 진행되지는 않습니다. 기후 변화의 가장 심각한 영향을 막으려면 더 많은 투자와 함께 기후 기술을 개발하고 배포하려는 노력을 대폭 가속화해야 합니다.</p><p>미국 인플레이션 감소법(IRA)의 효과가 재생에너지 시장에 구체화되기 시작했습니다. IRA는 이제 법이 발효되기 전 예상했던 것보다 태양광, 저장소(리튬을 포함한 기존의 수력 펌프 저장소를 포함), 지상 풍력 발전 용량을 2.7배 더 빠르게 늘릴 수 있는 잠재력을 갖게 되었습니다. 그러나 그 목표를 달성한다는 것은 향후 3~5년 동안 악화될 수 있는 심각한 건설 및 노동력 부족을 극복하는 것을 의미합니다. 2030년까지 지상 풍력 및 태양광 프로젝트를 위한 자본 투자에 약 7,000억~8,000억 달러가 걸려 있습니다. 이러한 프로젝트를 실현하기 위해 재생에너지 기업들은 파트너십, 리스크 소유권 및 계약, 인력 개발, 그리고 디지털 및 기술에 대한 새로운 접근 방식을 수립할 수 있습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5oPl0BLZs-wVZ4V2cPap1g.png" /><figcaption><a href="https://jsfiddle.net/gh/get/library/pure/realgrid/realchart-demo/tree/master/blog/energy-ira">Try RealChart on jsfiddle</a></figcaption></figure><p>출처: <a href="https://www.mckinsey.com/featured-insights/2023-year-in-review/2023-the-year-in-charts">https://www.mckinsey.com/featured-insights/2023-year-in-review/2023-the-year-in-charts</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bc9c1ed0b63c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/realgrid/realchart%EB%A1%9C-%EA%B7%B8%EB%A0%A4%EB%B3%B8-2023-mckinsey-%EB%8D%B0%EC%9D%B4%ED%84%B0-%EC%8B%9C%EA%B0%81%ED%99%94-bc9c1ed0b63c">RealChart로 그려본 2023 Mckinsey 데이터 시각화</a> was originally published in <a href="https://medium.com/realgrid">RealGrid Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Infographic Design Effects]]></title>
            <link>https://medium.com/@nanturtle/infographic-design-effects-b0b80cde1586?source=rss-c44163a35787------2</link>
            <guid isPermaLink="false">https://medium.com/p/b0b80cde1586</guid>
            <dc:creator><![CDATA[Byoung Jin Yu]]></dc:creator>
            <pubDate>Sun, 11 Feb 2024 23:33:28 GMT</pubDate>
            <atom:updated>2024-02-11T23:33:28.594Z</atom:updated>
            <content:encoded><![CDATA[<p>CUT THROUGH THE NOISE<br>72% of marketers report that visual content is more effective than text-based marketing, and publishers who use infographics grow traffic 12% faster than those who don’t.</p><p>GO VIRAL<br>Whether you’re after likes, shares, or +1s, infographics have great virality. For example, tweets with images receive 18% more clicks, 89% more favorites and 150% more retweets.</p><p>SHOW. DON’T TELL.<br>The average human attention span is 8 seconds, and our brains process images 60,000 times faster than text. Infographics make it easier to grab your viewer before the next distraction does.</p><p>ref. <a href="https://visual.ly/product/infographic-design">https://visual.ly/product/infographic-design</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b0b80cde1586" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Playwright 테스트 시간 절약 방법]]></title>
            <link>https://medium.com/realgrid/playwright-%ED%85%8C%EC%8A%A4%ED%8A%B8-%EC%8B%9C%EA%B0%84-%EC%A0%88%EC%95%BD-%EB%B0%A9%EB%B2%95-e0ae1c339169?source=rss-c44163a35787------2</link>
            <guid isPermaLink="false">https://medium.com/p/e0ae1c339169</guid>
            <category><![CDATA[charts]]></category>
            <category><![CDATA[playwright-test]]></category>
            <category><![CDATA[realchart]]></category>
            <category><![CDATA[realgrid]]></category>
            <category><![CDATA[e2e-testing]]></category>
            <dc:creator><![CDATA[Byoung Jin Yu]]></dc:creator>
            <pubDate>Tue, 30 Jan 2024 04:18:01 GMT</pubDate>
            <atom:updated>2024-01-30T04:21:32.803Z</atom:updated>
            <content:encoded><![CDATA[<p>UI 컴포넌트는 테스트가 매우 중요한 제품군 중 하나다. 특히, OOP기반의 구조는 하나의 속성이나 기능의 수정이 다른 많은 구현체에 영향을 미칠 수 있다. 각 클래스들이 긴밀하게 설계되었다면 더욱 그렇다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ER9t9Pjs0hMvl_GZ" /><figcaption>Photo by <a href="https://unsplash.com/@lastnameeaster?utm_source=medium&amp;utm_medium=referral">La-Rel Easter</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Playwright는 브라우저 기반의 End-to-End(E2E) 테스트를 실행하는 도구다. 여러 가지 브라우저에서 UI 테스트를 할 수 있다.</p><p>playwright.config.ts 에서는 다음과 같은 기본 구성을 같는다.</p><pre>/**<br> * See https://playwright.dev/docs/test-configuration.<br> */<br>export default defineConfig({<br>  testDir: &#39;./test/e2e&#39;,<br>  /* Run tests in files in parallel */<br>  fullyParallel: true,<br>  /* Fail the build on CI if you accidentally left test.only in the source code. */<br>  forbidOnly: !!process.env.CI,<br>  /* Retry on CI only */<br>  retries: process.env.CI ? 2 : 0,<br>  /* Opt out of parallel tests on CI. */<br>  workers: process.env.CI ? 1 : undefined,<br>...})</pre><p>테스트를 병렬로 실행하기 위한 fullyParallel 이 <em>true</em>로 설정되어 있고 workers 가 환경변수에 의해 설정된다. 참고로 Show browser를 활성화 하면 병렬 실행은 적용되지 않는다. workers 속성은 <em>number</em>타입이나 50% 같은 <em>string</em>타입도 지원한다. workers를 설정하지 않으면 50% 가 기본값이 된다. 이 때, 퍼센트 값은 기기의 cpu core수를 기준으로 계산된다.</p><p>또는 test 실행 script에 다음과 같이 매개변수를 추가해줘도 된다.</p><pre>&quot;test:chrome&quot;: &quot;npx playwright test - project=chromium - workers=100%&quot;</pre><p>개발 중인 <a href="https://realchart.co.kr/">RealChart</a>는 1,600여건의 playwright 테스트 케이스가 있다. playwright 기본 설정으로는 chrome 브라우저 테스트 한 가지만 MacBook Pro m2(8core)에서 13분 정도 소요되었다. 이 중 1,100여건이 스냅샷 테스트이다. 앞으로 테스트 케이스는 더 늘어날 것이고, 테스트 시간이 너무 오래 걸릴 것으로 예상했다. 다른 개발팀의 경험을 들어보니 github action 자원으로도 1시간은 족히 넘길 것 같았다. Kubernetes같은 분산 테스트 컴퓨팅 환경이 필요해 보였다. 아니면…</p><p>workers 를 높게 설정해도 될까? 현재 코어수의 4배인 32로 workers 를 설정하고 실행해보았다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PcIp5_UF04ID0vVuGSrDdg.png" /></figure><p>workers 수만큼 chrominum이 동시에 실행되는 것 같았다. 그리고 처음에는 테스트 실행속도가 매우 빠른 것 같았다. 그러나 일정 시간이 경과하고나서는 테스트코드의 timeout이 발생하기 시작했다. 수행 결과는 기본 설정에 비해 크게 줄지 않았다. 개발환경마다 적절한 세팅이 필요해 보였다. 필요에 따라서는 test timeout도 늘릴 필요가 있다.</p><p>여러가지 실험을 해보고, 300% 설정에서 4분 정도로 처음 13여분에서 3배 이상 시간이 절약됐다. Macbook Pro M1(10 core)을 가진 다른 개발자 환경에서는 3분대에서 테스트가 완료되었다.</p><p>컴퓨팅 스펙이 높다면 더 빠른 테스트가 가능할테지만, 반대로 스펙이 낮다면 오히려 역효과가 날 수 있으니 각 제품별 테스트 기기별로 최적값을 찾아야 한다. 그럼에도 불구하고 분산 테스트 환경을 구축하는 것에 비해 시간과 비용을 많이 아낄 수 있으므로 시도해 볼만 하다.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e0ae1c339169" width="1" height="1" alt=""><hr><p><a href="https://medium.com/realgrid/playwright-%ED%85%8C%EC%8A%A4%ED%8A%B8-%EC%8B%9C%EA%B0%84-%EC%A0%88%EC%95%BD-%EB%B0%A9%EB%B2%95-e0ae1c339169">Playwright 테스트 시간 절약 방법</a> was originally published in <a href="https://medium.com/realgrid">RealGrid Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Amazon EKS의 서비스를 EIP와 연결하는 방법]]></title>
            <link>https://medium.com/hatiolab/amazon-eks%EC%9D%98-%EC%84%9C%EB%B9%84%EC%8A%A4%EB%A5%BC-eip%EC%99%80-%EC%97%B0%EA%B2%B0%ED%95%98%EB%8A%94-%EB%B0%A9%EB%B2%95-42bbc335cf1a?source=rss-c44163a35787------2</link>
            <guid isPermaLink="false">https://medium.com/p/42bbc335cf1a</guid>
            <category><![CDATA[load-balancer]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[ek]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[iot]]></category>
            <dc:creator><![CDATA[Byoung Jin Yu]]></dc:creator>
            <pubDate>Sun, 01 May 2022 09:14:08 GMT</pubDate>
            <atom:updated>2022-05-01T09:14:08.462Z</atom:updated>
            <content:encoded><![CDATA[<p>대부분의 온라인 서비스는 dns기반으로 운영합니다. 그러나 항상 예외가 발생하기 마련입니다. 전자저울의 측정값을 미들웨어로 전달해야 했는데, 전자저울이 Endpoint로 IP만 설정할 수 있었습니다. 센서값을 받아 미들웨어로 전달하는 서비스는 SaaS 구성 중 하나였으므로 단순히 EC2로 해결하는 것이 아니라 EKS에 구성해야 했습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VdQWYSA6r-X5i3vvtXPI5g.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@budding?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Add Weed</a> on <a href="https://unsplash.com/s/photos/scale?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>먼저 EKS에 <a href="https://docs.aws.amazon.com/ko_kr/eks/latest/userguide/aws-load-balancer-controller.html">AWS Load Balancer Controller</a>를 추가 설치합니다. 이 컨트롤러는 Ingress를 생성할 때 ALB를, LoadBalancer 유형의 서비스를 생성할 때 NLB를 프로비저닝 하도록 합니다.</p><h4><a href="https://docs.aws.amazon.com/ko_kr/eks/latest/userguide/network-load-balancing.html#:~:text=%EC%9C%A0%EB%B0%9C%ED%95%A0%20%EC%88%98%20%EC%9E%88%EC%8A%B5%EB%8B%88%EB%8B%A4.-,%EB%84%A4%ED%8A%B8%EC%9B%8C%ED%81%AC%20%EB%A1%9C%EB%93%9C%20%EB%B0%B8%EB%9F%B0%EC%84%9C%20%EC%83%9D%EC%84%B1,-IP%20%EB%98%90%EB%8A%94%20%EC%9D%B8%EC%8A%A4%ED%84%B4%EC%8A%A4">IP 대상으로 Network Load Balancer 생성</a></h4><p>aws-load-balancer-type 의 external 값은 추가로 설치한 AWS Load Balancer Controller를 사용하도록 합니다.</p><pre>service.beta.kubernetes.io/aws-load-balancer-type: &quot;external&quot;<br>service.beta.kubernetes.io/aws-load-balancer-nlb-target-type: &quot;ip&quot;</pre><p>Public subnet에 NLB를 생성하려면 다음 annotation이 필요합니다.</p><pre>service.beta.kubernetes.io/aws-load-balancer-scheme: &quot;internet-facing&quot;</pre><p>aws-load-balancer-eip-allocations 로 NLB에 EIP를 할당할 수 있습니다. Allocation IDs 수는 로드 밸런서에 사용되는 subnet 수와 일치해야 합니다.</p><pre>service.beta.kubernetes.io/aws-load-balancer-eip-allocations: eipalloc-xxxxxxxxxxxxxxxxx,eipalloc-yyyyyyyyyyyyyyyyy</pre><p>만약 Allocation ID 수와 subnet 수가 일치하지 않으면 다음과 같은 에러가 발생합니다.</p><blockquote>Warning FailedBuildModel 10s (x15 over 94s) service Failed build model due to number of EIP allocations (1) and subnets (2) must match</blockquote><p>단일 Endpoint IP가 필요하므로 하나의 EIP와 하나의 서브넷을 구성했습니다. 다음은 Service 구성 예제입니다.</p><pre>apiVersion: v1<br>kind: Service<br>metadata:<br>  labels:<br>    app: my-app<br>  name: my-nlb<br>  annotations:<br>    service.beta.kubernetes.io/aws-load-balancer-type: external<br>    service.beta.kubernetes.io/aws-load-balancer-nlb-target-type: ip<br>    service.beta.kubernetes.io/aws-load-balancer-scheme: internet-facing<br>    service.beta.kubernetes.io/aws-load-balancer-subnets: subnet-xxxxxx<br>    service.beta.kubernetes.io/aws-load-balancer-eip-allocations: eipalloc-xxxxxxxx<br>spec:<br>  type: LoadBalancer<br>  ports:<br>    - name: &quot;8080&quot;<br>      protocol: TCP<br>      port: 8080<br>      targetPort: 8080<br>  selector:<br>    app: my-app</pre><p>다음과 같은 에러가 발생한다면, 기존의 NLB가 여전히 EIP와 바인딩되어 있기 때문입니다. 기존 NLB가 완전히 삭제되었는지 확인해 볼 필요가 있습니다.</p><blockquote>Warning FailedDeployModel 26s service Failed deploy model due to ResourceInUse: The allocation IDs are not available for use</blockquote><h4><strong>Node Selector</strong></h4><p>Pod를 생성해서 EIP로 연결되는 것을 확인하고, Pod를 재시작 했더니 EIP로 연결되지 않는 문제가 발생했습니다. 운영중인 EKS는 2개의 public subnet을 가지고 있었는데, Pod가 위처럼 설정한 서브넷과 다른 서브넷에 생성했기 때문입니다. 이를 해결하려면 Deployment spec에 nodeSelector를 지정해서 의도한 서브넷을 선택하도록 해야합니다. subnet을 직접 지정할 수 없어서 subnet이 속한 zone으로 선택하도록 했습니다.</p><pre>nodeSelector: <br>  topology.kubernetes.io/zone: ap-northeast-2c</pre><p>nodeSelector는 더 다양한 구성이 가능한데 다음의 글도 참고하시면 좋습니다.</p><p><a href="https://medium.com/kubernetes-tutorials/learn-how-to-assign-pods-to-nodes-in-kubernetes-using-nodeselector-and-affinity-features-e62c437f3cf8">Learn How to Assign Pods to Nodes in Kubernetes Using nodeSelector and Affinity Features</a></p><blockquote><strong><em>실행 환경<br></em></strong>AWS Load Balancer Controller<br>- amazon/aws-alb-ingress-controller:v2.2.1 <br>Kubernetes version<br>- 1.21</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=42bbc335cf1a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hatiolab/amazon-eks%EC%9D%98-%EC%84%9C%EB%B9%84%EC%8A%A4%EB%A5%BC-eip%EC%99%80-%EC%97%B0%EA%B2%B0%ED%95%98%EB%8A%94-%EB%B0%A9%EB%B2%95-42bbc335cf1a">Amazon EKS의 서비스를 EIP와 연결하는 방법</a> was originally published in <a href="https://medium.com/hatiolab">hatiolab</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RabbitMQ— Kafka — S3 Pipeline]]></title>
            <link>https://medium.com/hatiolab/rabbitmq-kafka-s3-pipeline-5f6671019bc6?source=rss-c44163a35787------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f6671019bc6</guid>
            <category><![CDATA[data-pipeline]]></category>
            <category><![CDATA[s3]]></category>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[mqtt]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Byoung Jin Yu]]></dc:creator>
            <pubDate>Sun, 24 Apr 2022 14:13:51 GMT</pubDate>
            <atom:updated>2022-04-24T14:28:12.615Z</atom:updated>
            <content:encoded><![CDATA[<h3>RabbitMQ— Kafka — S3 Data Pipeline</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*Rn8Dz9tlEfaGqaRn" /><figcaption>Photo by <a href="https://unsplash.com/@chris_dion?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Christophe Dion</a> on <a href="https://unsplash.com/s/photos/pipeline?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>데이터의 수많은 활용 사례들로 데이터 레이크를 구축하기 위한 데이터 파이프라인 구성방법은 매우 다양하다. 그 중 하나는 IoT 데이터를 보관하고 활용하기 위한 파이프라인 구성이다. 구축비용과 시간을 아낄 수 있는 AWS의 레퍼런스 중 하나는 AWS IoT, Kinesis Firehose, S3로 구성되는 파이프라인이다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZzbC6mEgeuZwbJQT.png" /><figcaption><a href="https://docs.aws.amazon.com/solutions/latest/constructs/aws-iot-kinesisfirehose-s3.html">AWS IoT — Kinesis Firehose — S3</a></figcaption></figure><p>AWS IoT는 프로비저닝이 필요하다. 그러나 사용 중인 IoT 기기들이 AWS와 프로비저닝하기 어려울 수 있다. 필자의 경우도 MQTT로 통신하는 IoT 기기들로 이미 협약이 끝난 상태였고, RabbitMQ를 이용하는 아키텍처로 진행 중이었다. IoT 데이터는 대부분 작은 사이즈로 많은 트래픽이 발생한다. 우리는 이를 Kafka로 전송한 뒤 S3에 저장하고, Athena를 이용해 조회할 수 있는 아키텍쳐를 설계했다. 몇 가지 PoC를 진행했는데 3가지 케이스를 소개한다.</p><h3>Amazon MQ — MSK— S3 Pipeline</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GS6_murvQx8fgZ9KJUvaaw.jpeg" /><figcaption>Amazone MQ —MSK — S3 Pipeline</figcaption></figure><p>첫 번째 케이스는 RabbitMQ —MSK( Kafka) — S3로 이어지는 파이프라인이다. Amazon MQ는 Apache Active MQ와 RabbitMQ를 지원한다. 여기서는 RabbitMQ를 사용했다. RabbitMQ는 기본적으로 MQTT를 지원하지 않으므로 플러그인 설치가 필요하다. MQTT는 실시간성 데이터 통신이고 AMQP는 큐 기반으로 데이터를 소비(consume)하는 구조다. 데이터를 소비하기 위해 AWS Lambda를 활용했는데 Lambda는 serverless 서비스 이므로 데이터를 소비하기 위해서는 AMQP가 적합하다. Lambda Trigger는 이를 위한 Amazon MQ를 지원한다. MQ Trigger를 사용하면 별도의 AMQP 소비 코드를 작성할 필요가 없다. (<a href="https://docs.aws.amazon.com/lambda/latest/dg/with-mq.html">Using Lambda with Amazon MQ</a>)<br>nodejs기반의 lambda를 생성하고 Kafka로 전송하기 위해서 kafkajs 라이브러리를 사용했다. Kakfa데이터를 S3로 보내는 lambda에서는 Kafka Trigger를 사용했다. Lambda에서 제공하는 Trigger들을 사용하면 개발 시간을 많이 단축할 수 있다.</p><h3>RabbitMQ —MSK — S3 Pipeline</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R6IzhLgvo1L4ZJ9mrDKtJg.jpeg" /><figcaption>RabbitMQ —MSK — S3 Pipeline</figcaption></figure><p>두 번째 케이스는 첫 번째와 마찬가지로 RabbitMQ — Kafka — S3 파이프라인이지만 Amazon MQ가 아니라 EKS Pod로 운영하는 자체 RabbitMQ 서비스를 사용하는 경우이다. 아쉽게도 Lambda에서는 외부 RabbitMQ 서비스와 연계할 수 있는 Trigger가 없었다. 그래서 amqplib 라이브러리를 이용해서 nodejs기반의 lambda를 구현해야 했다. Lambda를 주기적으로 트리거 해야하므로 Event Bridge를 이용해 Invoke 시켰다. 그 이후는 첫 번째 케이스와 같다.</p><h3>RabbitMQ — Confluent Kafka — S3</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vJCr-3wC9JC22lECwKvtqQ.jpeg" /><figcaption>RabbitMQ — Confluent Kafka— S3</figcaption></figure><p>마지막으로 MSK 대신 Confluent Kafka 를 사용하는 파이프라인이다. Confluent는 완전관리형 Kafka서비스로 Amazon MSK에 비해 관리 포인트가 더 적은 것이 장점이다. 또한 Confluent는 많은 Kafka 커넥터들이 준비되어 있다. Confluent의 가격정책 중 free 또는 standard는 Private VPC를 사용할 수 없어서 이전 구성과 다르게 Public한 연결과 인증키 구성이 필요했고 이 과정은 Confluent의 PoC 지원이 있었다. RabbitMQ 비용을 줄이기 위해 Amzon MQ는 내리고, 두 번재 케이스와 같이 EKS Pod를 사용했다. Confluent에서 제공하는 MQTT Source Connector를 이용해서 MQTT 토픽을 곧바로 소비할 수 있고, S3 Sink Connector로 S3로 전송할 수 있다. 코딩 없이 쉽게 구성이 가능하다. 다만 Kafka Connector는 EC2 같은 리소스를 사용하므로 비용이 증가한다.</p><h3><strong>마치며.</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BfyxQb9UAMEZ1o9PqxwjhA.jpeg" /></figure><p>최근 데이터 파이프라인은 또 다시 변경되었다. IoT 데이터는 데이터베이스로 우선 저장되고, 이후 CDC로 Kafka에 전달된다. AMQP Trigger, Lambda 구성의 주기적 데이터 소비가 아닌 실시간 데이터 처리가 필요했고, Confluent 케이스 처럼 MQTT Source Connector가 하는 일을 자체 개발한 서비스로 작동하게 했다. 데이터 파이프라인은 정말이지 다양한 구성이 가능하며 시간단축, 비용최적화, 성능최적화 등 어떤 구성이 적합한지 늘 고민이 필요해 보인다.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f6671019bc6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hatiolab/rabbitmq-kafka-s3-pipeline-5f6671019bc6">RabbitMQ— Kafka — S3 Pipeline</a> was originally published in <a href="https://medium.com/hatiolab">hatiolab</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Preprocess with AWS Glue]]></title>
            <link>https://medium.com/hatiolab/data-preprocess-with-aws-glue-9bda5b143312?source=rss-c44163a35787------2</link>
            <guid isPermaLink="false">https://medium.com/p/9bda5b143312</guid>
            <category><![CDATA[data-preprocessing]]></category>
            <category><![CDATA[glue]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[spark]]></category>
            <dc:creator><![CDATA[Byoung Jin Yu]]></dc:creator>
            <pubDate>Thu, 14 Apr 2022 06:57:50 GMT</pubDate>
            <atom:updated>2022-04-14T06:57:50.749Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aTwZq7ceSHClNuAconBNig.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@mbaumi?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Mika Baumeister</a> on <a href="https://unsplash.com/s/photos/big-data?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>If you are a newbie on AWS, It’s very confusing to use AWS services. I can bet you won’t know where or how to start your mission. If you have done some getting started examples, and still don’t know concepts or mechanisms then I recommend reading <a href="https://aws.amazon.com/glue/faqs/">AWS Glue FAQ</a> also. It will be a bit boring though, I heard FAQ is very important for SAA(AWS Certified Solutions Architect; Associate Certification). You don’t need to understand everything, AWS World would be bigger than you thought.</p><p><strong>Development Environment</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zzNZGQthRhOcTLlxJZ4iBg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@markusspiske?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Markus Spiske</a> on <a href="https://unsplash.com/s/photos/sandbox?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>In most cases your mission will be more complicated than basic examples, You would need custom scripts out of the Glue Studio GUI. AWS Glue Studio is not convenient to test and debug source code. So it would be easier to use a docker image for development locally.<br><a href="https://aws.amazon.com/blogs/big-data/developing-aws-glue-etl-jobs-locally-using-a-container/">https://aws.amazon.com/blogs/big-data/developing-aws-glue-etl-jobs-locally-using-a-container/</a></p><p>But there are some limitations, this supports glue 1.0 only now and does not support AWS Glue Parquet writer (<a href="https://docs.aws.amazon.com/glue/latest/dg/aws-glue-programming-etl-format.html#aws-glue-programming-etl-format-glue-parquet">format=“glueparquet</a>”).<br>Without a container, if you want to develop locally and check more limitations, follow the next link<br><a href="https://docs.aws.amazon.com/glue/latest/dg/aws-glue-programming-etl-libraries.html">https://docs.aws.amazon.com/glue/latest/dg/aws-glue-programming-etl-libraries.html</a></p><p>If you succeed to create a docker container with a glue image, you can access jupyter notebook via <a href="http://localhost:8888/"><em>http://localhost:8888</em></a> . In my case, I’ve already had jupyter notebook port 8888. So I’d changed to port 8080.</p><pre>docker run -itd -p 8080:8888 -p 4040:4040 -v ~/.aws:/root/.aws:ro --name glue_jupyter amazon/aws-glue-libs:glue_libs_1.0.0_image_01 /home/jupyter/jupyter_start.sh</pre><p>You should be done ‘aws configure’ before running this command.</p><p>You can select new notebook as PySpark, Python 3, Spark, and SparkR. Default Glue Scripts includes ‘from pyspark.context import SparkContext’ PySpark would be the right choice.</p><p>At first, I recommend using Job Visual Editor of Glue Studio. After setting basic things such as S3 bucket source and target, reusing an auto-generated script is helpful. Copy or download it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/265/1*TipxBnJK6-3cf-1wDhfkdA.png" /><figcaption>Glue Job Visual Editor — Default flow</figcaption></figure><p>There is one you should fix for Auto-generated script in the development environment because of no ‘<em>sys.argv</em>’ values.</p><pre>## <a href="http://twitter.com/params">@params</a>: [JOB_NAME]<br># args = getResolvedOptions(sys.argv, [&#39;JOB_NAME&#39;])<br>args = { &quot;JOB_NAME&quot;: &quot;job0&quot;}</pre><p>When only importing script lines as a cell runs correctly, You can see the below output image including ‘SparkSeesion available’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/633/1*QYQd81lTu_YnNJN8AEC-AQ.png" /><figcaption>screenshot after running an import cell</figcaption></figure><p><strong>Mission</strong></p><p>My mission was to append weather data to a time-series dataset. 3 datasets are used. <br>- OBS: Observations have their ID, name, location, and so on.<br>- Weathers: Daily Weather data contains a timestamp, average temperature, raindrop, average wind speed by observations<br>- Auctions: Daily time-series dataset contains item_id, timestamp, target_value, latitude, and longitude.</p><p>It needs 2 steps.<br> 1. Finding closest OBS<br> 2. Joining weather data with OBS</p><p><strong>Using udf</strong></p><p>This is basic usage of udf(from pyspark.sql.functions). DataSource1 has a location field and an example of its value is ‘35.1234_127.1234’. I had to split and set to a new column. Types are from ‘pyspark.sql.types’.</p><pre>get_lat = udf(lambda x: float(x.split(&#39;_&#39;)[0]), FloatType())<br>get_lon = udf(lambda x: float(x.split(&#39;_&#39;)[1]), FloatType())</pre><pre>df1 = DataSource1.toDF()<br>df1 = df1.withColumn(&#39;lat&#39;, get_lat(df1[&#39;location&#39;]))\<br>    .withColumn(&#39;lon&#39;, get_lon(df1[&#39;location&#39;]))\<br>    .drop(&#39;location&#39;)</pre><pre>df1.printSchema()</pre><p><strong>DynamicFrame.fromDF</strong></p><p>To write the result to S3, it’s required DynamicFrame from ‘<em>awsglue.dynamicframe</em>’. And you can not use ‘glueparquet’ format in this development environment as mentioned previously. Change this at production mode in console or you can use parameters.</p><pre>DataSink0 = glueContext.write_dynamic_frame.from_options(frame = DynamicFrame.fromDF(df1, glueContext, &#39;OBS&#39;), connection_type = &quot;s3&quot;, format = &quot;csv&quot;, connection_options = {&quot;path&quot;: &quot;s3://target/to/path/&quot;, &quot;partitionKeys&quot;: []}, transformation_ctx = &quot;DataSink0&quot;)<br>job.commit()</pre><p><strong>Glue 1.0 vs Glue 2.0</strong></p><p><a href="https://aws.amazon.com/blogs/aws/aws-glue-version-2-0-featuring-10x-faster-job-start-times-and-1-minute-minimum-billing-duration/?nc1=h_ls">AWS Glue version 2.0 featuring 10x faster job start times and 1-minute minimum billing duration.</a> In my case, Glue 1.0 took about 5 minutes more to run a job on AWS cloud. I couldn’t find the reason not to use Glue 2.0. However, we can not escape Glue 1.0 in the development environment using docker container yet. Our test environment is also fast though. <a href="https://docs.aws.amazon.com/glue/latest/dg/release-notes.html">Both support Spark 2.4.3</a>, but sometimes these showed different results that one succeeds in development(Glue 1.0) and the other fails in AWS Glue console run(Glue 2.0) when ‘<em>udf</em>’ return type was written as a string.</p><pre>AttributeError: &#39;NoneType&#39; object has no attribute &#39;_jvm&#39;</pre><p>This may be part of it. Nevertheless, the glue 2.0 setting is recommended in a console environment as production. Yes, it’s still going to be a bit confusing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/603/1*cuTfRZiOPFPKxsFs50K1RQ.png" /></figure><p><strong>withColumn</strong></p><p>This is some source code finding the closest observation with latitude and longitude. ‘<em>df0</em>’ is observations and ‘<em>df1</em>’ is auctions dataset which has a location. As a result, that’s appending the closest observation’s ID to df1. At first, I thought it needs row iterations as using 2 columns and double loops, but it’s possible using a ‘<em>withColumn</em>’.</p><pre># source from <a href="https://stackoverflow.com/a/41337005/14539284">https://stackoverflow.com/a/41337005/14539284</a><br>def distance(lat1, lon1, lat2, lon2):<br>    p = 0.017453292519943295<br>    hav = 0.5 - cos((lat2-lat1)*p)/2 + cos(lat1*p)*cos(lat2*p) * (1-cos((lon2-lon1)*p)) / 2<br>    return 12742 * asin(sqrt(hav))</pre><pre>def closest(data, v):<br>    return min(data, key=lambda p: distance(v[&#39;lat&#39;],v[&#39;lon&#39;],p[&#39;lat&#39;],p[&#39;lon&#39;]))</pre><pre>obs = list(map(lambda row: row.asDict(), df0.collect()))<br>set_obs = udf(lambda x, y: closest(obs, { &quot;lat&quot;: x, &quot;lon&quot;: y })[&#39;id&#39;])</pre><pre>df1 = df1.withColumn(&#39;obs&#39;, set_obs(df1[&quot;lat&quot;], df1[&quot;lon&quot;]))<br>df1.printSchema()</pre><p><strong>iterrows</strong></p><p>Actually, I’m also a newbie on spark. Just, I had the experience of using ‘<em>applyInPandas’</em> with spark 3.0. but I failed most methods in this environment. We are in the limited environment AWS Glue 1.0 which supports spark 2.4. (Recently Glue 3.0 is available in the console, supports spark 3.1). There are methods of looping rows with spark dataframe, but I couldn’t do these. I may have applied something wrong, but it failed, at least in my development environment. You can check more pyspark techniques as the next links.<br><em>- </em><a href="https://towardsdatascience.com/5-ways-to-add-a-new-column-in-a-pyspark-dataframe-4e75c2fd8c08"><em>https://towardsdatascience.com/5-ways-to-add-a-new-column-in-a-pyspark-dataframe-4e75c2fd8c08</em></a><em><br>- </em><a href="https://sparkbyexamples.com/pyspark/pyspark-loop-iterate-through-rows-in-dataframe/"><em>https://sparkbyexamples.com/pyspark/pyspark-loop-iterate-through-rows-in-dataframe/</em></a></p><p><strong>Restart kernel or spark.stop()</strong></p><p>During work, you may see the next errors. After doing your job, just run ‘spark.stop()’ on every task or restart the kernel to continue works.</p><pre>An error was encountered:<br>Invalid status code &#39;404&#39; from <a href="http://localhost:8998/sessions/8">http://localhost:8998/sessions/8</a> with error payload: {&quot;msg&quot;:&quot;Session &#39;8&#39; not found.&quot;}</pre><p><strong>Joining weather data</strong></p><p>Finally, created a new job with the result of the above and weather dataset. ‘Left join’ was used obs(observation id) and timestamp as keys. It’s done using Glue Studio GUI only.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Lv9FjlcsRGtlJiVzCHSkVQ.png" /><figcaption>Glue Studio Job — Left Join datasets</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9bda5b143312" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hatiolab/data-preprocess-with-aws-glue-9bda5b143312">Data Preprocess with AWS Glue</a> was originally published in <a href="https://medium.com/hatiolab">hatiolab</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Preprocess with AWS Glue]]></title>
            <link>https://medium.com/geekculture/data-preprocess-with-aws-glue-27890c69a8ee?source=rss-c44163a35787------2</link>
            <guid isPermaLink="false">https://medium.com/p/27890c69a8ee</guid>
            <category><![CDATA[pyspark]]></category>
            <category><![CDATA[withcolumn]]></category>
            <category><![CDATA[preprocesing]]></category>
            <category><![CDATA[iterrows]]></category>
            <category><![CDATA[aws-glue]]></category>
            <dc:creator><![CDATA[Byoung Jin Yu]]></dc:creator>
            <pubDate>Wed, 25 Aug 2021 05:00:18 GMT</pubDate>
            <atom:updated>2021-08-26T07:58:28.011Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aTwZq7ceSHClNuAconBNig.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@mbaumi?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Mika Baumeister</a> on <a href="https://unsplash.com/s/photos/big-data?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>If you are a newbie on AWS, It’s very confusing to use AWS services. I can bet you won’t know where or how to start your mission. If you have done some getting started examples, and still don’t know concepts or mechanisms then I recommend reading <a href="https://aws.amazon.com/glue/faqs/">AWS Glue FAQ</a> also. It will be a bit boring though, I heard FAQ is very important for SAA(AWS Certified Solutions Architect; Associate Certification). You don’t need to understand everything, AWS World would be bigger than you thought.</p><p><strong>Development Environment</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zzNZGQthRhOcTLlxJZ4iBg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@markusspiske?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Markus Spiske</a> on <a href="https://unsplash.com/s/photos/sandbox?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>In most cases your mission will be more complicated than basic examples, You would need custom scripts out of the Glue Studio GUI. AWS Glue Studio is not convenient to test and debug source code. So it would be easier to use a docker image for development locally.<br><a href="https://aws.amazon.com/blogs/big-data/developing-aws-glue-etl-jobs-locally-using-a-container/">https://aws.amazon.com/blogs/big-data/developing-aws-glue-etl-jobs-locally-using-a-container/</a></p><p>But there are some limitations, this supports glue 1.0 only now and does not support AWS Glue Parquet writer (<a href="https://docs.aws.amazon.com/glue/latest/dg/aws-glue-programming-etl-format.html#aws-glue-programming-etl-format-glue-parquet">format=“glueparquet</a>”).<br>Without a container, if you want to develop locally and check more limitations, follow the next link<br><a href="https://docs.aws.amazon.com/glue/latest/dg/aws-glue-programming-etl-libraries.html">https://docs.aws.amazon.com/glue/latest/dg/aws-glue-programming-etl-libraries.html</a></p><p>If you succeed to create a docker container with a glue image, you can access jupyter notebook via <a href="http://localhost:8888/"><em>http://localhost:8888</em></a> . In my case, I’ve already had jupyter notebook port 8888. So I’d changed to port 8080.</p><pre>docker run -itd -p 8080:8888 -p 4040:4040 -v ~/.aws:/root/.aws:ro --name glue_jupyter amazon/aws-glue-libs:glue_libs_1.0.0_image_01 /home/jupyter/jupyter_start.sh</pre><p>You should be done ‘aws configure’ before running this command.</p><p>You can select new notebook as PySpark, Python 3, Spark, and SparkR. Default Glue Scripts includes ‘from pyspark.context import SparkContext’ PySpark would be the right choice.</p><p>At first, I recommend using Job Visual Editor of Glue Studio. After setting basic things such as S3 bucket source and target, reusing an auto-generated script is helpful. Copy or download it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/265/1*TipxBnJK6-3cf-1wDhfkdA.png" /><figcaption>Glue Job Visual Editor — Default flow</figcaption></figure><p>There is one you should fix for Auto-generated script in the development environment because of no ‘<em>sys.argv</em>’ values.</p><pre>## <a href="http://twitter.com/params">@params</a>: [JOB_NAME]<br># args = getResolvedOptions(sys.argv, [&#39;JOB_NAME&#39;])<br>args = { &quot;JOB_NAME&quot;: &quot;job0&quot;}</pre><p>When only importing script lines as a cell runs correctly, You can see the below output image including ‘SparkSeesion available’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/633/1*QYQd81lTu_YnNJN8AEC-AQ.png" /><figcaption>screenshot after running an import cell</figcaption></figure><p><strong>Mission</strong></p><p>My mission was to append weather data to a time-series dataset. 3 datasets are used. <br>- OBS: Observations have their ID, name, location, and so on.<br>- Weathers: Daily Weather data contains a timestamp, average temperature, raindrop, average wind speed by observations<br>- Auctions: Daily time-series dataset contains item_id, timestamp, target_value, latitude, and longitude.</p><p>It needs 2 steps.<br> 1. Finding closest OBS<br> 2. Joining weather data with OBS</p><p><strong>Using udf</strong></p><p>This is basic usage of udf(from pyspark.sql.functions). DataSource1 has a location field and an example of its value is ‘35.1234_127.1234’. I had to split and set to a new column. Types are from ‘pyspark.sql.types’.</p><pre>get_lat = udf(lambda x: float(x.split(&#39;_&#39;)[0]), FloatType())<br>get_lon = udf(lambda x: float(x.split(&#39;_&#39;)[1]), FloatType())</pre><pre>df1 = DataSource1.toDF()<br>df1 = df1.withColumn(&#39;lat&#39;, get_lat(df1[&#39;location&#39;]))\<br>    .withColumn(&#39;lon&#39;, get_lon(df1[&#39;location&#39;]))\<br>    .drop(&#39;location&#39;)</pre><pre>df1.printSchema()</pre><p><strong>DynamicFrame.fromDF</strong></p><p>To write the result to S3, it’s required DynamicFrame from ‘<em>awsglue.dynamicframe</em>’. And you can not use ‘glueparquet’ format in this development environment as mentioned previously. Change this at production mode in console or you can use parameters.</p><pre>DataSink0 = glueContext.write_dynamic_frame.from_options(frame = DynamicFrame.fromDF(df1, glueContext, &#39;OBS&#39;), connection_type = &quot;s3&quot;, format = &quot;csv&quot;, connection_options = {&quot;path&quot;: &quot;s3://target/to/path/&quot;, &quot;partitionKeys&quot;: []}, transformation_ctx = &quot;DataSink0&quot;)<br>job.commit()</pre><p><strong>Glue 1.0 vs Glue 2.0</strong></p><p><a href="https://aws.amazon.com/blogs/aws/aws-glue-version-2-0-featuring-10x-faster-job-start-times-and-1-minute-minimum-billing-duration/?nc1=h_ls">AWS Glue version 2.0 featuring 10x faster job start times and 1-minute minimum billing duration.</a> In my case, Glue 1.0 took about 5 minutes more to run a job on AWS cloud. I couldn’t find the reason not to use Glue 2.0. However, we can not escape Glue 1.0 in the development environment using docker container yet. Our test environment is also fast though. <a href="https://docs.aws.amazon.com/glue/latest/dg/release-notes.html">Both support Spark 2.4.3</a>, but sometimes these showed different results that one succeeds in development(Glue 1.0) and the other fails in AWS Glue console run(Glue 2.0) when ‘<em>udf</em>’ return type was written as a string.</p><pre>AttributeError: &#39;NoneType&#39; object has no attribute &#39;_jvm&#39;</pre><p>This may be part of it. Nevertheless, the glue 2.0 setting is recommended in a console environment as production. Yes, it’s still going to be a bit confusing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/603/1*cuTfRZiOPFPKxsFs50K1RQ.png" /></figure><p><strong>withColumn</strong></p><p>This is some source code finding the closest observation with latitude and longitude. ‘<em>df0</em>’ is observations and ‘<em>df1</em>’ is auctions dataset which has a location. As a result, that’s appending the closest observation’s ID to df1. At first, I thought it needs row iterations as using 2 columns and double loops, but it’s possible using a ‘<em>withColumn</em>’.</p><pre># source from <a href="https://stackoverflow.com/a/41337005/14539284">https://stackoverflow.com/a/41337005/14539284</a><br>def distance(lat1, lon1, lat2, lon2):<br>    p = 0.017453292519943295<br>    hav = 0.5 - cos((lat2-lat1)*p)/2 + cos(lat1*p)*cos(lat2*p) * (1-cos((lon2-lon1)*p)) / 2<br>    return 12742 * asin(sqrt(hav))</pre><pre>def closest(data, v):<br>    return min(data, key=lambda p: distance(v[&#39;lat&#39;],v[&#39;lon&#39;],p[&#39;lat&#39;],p[&#39;lon&#39;]))</pre><pre>obs = list(map(lambda row: row.asDict(), df0.collect()))<br>set_obs = udf(lambda x, y: closest(obs, { &quot;lat&quot;: x, &quot;lon&quot;: y })[&#39;id&#39;])</pre><pre>df1 = df1.withColumn(&#39;obs&#39;, set_obs(df1[&quot;lat&quot;], df1[&quot;lon&quot;]))<br>df1.printSchema()</pre><p><strong>iterrows</strong></p><p>Actually, I’m also a newbie on spark. Just, I had the experience of using ‘<em>applyInPandas’</em> with spark 3.0. but I failed most methods in this environment. We are in the limited environment AWS Glue 1.0 which supports spark 2.4. (Recently Glue 3.0 is available in the console, supports spark 3.1). There are methods of looping rows with spark dataframe, but I couldn’t do these. I may have applied something wrong, but it failed, at least in my development environment. You can check more pyspark techniques as the next links.<br><em>- </em><a href="https://towardsdatascience.com/5-ways-to-add-a-new-column-in-a-pyspark-dataframe-4e75c2fd8c08"><em>https://towardsdatascience.com/5-ways-to-add-a-new-column-in-a-pyspark-dataframe-4e75c2fd8c08</em></a><em><br>- </em><a href="https://sparkbyexamples.com/pyspark/pyspark-loop-iterate-through-rows-in-dataframe/"><em>https://sparkbyexamples.com/pyspark/pyspark-loop-iterate-through-rows-in-dataframe/</em></a></p><p><strong>Restart kernel or spark.stop()</strong></p><p>During work, you may see the next errors. After doing your job, just run ‘spark.stop()’ on every task or restart the kernel to continue works.</p><pre>An error was encountered:<br>Invalid status code &#39;404&#39; from <a href="http://localhost:8998/sessions/8">http://localhost:8998/sessions/8</a> with error payload: {&quot;msg&quot;:&quot;Session &#39;8&#39; not found.&quot;}</pre><p><strong>Joining weather data</strong></p><p>Finally, created a new job with the result of the above and weather dataset. ‘Left join’ was used obs(observation id) and timestamp as keys. It’s done using Glue Studio GUI only.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Lv9FjlcsRGtlJiVzCHSkVQ.png" /><figcaption>Glue Studio Job — Left Join datasets</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=27890c69a8ee" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/data-preprocess-with-aws-glue-27890c69a8ee">Data Preprocess with AWS Glue</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>