<feed xmlns="http://www.w3.org/2005/Atom"><title>機械学習Tips保管庫</title><link href="https://study-storage.amebaownd.com"></link><subtitle>データ解析、機械学習のための学習内容の保管庫。復習用。</subtitle><id>https://study-storage.amebaownd.com</id><author><name>yooooshi</name></author><updated>2025-12-27T05:56:06+00:00</updated><entry><title><![CDATA[VARモデル]]></title><link rel="alternate" href="https://study-storage.amebaownd.com/posts/58486861/"></link><id>https://study-storage.amebaownd.com/posts/58486861</id><summary><![CDATA[▶ VARモデルの解説とコード例１(Git)▶ VARモデルの解説とコード例２(Git)]]></summary><author><name>yooooshi</name></author><published>2025-12-27T05:56:06+00:00</published><updated>2026-01-27T05:57:26+00:00</updated><content type="html"><![CDATA[
		<div>
			<p><br></p><h2><b><a href="https://github.com/yoshi-cow/VAR_model/blob/main/var_model_1.ipynb" class="u-lnk-clr">▶ VARモデルの解説とコード例１(Git)</a></b></h2><p><a href="https://study-storage.amebaownd.com/posts/23344665?categoryIds=4669090" class="u-lnk-clr"><br></a></p><h2><b><a href="https://study-storage.amebaownd.com/posts/23344665?categoryIds=4669090" class="u-lnk-clr">▶ VARモデルの解説とコード例２(Git)</a></b></h2>
		</div>
	]]></content></entry><entry><title><![CDATA[状態空間モデル]]></title><link rel="alternate" href="https://study-storage.amebaownd.com/posts/58486846/"></link><id>https://study-storage.amebaownd.com/posts/58486846</id><summary><![CDATA[状態空間モデル(線形ガウス)の解説とコード実装例(python)非ガウス・非線形モデルは未記載▶ 状態空間モデル(線形ガウスモデル)の構築例(Git)▶ 状態空間モデルの基本説明ページ  ]]></summary><author><name>yooooshi</name></author><published>2025-12-27T05:47:11+00:00</published><updated>2026-01-27T05:53:04+00:00</updated><content type="html"><![CDATA[
		<div>
			<p>状態空間モデル(線形ガウス)の解説とコード実装例(python)</p><p>非ガウス・非線形モデルは未記載</p><p><br></p><h2><b><a href="https://github.com/yoshi-cow/State-Space-Model-v1-Gaussian-Linear/tree/main" class="u-lnk-clr">▶ 状態空間モデル(線形ガウスモデル)の構築例(Git)</a></b></h2><p><a href="https://study-storage.amebaownd.com/posts/18585389" class="u-lnk-clr"><br></a></p><h2><b><a href="https://study-storage.amebaownd.com/posts/18585389" class="u-lnk-clr">▶ 状態空間モデルの基本説明ページ</a></b></h2><p>&nbsp;&nbsp;</p>
		</div>
	]]></content></entry><entry><title><![CDATA[LangGraph]]></title><link rel="alternate" href="https://study-storage.amebaownd.com/posts/57102005/"></link><id>https://study-storage.amebaownd.com/posts/57102005</id><summary><![CDATA[　　・以下の書籍/Udemyでの学習内容の備忘録　　　　・『LangChainとLangGraphによるRAG・AIエージェント実践入門』　　　　・『Complete Agentic AI Bootcamp With LangGraph and Langchain』・基本操作　　・LangGraphの概念・用語　　　　  ▶ notebook　　・LangGraphにより基本的なマルチエージェント構築例　　　　  ▶ notebook　　・チェックポイントについて　　　　  ▶ notebook　　・マルチエージェント構築例2　　　　  ▶ notebook　　・リデューサーとツール呼び出しの基本（ToolNodeの利用）　　　　  ▶ notebook　　・複数ツールの利用（最適なツールを一つ選択して実行）　　　　  ▶ notebook　　・React型エージェントとメモリ機能について（create_react_agent関数を使わない版）　　　　  ▶ notebook　　・create_react_agent関数によるReact型エージェント作成　　　  　▶ notebook　　・ストリーム出力について　　　  　▶ notebook　　・ヒューマンフィードバックの適用　　　  　▶ notebook・Agentic RAG　　・エージェントによる最適なベクトルDBの選択　　　  　▶ notebook　　・ベクトル検索結果に対するセルフリフレクションの適用　　　  　▶ notebook　　・クエリ内容を分析して、動的にRAGのクエリを最適化　　　  　▶ notebook・エージェントデザインパターン　　・主要なエージェントデザインパターン　　　　　▶ notebook　　・Passive Goal Creator：ユーザーからの具体的な目標を抽出するパターン　　　　　▶ notebook　　・Prompt Response Optimizer：生成された目標やユーザー要求を、より効果的なプロンプトに変換しLLMからより質の高い回答を得るパターン　　　　　▶ notebook　　・Single-Path Plan Generator：設定された目標を達成するための一連の具体的なステップを生成するパターン　　　　　▶ notebook　　　・Multi-Path Plan Generator：タスク分解時に複数の選択肢を同時に生成し、実行時のコンテキストに応じて実行エージェント自身に都度適切な選択をさせるパターン　　　　　▶ notebook　　・Self-Reflection and Cross-Reflection：タスクの実行結果をエージェント自身で振り返ることで、その実行内容を自己改善させる　　　　　▶ notebook　　・Role-Based Cooperation：AIエージェントが協調してタスク実行　　　　　▶ notebook　　・サブクラスに分解して順番に処理　　　　　▶ notebook　　・複数ノードが独立して動くことができるときに、並列化を適用　　　　　▶ notebook　　・条件分岐による様々なノードへのルーティング　　　　　▶ notebook　　・管理エージェントがサブタスクに分解して、作業用エージェントに依頼　　　　　▶ notebook　　・LLM出力結果を評価用サブエージェントが評価　　　　　▶ notebook・アプリ構築例　　・Streamlitを用いたLangGraphアプリ　　　　　▶ notebook　　・APIによるLangGraphの呼び出し(FastAPI)とLangGraph Studioによるデバッグ　　　　　▶ notebook]]></summary><author><name>yooooshi</name></author><published>2025-05-03T04:20:04+00:00</published><updated>2025-07-22T12:11:03+00:00</updated><content type="html"><![CDATA[
		<div>
			<p><b>　　・以下の書籍/Udemyでの学習内容の備忘録</b></p><p><b>　　　　・</b>『<a href="https://gihyo.jp/book/2024/978-4-297-14530-9" target="_blank" class="u-lnk-clr">LangChainとLangGraphによるRAG・AIエージェント実践入門</a>』</p><p>　　　　・『<a href="https://www.udemy.com/course/complete-agentic-ai-bootcamp-with-langgraph-and-langchain/?couponCode=24T3MT100725JP" target="_blank" class="u-lnk-clr">Complete Agentic AI Bootcamp With LangGraph and Langchain</a>』</p><p><b><br></b></p><h2><b>・基本操作</b></h2><h3><b>　　・</b>LangGraphの概念・用語</h3><h3><a href="https://github.com/yoshi-cow/study_LangGraph/blob/main/01_about_LangGraph.ipynb" target="_blank" class="u-lnk-clr">　　　　&nbsp; ▶ notebook</a></h3><h3>　　・LangGraphにより基本的なマルチエージェント構築例</h3><h3><a href="https://github.com/yoshi-cow/study_LangGraph/blob/main/02_LangGraph_sample_code_1.ipynb" target="_blank" class="u-lnk-clr">　　　　&nbsp; ▶ notebook</a></h3><h3>　　・チェックポイントについて</h3><h3><a href="https://github.com/yoshi-cow/study_LangGraph/blob/main/03_about_CheckPoint.ipynb" target="_blank" class="u-lnk-clr">　　　　&nbsp; ▶ notebook</a></h3><h3>　　・マルチエージェント構築例2</h3><h3><a href="https://github.com/yoshi-cow/study_LangGraph/blob/main/04_make_requirements_definition_agent.ipynb" target="_blank" class="u-lnk-clr">　　　　&nbsp; ▶ notebook</a></h3><h3>　　・リデューサーとツール呼び出しの基本（ToolNodeの利用）</h3><h3><a href="https://github.com/yoshi-cow/study_LangGraph/blob/main/13_ChainsLangGraph.ipynb" target="_blank" class="u-lnk-clr">　　　　&nbsp; ▶ notebook</a></h3><h3>　　・複数ツールの利用（最適なツールを一つ選択して実行）</h3><h3><a href="https://github.com/yoshi-cow/study_LangGraph/blob/main/14_chatbotswithmultipletools.ipynb" target="_blank" class="u-lnk-clr">　　　　&nbsp; ▶ notebook</a></h3><h3>　　・React型エージェントとメモリ機能について（create_react_agent関数を使わない版）</h3><h3><a href="https://github.com/yoshi-cow/study_LangGraph/blob/main/15_ReActAgents.ipynb" target="_blank" class="u-lnk-clr">　　　　&nbsp; ▶ notebook</a></h3><h3>　　・create_react_agent関数によるReact型エージェント作成</h3><h3><a href="https://github.com/yoshi-cow/study_LangGraph/blob/main/09_create_react_agent_func.ipynb" target="_blank" class="u-lnk-clr">　　　&nbsp; 　▶ notebook</a></h3><h3>　　・ストリーム出力について</h3><h3><a href="https://github.com/yoshi-cow/study_LangGraph/blob/main/16_streaming.ipynb" target="_blank" class="u-lnk-clr">　　　&nbsp; 　▶ notebook</a></h3><h3>　　・ヒューマンフィードバックの適用</h3><h3><a href="https://github.com/yoshi-cow/study_LangGraph/blob/main/22_Humanintheloop.ipynb" target="_blank" class="u-lnk-clr">　　　&nbsp; 　▶ notebook</a></h3><p><br></p><h2><b>・Agentic RAG</b></h2><h3><b>　　・エージェントによる最適なベクトルDBの選択</b></h3><h3>　　　<a href="https://github.com/yoshi-cow/study_LangGraph/blob/main/23_AgenticRAG.ipynb" target="_blank" class="u-lnk-clr">  　▶ notebook</a></h3><h3>　　・ベクトル検索結果に対するセルフリフレクションの適用</h3><h3>　　　<a href="https://github.com/yoshi-cow/study_LangGraph/blob/main/24_CorrectiveRAG.ipynb" target="_blank" class="u-lnk-clr">  　▶ notebook</a></h3><h3>　　・クエリ内容を分析して、動的にRAGのクエリを最適化</h3><h3>　　　<a href="https://github.com/yoshi-cow/study_LangGraph/blob/main/25_AdaptiveRAG.ipynb" target="_blank" class="u-lnk-clr">  　▶ notebook</a></h3><p><br></p><h2><b>・エージェントデザインパターン</b></h2><h3>　　・主要なエージェントデザインパターン</h3><h3><a href="https://github.com/yoshi-cow/study_LangGraph/blob/main/05_about_agent_design_pattern.ipynb" target="_blank" class="u-lnk-clr">　　　　　▶ notebook</a></h3><h3>　　・Passive Goal Creator：ユーザーからの具体的な目標を抽出するパターン</h3><h3><a href="https://github.com/yoshi-cow/study_LangGraph/blob/main/06_Passive_Goal_Creator.ipynb" target="_blank" class="u-lnk-clr">　　　　　▶ notebook</a></h3><h3>　　・Prompt Response Optimizer：生成された目標やユーザー要求を、より効果的なプロンプトに変換しLLMからより質の高い回答を得るパターン</h3><h3><a href="https://github.com/yoshi-cow/study_LangGraph/blob/main/07_Prompt_Response_Optimizer.ipynb" target="_blank" class="u-lnk-clr">　　　　　▶ notebook</a></h3><h3>　　・Single-Path Plan Generator：設定された目標を達成するための一連の具体的なステップを生成するパターン</h3><h3><a href="https://github.com/yoshi-cow/study_LangGraph/blob/main/08_Single-Path_Plan_Generator.ipynb" target="_blank" class="u-lnk-clr">　　　　　▶ notebook</a></h3><h3>　　　・Multi-Path Plan Generator：タスク分解時に複数の選択肢を同時に生成し、実行時のコンテキストに応じて実行エージェント自身に都度適切な選択をさせるパターン</h3><h3><a href="https://github.com/yoshi-cow/study_LangGraph/blob/main/10_Multi-Path_Plan_Generator.ipynb" target="_blank" class="u-lnk-clr">　　　　　▶ notebook</a></h3><h3>　　・Self-Reflection and Cross-Reflection：タスクの実行結果をエージェント自身で振り返ることで、その実行内容を自己改善させる</h3><h3><a href="https://github.com/yoshi-cow/study_LangGraph/blob/main/11_Self-Reflection_and_Cross-Reflection.ipynb" target="_blank" class="u-lnk-clr">　　　　　▶ notebook</a></h3><h3>　　・Role-Based Cooperation：AIエージェントが協調してタスク実行</h3><h3><a href="https://github.com/yoshi-cow/study_LangGraph/blob/main/12_Role-Based_Cooperation.ipynb" target="_blank" class="u-lnk-clr">　　　　　▶ notebook</a></h3><h3>　　・サブクラスに分解して順番に処理</h3><h3><a href="https://github.com/yoshi-cow/study_LangGraph/blob/main/17_prompting_chaining.ipynb" target="_blank" class="u-lnk-clr">　　　　　▶ notebook</a></h3><h3>　　・複数ノードが独立して動くことができるときに、並列化を適用</h3><h3><a href="https://github.com/yoshi-cow/study_LangGraph/blob/main/18_parallelization.ipynb" target="_blank" class="u-lnk-clr">　　　　　▶ notebook</a></h3><h3>　　・条件分岐による様々なノードへのルーティング</h3><h3><a href="https://github.com/yoshi-cow/study_LangGraph/blob/main/19_Routing.ipynb" target="_blank" class="u-lnk-clr">　　　　　▶ notebook</a></h3><h3>　　・管理エージェントがサブタスクに分解して、作業用エージェントに依頼</h3><h3><a href="https://github.com/yoshi-cow/study_LangGraph/blob/main/20_orchestrator-worker.ipynb" target="_blank" class="u-lnk-clr">　　　　　▶ notebook</a></h3><h3>　　・LLM出力結果を評価用サブエージェントが評価</h3><h3><a href="https://github.com/yoshi-cow/study_LangGraph/blob/main/21_Evaluator-optimizer.ipynb" target="_blank" class="u-lnk-clr">　　　　　▶ notebook</a></h3><p><br></p><h2><b>・アプリ構築例</b></h2><h3>　　・Streamlitを用いたLangGraphアプリ</h3><h3>　　　　　<a href="https://github.com/yoshi-cow/study_LangGraph/tree/main/26_LangGraph_app_with_Streamlit" target="_blank" class="u-lnk-clr">▶ notebook</a></h3><h3>　　・APIによるLangGraphの呼び出し(FastAPI)とLangGraph Studioによるデバッグ</h3><h3>　　　　　<a href="https://github.com/yoshi-cow/study_LangGraph/tree/main/27_LangGraph_app_with_FastAPI" target="_blank" class="u-lnk-clr">▶ notebook</a></h3>
		</div>
	]]></content></entry><entry><title><![CDATA[LangChain & RAG]]></title><link rel="alternate" href="https://study-storage.amebaownd.com/posts/57082660/"></link><id>https://study-storage.amebaownd.com/posts/57082660</id><summary><![CDATA[・LCEL(LangChain Expression Language)について　▶ 解説notebook・RAG基本　▶ notebook(基本解説)　▶ 日本企業の業績pdfを用いたシンプルRAG構築コード・Advanced RAG　▶ Query Transformation　▶ Routing　▶ Query Construction　▶ RAG Fusionやハイブリッド検索など・LangSmith　▶ テスト用データの合成　▶ オフライン評価]]></summary><author><name>yooooshi</name></author><published>2025-04-27T12:00:00+00:00</published><updated>2025-07-22T12:10:45+00:00</updated><content type="html"><![CDATA[
		<div>
			<h3><b>・LCEL(LangChain Expression Language)について<br></b><b>　<a href="https://github.com/yoshi-cow/study_LangChain/blob/main/01_study_LCEL.ipynb" target="_blank" class="u-lnk-clr">▶ 解説notebook</a></b></h3><p><br></p><h3><b>・RAG基本</b></h3><h3>　<b><a href="https://github.com/yoshi-cow/learn_rag/blob/main/tutrial_1.ipynb" target="_blank" class="u-lnk-clr">▶ notebook(基本解説)</a></b></h3><h3><a href="https://github.com/yoshi-cow/learn_rag/blob/main/create_rag_1.ipynb" class="u-lnk-clr">　</a><b><a href="https://github.com/yoshi-cow/learn_rag/blob/main/create_rag_1.ipynb" target="_blank" class="u-lnk-clr">▶&nbsp;日本企業の業績pdfを用いたシンプルRAG構築コード</a></b></h3><p><br></p><h3>・Advanced RAG</h3><h3>　<a href="https://github.com/yoshi-cow/learn_rag/blob/main/query_transformation.ipynb" target="_blank" class="u-lnk-clr">▶&nbsp;Query Transformation</a></h3><h3><a href="https://github.com/yoshi-cow/learn_rag/blob/main/routing.ipynb" class="u-lnk-clr">　</a><b><a href="https://github.com/yoshi-cow/learn_rag/blob/main/routing.ipynb" target="_blank" class="u-lnk-clr">▶&nbsp;Routing</a></b></h3><h3>　<a href="https://github.com/yoshi-cow/learn_rag/blob/main/query_constraction.ipynb" target="_blank" class="u-lnk-clr">▶&nbsp;Query Construction</a></h3><h3>　<a href="https://github.com/yoshi-cow/study_LangChain/blob/main/04_study_advanced_RAG.ipynb" target="_blank" class="u-lnk-clr">▶ RAG Fusionやハイブリッド検索など</a></h3><h3><br>・LangSmith</h3><h3><a href="https://github.com/yoshi-cow/study_LangChain/blob/main/02_make_synth_data_v2.ipynb" target="_blank" class="u-lnk-clr">　</a><a href="https://github.com/yoshi-cow/study_LangChain/blob/main/02_making_test_data.ipynb" target="_blank" class="u-lnk-clr">▶ テスト用データの合成</a></h3><h3><a href="https://github.com/yoshi-cow/study_LangChain/blob/main/03_study_LangSmith_offline_evaluation.ipynb" target="_blank" class="u-lnk-clr">　▶ オフライン評価</a></h3>
		</div>
	]]></content></entry><entry><title><![CDATA[CNN, TCN]]></title><link rel="alternate" href="https://study-storage.amebaownd.com/posts/55123061/"></link><id>https://study-storage.amebaownd.com/posts/55123061</id><summary><![CDATA[The structure of CNN　- Convolution Layer / Max Pooling / Padding / Stride and so on   ▶ explanation_notebookChannel in CNN   ▶ explanation_notebookDifference between Kernel and channel   ▶ explanation_notebookParameters of nn.Conv1d of PyTorch   ▶ explanation_notebookPredicting Energy Production by TCN   ▶ explanation_notebookAnalyzing codes of TCN class in Darts library   ▶ explanation_notebookOther sample codes of TCN - This sample code doesn't do left padding so data leakage occurs   ▶ explanation_notebook]]></summary><author><name>yooooshi</name></author><published>2024-08-29T10:47:14+00:00</published><updated>2024-08-31T04:28:04+00:00</updated><content type="html"><![CDATA[
		<div>
			<h2><b>The structure of CNN</b></h2><p><b>　-&nbsp;</b>Convolution Layer / Max Pooling / Padding / Stride and so on</p><p><b>&nbsp; &nbsp;<a href="https://github.com/yoshi-cow/study_pytorch_v1/blob/main/cnn_for_time_series/008_CNN.ipynb" class="u-lnk-clr">▶ explanation_notebook</a></b></p><p><br></p><h2><b>Channel in CNN</b></h2><p>&nbsp; &nbsp;<b><a href="https://github.com/yoshi-cow/study_pytorch_v1/blob/main/cnn_for_time_series/Channel_in%20_CNN.ipynb" class="u-lnk-clr">▶ explanation_notebook</a><br></b></p><p><br></p><h2><b>Difference between Kernel and channel</b></h2><p>&nbsp; &nbsp;<b><a href="https://github.com/yoshi-cow/study_pytorch_v1/blob/main/cnn_for_time_series/Difference_between_Kernel_and_channel.ipynb" class="u-lnk-clr">▶ explanation_notebook</a></b><br></p><p><br></p><h2><b>Parameters of nn.Conv1d of PyTorch</b></h2><p>&nbsp; &nbsp;<b><a href="https://github.com/yoshi-cow/study_pytorch_v1/blob/main/cnn_for_time_series/Prameters_of_Conv1d_function.ipynb" class="u-lnk-clr">▶ explanation_notebook</a></b><br></p><p><br></p><h2><b>Predicting Energy Production by TCN</b></h2><p>&nbsp; &nbsp;<b><a href="https://github.com/yoshi-cow/study_pytorch_v1/blob/main/cnn_for_time_series/Predicting_energy_production.ipynb" class="u-lnk-clr">▶ explanation_notebook</a></b></p><p><br></p><h2><b>Analyzing codes of TCN class in Darts library</b></h2><p>&nbsp; &nbsp;<b><a href="https://github.com/yoshi-cow/study_pytorch_v1/blob/main/cnn_for_time_series/analysis_of_TCN_of_darts.ipynb" class="u-lnk-clr">▶ explanation_notebook</a></b></p><p><br></p><h2><b>Other sample codes of TCN</b></h2><p>&nbsp;- This sample code doesn't do left padding so data leakage occurs</p><p>&nbsp; &nbsp;<b><a href="https://github.com/yoshi-cow/study_pytorch_v1/blob/main/cnn_for_time_series/Temporal_Convolutional_Networks.ipynb" class="u-lnk-clr">▶ explanation_notebook</a></b></p>
		</div>
	]]></content></entry><entry><title><![CDATA[Radom Seed & Initial value dependece]]></title><link rel="alternate" href="https://study-storage.amebaownd.com/posts/55120748/"></link><id>https://study-storage.amebaownd.com/posts/55120748</id><summary><![CDATA[Following answers are created by GPT1. Influence of Random Seed in PyTorchWhen you're running a PyTorch model for time series forecasting, the random seed is used to initialize the random numer generator, which impacts varios parts of your model training process.This includes:1. Weight Initialization: The initial weights of your neural network are randomly assigned. Different random seeds lead to different initial weights, which can result in different convergence paths and, consequenctly, different final models.2. Batch Sampling: If you're using stochastic gradient descent (SGD) or any variant, the order in which data batches are fed into the model can change with different random seeds. This can also lead to different model training dynamics.3. Dropout: If your model uses dropout, the specific neurons dropped during training are chosen randomly. Changing the random seed will change which neurons are dropped at each step.Because of these factors, even with the same dataset and model architecture, changing the random seed can lead to different model parameters and, thus, different results.How Popular Data Scientists Deal with Result Variability:1. Multiple Runs with Different Seeds: A common approach is to train the model multiple times using different random seeds and then average the results. This helps in estimating the expected performance of the model more robustly.2. Seed Fixation: To ensure reporducibility, data scientists often fix the random seed across the entire pipeline, including model initialization, data loading, and any other random processes.3. Cross-Validation: Instead of relying on a single train-test split, they use cross-validation to assess the model's performance. This helps in understanding how the model performance across different subsets of the data, which can reduce the variability due to random seed changes.4. Model Ensembling: By training multiple models with different random seeds and combining their predictions, they can create a more robust predictor that's less sensitive to any single model's random initialization.5. Reporting Variance: When presenting results, they often report not just the mean performance but alose the variance (or standard deviation) across different seeds. This provides a clearer picture of the model's stability.By understanding and controlling for the effects of random seeds, you can make your models more robust and your results more reliable.2. Initail Value Dependent ProblemThe "Initial value dependent problem" in Deep Learning refers to the sensitivity of a neural network's training process and final performance to the initial values of the model's parameters, especially the weights. This is particularly important because deep learning models are typically trained using iterative optimization methods like gradient descent, where the starting point (initial values of weights) can significantly influence the optimization path and the resulting model.Key Aspects of the Initial Value Dependent Problem:1. Convergence to Local Minima: Neural networks have highly non-convex loss landscapes with many local minima and saddle points. Depending on the initial weights, the optimization process might converge to a different local minimum. Some of these minima might be good (low loss and generalizez well), while others might be suboptimal.2. Tranining Dynamics: The trajectory taken during training, including how fast the model converges and whether it gets stuck in certain regions of the loss landscape, can vary based on the initial weights. Poor initialization can lead to slow convergence or even divergence.3. Symmetric Breaking: In some network architectures, especially those with layers having identical neurons (like in fully connected layers or convolutional layers), initializing all weights to the same value can cause symmetry issues. if all neurons starts with the same weights, they will receive the same gradient updates, resulting in them learning the same features, which limits the expressiveness of the model.4. Vanishing / Exploding Gradients: Certain initial values can exacerbate the vanishing or exploding gradient problem, especially in deeper networks. If weights are initialized too small, gradients can vanish, making it difficult for the network to learn. If initialized too large, gradients can explode, leading to unstable updates.Strategies to Mitigate Inital Value Dependent Problems:1. Careful Weight Initialization: Modern initialization techniques like Xavier (Glorot) initialization, He initialization, and others are designed to set the initial weights in a way that maintains a good balance of the variance of the inputs and outpus across layers, reducing the chances of vanishing / exploding gradients.2. Batch Normalization: This technique helps mitigate the effects of poor initializationby normalizing the inputs to each layer, which can stabilize and accelerate training.3. Adaptive Learning Rates: Optimizers like Adam, RMSprop, and others adjust learning rates dynamically during training, helping the model recover from poor initializations.4. Multiple Trials with Dfferent Seeds: As mentioned before, running the training process multiple times with different initial values and then averaging the results or choosing the best-performing model can reduce the dependency on any particular initialization.The initial value dependent problem highlights the importance of good practices in weight initialization and the need for robust optimization techniques to ensure that the  deep learning models perform well regardless of the initial values.3. The relationship between Initial value dependence and setting Random SeedThere is a direct relationship between the initial value dependent problem and the setting of the random seed in deep learning.Connection Between Inital Value Dependence and Random Seed:1. Weight Initialization: When a random seed is set in your code, it controls the random number generator that is responsible for initializaing the weights of the neural network. Dfferent random seeds will result in different initial weight values. Since the initial weights heavily influence the training process and the eventual model performance, changing the random seed can lead to variations in the outcome due to this initial value dependency.2. Reproducibility: Setting a random seed allows you to cotrol and reproduce the initial conditions of your model. This means that every time you run your training process with the same random seed, you should get the same sequence of random numbers, leading to the same weight initialization and other random processes (like dropout or data shuffling). This makes the experiments reproducible, which is crucial for debugging, tuning, and reporting results. 3. Addressing Initla Value Dependency: By experimenting with different random seeds, you can explore how sensitive your model is to initializze conditions. If your model's performance varies significantly with different seeds, it suggests a strong initial value dependency. This can be mitigated by using techniques like better weight initialization strategies, ensumbling, or simply averaging the results across multiple seeds.Summary of the Relationship:・Initial value dependence refers to the sensitivity of model performance to the starting weights, which are determined by random initialization.・Setting a random seed controls this initialization process and other stochastic elements in the model, allowing for reproducibility and enabling you to study the effects of different initial conditions on your model's performance.By understanding and managing the relationship between random seed settings and initial value dependence, you can make your deep learning models more robust and consistent.]]></summary><author><name>yooooshi</name></author><published>2024-08-28T12:05:47+00:00</published><updated>2024-08-29T06:17:33+00:00</updated><content type="html"><![CDATA[
		<div>
			<p>Following answers are created by GPT</p><h2><b>1. Influence of Random Seed in PyTorch</b></h2><p>When you're running a PyTorch model for time series forecasting, the random seed is used to initialize the random numer generator, which impacts varios parts of your model training process.</p><p>This includes:</p><p>1. <b>Weight Initialization</b>: The initial weights of your neural network are randomly assigned. Different random seeds lead to different initial weights, which can result in different convergence paths and, consequenctly, different final models.</p><p>2. <b>Batch Sampling</b>: If you're using stochastic gradient descent (SGD) or any variant, the order in which data batches are fed into the model can change with different random seeds. This can also lead to different model training dynamics.</p><p>3. <b>Dropout</b>: If your model uses dropout, the specific neurons dropped during training are chosen randomly. Changing the random seed will change which neurons are dropped at each step.</p><p><br></p><p>Because of these factors, even with the same dataset and model architecture, changing the random seed can lead to different model parameters and, thus, different results.</p><p><br></p><h3>How Popular Data Scientists Deal with Result Variability:</h3><p>1. <b>Multiple Runs with Different Seeds</b>: A common approach is to train the model multiple times using different random seeds and then average the results. This helps in estimating the expected performance of the model more robustly.</p><p>2. <b>Seed Fixation:</b>&nbsp;To ensure reporducibility, data scientists often fix the random seed across the entire pipeline, including model initialization, data loading, and any other random processes.</p><p>3. <b>Cross-Validation:</b>&nbsp;Instead of relying on a single train-test split, they use cross-validation to assess the model's performance. This helps in understanding how the model performance across different subsets of the data, which can reduce the variability due to random seed changes.</p><p>4. <b>Model Ensembling:</b>&nbsp;By training multiple models with different random seeds and combining their predictions, they can create a more robust predictor that's less sensitive to any single model's random initialization.</p><p>5. <b>Reporting Variance:</b>&nbsp;When presenting results, they often report not just the mean performance but alose the variance (or standard deviation) across different seeds. This provides a clearer picture of the model's stability.</p><p><br></p><p>By understanding and controlling for the effects of random seeds, you can make your models more robust and your results more reliable.</p><p><br></p><p><br></p><h2><b>2. Initail Value Dependent Problem</b></h2><p>The "Initial value dependent problem" in Deep Learning refers to the sensitivity of a neural network's training process and final performance to the initial values of the model's parameters, especially the weights. This is particularly important because deep learning models are typically trained using iterative optimization methods like gradient descent, where the starting point (initial values of weights) can significantly influence the optimization path and the resulting model.</p><p><br></p><h3>Key Aspects of the Initial Value Dependent Problem:</h3><p>1. <b>Convergence to Local Minima:</b>&nbsp;Neural networks have highly non-convex loss landscapes with many local minima and saddle points. Depending on the initial weights, the optimization process might converge to a different local minimum. Some of these minima might be good (low loss and generalizez well), while others might be suboptimal.</p><p>2. <b>Tranining Dynamics:</b>&nbsp;The trajectory taken during training, including how fast the model converges and whether it gets stuck in certain regions of the loss landscape, can vary based on the initial weights. Poor initialization can lead to slow convergence or even divergence.</p><p>3. <b>Symmetric Breaking:</b>&nbsp;In some network architectures, especially those with layers having identical neurons (like in fully connected layers or convolutional layers), initializing all weights to the same value can cause symmetry issues. if all neurons starts with the same weights, they will receive the same gradient updates, resulting in them learning the same features, which limits the expressiveness of the model.</p><p>4. <b>Vanishing / Exploding Gradients:</b>&nbsp;Certain initial values can exacerbate the vanishing or exploding gradient problem, especially in deeper networks. If weights are initialized too small, gradients can vanish, making it difficult for the network to learn. If initialized too large, gradients can explode, leading to unstable updates.</p><p><br></p><h3>Strategies to Mitigate Inital Value Dependent Problems:</h3><p>1. <b>Careful Weight Initialization:</b>&nbsp;Modern initialization techniques like Xavier (Glorot) initialization, He initialization, and others are designed to set the initial weights in a way that maintains a good balance of the variance of the inputs and outpus across layers, reducing the chances of vanishing / exploding gradients.</p><p>2. <b>Batch Normalization:</b>&nbsp;This technique helps mitigate the effects of poor initializationby normalizing the inputs to each layer, which can stabilize and accelerate training.</p><p>3. <b>Adaptive Learning Rates:</b>&nbsp;Optimizers like Adam, RMSprop, and others adjust learning rates dynamically during training, helping the model recover from poor initializations.</p><p>4. <b>Multiple Trials with Dfferent Seeds:</b>&nbsp;As mentioned before, running the training process multiple times with different initial values and then averaging the results or choosing the best-performing model can reduce the dependency on any particular initialization.</p><p><br></p><p>The initial value dependent problem highlights the importance of good practices in weight initialization and the need for robust optimization techniques to ensure that the&nbsp; deep learning models perform well regardless of the initial values.</p><p><br></p><p><br></p><h2><b>3. The relationship between Initial value dependence and setting Random Seed</b></h2><p>There is a direct relationship between the initial value dependent problem and the setting of the random seed in deep learning.</p><h3>Connection Between Inital Value Dependence and Random Seed:</h3><p>1. <b>Weight Initialization:</b>&nbsp;When a random seed is set in your code, it controls the random number generator that is responsible for initializaing the weights of the neural network. Dfferent random seeds will result in different initial weight values. Since the initial weights heavily influence the training process and the eventual model performance, changing the random seed can lead to variations in the outcome due to this initial value dependency.</p><p>2. <b>Reproducibility:</b>&nbsp;Setting a random seed allows you to cotrol and reproduce the initial conditions of your model. This means that every time you run your training process with the same random seed, you should get the same sequence of random numbers, leading to the same weight initialization and other random processes (like dropout or data shuffling). This makes the experiments reproducible, which is crucial for debugging, tuning, and reporting results.&nbsp;</p><p>3. <b>Addressing Initla Value Dependency:</b>&nbsp;By experimenting with different random seeds, you can explore how sensitive your model is to initializze conditions. If your model's performance varies significantly with different seeds, it suggests a strong initial value dependency. This can be mitigated by using techniques like better weight initialization strategies, ensumbling, or simply averaging the results across multiple seeds.</p><p><br></p><h3>Summary of the Relationship:</h3><p>・<b>Initial value dependence</b> refers to the sensitivity of model performance to the starting weights, which are determined by random initialization.</p><p>・<b>Setting a random seed</b> controls this initialization process and other stochastic elements in the model, allowing for reproducibility and enabling you to study the effects of different initial conditions on your model's performance.</p><p><br></p><p>By understanding and managing the relationship between random seed settings and initial value dependence, you can make your deep learning models more robust and consistent.</p><p><br></p><p><br></p><p><br></p><p><br></p><p><br></p><p><br></p><p><br></p><p><br></p><p><br></p><p><br></p><p><br></p><p><br></p>
		</div>
	]]></content></entry><entry><title><![CDATA[シーケンスデータでの、データの独立性について]]></title><link rel="alternate" href="https://study-storage.amebaownd.com/posts/55100500/"></link><id>https://study-storage.amebaownd.com/posts/55100500</id><summary><![CDATA[以下は、シニアデータサイエンティストとの会話で解らなかった点をgptに聞いた回答Question:現在、以下のような日次データがあります。・為替取引データ・1年の取引回数が255回なので、1年で255レコードある上記データで、sequence lengthが60日のLSTMモデルを作成しようとしている所、あるデータサイエンティストから次のように言われました。「sequence lengthが60日なので、独立したデータがあるのは1年に4日程度しかないなあ・・・」私には、この言葉の意味がよく解りません。このデータサイエンティストは何を言いたかったのか推測してください。Answer by GPT:このデータサイエンティストが言っていることを推測すると、LSTMモデルにおけるシーケンスの重複に関する問題を指摘している可能性が高いです。具体的にはsequence lengthが60日という設定でLSTMモデルを構築する場合、以下のようなデータの扱いになります。1. シーケンスの重複：LSTMモデルでは、例えば最初の60日のデータを使用して予測を行い、次にその次の日のデータを追加して再び60日分を使って予測を行います。この方法だと、1日分だけ新しいデータが追加され、残りの59日分は前のシーケンスと重複します。2. 独立したシーケンスの数：この考え方でいくと、完全に独立したデータシーケンス（すなわち、重複のないシーケンス）は、1年（255日）のデータに対して4つしか得られません。これは255日÷60日 ≈ 4.25と計算されます。つまり、独立したデータシーケンスを取得するには、255日間のデータを60日ずつ区切っていくと、最初の60日間、次の60日間、さらにその次の60日間、そして最後の75日間が残るため、実質的に4つの独立したシーケンスしか得られないということです。3. データの独立性の問題：データサイエンティストが指摘しているのは、重複したシーケンスが多くなると、LSTMモデルが同じパターンを何度も学習してしまう可能性があり、モデルの性能に影響を与えるという点です。実際には、過剰な重複はモデルが過学習しやすくなる原因にもなります。このため、「独立したデータがあるのは1年に4日程度しかない」という言葉は、重複するシーケンスが多いことを懸念していることを示していると思われます。データの独立性の問題とはデータの独立性の問題は、特に時系列データやLSTMなどのリカレントニューラルネットワーク(RNN)モデルを扱う際に重要な考慮事項です。この問題は、データサンプルがどれだけ「独立」しているか、つまり、あるサンプルが他のサンプルに影響を与えずに学習されるかどうかに関わります。1. データの独立性とは？データの独立性は、あるデータポイントやシーケンスが他のデータポイントやシーケンスと関連していないことを指します。具体的には、あるサンプルを使ってモデルを訓練しているとき、そのサンプルが他のサンプルとどれだけ異なり、独自の情報を提供しているかが重要です。2. 時系列データにおける独立性の問題時系列データでは、データポイントが時間軸に沿って連続しているため、自然と前後のデータポイントとの間に強い関連性が生まれます。たとえば、為替データの場合、今日の為替レートは昨日のレートと非常に関連しています。LSTMモデルは、データの時間的な依存関係を考慮して学習を行うため、この依存性を利用して予測を行います。しかし、問題は次のようなケースで生じます。・シーケンスの重複：前述のように、LSTMモデルにおいてsequence lengthを60日に設定すると、例えば1年分のデータに対して次のようなシーケンスが生成されます。　　・シーケンス1：日次データの1日目から60日目　　・シーケンス2：日次データの2日目から61日目　　・…と続きます。　この場合、シーケンス1とシーケンス2は59日分のデータが重複しています。　つまり、シーケンス1とシーケンス2の独立性が低くなります。・モデルの学習における影響：重複したデータが多くなると、モデルは似たようなパターンを何度も学習することになります。この結果、モデルは過学習に陥りやすくなります。過学習とは、モデルが訓練データに対して非常に良い成績を示す一方で、未知のデータ（テストデータ）に対する汎化性能が低下する現象です。3. データの独立性を確保する方法・サンプリングの工夫：シーケンスが重複しないように、データのサンプリングを工夫することが考えられます。例えば、シーケンスを1日ずつずらすのではなく、60日間隔でサンプリングすることで、独立したシーケンスを作成します。・データ拡張（Data Augmentation）：新たなデータを生成することで、独立性の高いデータセットを作ることも一つの方法です。時系列データの特性を保ちながら、微妙に異なるデータを作り出します。・異なる期間のデータを使用する：データを異なる期間で区切ってシーケンスを作成することで、異なる市場環境や条件下のシーケンスを学習させることができます。これにより、モデルがより汎用的なパターンを学習しやすくなります。4. 結論データの独立性は、LSTMモデルの学習において、モデルの汎化性能を維持するために重要な要素です。独立性の低いデータを使用すると、モデルが特定のパターンに過度に適応し、道のデータに対してうまく機能しなくなるリスクがあります。シーケンスの重複を避けるための工夫や、独立性の高いデータセットを作成する方法を検討することが重要です。sequence lengthについて時系列データを扱うモデルで「sequence length」の考え方が登場するのは、主にディープラーニング（特にリカレントニューラルネットワーク(RNN)、LSTM、GRU、Transformerなど）ですが、これはディープラーニングに限った概念ではありません。以下のように、他の手法でも似たような概念が存在します。1. 従来の統計的時系列モデル従来の統計的時系列モデルでも、過去のデータを使用する際に、どの程度の過去のデータを使うかを決めることが重要です。具体的な例を挙げると：・自己回帰モデル(ARモデル)：自己回帰(AR)モデルでは、現在の値を過去の一定期間（ラグ）の値の線形結合として表現します。ここでの「ラグ」の数は、ディープラーニングにおけるsequence lengthに相当するものと考えることができます。AR(1)モデルでは1つの過去の値を使いますが、AR(2)モデルでは2つの過去の値を使います。・移動平均モデル(MAモデル)：移動平均(MA)モデルでは、過去の誤差項の一定期間（ラグ）を使って現在の値を説明します。ここで使用するラグの数もsequence lengthに類似した概念です。・ARIMAモデル：ARIMA(自己回帰和分移動平均)モデルは、ARとMAの要素を組み合わせたモデルで、データのラグに基づいて予測を行います。2. フィーチャーエンジニアリングにおけるsequence length機械学習モデル（例えば、回帰モデルや決定木ベースのモデル）でも、過去のデータを特徴量として扱う際に、sequence lengthに相当する概念が表れます。例えば、株価の予測において、前日の株価だけでなく、前の7日間の株価を特徴量として使う場合、その7日間がsequence lengthに相当します。3. ディープラーニングモデルディープラーニングモデル、特にLSTMやGRUなどのRNN系モデルでは、sequence lengthが特に重要です。これらのモデルは、過去のデータの連続的な依存関係をモデル化するため、過去のデータの「長さ」や「範囲」を決定するsequence lengthが直接的にモデルの性能に影響を与えます。また、Transformerベースのモデルでも、入力シーケンスの長さを考慮する必要があります。例えば、Transformerモデルにおいても、入力シーケンスが長すぎると計算コストが増加し、短すぎると重要な情報が欠落する可能性があります。4. 結論「sequence length」という概念は、ディープラーニングにおいて特に顕著に扱われますが、これはディープラーニングに限定されたものではありません。時系列データを扱う様々なモデリング手法で、過去のデータをどの程度の範囲で使用するかを決定することが重要であり、それぞれの手法において「sequence length」に相当する考え方が存在します。データの独立性の問題を避けるには？データの独立性の問題とは、どのモデルを使っても完全に避けることは難しいですが、モデルやデータの取り扱い方によってその影響を最小限に抑えることが可能です。以下に、モデルごとの特性とデータの独立性に関連する問題について説明します。1. 統計的時系列モデル統計的時系列モデル（AR, MA, ARIMAなど）は、過去の値に基づいて予測を行います。これらのモデルは、データの依存性を前提にしているため、独立性の問題がある意味で組み込まれています。・依存性が前提：これらのモデルは、過去のデータとの相関や依存関係を明示的にモデル化しているため、独立性というよりは、依存関係のモデル化が目的です。・独立性の確保が難しい：このため、データが独立していないこと自体が問題になるわけではなく、むしろ依存性を正確にとらえることが重要です。2. ディープラーニングモデル（LSTM, GRU, Transformerなど）ディープラーニングモデルでは、特にLSTMやGRUのようなリカレントニューラルネットワーク(RNN)モデルは、過去のデータシーケンスから情報を学習し、それを未来の予測に活用します。・データの重複：これらのモデルは、シーケンスが重複することが多く、そのためデータの独立性が問題になることがあります。同じデータポイントが何度もモデルに入力されると、過学習のリスクが高まります。・データの拡張や工夫が必要：データの独立性を改善するために、データのサンプリング方法を工夫したり、データ拡張（data augmentation）技術を用いたりすることで、この問題を軽減できます。3. 伝統的な機械学習モデル決定木やランダムフォレスト、サポートベクターマシン(SVM)などの伝統的な機械学習モデルでは、時系列データを扱う場合、過去のデータポイントを特徴量として使用することがあります。・特徴量の選択に依存：どの過去のデータポイントを使用するか（例えば、過去1日、3日、7日のデータを使うなど）に依存しているため、データが独立していない場合、モデルの学習に影響を与える可能性があります。・シャッフルなどの工夫：データが独立していないことが問題となる場合、データをシャッフルしたり、適切に分割して学習データとテストデータに分けるなど、データの工夫が必要です。4. 結論データの独立性の問題は、時系列データを扱うすべてのモデルにおいてある程度避けられないものですが、モデルや手法に応じた適切なデータ処理や工夫によって、その影響を最小限に抑えることができます。ディープラーニングモデルでは特に顕著ですが、適切なサンプリング、データ拡張、モデル選択、パラメータ調整によって、データの依存性を考慮しつつも効果的な予測を行うことが可能です。]]></summary><author><name>yooooshi</name></author><published>2024-08-26T12:30:12+00:00</published><updated>2024-08-27T02:41:37+00:00</updated><content type="html"><![CDATA[
		<div>
			<p>以下は、シニアデータサイエンティストとの会話で解らなかった点をgptに聞いた回答</p><h2>Question:</h2><p>現在、以下のような日次データがあります。</p><p>・為替取引データ</p><p>・1年の取引回数が255回なので、1年で255レコードある</p><p>上記データで、sequence lengthが60日のLSTMモデルを作成しようとしている所、あるデータサイエンティストから次のように言われました。</p><p>「sequence lengthが60日なので、独立したデータがあるのは1年に4日程度しかないなあ・・・」</p><p>私には、この言葉の意味がよく解りません。このデータサイエンティストは何を言いたかったのか推測してください。</p><h2>Answer by GPT:</h2><p>このデータサイエンティストが言っていることを推測すると、LSTMモデルにおけるシーケンスの重複に関する問題を指摘している可能性が高いです。具体的にはsequence lengthが60日という設定でLSTMモデルを構築する場合、以下のようなデータの扱いになります。</p><h3>1. シーケンスの重複：</h3><p>LSTMモデルでは、例えば最初の60日のデータを使用して予測を行い、次にその次の日のデータを追加して再び60日分を使って予測を行います。この方法だと、1日分だけ新しいデータが追加され、残りの59日分は前のシーケンスと重複します。</p><h3>2. 独立したシーケンスの数：</h3><p>この考え方でいくと、完全に独立したデータシーケンス（すなわち、重複のないシーケンス）は、1年（255日）のデータに対して4つしか得られません。これは255日÷60日 ≈ 4.25と計算されます。つまり、独立したデータシーケンスを取得するには、255日間のデータを60日ずつ区切っていくと、最初の60日間、次の60日間、さらにその次の60日間、そして最後の75日間が残るため、実質的に4つの独立したシーケンスしか得られないということです。</p><h3>3. データの独立性の問題：</h3><p>データサイエンティストが指摘しているのは、重複したシーケンスが多くなると、LSTMモデルが同じパターンを何度も学習してしまう可能性があり、モデルの性能に影響を与えるという点です。実際には、過剰な重複はモデルが過学習しやすくなる原因にもなります。</p><p><br></p><p>このため、「独立したデータがあるのは1年に4日程度しかない」という言葉は、重複するシーケンスが多いことを懸念していることを示していると思われます。</p><p><br></p><h2><b>データの独立性の問題とは</b></h2><p>データの独立性の問題は、特に時系列データやLSTMなどのリカレントニューラルネットワーク(RNN)モデルを扱う際に重要な考慮事項です。この問題は、データサンプルがどれだけ「独立」しているか、つまり、あるサンプルが他のサンプルに影響を与えずに学習されるかどうかに関わります。</p><h3>1. データの独立性とは？</h3><p>データの独立性は、あるデータポイントやシーケンスが他のデータポイントやシーケンスと関連していないことを指します。具体的には、あるサンプルを使ってモデルを訓練しているとき、そのサンプルが他のサンプルとどれだけ異なり、<u>独自の情報を提供しているか</u>が重要です。</p><h3>2. 時系列データにおける独立性の問題</h3><p>時系列データでは、データポイントが時間軸に沿って連続しているため、自然と前後のデータポイントとの間に強い関連性が生まれます。たとえば、為替データの場合、今日の為替レートは昨日のレートと非常に関連しています。</p><p>LSTMモデルは、データの時間的な依存関係を考慮して学習を行うため、この依存性を利用して予測を行います。しかし、問題は次のようなケースで生じます。</p><p><b>・シーケンスの重複：</b>前述のように、LSTMモデルにおいてsequence lengthを60日に設定すると、例えば1年分のデータに対して次のようなシーケンスが生成されます。</p><p>　　・シーケンス1：日次データの1日目から60日目</p><p>　　・シーケンス2：日次データの2日目から61日目</p><p>　　・…と続きます。</p><p>　この場合、シーケンス1とシーケンス2は59日分のデータが重複しています。</p><p>　つまり、シーケンス1とシーケンス2の独立性が低くなります。</p><p>・<b>モデルの学習における影響：</b>重複したデータが多くなると、モデルは似たようなパターンを何度も学習することになります。この結果、モデルは過学習に陥りやすくなります。過学習とは、モデルが訓練データに対して非常に良い成績を示す一方で、未知のデータ（テストデータ）に対する汎化性能が低下する現象です。</p><h3>3. データの独立性を確保する方法</h3><p><b>・サンプリングの工夫：</b>シーケンスが重複しないように、データのサンプリングを工夫することが考えられます。例えば、シーケンスを1日ずつずらすのではなく、60日間隔でサンプリングすることで、独立したシーケンスを作成します。</p><p><b>・データ拡張（Data Augmentation）：</b>新たなデータを生成することで、独立性の高いデータセットを作ることも一つの方法です。時系列データの特性を保ちながら、微妙に異なるデータを作り出します。</p><p><b>・異なる期間のデータを使用する：</b>データを異なる期間で区切ってシーケンスを作成することで、異なる市場環境や条件下のシーケンスを学習させることができます。これにより、モデルがより汎用的なパターンを学習しやすくなります。</p><h3>4. 結論</h3><p>データの独立性は、LSTMモデルの学習において、モデルの汎化性能を維持するために重要な要素です。独立性の低いデータを使用すると、モデルが特定のパターンに過度に適応し、道のデータに対してうまく機能しなくなるリスクがあります。シーケンスの重複を避けるための工夫や、独立性の高いデータセットを作成する方法を検討することが重要です。</p><p><br></p><h2><b>sequence lengthについて</b></h2><p>時系列データを扱うモデルで「sequence length」の考え方が登場するのは、主にディープラーニング（特にリカレントニューラルネットワーク(RNN)、LSTM、GRU、Transformerなど）ですが、これはディープラーニングに限った概念ではありません。以下のように、他の手法でも似たような概念が存在します。</p><h3>1. 従来の統計的時系列モデル</h3><p>従来の統計的時系列モデルでも、過去のデータを使用する際に、どの程度の過去のデータを使うかを決めることが重要です。具体的な例を挙げると：</p><p><b>・自己回帰モデル(ARモデル)：</b>自己回帰(AR)モデルでは、現在の値を過去の一定期間（ラグ）の値の線形結合として表現します。ここでの「ラグ」の数は、ディープラーニングにおけるsequence lengthに相当するものと考えることができます。AR(1)モデルでは1つの過去の値を使いますが、AR(2)モデルでは2つの過去の値を使います。</p><p><b>・移動平均モデル(MAモデル)：</b>移動平均(MA)モデルでは、過去の誤差項の一定期間（ラグ）を使って現在の値を説明します。ここで使用するラグの数もsequence lengthに類似した概念です。</p><p><b>・ARIMAモデル：</b>ARIMA(自己回帰和分移動平均)モデルは、ARとMAの要素を組み合わせたモデルで、データのラグに基づいて予測を行います。</p><h3>2. フィーチャーエンジニアリングにおけるsequence length</h3><p>機械学習モデル（例えば、回帰モデルや決定木ベースのモデル）でも、過去のデータを特徴量として扱う際に、sequence lengthに相当する概念が表れます。例えば、株価の予測において、前日の株価だけでなく、前の7日間の株価を特徴量として使う場合、その7日間がsequence lengthに相当します。</p><h3>3. ディープラーニングモデル</h3><p>ディープラーニングモデル、特にLSTMやGRUなどのRNN系モデルでは、sequence lengthが特に重要です。これらのモデルは、過去のデータの連続的な依存関係をモデル化するため、過去のデータの「長さ」や「範囲」を決定するsequence lengthが直接的にモデルの性能に影響を与えます。</p><p>また、Transformerベースのモデルでも、入力シーケンスの長さを考慮する必要があります。例えば、Transformerモデルにおいても、入力シーケンスが長すぎると計算コストが増加し、短すぎると重要な情報が欠落する可能性があります。</p><h3>4. 結論</h3><p>「sequence length」という概念は、ディープラーニングにおいて特に顕著に扱われますが、これはディープラーニングに限定されたものではありません。時系列データを扱う様々なモデリング手法で、過去のデータをどの程度の範囲で使用するかを決定することが重要であり、それぞれの手法において「sequence length」に相当する考え方が存在します。</p><p><br></p><h2><b>データの独立性の問題を避けるには？</b></h2><p>データの独立性の問題とは、どのモデルを使っても完全に避けることは難しいですが、モデルやデータの取り扱い方によってその影響を最小限に抑えることが可能です。以下に、モデルごとの特性とデータの独立性に関連する問題について説明します。</p><h3>1. 統計的時系列モデル</h3><p>統計的時系列モデル（AR, MA, ARIMAなど）は、過去の値に基づいて予測を行います。これらのモデルは、データの依存性を前提にしているため、独立性の問題がある意味で組み込まれています。</p><p><b>・依存性が前提：</b>これらのモデルは、過去のデータとの相関や依存関係を明示的にモデル化しているため、独立性というよりは、依存関係のモデル化が目的です。</p><p><b>・独立性の確保が難しい：</b>このため、データが独立していないこと自体が問題になるわけではなく、むしろ<u>依存性を正確にとらえることが重要</u>です。</p><h3><b>2. ディープラーニングモデル（LSTM, GRU, Transformerなど）</b></h3><p>ディープラーニングモデルでは、特にLSTMやGRUのようなリカレントニューラルネットワーク(RNN)モデルは、過去のデータシーケンスから情報を学習し、それを未来の予測に活用します。</p><p><b>・データの重複：</b>これらのモデルは、シーケンスが重複することが多く、そのためデータの独立性が問題になることがあります。同じデータポイントが何度もモデルに入力されると、過学習のリスクが高まります。</p><p><b>・データの拡張や工夫が必要：</b>データの独立性を改善するために、データのサンプリング方法を工夫したり、データ拡張（data augmentation）技術を用いたりすることで、この問題を軽減できます。</p><h3>3. 伝統的な機械学習モデル</h3><p>決定木やランダムフォレスト、サポートベクターマシン(SVM)などの伝統的な機械学習モデルでは、時系列データを扱う場合、過去のデータポイントを特徴量として使用することがあります。</p><p><b>・特徴量の選択に依存：</b>どの過去のデータポイントを使用するか（例えば、過去1日、3日、7日のデータを使うなど）に依存しているため、データが独立していない場合、モデルの学習に影響を与える可能性があります。</p><p><b>・シャッフルなどの工夫：</b>データが独立していないことが問題となる場合、データをシャッフルしたり、適切に分割して学習データとテストデータに分けるなど、データの工夫が必要です。</p><h3>4. 結論</h3><p>データの独立性の問題は、時系列データを扱うすべてのモデルにおいてある程度避けられないものですが、モデルや手法に応じた適切なデータ処理や工夫によって、その影響を最小限に抑えることができます。ディープラーニングモデルでは特に顕著ですが、適切なサンプリング、データ拡張、モデル選択、パラメータ調整によって、データの依存性を考慮しつつも効果的な予測を行うことが可能です。</p><p><br></p><p><br></p><p><br></p><p><br></p><p><br></p><p><br></p><p><br></p><p><br></p><p><br></p>
		</div>
	]]></content></entry><entry><title><![CDATA[Transformer]]></title><link rel="alternate" href="https://study-storage.amebaownd.com/posts/55076529/"></link><id>https://study-storage.amebaownd.com/posts/55076529</id><summary><![CDATA[・Transformer概要      ▶︎ study notebook1              ・構造      ▶︎ study notebook2              ・PyTorchでの実装例・What are Embedding Layers      ▶︎ study notebook1・Time Series Data Encoding for Deep Learning      ▶︎ study notebook1・Transformer for Time Series      ▶︎ study notebook1               ・Transformer having features for  Time Series Forecasting      ▶︎ study notebook2               ・Positional Encodingの説明・Informer      ▶︎ study notebook1                ・Informerの基本構造]]></summary><author><name>yooooshi</name></author><published>2024-08-24T07:13:16+00:00</published><updated>2024-08-31T04:27:09+00:00</updated><content type="html"><![CDATA[
		<div>
			<h2><b>・Transformer概要</b></h2><h3><a href="https://github.com/yoshi-cow/study_pytorch_v1/blob/main/by_youtube2/010_intro_transformers.ipynb" target="_blank" class="u-lnk-clr">&nbsp; &nbsp; &nbsp; ▶︎ study notebook1</a></h3><p>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ・構造</p><h3><a href="https://github.com/yoshi-cow/study_pytorch_v1/blob/main/time_series_forecasting/18_Pytorch_Transformer_from_scratch.ipynb" target="_blank" class="u-lnk-clr">&nbsp; &nbsp; &nbsp; ▶︎ study notebook2</a></h3><p>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ・PyTorchでの実装例<br></p><p><br></p><h2><b>・What are Embedding Layers</b></h2><h3><a href="https://github.com/yoshi-cow/study_pytorch_v1/blob/main/by_youtube2/011_Embedding.ipynb" target="_blank" class="u-lnk-clr">&nbsp; &nbsp; &nbsp; ▶︎ study notebook1</a></h3><p><br></p><h2><b>・Time Series Data Encoding for Deep Learning</b></h2><h3><a href="https://github.com/yoshi-cow/study_pytorch_v1/blob/main/by_youtube2/015_Time_Series_Data_Encoding_for_Deep_Learning.ipynb" target="_blank" class="u-lnk-clr">&nbsp; &nbsp; &nbsp; ▶︎ study notebook1</a></h3><p><br></p><h2><b>・Transformer for Time Series</b></h2><h3><a href="https://github.com/yoshi-cow/study_pytorch_v1/blob/main/time_series_forecasting/11_gpt_Transformer_time_series_forecasting.ipynb" target="_blank" class="u-lnk-clr">&nbsp; &nbsp; &nbsp; ▶︎ study notebook1</a></h3><p>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;・Transformer having features for&nbsp; Time Series Forecasting</p><h3><a href="https://github.com/yoshi-cow/study_pytorch_v1/blob/main/time_series_forecasting/21_Transformer-Based_Time_Series%20with_PyTorch.ipynb" target="_blank" class="u-lnk-clr">&nbsp; &nbsp; &nbsp; ▶︎ study notebook2</a></h3><p>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;・Positional Encodingの説明</p><h2><b>・Informer</b></h2><h3><a href="https://github.com/yoshi-cow/study_Transformer/blob/main/Informer_explanation.ipynb" target="_blank" class="u-lnk-clr">&nbsp; &nbsp; &nbsp; ▶︎ study notebook1&nbsp;</a></h3><p>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;・Informerの基本構造<br></p>
		</div>
	]]></content></entry><entry><title><![CDATA[転移学習]]></title><link rel="alternate" href="https://study-storage.amebaownd.com/posts/55076490/"></link><id>https://study-storage.amebaownd.com/posts/55076490</id><summary><![CDATA[・転移学習とは        ▶︎ study notebook1・転移学習利用例        ▶︎ study notebook1]]></summary><author><name>yooooshi</name></author><published>2024-08-24T06:57:05+00:00</published><updated>2024-08-24T06:57:06+00:00</updated><content type="html"><![CDATA[
		<div>
			<h2><b>・転移学習とは</b></h2><h3><b><a href="https://github.com/yoshi-cow/study_pytorch_v1/blob/main/by_youtube_1/Y7_transfer_learning.ipynb" target="_blank" class="u-lnk-clr">&nbsp; &nbsp; &nbsp; &nbsp; ▶︎ study notebook1</a></b></h3><p><br></p><h2><b>・転移学習利用例</b></h2><h3><a href="https://github.com/yoshi-cow/study_pytorch_v1/blob/main/by_youtube2/009_Pretrained_Neural_Network.ipynb" target="_blank" class="u-lnk-clr">&nbsp; &nbsp; &nbsp; &nbsp; ▶︎ study notebook1</a></h3>
		</div>
	]]></content></entry><entry><title><![CDATA[Many-to-One and Many-to-Many tasks]]></title><link rel="alternate" href="https://study-storage.amebaownd.com/posts/55076390/"></link><id>https://study-storage.amebaownd.com/posts/55076390</id><summary><![CDATA[The example provided, both in the original and modified forms, represents a many-to-one task rather than a many-to-many task. Let's clarify the distinctions and why this example fits into the many-to-one category:Many-to-One Tasks:Definition:In many-to-one tasks, the model processes a sequence of inputs to make a single output prediction. These tasks are common in scenarios where you have temporal or sequential data, and you want to predict a single outcome based on the entire sequence. Examples include sentiment analysis from a sequence of text, stock price prediction based on a series of historical data points, or weather forecasting from a sequence of meteorological measurements.  Example Context:In the provided LSTM example, the task involves predicting a single stock price based on the past 7 days of data, where each day includes 5 features (high price, low price, volume, GDP, CPI). This is a classic example of a many-to-one task because you are using many inputs (the sequential data over 7 days) to predict a single output (the stock price at the end of the sequence).Many-to-Many Tasks:Definition: Many-to-many tasks involve mapping a sequence of inputs to a sequence of outputs. This category includes tasks where each time step in the input sequence is associated with a corresponding output. Examples of many-to-many tasks are machine translation (translating a sentence in one language to another, word by word or phrase by phrase) and video frame prediction (predicting future frames based on past frames).Differentiation: The key difference from the many-to-one setup is that in many-to-many, you are interested in the outputs at each time step, not just a summary prediction at the end. An LSTM model for a many-to-many task would be structured to return an output at each time step of the sequence.Summary of the Provided Example:Given the objective to predict a single stock price from a sequence of 7 days' data, the task aligns with the many-to-one framework:Input: A sequence of data points (each with 5 features) representing 7 consecutive days.Output: A single predicted value (the stock price) at the end of the sequence.The LSTM model is designed to process the input sequence through its recurrent layers, culminating in a single output prediction, which is why it's categorized as a many-to-one LSTM task in this context.]]></summary><author><name>yooooshi</name></author><published>2024-08-24T06:17:17+00:00</published><updated>2024-08-24T06:17:17+00:00</updated><content type="html"><![CDATA[
		<div>
			<p>The example provided, both in the original and modified forms, represents a <b>many-to-one</b> task rather than a many-to-many task. Let's clarify the distinctions and why this example fits into the many-to-one category:</p><p><br></p><h2><b>Many-to-One Tasks:</b></h2><h3>Definition:</h3><p>In many-to-one tasks, the model processes a sequence of inputs to make a single output prediction. These tasks are common in scenarios where you have temporal or sequential data, and you want to predict a single outcome based on the entire sequence. Examples include sentiment analysis from a sequence of text, stock price prediction based on a series of historical data points, or weather forecasting from a sequence of meteorological measurements.</p><p>  </p><h3>Example Context:</h3><p>In the provided LSTM example, the task involves predicting a single stock price based on the past 7 days of data, where each day includes 5 features (high price, low price, volume, GDP, CPI). This is a classic example of a many-to-one task because you are using many inputs (the sequential data over 7 days) to predict a single output (the stock price at the end of the sequence).</p><p><br></p><h2><b>Many-to-Many Tasks:</b></h2><h3>Definition:&nbsp;</h3><p>Many-to-many tasks involve mapping a sequence of inputs to a sequence of outputs. This category includes tasks where each time step in the input sequence is associated with a corresponding output. Examples of many-to-many tasks are machine translation (translating a sentence in one language to another, word by word or phrase by phrase) and video frame prediction (predicting future frames based on past frames).</p><h3>Differentiation:&nbsp;</h3><p>The key difference from the many-to-one setup is that in many-to-many, you are interested in the outputs at each time step, not just a summary prediction at the end. An LSTM model for a many-to-many task would be structured to return an output at each time step of the sequence.</p><p><br></p><h2><b>Summary of the Provided Example:</b></h2><p>Given the objective to predict a single stock price from a sequence of 7 days' data, the task aligns with the many-to-one framework:</p><h3>Input:&nbsp;</h3><p>A sequence of data points (each with 5 features) representing 7 consecutive days.</p><h3>Output:&nbsp;</h3><p>A single predicted value (the stock price) at the end of the sequence.</p><p><br></p><p>The LSTM model is designed to process the input sequence through its recurrent layers, culminating in a single output prediction, which is why it's categorized as a many-to-one LSTM task in this context.</p>
		</div>
	]]></content></entry><entry><title><![CDATA[RNN, LSTM]]></title><link rel="alternate" href="https://study-storage.amebaownd.com/posts/55076382/"></link><id>https://study-storage.amebaownd.com/posts/55076382</id><summary><![CDATA[・基本     ▶︎ study notebook1             ・Linear Regression とLogistic Regression     ▶︎ study notebook2             ・Feed-Forwad Neural Network・RNN     ▶︎ study notebook1・LSTM     ▶︎ study notebook1             ・LSTM基礎     ▶︎ study notebook2             ・LSTMの時系列データへの適用例1     ▶︎ study notebook3             ・LSTMの時系列データへの適用例2     ▶︎ study notebook4             ・LSTM with Features     ▶︎ study notebook5             ・LSTM Input and Output Structure     ▶︎ documents              ・Many-to-One and Many-to-Many tasks in LSTM     ▶︎ study notebook6             ・LSTMの時系列データへの適用例3]]></summary><author><name>yooooshi</name></author><published>2024-08-24T06:13:45+00:00</published><updated>2024-08-29T10:56:42+00:00</updated><content type="html"><![CDATA[
		<div>
			<h2>・基本</h2><h3><b><a href="https://github.com/yoshi-cow/study_pytorch_v1/blob/main/by_youtube_1/Y1_Linear_%26%20Logisted%20Regression.ipynb" target="_blank" class="u-lnk-clr">&nbsp; &nbsp; &nbsp;▶︎ study notebook1</a></b></h3><p>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;・Linear Regression とLogistic Regression</p><p><a href="https://github.com/yoshi-cow/study_pytorch_v1/blob/main/by_youtube_1/Y5_feed_forwad_Neural_Network.ipynb" target="_blank" class="u-lnk-clr" style="font-size: 16px; font-weight: 700; letter-spacing: 0.2px;">&nbsp; &nbsp; &nbsp;▶︎ study notebook2</a></p><p>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;・Feed-Forwad Neural Network<b><br></b></p><h2><b><br>・RNN</b></h2><h3><a href="https://github.com/yoshi-cow/study_pytorch_v1/blob/main/by_youtube_1/Y9_RNN.ipynb" target="_blank" class="u-lnk-clr">&nbsp; &nbsp; &nbsp;▶︎ study notebook1</a></h3><p><b><br></b></p><h2><b>・LSTM</b></h2><h3>&nbsp; &nbsp; &nbsp;<a href="https://github.com/yoshi-cow/study_pytorch_v1/blob/main/by_youtube_1/Y10_LSTM.ipynb" target="_blank" class="u-lnk-clr">▶︎ study notebook1</a></h3><p>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;・LSTM基礎<a href="https://github.com/yoshi-cow/study_pytorch_v1/blob/main/by_youtube2/016_LSTM_Based_Time_Series.ipynb" class="u-lnk-clr"><br></a></p><h3><a href="https://github.com/yoshi-cow/study_pytorch_v1/blob/main/by_youtube2/016_LSTM_Based_Time_Series.ipynb" target="_blank" class="u-lnk-clr">&nbsp; &nbsp; &nbsp;▶︎ study notebook2</a></h3><p>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;・LSTMの時系列データへの適用例1</p><h3><a href="https://github.com/yoshi-cow/study_pytorch_v1/blob/main/time_series_forecasting/14_LSTM-Based_Time_Series_with_PyTorch.ipynb" target="_blank" class="u-lnk-clr">&nbsp; &nbsp; &nbsp;▶︎ study notebook3</a></h3><p>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;・LSTMの時系列データへの適用例2</p><h3><a href="https://github.com/yoshi-cow/study_pytorch_v1/blob/main/time_series_forecasting/10_gpt_LSTM_time_series_forecasting.ipynb" target="_blank" class="u-lnk-clr">&nbsp; &nbsp; &nbsp;▶︎ study notebook4</a></h3><p>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;・LSTM with Features<a href="https://github.com/yoshi-cow/study_pytorch_v1/blob/main/time_series_forecasting/13_LSTM_Input%26Output_structure.ipynb" class="u-lnk-clr"><br></a></p><h3><a href="https://github.com/yoshi-cow/study_pytorch_v1/blob/main/time_series_forecasting/13_LSTM_Input%26Output_structure.ipynb" target="_blank" class="u-lnk-clr">&nbsp; &nbsp; &nbsp;▶︎ study notebook5</a></h3><p>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;・LSTM Input and Output Structure</p><h3><a href="https://study-storage.amebaownd.com/posts/55076390" target="_blank" class="u-lnk-clr">&nbsp; &nbsp; &nbsp;▶︎ documents</a></h3><p>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ・Many-to-One and Many-to-Many tasks in LSTM</p><h3><a href="https://github.com/yoshi-cow/study_pytorch_v1/blob/main/time_series_forecasting/26_stock_forecasting_by_LSTM.ipynb" target="_blank" class="u-lnk-clr">&nbsp; &nbsp; &nbsp;▶︎ study notebook6</a></h3><p>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;・LSTMの時系列データへの適用例3</p>
		</div>
	]]></content></entry><entry><title><![CDATA[Modeling関連]]></title><link rel="alternate" href="https://study-storage.amebaownd.com/posts/55076045/"></link><id>https://study-storage.amebaownd.com/posts/55076045</id><summary><![CDATA[・PyTorchにおけるShape操作      ▶︎ study notebook1　　　　・reshape, view, squeeze, transpose, permute      ▶︎ study notebook2　　　　・Unfoldについて      ▶︎ study notebook3　　　　・squeezeについて      ▶︎ study notebook4　　　　・次元を指定したsumについて・batchとmini batch      ▶︎ study notebook1・学習データの逐次更新(２年ごと更新など)と、全期間データの利用      ▶︎ study notebook1・Differentiable Function（back propagationを担保する変数操作）      ▶︎ study notebook1・Hyperparameterの種類とparameter tuning      ▶︎ study notebook1                ・parameterの種類      ▶︎ study notebook2                ・Bayesian parameter tuning・End-to-End Training PipelineとFine tuning      ▶︎ study notebook1・ カスタム損失関数の作成      ▶︎ study notebook1・Data Leakage      ▶︎ study notebook1・multiply tensors with different dimension      ▶︎ study notebook1・Normalization method      ▶︎ study notebook1                ・Normalization method of dividing by first record      ▶︎ study notebook2                ・Rolling Window Normalization・ Rolling Window Correlation      ▶︎ study notebook1・Output Feature Order      ▶︎ study notebook1・modelの再現性      ▶︎ study notebook1・train, validation, testへの分割      ▶︎ study notebook1・Random Seed & Initial Value Dependent Problem      ▶︎ 説明ページ ]]></summary><author><name>yooooshi</name></author><published>2024-08-24T03:39:50+00:00</published><updated>2024-08-29T06:20:34+00:00</updated><content type="html"><![CDATA[
		<div>
			<h2><b>・PyTorchにおけるShape操作</b></h2><h3><a href="https://github.com/yoshi-cow/study_pytorch_v1/blob/main/time_series_forecasting/04_changing_shape_methods.ipynb" target="_blank" class="u-lnk-clr">&nbsp; &nbsp; &nbsp; ▶︎ study notebook1</a></h3><p>　　　　・reshape, view, squeeze, transpose, permute</p><h3><a href="https://github.com/yoshi-cow/study_pytorch_v1/blob/main/time_series_forecasting/03_Change_Shape_of_Tensor_by_Unfold.ipynb" target="_blank" class="u-lnk-clr">&nbsp; &nbsp; &nbsp; ▶︎ study notebook2</a></h3><p>　　　　・Unfoldについて<b><a href="https://github.com/yoshi-cow/study_pytorch_v1/blob/main/time_series_forecasting/19_pytorch%E3%81%AEsqueeze%E3%81%AB%E3%81%A4%E3%81%84%E3%81%A6.ipynb" class="u-lnk-clr"><br></a></b></p><h3><a href="https://github.com/yoshi-cow/study_pytorch_v1/blob/main/time_series_forecasting/19_pytorch%E3%81%AEsqueeze%E3%81%AB%E3%81%A4%E3%81%84%E3%81%A6.ipynb" target="_blank" class="u-lnk-clr">&nbsp; &nbsp; &nbsp; ▶︎ study notebook3</a></h3><p>　　　　・squeezeについて<a href="https://github.com/yoshi-cow/study_pytorch_v1/blob/main/time_series_forecasting/28_Summalize_tesor.ipynb" class="u-lnk-clr"><br></a></p><h3><a href="https://github.com/yoshi-cow/study_pytorch_v1/blob/main/time_series_forecasting/28_Summalize_tesor.ipynb" target="_blank" class="u-lnk-clr">&nbsp; &nbsp; &nbsp; ▶︎ study notebook4</a></h3><p>　　　　・次元を指定したsumについて</p><p><br></p><h2><b>・batchとmini batch</b></h2><h3><b><a href="https://github.com/yoshi-cow/study_pytorch_v1/blob/main/time_series_forecasting/02_batch_and_minibatch.ipynb" target="_blank" class="u-lnk-clr">&nbsp; &nbsp; &nbsp; ▶︎ study notebook1</a></b></h3><p><br></p><h2><b>・学習データの逐次更新(２年ごと更新など)と、全期間データの利用</b></h2><h3><a href="https://github.com/yoshi-cow/study_pytorch_v1/blob/main/time_series_forecasting/01_About_Retraing_Model.ipynb" target="_blank" class="u-lnk-clr">&nbsp; &nbsp; &nbsp; ▶︎ study notebook1</a></h3><p><br></p><h2><b>・Differentiable Function（back propagationを担保する変数操作）</b></h2><h3><a href="https://github.com/yoshi-cow/study_pytorch_v1/blob/main/by_youtube_1/Y13_Differentiable_Function_and_grad_fn_attribute_in_PyTorch.ipynb" target="_blank" class="u-lnk-clr">&nbsp; &nbsp; &nbsp; ▶︎ study notebook1</a></h3><h2><b><br></b></h2><h2><b>・Hyperparameterの種類とparameter tuning</b></h2><h3><a href="https://github.com/yoshi-cow/study_pytorch_v1/blob/main/by_youtube2/013_Hyperparamters.ipynb" target="_blank" class="u-lnk-clr">&nbsp; &nbsp; &nbsp; ▶︎ study notebook1</a></h3><p>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ・parameterの種類</p><h3><a href="https://github.com/yoshi-cow/study_pytorch_v1/blob/main/by_youtube2/014_Bayesian_Hyperparameter_Optimization.ipynb" target="_blank" class="u-lnk-clr">&nbsp; &nbsp; &nbsp; ▶︎ study notebook2</a></h3><p>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ・Bayesian parameter tuning</p><p><br></p><h2><b>・End-to-End Training PipelineとFine tuning</b></h2><h3><a href="https://github.com/yoshi-cow/study_pytorch_v1/blob/main/time_series_forecasting/09_EndToEnd_vs_FineTunining.ipynb" target="_blank" class="u-lnk-clr">&nbsp; &nbsp; &nbsp; ▶︎ study notebook1</a></h3><p><br></p><h2><b>・ カスタム損失関数の作成</b></h2><h3><a href="https://github.com/yoshi-cow/study_pytorch_v1/blob/main/time_series_forecasting/05_custom_loss_function_in_PyTorch.ipynb" target="_blank" class="u-lnk-clr">&nbsp; &nbsp; &nbsp; ▶︎ study notebook1</a></h3><p><br></p><h2><b>・Data Leakage</b></h2><h3><a href="https://study-storage.amebaownd.com/posts/55076026" target="_blank" class="u-lnk-clr">&nbsp; &nbsp; &nbsp; ▶︎ study notebook1</a></h3><p><br></p><h2><b>・multiply tensors with different dimension</b></h2><h3><a href="https://github.com/yoshi-cow/study_pytorch_v1/blob/main/time_series_forecasting/15_multiply%26sum_different_dimension.ipynb" target="_blank" class="u-lnk-clr">&nbsp; &nbsp; &nbsp; ▶︎ study notebook1</a></h3><p><br></p><h2><b>・Normalization method</b></h2><h3><a href="https://github.com/yoshi-cow/study_pytorch_v1/blob/main/time_series_forecasting/16_Normalization_div_by_first_record.ipynb" target="_blank" class="u-lnk-clr">&nbsp; &nbsp; &nbsp; ▶︎ study notebook1</a></h3><p>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ・Normalization method of dividing by first record</p><h3><a href="https://github.com/yoshi-cow/study_pytorch_v1/blob/main/time_series_forecasting/30_Rolling_Window_Normalization.ipynb" target="_blank" class="u-lnk-clr">&nbsp; &nbsp; &nbsp; ▶︎ study notebook2</a></h3><p>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ・Rolling Window Normalization<br></p><p><br></p><h2><b>・ Rolling Window Correlation</b></h2><h3><a href="https://github.com/yoshi-cow/study_pytorch_v1/blob/main/time_series_forecasting/31_rolling_window_correlation.ipynb" target="_blank" class="u-lnk-clr">&nbsp; &nbsp; &nbsp; ▶︎ study notebook1</a></h3><p><br></p><h2><b>・Output Feature Order</b></h2><h3><a href="https://github.com/yoshi-cow/study_pytorch_v1/blob/main/time_series_forecasting/17_output_feature_order_in_DL.ipynb" target="_blank" class="u-lnk-clr">&nbsp; &nbsp; &nbsp; ▶︎ study notebook1</a></h3><p><br></p><h2><b>・modelの再現性</b></h2><h3><a href="https://github.com/yoshi-cow/study_pytorch_v1/blob/main/time_series_forecasting/20_reproducibility_method.ipynb" target="_blank" class="u-lnk-clr">&nbsp; &nbsp; &nbsp; ▶︎ study notebook1</a></h3><p><br></p><h2><b>・train, validation, testへの分割</b></h2><h3><a href="https://github.com/yoshi-cow/study_pytorch_v1/blob/main/time_series_forecasting/27_train_validation_test_in_PyTorch.ipynb" target="_blank" class="u-lnk-clr">&nbsp; &nbsp; &nbsp; ▶︎ study notebook1</a></h3><p><br></p><h2><b>・Random Seed &amp; Initial Value Dependent Problem</b></h2><p>&nbsp; &nbsp; &nbsp; <b><a href="https://study-storage.amebaownd.com/posts/55120748" class="u-lnk-clr">▶︎ 説明ページ</a></b>&nbsp;<br></p>
		</div>
	]]></content></entry><entry><title><![CDATA[Data Leakage]]></title><link rel="alternate" href="https://study-storage.amebaownd.com/posts/55076026/"></link><id>https://study-storage.amebaownd.com/posts/55076026</id><summary><![CDATA[Data leakage in NormalizationData leakage refers to a situation in a machine learning project where information from outside the training dataset is used to create the model. This can lead to overly optimistic performance estimates during training and validation, because the model has essentially been given access to data it wouldn't have in a real-world scenario, leading to poor performance on unseen data.In the context of feature normalization, data leakage can occur if you normalize your entire dataset (including both training and test data) together, before splitting it into training and test sets. The correct procedure is to split your data first and then normalize the training and test data separately.How to Avoid Data Leakage During Normalization1. Split Your Data First: Before any preprocessing, including normalization, split your dataset into training, validation, and test sets. This ensures that the preprocessing of the training data does not influence the preprocessing of the test data and vice versa.2. Fit the Scaler on Training Data Only: When normalizing (or standardizing) your features, you should fit your scaler (or normalization parameters) only on the training data. This means calculating the mean and standard deviation (for standard scaling) or the minimum and maximum values (for min-max normalization) using only the training data.3. Apply the Same Transformation to Test Data: After fitting the scaler on the training data, use the same parameters (mean, standard deviation, min, max, etc.) to transform the test data. This mimics the real-world scenario where the model is applied to new, unseen data, ensuring that the test data is scaled based on the distribution of the training data only.Example in PythonAssuming you are using `scikit-learn` for normalization, here is how you might properly normalize your data to avoid data leakage:```pythonfrom sklearn.model_selection import train_test_splitfrom sklearn.preprocessing import StandardScaler# Assume X is your feature matrix and y are your labelsX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)# Create a StandardScaler objectscaler = StandardScaler()# Fit on the training datascaler.fit(X_train)# Transform the training dataX_train_scaled = scaler.transform(X_train)# Transform the test data using the same scalerX_test_scaled = scaler.transform(X_test)```By following these steps, you can prevent data leakage during the normalization process, ensuring that your model's evaluation metrics accurately reflect its performance on truly unseen data.]]></summary><author><name>yooooshi</name></author><published>2024-08-24T03:30:56+00:00</published><updated>2024-08-24T05:12:02+00:00</updated><content type="html"><![CDATA[
		<div>
			<h2><h2><b>Data leakage in Normalization</b></h2><p>Data leakage refers to a situation in a machine learning project where information from outside the training dataset is used to create the model. This can lead to overly optimistic performance estimates during training and validation, because the model has essentially been given access to data it wouldn't have in a real-world scenario, leading to poor performance on unseen data.</p><p>In the context of feature normalization, data leakage can occur if you normalize your entire dataset (including both training and test data) together, before splitting it into training and test sets. The correct procedure is to split your data first and then normalize the training and test data separately.</p><p><br></p><h2>How to Avoid Data Leakage During Normalization</h2><h3>1. Split Your Data First:&nbsp;</h3><p>Before any preprocessing, including normalization, split your dataset into training, validation, and test sets. This ensures that the preprocessing of the training data does not influence the preprocessing of the test data and vice versa.</p><h3>2. Fit the Scaler on Training Data Only:&nbsp;</h3><p>When normalizing (or standardizing) your features, you should fit your scaler (or normalization parameters) only on the training data. This means calculating the mean and standard deviation (for standard scaling) or the minimum and maximum values (for min-max normalization) using only the training data.</p><h3>3. Apply the Same Transformation to Test Data:&nbsp;</h3><p>After fitting the scaler on the training data, use the same parameters (mean, standard deviation, min, max, etc.) to transform the test data. This mimics the real-world scenario where the model is applied to new, unseen data, ensuring that the test data is scaled based on the distribution of the training data only.</p><p><br></p><h2><b>Example in Python</b></h2><p>Assuming you are using `scikit-learn` for normalization, here is how you might properly normalize your data to avoid data leakage:</p><p>```python</p><p>from sklearn.model_selection import train_test_split</p><p>from sklearn.preprocessing import StandardScaler</p><p># Assume X is your feature matrix and y are your labels</p><p>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)</p><p># Create a StandardScaler object</p><p>scaler = StandardScaler()</p><p># Fit on the training data</p><p>scaler.fit(X_train)</p><p># Transform the training data</p><p>X_train_scaled = scaler.transform(X_train)</p><p># Transform the test data using the same scaler</p><p>X_test_scaled = scaler.transform(X_test)</p><p>```</p><p>By following these steps, you can prevent data leakage during the normalization process, ensuring that your model's evaluation metrics accurately reflect its performance on truly unseen data.</p></h2>
		</div>
	]]></content></entry><entry><title><![CDATA[Pytorch基本]]></title><link rel="alternate" href="https://study-storage.amebaownd.com/posts/55075956/"></link><id>https://study-storage.amebaownd.com/posts/55075956</id><summary><![CDATA[・DatasetとDataLoader      ▶︎ study_notebook1      ▶︎ study_notebook2・ SoftmaxとCross Entropy      ▶︎ study_notebook1・ Activation Function      ▶︎ study_notebook1・ Saving and Loading model      ▶︎ study_notebook1      ▶︎ study_notebook2・ Adjust Learning Rate      ▶︎ study_notebook1      ▶︎ study_notebook2      ▶︎ study_notebook3・ Early Stopping      ▶︎ study_notebook1      ▶︎ study_notebook2・ ClassとSequenceの利用      ▶︎ study_notebook1・ Dropout Regularization      ▶︎ study_notebook1・ K-Fold Cross Validation      ▶︎ study_notebook1・ torch.compile()について      ▶︎ study_notebook1・ Batch Normalization      ▶︎ study_notebook1・ モデル構築フロー      ▶︎ study_notebook1・ PyTorch Lightning      ▶︎ study_notebook1             ・Lightningへの書き換え方法説明1      ▶︎ study_notebook2             ・How to use PyTorch Lightning DataModule      ▶︎ study_notebook3             ・Lightningへの書き換え方法説明2]]></summary><author><name>yooooshi</name></author><published>2024-08-24T03:03:57+00:00</published><updated>2024-08-24T06:27:32+00:00</updated><content type="html"><![CDATA[
		<div>
			<h2><b>・DatasetとDataLoader</b></h2><h3>&nbsp; &nbsp; &nbsp; <b><a href="https://github.com/yoshi-cow/study_pytorch_v1/blob/main/by_youtube_1/Y2_Dataset_DataLoader.ipynb" target="_blank" class="u-lnk-clr">▶︎ study_notebook1</a></b></h3><h3><a href="https://github.com/yoshi-cow/study_pytorch_v1/blob/main/time_series_forecasting/07_Dataset%26DataLoader_class_in_PyTorch.ipynb" class="u-lnk-clr">&nbsp; &nbsp; &nbsp; <b>▶︎ study_notebook2</b></a></h3><p><br></p><h2><b>・ SoftmaxとCross Entropy</b></h2><h3>&nbsp; &nbsp; &nbsp; <a href="https://github.com/yoshi-cow/study_pytorch_v1/blob/main/by_youtube_1/Y3_Softmax_CrossEntropy.ipynb" target="_blank" class="u-lnk-clr">▶︎ study_notebook1</a></h3><p><br></p><h2><b>・ Activation Function</b></h2><h3><a href="https://github.com/yoshi-cow/study_pytorch_v1/blob/main/by_youtube_1/Y4_activation_function.ipynb" target="_blank" class="u-lnk-clr">&nbsp; &nbsp; &nbsp; ▶︎ study_notebook1</a></h3><p><br></p><h2><b>・ Saving and Loading model</b></h2><h3><a href="https://github.com/yoshi-cow/study_pytorch_v1/blob/main/by_youtube_1/Y8_save_and_load_model.ipynb" target="_blank" class="u-lnk-clr">&nbsp; &nbsp; &nbsp; ▶︎ study_notebook1</a></h3><h3><a href="https://github.com/yoshi-cow/study_pytorch_v1/blob/main/time_series_forecasting/29_Save_and_Load_trained_Model.ipynb" target="_blank" class="u-lnk-clr">&nbsp; &nbsp; &nbsp; ▶︎ study_notebook2</a></h3><p><br></p><h2><b>・ Adjust Learning Rate</b></h2><h3><a href="https://github.com/yoshi-cow/study_pytorch_v1/blob/main/by_youtube_1/Y12_Adjust_Learning_Rate.ipynb" target="_blank" class="u-lnk-clr">&nbsp; &nbsp; &nbsp; ▶︎ study_notebook1</a></h3><h3><a href="https://github.com/yoshi-cow/study_pytorch_v1/blob/main/by_youtube2/004_Learning_Rate_Schedules.ipynb" target="_blank" class="u-lnk-clr">&nbsp; &nbsp; &nbsp; ▶︎ study_notebook2</a></h3><h3><a href="https://github.com/yoshi-cow/study_pytorch_v1/blob/main/time_series_forecasting/12_Learning_rate_scheduler.ipynb" target="_blank" class="u-lnk-clr">&nbsp; &nbsp; &nbsp; ▶︎ study_notebook3</a></h3><p><br></p><h2><b>・ Early Stopping</b></h2><h3><a href="https://github.com/yoshi-cow/study_pytorch_v1/blob/main/by_youtube2/001_Early_Stopping.ipynb" target="_blank" class="u-lnk-clr">&nbsp; &nbsp; &nbsp; ▶︎ study_notebook1</a></h3><h3><a href="https://github.com/yoshi-cow/study_pytorch_v1/blob/main/time_series_forecasting/08_Early_Stopping_during_learning.ipynb" target="_blank" class="u-lnk-clr">&nbsp; &nbsp; &nbsp; ▶︎ study_notebook2</a></h3><p><br></p><h2><b>・ ClassとSequenceの利用</b></h2><h3><a href="https://github.com/yoshi-cow/study_pytorch_v1/blob/main/by_youtube2/002_Class_or_Sequence.ipynb" target="_blank" class="u-lnk-clr">&nbsp; &nbsp; &nbsp; ▶︎ study_notebook1</a></h3><p><br></p><h2><b>・&nbsp;Dropout Regularization</b></h2><h3><a href="https://github.com/yoshi-cow/study_pytorch_v1/blob/main/by_youtube2/005_Dropout_Regularization.ipynb" target="_blank" class="u-lnk-clr">&nbsp; &nbsp; &nbsp; ▶︎ study_notebook1</a></h3><p><br></p><h2><b>・&nbsp;K-Fold Cross Validation</b></h2><h3><a href="https://github.com/yoshi-cow/study_pytorch_v1/blob/main/by_youtube2/003_K-Fold_Cross_Validation.ipynb" target="_blank" class="u-lnk-clr">&nbsp; &nbsp; &nbsp; ▶︎ study_notebook1</a></h3><p><br></p><h2><b>・&nbsp;torch.compile()について</b></h2><h3><a href="https://github.com/yoshi-cow/study_pytorch_v1/blob/main/by_youtube2/005%E8%A3%9C_torch_compile%E3%81%AB%E3%81%A4%E3%81%84%E3%81%A6.ipynb" target="_blank" class="u-lnk-clr">&nbsp; &nbsp; &nbsp; ▶︎ study_notebook1</a></h3><p><br></p><h2><b>・&nbsp;Batch Normalization</b></h2><h3><a href="https://github.com/yoshi-cow/study_pytorch_v1/blob/main/by_youtube2/006_Batch_Normalization.ipynb" target="_blank" class="u-lnk-clr">&nbsp; &nbsp; &nbsp; ▶︎ study_notebook1</a></h3><p><br></p><h2><b>・ モデル構築フロー</b></h2><h3><a href="https://qiita.com/yooooshiii/items/dc281e8d70caf4b0d084" target="_blank" class="u-lnk-clr">&nbsp; &nbsp; &nbsp; ▶︎ study_notebook1</a></h3><p><br></p><h2><b>・ PyTorch Lightning</b></h2><h3><a href="https://qiita.com/yooooshiii/items/b18b09381453c7bf657c" target="_blank" class="u-lnk-clr">&nbsp; &nbsp; &nbsp; ▶︎ study_notebook1</a></h3><p>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;・Lightningへの書き換え方法説明1</p><h3><a href="https://github.com/yoshi-cow/study_pytorch_v1/blob/main/by_youtube_1/How_to_use_Lightning_DataModule.ipynb" target="_blank" class="u-lnk-clr">&nbsp; &nbsp; &nbsp; ▶︎ study_notebook2</a></h3><p>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;・How to use PyTorch Lightning DataModule</p><h3><a href="https://github.com/yoshi-cow/study_pytorch_v1/blob/main/by_youtube_1/Y11_PyTorch_Lightning.ipynb" target="_blank" class="u-lnk-clr">&nbsp; &nbsp; &nbsp; ▶︎ study_notebook3</a></h3><p>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;・Lightningへの書き換え方法説明2</p>
		</div>
	]]></content></entry><entry><title><![CDATA[Compare Machine Learning Model and Deep Learning Model for Time Series]]></title><link rel="alternate" href="https://study-storage.amebaownd.com/posts/55075760/"></link><id>https://study-storage.amebaownd.com/posts/55075760</id><summary><![CDATA[These answers are made by GPT.Traditional Machine Learning Models:Pros:・Interpretability: Traditional models like linear regression or decision trees are generally easier to interpret. You can understand how each variable contributes to the final prediction.・Efficiency: They often require less training data and computational power compared to Deep Learning models.・Good for linear relationships: They excel at capturing linear relationships between variables.Cons:・Limited complexity: They might struggle to capture complex non-linear relationships between variables.・Feature engineering: Often require manual feature engineering to extract relevant information from the data, which can be time-consuming and domain-specific.Deep Learning Models (Transformers):Pros:・Captures complex relationships: Transformers can learn and capture intricate non-linear relationships between variables, even if they're not explicitly defined.・Automatic feature learning: They automatically learn features from the data, potentially reducing the need for manual feature engineering.Cons:・Black box nature: Understanding how a Transformer model arrives at a prediction can be challenging. This lack of interpretability might be a drawback in some cases.・Data hungry: Transformers often require large amounts of high-quality training data to perform well. With limited data, they might underperform compared to simpler models.・Computational cost: Training Transformers can be computationally expensive, especially for large datasets.Choosing the Right Model:If the relationships are likely linear and interpretability is crucial, a traditional model might be a good choice.If the relationships are complex and interpretability is less of a concern, a Transformer model could be a better option, especially if you have a large amount of training data.Here's an additional tip: You can consider using a hybrid approach. Combine a traditional model's interpretability with a Transformer's ability to capture complex relationships. For example, use a Transformer for feature extraction and then feed those features into a traditional model for prediction.Ultimately, the best way to decide is to experiment with both types of models on your specific data and see which one performs better for your task.]]></summary><author><name>yooooshi</name></author><published>2024-08-24T01:38:06+00:00</published><updated>2024-08-29T10:31:43+00:00</updated><content type="html"><![CDATA[
		<div>
			<p>These answers are made by GPT.</p><p><br></p><h2><b>Traditional Machine Learning Models:</b></h2><p><b>Pros:</b></p><p>・<b>Interpretability</b>: Traditional models like linear regression or decision trees are generally easier to interpret. You can understand how each variable contributes to the final prediction.</p><p>・<b>Efficiency</b>: They often require less training data and computational power compared to Deep Learning models.</p><p>・<b>Good for linear relationships</b>: They excel at capturing linear relationships between variables.</p><p><b>Cons:</b></p><p>・<b>Limited complexity</b>: They might struggle to capture complex non-linear relationships between variables.</p><p>・<b>Feature engineering</b>: Often require manual feature engineering to extract relevant information from the data, which can be time-consuming and domain-specific.</p><p><br></p><h2><b>Deep Learning Models (Transformers):</b></h2><p><b>Pros:</b></p><p>・<b>Captures complex relationships</b>: Transformers can learn and capture intricate non-linear relationships between variables, even if they're not explicitly defined.</p><p>・<b>Automatic feature learning</b>: They automatically learn features from the data, potentially reducing the need for manual feature engineering.</p><p><b>Cons:</b></p><p>・<b>Black box nature</b>: Understanding how a Transformer model arrives at a prediction can be challenging. This lack of interpretability might be a drawback in some cases.</p><p>・<b>Data hungry</b>: Transformers often require large amounts of high-quality training data to perform well. With limited data, they might underperform compared to simpler models.</p><p>・<b>Computational cost</b>: Training Transformers can be computationally expensive, especially for large datasets.</p><p><br></p><h2><b>Choosing the Right Model:</b></h2><p>If the relationships are likely linear and interpretability is crucial, a traditional model might be a good choice.</p><p>If the relationships are complex and interpretability is less of a concern, a Transformer model could be a better option, especially if you have a large amount of training data.</p><p>Here's an additional tip: You can consider using a hybrid approach. Combine a traditional model's interpretability with a Transformer's ability to capture complex relationships. For example, use a Transformer for feature extraction and then feed those features into a traditional model for prediction.</p><p>Ultimately, the best way to decide is to experiment with both types of models on your specific data and see which one performs better for your task.</p>
		</div>
	]]></content></entry><entry><title><![CDATA[正準相関分析(Canonical Correlation Analysis)]]></title><link rel="alternate" href="https://study-storage.amebaownd.com/posts/27995102/"></link><id>https://study-storage.amebaownd.com/posts/27995102</id><summary><![CDATA[以下にpythonコード記載https://yoshi-cow.github.io/statistics.github.io/canonical_correlation_analysis.html]]></summary><author><name>yooooshi</name></author><published>2021-12-22T12:47:58+00:00</published><updated>2021-12-22T12:47:58+00:00</updated><content type="html"><![CDATA[
		<div>
			<p>以下にpythonコード記載</p><p><a href="https://yoshi-cow.github.io/statistics.github.io/canonical_correlation_analysis.html" target="_blank" class="u-lnk-clr"><u>https://yoshi-cow.github.io/statistics.github.io/canonical_correlation_analysis.html</u></a><br></p>
		</div>
	]]></content></entry><entry><title><![CDATA[線形回帰式でのカテゴリ変数使用時の注意点]]></title><link rel="alternate" href="https://study-storage.amebaownd.com/posts/24823631/"></link><link rel="enclosure" type="image/png" href="https://cdn.amebaowndme.com/madrid-prd/madrid-web/images/sites/635143/56d924e407da9d38ec9fb736dd75df42_5399a4ba8020a3c41406d71f18c5cef5.png"></link><id>https://study-storage.amebaownd.com/posts/24823631</id><summary><![CDATA[ランク落ち（多重共線性）最小二乗法でのパラメータ推定は、　　α = (X・t_X)_(-1) ・t_X・Y 　（X：行列、t_X：Xの 転置行列、(X・t_X)_(-1)：(X・t_X)の逆行列、Y：行列）で行うが、データ間に相関があるとランク落ちが発生し、(X・tX)に逆行列が無くなるので、αが求められなくなる。なので、例えば、性別を"man"列、と"woman"列で２つ用意し、それぞれ0/1で表すと、man列とwoman列で相関あるので、ランク落ちが発生する。なので、カテゴリ変数を数値化するときは、man列だけとかにする。（利用する機械学習モデルに正則化項があれば、相関消えるので問題ないが、時系列の統計モデル(ARモデル等)には、正則化項がないので注意！）正則化の例・リッジ回帰　　　α = (X・t_X + λ・I)_(-1) ・t_X・Y 　（X：行列、t_X：Xの 転置行列、(X・t_X)_(-1)：(X・t_X)の逆行列、Y：行列、 I：単位行列） 正則化項として「λ・I」を足すことで、ランク落ちをなくしている。以下の例だと、X・t_Xは、逆行列が存在しないため、αが求められないが、正則化項として λ・Iを加えていることで、ランク落ちが無くなり、αが求められる形に変わった。]]></summary><author><name>yooooshi</name></author><published>2021-12-04T04:51:47+00:00</published><updated>2021-12-04T04:54:43+00:00</updated><content type="html"><![CDATA[
		<div>
			<h2>ランク落ち（多重共線性）</h2><p>最小二乗法でのパラメータ推定は、</p><p>　　<b>α =&nbsp;(X・t_X)_(-1) ・t_X・Y</b></p><p>&nbsp;　（X：行列、t_X：Xの 転置行列、(X・t_X)_(-1)：(X・t_X)の逆行列、Y：行列）</p><p>で行うが、データ間に相関があるとランク落ちが発生し、(X・tX)に逆行列が無くなるので、αが求められなくなる。</p><p>なので、例えば、性別を"man"列、と"woman"列で２つ用意し、それぞれ0/1で表すと、man列とwoman列で相関あるので、ランク落ちが発生する。なので、カテゴリ変数を数値化するときは、man列だけとかにする。（利用する機械学習モデルに正則化項があれば、相関消えるので問題ないが、時系列の統計モデル(ARモデル等)には、正則化項がないので注意！）</p><p><br></p><h2>正則化の例</h2><p><b>・リッジ回帰</b></p><p>　　　<b>α = (X・t_X + λ・I)_(-1) ・t_X・Y</b></p><p> 　（X：行列、t_X：Xの 転置行列、(X・t_X)_(-1)：(X・t_X)の逆行列、Y：行列、 I：単位行列）</p><p>&nbsp;正則化項として「<b>λ・</b>I」を足すことで、ランク落ちをなくしている。</p><p>以下の例だと、X・t_Xは、逆行列が存在しないため、αが求められないが、正則化項として λ・Iを加えていることで、ランク落ちが無くなり、αが求められる形に変わった。</p>
		</div>
	
		<div>
			<img src="https://cdn.amebaowndme.com/madrid-prd/madrid-web/images/sites/635143/56d924e407da9d38ec9fb736dd75df42_5399a4ba8020a3c41406d71f18c5cef5.png?width=960" width="100%">
		</div>
		

		<div>
			<p>上は、行列式も0になり逆行列が無いが、下のようにλ・Iを加えることで、ランク落ちが無くなり、行列式も0ではなくなり、逆行列が存在するように変わった。</p>
		</div>
	
		<div>
			<img src="https://cdn.amebaowndme.com/madrid-prd/madrid-web/images/sites/635143/999784834bf451ab397d4d1d8e1978f0_bdfa4b5a68f71aa95ac8e538f439e0a8.png?width=960" width="100%">
		</div>
		
]]></content></entry><entry><title><![CDATA[VARモデル]]></title><link rel="alternate" href="https://study-storage.amebaownd.com/posts/23344665/"></link><link rel="enclosure" type="image/png" href="https://cdn.amebaowndme.com/madrid-prd/madrid-web/images/sites/635143/bf8468a7d5923068dd75fbcd9ef9c808_3a73e6875cc34116141a9ee1dec34105.png"></link><id>https://study-storage.amebaownd.com/posts/23344665</id><summary><![CDATA[VARモデルとはベクトル自己回帰モデル(VAR model： vector autoregressive model)は、ARモデルをベクトルに一般化したもの。(ARなので、データは定常性が前提)例えば、個人消費と個人収入の指標という２つの時系列データがあった場合、以下のようにお互いに影響しあっていると考えることができる。消費が増えた後に（お店などが繁盛するため）収入が増える収入が増えた後に（使えるお金が増えたので）消費が増えるこのような状況をVARによりモデル化できる。要は、時系列データが互いに影響を及ぼしあっているのを表現した時系列モデルがVARモデル。VARモデルの構造例）２変量のVAR(1)モデル]]></summary><author><name>yooooshi</name></author><published>2021-11-08T12:54:16+00:00</published><updated>2021-11-10T12:37:10+00:00</updated><content type="html"><![CDATA[
		<div>
			<h2><b>VARモデルとは</b></h2><p>ベクトル自己回帰モデル(VAR model： vector autoregressive model)は、ARモデルをベクトルに一般化したもの。(ARなので、<b>データは定常性が前提</b>)</p><p>例えば、個人消費と個人収入の指標という２つの時系列データがあった場合、以下のようにお互いに影響しあっていると考えることができる。</p><ul><li>消費が増えた後に（お店などが繁盛するため）収入が増える</li><li>収入が増えた後に（使えるお金が増えたので）消費が増える</li></ul><p>このような状況をVARによりモデル化できる。</p><p>要は、時系列データが互いに影響を及ぼしあっているのを表現した時系列モデルがVARモデル。</p><p><br></p><h2><b>VARモデルの構造</b></h2><p>例）２変量のVAR(1)モデル</p>
		</div>
	
		<div>
			<img src="https://cdn.amebaowndme.com/madrid-prd/madrid-web/images/sites/635143/bf8468a7d5923068dd75fbcd9ef9c808_3a73e6875cc34116141a9ee1dec34105.png?width=960" width="100%">
		</div>
		

		<div>
			<p>イメージにすると</p><p>　2001年の消費 = c1 + Φ11 * 2000年の消費 + Φ12 * 2000年の収入 + ノイズ</p><p>　2001年の収入 =&nbsp;c2 + Φ21 * 2000年の消費 + Φ22 * 2000年の収入 + ノイズ</p><p>消費・収入ともに「過去の消費と、過去の収入」という同じ説明変数が使われている。</p><p>かく乱項ε1t と ε2tはホワイトノイズで、過去の自身のかく乱項と相関を持たない。しかし、同時点のかく乱項同士は相関を持っていてもかまわない。</p><p><br></p><h3><b>statsmodelsによる例</b></h3><p><a href="https://yoshi-cow.github.io/statistics.github.io/VAR_model.html" target="_blank" class="u-lnk-clr"><u>リンクのコード参照</u></a></p><p><br></p><p><br></p><h2><b>Granger因果性検定</b></h2><p>ある変数(群)が他の変数(群)の予測の向上に役立つかどうかを判定する手法</p><p><br></p><p>(1) 2001年の収入 = c2 + Φ21 * 2000年の消費 + Φ22 * 2000年の収入 + ノイズ①</p><p>(2) 2001年の収入 = c2 +&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Φ22 * 2000年の収入 + ノイズ②<br></p><p>ノイズ①が「相手のデータも使った時の予測残差」</p><p>ノイズ②が「相手がいない時の予測残差」</p><p>この２つの予測残差の残差平方和の大小を比較して「相手のデータを使うことで、予測残差が有意に減少したか」を検定する。</p><ul><li>帰無仮説：予測残差は減少しない</li><li>対立仮説：予測残差は減少する -&gt; Grangerの因果があるとみなせる</li></ul><p><b><i>※ 定常データにしか適用できないので注意！</i></b></p><p><b><i><br></i></b></p><h3><b><i>コード例</i></b></h3><p><i><a href="https://yoshi-cow.github.io/statistics.github.io/granger.html" target="_blank" class="u-lnk-clr" style=""><u>リンクのコード参照</u></a></i></p><p><br></p><p><br></p><p><br></p><p><br></p><p><br></p>
		</div>
	]]></content></entry><entry><title><![CDATA[見せかけの回帰と対策・共和分]]></title><link rel="alternate" href="https://study-storage.amebaownd.com/posts/23103354/"></link><link rel="enclosure" type="image/png" href="https://cdn.amebaowndme.com/madrid-prd/madrid-web/images/sites/635143/3351304ca9a5ce4730f660533a7e5e55_83387220a2b7ff99aa3f03964efe1994.png"></link><id>https://study-storage.amebaownd.com/posts/23103354</id><summary><![CDATA[「時系列分析と状態空間モデルの基礎」より見せかけの回帰単位根のあるデータ同士の回帰分析にかけると有意な回帰係数が得られる現象を『見せかけの回帰』という。定常AR過程同士の回帰分析でも『見せかけの回帰』が生じる。原因見せかけの回帰の発生理由として、「残差に自己相関がある」ことが言われている。残差に自己相関があると、最小二乗推定量における有効性が失われる。すなわち推定されたパラメタが「最も分散が小さい推定量である」という保証が得られなくなってしまう。残差に対して正の自己相関があった場合、以下の問題が発生係数の分散の過小推定決定係数R²が過大となる係数のt検定が使えなくなる残差の自己相関の有無を調べる方法Durbin-Watson検定(DW検定)の使用]]></summary><author><name>yooooshi</name></author><published>2021-11-03T03:35:37+00:00</published><updated>2021-11-07T01:47:23+00:00</updated><content type="html"><![CDATA[
		<div>
			<p>「時系列分析と状態空間モデルの基礎」より</p><p><br></p><h2><b>見せかけの回帰</b></h2><ul><li>単位根のあるデータ同士の回帰分析にかけると有意な回帰係数が得られる現象を『見せかけの回帰』という。</li><li>定常AR過程同士の回帰分析でも『見せかけの回帰』が生じる。</li></ul><p><br></p><h2><b>原因</b></h2><p>見せかけの回帰の発生理由として、<b>「残差に自己相関がある」</b>ことが言われている。</p><p>残差に自己相関があると、最小二乗推定量における有効性が失われる。すなわち推定されたパラメタが「最も分散が小さい推定量である」という保証が得られなくなってしまう。</p><p><br></p><p>残差に対して正の自己相関があった場合、以下の問題が発生</p><ul><li>係数の分散の過小推定</li><li>決定係数R²が過大となる</li><li>係数のt検定が使えなくなる</li></ul><p><br></p><h2><b>残差の自己相関の有無を調べる方法</b></h2><p>Durbin-Watson検定(DW検定)の使用</p>
		</div>
	
		<div>
			<img src="https://cdn.amebaowndme.com/madrid-prd/madrid-web/images/sites/635143/3351304ca9a5ce4730f660533a7e5e55_83387220a2b7ff99aa3f03964efe1994.png?width=960" width="100%">
		</div>
		

		<div>
			<p>残差の１次の自己相関が０であった場合は、DW統計量はおよそ２になることが知られている。DW統計量が２からどれほど離れているかを確認すれば、残差の自己相関の有無について、おおよその検討がつく。</p><p><a href="https://en.wikipedia.org/wiki/Durbin%E2%80%93Watson_statistic" target="_blank" class="u-lnk-clr"><u>wikiのDW検定の説明</u></a></p><p><br></p><h2><b>pythonによるDW検定例</b></h2><p><a href="https://yoshi-cow.github.io/statistics.github.io/DW_test.html" target="_blank" class="u-lnk-clr"><u><b>リンクのコード参照</b></u></a></p><p><br></p><h2><b>見せかけの回帰を防ぐ方法</b></h2><p>見せかけの回帰を防ぐには、過去のデータをモデルに組み込み、データの持つ自己相関を表現するモデルを作る。</p><p>ARIMAXモデルやベクトル自己回帰モデル(VAR)、状態空間モデルなどが候補となる。</p><p>また、残差の自己相関を明示的にモデルに組み込む回帰モデルとして、一般化最小二乗法(GLS)が知られている。</p><p>別の方法としては、単位根を持つデータの場合、差分系列へ回帰分析を実行する。</p><p>差分をとることでランダムウォークがただのホワイトノイズになり、見せかけの回帰が起こらなくなる。ただし、<b><u>差分をとる場合は共和分の確認必要で、共和分があったら差分をとる方法は使えない。</u></b></p><p><br></p><p>一般的な流れ、</p><ol><li>単位根の有無を検定(ADF検定 or KPSS検定)で確認</li><li>単位根がなければ<b>一般化最小二乗法(GLS)</b>を適用(Prais-Winsten法など利用）<br></li><li>単位根があれば、共和分の有無を確認したうえで、共和分がなければ差分系列への回帰分析を実施する</li></ol><p><br></p><h2><b>単位根検定</b></h2><ul><li>ADF検定</li><ul><li>仮定：y_t = Σ_i=1_to_℘(Φ_i * y_t-1) + ε_t　ε_t ~ W.N.(σ²)</li><li>上式で y_t が単位根過程に従うとき、AR特性方程式は z=1を解に持つので、単位根検定するためには、<br>　　　 Σ_i=1_to_℘(Φ_i) = 1<br>を検定する。<br>　　　ρ =&nbsp;Σ_i=1_to_℘(Φ_i)<br>とすると、</li><ul><ul><li>帰無仮説：ρ = 1 (単位根過程)&nbsp;</li><li>対立仮説：0 &lt; ρ &lt; 1 (弱定常過程)<br>として検定を行う。</li></ul></ul></ul><li><a href="https://yoshi-cow.github.io/statistics.github.io/ADF_test.html" target="_blank" class="u-lnk-clr"><u><b>コード例</b></u></a></li></ul><p><br></p><p><br></p><h2><b>共和分</b></h2><p>単位根を持つデータ同士で回帰分析をした場合、見せかけの回帰になることが多いが、データが共和分を持っているとその限りでない。</p><p>例えば、データx_tとy_tがそれぞれ単位根を持っており、y_tとx_tの線形結合が単位根を持たなくなったとしたら、両者は共和分の関係にある。</p><p>x_tとy_tで線形結合したときに、ランダムウォーク系列が無くなり、ホワイトノイズとなるような場合に共和分の関係が生じる。</p><p>共和分があるかどうかの検定：共和分検定（Engle-Grangerの方法など）</p><p><br></p><h3>共和分検定</h3><p>　単位根を持つデータに対して、OLSにより回帰直線を求める。そして残差を計算する。</p><p>残差に対して単位根検定を行い、単位根がなくなれば共和分ありとみなすのが共和分検定。</p><p>回帰式は一種の線形結合なので、共和分関係にあれば単位根は消える。</p><p>また、残差に対して単位根検定を行うため、通常のADF検定やKPSS検定は使えない。</p><p>Phillips-Ouliaris検定(PO検定)を使う。この検定の帰無仮説は「共和分関係がない」。</p><p><br></p><p><br></p><p><br></p>
		</div>
	]]></content></entry><entry><title><![CDATA[AR, MA, ARIMA, 及び各統計モデル用語について]]></title><link rel="alternate" href="https://study-storage.amebaownd.com/posts/23100835/"></link><id>https://study-storage.amebaownd.com/posts/23100835</id><summary><![CDATA[以下のリンク参照https://yoshi-cow.github.io/statistics.github.io/timeseries_analysis_basic_1.html]]></summary><author><name>yooooshi</name></author><published>2021-11-03T02:18:31+00:00</published><updated>2021-11-03T02:18:31+00:00</updated><content type="html"><![CDATA[
		<div>
			<p><br></p><p>以下のリンク参照</p><p><a href="https://yoshi-cow.github.io/statistics.github.io/timeseries_analysis_basic_1.html" class="u-lnk-clr"><u><b>https://yoshi-cow.github.io/statistics.github.io/timeseries_analysis_basic_1.html</b></u></a><br></p>
		</div>
	]]></content></entry><entry><title><![CDATA[statsmodelによるARIMAXなどのコード例]]></title><link rel="alternate" href="https://study-storage.amebaownd.com/posts/23100692/"></link><id>https://study-storage.amebaownd.com/posts/23100692</id><summary><![CDATA[以下のリンク参照https://yoshi-cow.github.io/statistics.github.io/time_series_sample_code.html]]></summary><author><name>yooooshi</name></author><published>2021-11-03T02:13:34+00:00</published><updated>2021-11-03T02:13:34+00:00</updated><content type="html"><![CDATA[
		<div>
			<p>以下のリンク参照</p><p><a href="https://yoshi-cow.github.io/statistics.github.io/time_series_sample_code.html" class="u-lnk-clr"><u><b>https://yoshi-cow.github.io/statistics.github.io/time_series_sample_code.html</b></u></a><br></p>
		</div>
	]]></content></entry><entry><title><![CDATA[モデルの同定]]></title><link rel="alternate" href="https://study-storage.amebaownd.com/posts/23100666/"></link><id>https://study-storage.amebaownd.com/posts/23100666</id><summary><![CDATA[ARMAモデルなどの次数の決定方法差分をとるか判断する：単位根検定ADF検定の利用帰無仮説：単位根あり対立仮説：単位根なしモデルの定常性・反転可能性のチェック次数決定ARモデルが定常であるときは、常に反転可能。そのためMA項における反転可能条件がARMAモデルの反転可能条件となる。定常性・反転可能性ともに、係数の特性方程式の解の絶対値が１よりも大きいことで確認できる。次数決定次数自動決定関数：ARmodel：statsmodels.tsa.ar_model.ar_select_orderARMAmodel：statsmodels.tsa.stattools.arma_order_select_ic リンクのコード参照評価：残差の自己相関のテストARIMAモデルを正しく推定できていた場合、残差は自己相関の無いホワイトノイズになる。残差に自己相関が残っていた場合は「未来を予測する情報がまだ残っている」ことになる。リンクのコード参照評価：残差の正規性のテスト時系列モデルの残差項として正規分布に従ったホワイトノイズが仮定されているため、正しくモデル化できている場合は、当てはめ残差も正規分布に従っているはず。正規性の検定として、Jarque-Bera検定やShapiro-Wilk検定を用いる。補statsmodelでのモデル作成後のsummaryの見方リンクのブログ参照モデルの同定方法のわかりやすいブログAdvanced Time Series Analysis with ARMA and ARIMA]]></summary><author><name>yooooshi</name></author><published>2021-11-03T02:12:29+00:00</published><updated>2021-11-06T06:23:09+00:00</updated><content type="html"><![CDATA[
		<div>
			<h2>ARMAモデルなどの次数の決定方法</h2><p><br></p><ol><li><b>差分をとるか判断する：単位根検定</b></li><p></p><ul><li>ADF検定の利用</li></ul><p></p><ol><ul><ul><ul><li><p style="display: inline !important;">帰無仮説：単位根あり</p></li><li>対立仮説：単位根なし</li></ul></ul></ul></ol><li><b>モデルの定常性・反転可能性のチェック</b><br></li><p></p><ul><ul><li>次数決定ARモデルが定常であるときは、常に反転可能。そのためMA項における反転可能条件がARMAモデルの反転可能条件となる。<br></li><li>定常性・反転可能性ともに、係数の特性方程式の解の絶対値が１よりも大きいことで確認できる。</li></ul></ul><li><b>次数決定</b></li><p></p><ul><ul><li>次数自動決定関数：</li><ul><li>ARmodel：<a href="https://www.statsmodels.org/devel/generated/statsmodels.tsa.ar_model.ar_select_order.html?highlight=ar_select" target="_blank" class="u-lnk-clr"><u><b>statsmodels.tsa.ar_model.ar_select_order</b></u></a></li><li>ARMAmodel：<a href="https://www.statsmodels.org/v0.13.0/generated/statsmodels.tsa.stattools.arma_order_select_ic.html" target="_blank" class="u-lnk-clr"><u><b>statsmodels.tsa.stattools.arma_order_select_ic</b></u></a>&nbsp;</li></ul><li><a href="https://yoshi-cow.github.io/statistics.github.io/time_series_sample_code.html" class="u-lnk-clr"><u>リンクのコード参照</u></a></li></ul></ul><p></p><li><b>評価：残差の自己相関のテスト</b></li><p></p><ul><ul><li>ARIMAモデルを正しく推定できていた場合、残差は自己相関の無いホワイトノイズになる。残差に自己相関が残っていた場合は「未来を予測する情報がまだ残っている」ことになる。</li><li><a href="https://yoshi-cow.github.io/statistics.github.io/time_series_sample_code.html" target="_blank" class="u-lnk-clr"><u>リンクのコード参照</u></a></li></ul></ul><p></p><li><b>評価：残差の正規性のテスト</b><br></li><p></p></ol><ol><p></p><p></p><ul><ul><li>時系列モデルの残差項として正規分布に従ったホワイトノイズが仮定されているため、正しくモデル化できている場合は、当てはめ残差も正規分布に従っているはず。</li><li>正規性の検定として、Jarque-Bera検定やShapiro-Wilk検定を用いる。</li></ul></ul></ol><ul><li><b>補</b></li><ul><li>statsmodelでのモデル作成後のsummaryの見方</li><ul><li><a href="https://analyzingalpha.com/interpret-arima-results" target="_blank" class="u-lnk-clr"><u>リンクのブログ参照</u></a></li></ul><li>モデルの同定方法のわかりやすいブログ</li><ul><li><a href="https://towardsdatascience.com/advanced-time-series-analysis-with-arma-and-arima-a7d9b589ed6d" target="_blank" class="u-lnk-clr"><u>Advanced Time Series Analysis with ARMA and ARIMA</u></a><br></li></ul></ul></ul><ol><p></p><p></p></ol><p><br></p><p><br></p>
		</div>
	]]></content></entry><entry><title><![CDATA[AWS EMRによる、streaming dataの分散処理実装]]></title><link rel="alternate" href="https://study-storage.amebaownd.com/posts/21391595/"></link><id>https://study-storage.amebaownd.com/posts/21391595</id><summary><![CDATA[以下のYouTubeで、AWS EMRによるspark streaming の実装を学ぶReal Time Analytics on Spark Tutorial [Part 10] | Spark Amazon EMR Elastic MapReduce -Great LearningReal Time Analytics on Spark Tutorial [Part 11] Spark Demo on EMR Elastic MapReduce | Great Learning■EMR nobebook利用時の注意点emr-5.30.0以降のを使うと、kernel起動エラーが起こるので、EMRのnotebook使うときは、emr-5.29.0を選択する。詳しくはリンク参照■仕様EMR上に置いたcsvファイルから１レコードづつkafkaに流し（ストリーミングデータの代わり）、kafkaからpysparkでデータ取得して可視化用に前処理した結果をnodejsで可視化する■EMR起動までの各設定security group作成　EC2 -> セキュリティグループ 　※ インバウンドルールは、すべてのipアドレスOK（anywhere）に設定すると、EMRでセキュリティエラーでクラスターが作成されないので、すべてのipをOKにしたいときは、SSHのみOKの設定にすること！！！（エラーについてはリンク1, リンク2参照）key pairsの作成    windowsからコンソールにログインする予定なので、キーファイルは.ppkで作成（プライベートkeyは作成時に自動ダウンロードされる）puttyダウンロード(リンク)windowsからAWSコンソールへログイン時に使うSSHツールEMRクラスター作成（以下は、詳細設定で設定）　・リリースは、spark3.1.1を使っているので、『emr-6.3.0』を選択し、ソフト一覧でsparkも選択入れる　・選択するソフトウエアは、今回はHadoopとsparkのみ　　（zookeeper使うソフト選択すると、zookeeperがインストールされるので、自分でkafkaインストールするときに、kafkaのzookeeperと被るので注意　・master node:1、slave node:2でクラスター数は３でとりあえず設定　・EC2 キーペアは、2で作成したkeyを選択　・EC2セキュリティグループの、マスタ・コアそれぞれに1で作成したsセキュリティグループを選択　・ハードウェアは、m4.largeをとりあえず選択　※クラスターの作成がうまくいくと『待機中』になる。AWS EMR コンソールへの接続TEST　(1) 作成したクラスターの「マスターパブリック DNS」をコピー　(2) 「Connect to the Master Node Using SSH」のリンクをクリック　(3) 接続するローカルpcで、PuTTYを立ち上げ、Host Nameにコピーした「マスターパブリック DNS」を貼り付け　(4) PuTTYのCategoryからSSH -> Authを選ぶ、Browseでダウンロードしたppkファイルを選択　(5) コンソール立ち上がったら、hadoopと入力してログイン　　ログイン出来たら、EMRと大きく表示される。※EMRのクラスタ作成時に、Zookeeperを使用するソフト選択すると、zookeeperもインストールされるので、kafkaをEMR上でインストールするなら、注意すること。EMRでのLISTENポートは、「sudo lsof -i -n -P | grep zookeeper」で確認コンソールからkafkaをEMRにインストール今回は、ストリーミングデータをkafkaで取得して、pysparkで読み込んで前処理して、kafkaに戻すシステムなので、まずはkafkaをEMRにインストールする。　kafkaのサイトリンク　(1) kafkaのダウンロード(※必ずBinaryをダウンロードすること！！！）　　wget https://archive.apache.org/dist/kafka/2.8.0/kafka_2.12-2.8.0.tgz　(2) kafkaの解凍　　tar -xzf kafka_2.12-2.8.0.tgz　(3) フォルダ名の変更　　mv kafka_2.12-2.8.0 kafka kafkaの起動   kafkaの起動は、メタデータ管理のzookeeperを起動してから、kafka Brokerを起動する。　(1) zookeeperの起動　　kafkaのファルダに入ってから起動　　cd kafka　　bin/zookeeper-server-start.sh config/zookeeper.properties　(2) Kafka Brokerの起動 　　最初のコンソールはzookeeperが起動中なので、別コンソールを開いて起動する。　　kafkaフォルダ内で、　　bin/kafka-server-start.sh config/server.properties　(3) テスト用のtopic生成　　別コンソールを開いて、kafkaが正しく起動しているか確認するため、topicを作成してみる　　 bin/kafka-topics.sh --create --zookeeper localhost:2181 --replication-factor 1 --partitions 1 --topic test　　※ kafkaのversionが3.0.0以上は、 --zookeeperオプションが無くなったので、3.0.0以降をダウンロードしたら、topic作成方法を確認すること！       以下コマンドで、作成したtestトピックの設定状況確認　　bin/kafka-topics.sh --describe --zookeeper localhost:2181 --topic test  以上までが、EMRの起動とコンソールへのアクセス■sparkによるkafka操作用設定repositoryから、Spark Integration For Kafkaをダウンロードwget https://repo1.maven.org/maven2/org/apache/spark/spark-streaming-kafka-0-10_2.12/3.1.2/spark-streaming-kafka-0-10_2.12-3.1.2.jar■kafkaでのストリーミングデータの送受信送信はコンソールからデータ流す（ストリーミングデータの変わり）トピックの作成bin/kafka-topics.sh --create --zookeeper localhost:2181 --replication-factor 1 --partitions 1 --topic orders_topicストリーミングデータ送信用トピック：order_topicストリーミングデータの送信実際のストリーミングデータの代わりに、s3ファイルのデータを取得して、コンソールから kafka-console-producer.sh でデータをkafkaに送るpush_orders_data_in_topic.sh■sparkによる前処理および、kafkaへの再送信kafkaから受け取ったデータをpysparkで可視化用に前処理した後、その結果を受け取り用kafkaトピックに送る別のEMRコンソール開いて、前処理後用のtopic作成bin/kafka-topics.sh --create --zookeeper localhost:2181 --replication-factor 1 --partitions 1 --topic orders_ten_sec_data前処理後データ送信用トピック：orders_ten_sec_datapykfkaのインストール　pysparkからトピック作るライブラリpip install pykafka■sparkによる前処理とnode.jsによるストリーミングデータの可視化別のコンソール開くnode.jsのインストール※8系はすでにサポート対象外だが、youtubeの仕様をそのままつかうcurl --silent --location https://rpm.nodesource.com/setup_8.x | sudo bash -sudo yum -y install nodejsnpm install expressnpm install socket.ionpm install kafka-nodecsvファイルを読み込んでコンソールからストリーミングデータの代わりとしてkafkaに流す(push_orders_data_in_topic.shスクリプトでストリーミングデータの代わりを送信)/bin/bash push_orders_data_in_topic.sh ../data/ordersdata ip--172-xxxx:9092 orders_dataspark用コンソール開いて、spark-submitで、kafkaからデータ取得して前処理して返すプログラム(spark_streaming_order_status.py)を実行spark-submit --jars spark-streaming-kafka-0-10-assembly_2.12-3.0.1.jar spark_streaming_order_status.py localhost:2181 orders_dataローカルPCから、emrのurlで見れないか試したら、ssh接続じゃないとダメなの気づいた・・・上記YouTubeのプログラムファイル場所：リンク]]></summary><author><name>yooooshi</name></author><published>2021-09-19T07:50:23+00:00</published><updated>2021-09-25T04:20:56+00:00</updated><content type="html"><![CDATA[
		<div>
			<h2>以下のYouTubeで、AWS EMRによるspark streaming の実装を学ぶ</h2><ul><li><a href="https://www.youtube.com/watch?v=fWW7FOQKMxY&amp;list=PLlgLmuG_KgbYzloqmmAZLbHnpzHyfhQxz&amp;index=3" target="_blank" class="u-lnk-clr"><u>Real Time Analytics on Spark Tutorial [Part 10] | Spark Amazon EMR Elastic MapReduce -Great Learning</u></a></li><li class=""><a href="https://www.youtube.com/watch?v=Tx5r38l4j_g&amp;list=PLlgLmuG_KgbYzloqmmAZLbHnpzHyfhQxz" target="_blank" class="u-lnk-clr"><u>Real Time Analytics on Spark Tutorial [Part 11] Spark Demo on EMR Elastic MapReduce | Great Learning</u></a><br></li></ul><p><br></p><h3>■EMR nobebook利用時の注意点</h3><p>emr-5.30.0以降のを使うと、kernel起動エラーが起こるので、EMRのnotebook使うときは、emr-5.29.0を選択する。<br></p><p>詳しくは<a href="https://forums.aws.amazon.com/thread.jspa?threadID=322445" target="_blank" class="u-lnk-clr"><u>リンク</u></a>参照</p><p><br></p><h3>■仕様</h3><p>EMR上に置いたcsvファイルから１レコードづつkafkaに流し（ストリーミングデータの代わり）、kafkaからpysparkでデータ取得して可視化用に前処理した結果をnodejsで可視化する</p><h3><br></h3><h3>■EMR起動までの各設定</h3><ol><li>security group作成<br>　EC2 -&gt; セキュリティグループ<br>&nbsp;　<b>※ インバウンドルールは、すべてのipアドレスOK（anywhere）に設定すると、EMRでセキュリティエラーでクラスターが作成されないので、すべてのipをOKにしたいときは、SSHのみOKの設定にすること！！！（エラーについては<a href="https://stackoverflow.com/questions/64708457/aws-emr-terminated-with-validation-error-security-group-error" target="_blank" class="u-lnk-clr"><u>リンク1</u></a>, <a href="https://docs.aws.amazon.com/emr/latest/ManagementGuide/emr-man-sec-groups.html" target="_blank" class="u-lnk-clr"><u>リンク2</u></a>参照）<br><br></b></li><li>key pairsの作成<br>&nbsp; &nbsp; windowsからコンソールにログインする予定なので、キーファイルは.ppkで作成<br>（プライベートkeyは作成時に自動ダウンロードされる）<br><br></li><li>puttyダウンロード(<a href="https://www.chiark.greenend.org.uk/~sgtatham/putty/latest.html" target="_blank" class="u-lnk-clr"><u>リンク</u></a>)<br>windowsからAWSコンソールへログイン時に使うSSHツール<br><br></li><li>EMRクラスター作成（以下は、詳細設定で設定）<br>　・リリースは、spark3.1.1を使っているので、『emr-6.3.0』を選択し、ソフト一覧でsparkも選択入れる<br>　・選択するソフトウエアは、今回は<b>Hadoopとsparkのみ<br></b>　　（zookeeper使うソフト選択すると、zookeeperがインストールされるので、自分でkafkaインストールするときに、kafkaのzookeeperと被るので注意<br>　・master node:1、slave node:2でクラスター数は３でとりあえず設定<br>　・EC2 キーペアは、2で作成したkeyを選択<br>　・EC2セキュリティグループの、マスタ・コアそれぞれに1で作成したsセキュリティグループを選択<br>　・ハードウェアは、m4.largeをとりあえず選択<br>　※クラスターの作成がうまくいくと『<b>待機中</b>』になる。<br><br></li><li>AWS EMR コンソールへの接続TEST<br>　(1) 作成したクラスターの「マスターパブリック DNS」をコピー<br>　(2) 「Connect to the Master Node Using SSH」のリンクをクリック<br>　(3)&nbsp;接続するローカルpcで、PuTTYを立ち上げ、Host Nameにコピーした「マスターパブリック DNS」を貼り付け<br>　(4)&nbsp;PuTTYのCategoryからSSH -&gt; Authを選ぶ、Browseでダウンロードしたppkファイルを選択<br>　(5) コンソール立ち上がったら、hadoopと入力してログイン<br>　　ログイン出来たら、EMRと大きく表示される。<br><b><br>※EMRのクラスタ作成時に、Zookeeperを使用するソフト選択すると、zookeeperもインストールされるので、kafkaをEMR上でインストールするなら、注意すること。<br>EMRでのLISTENポートは、「sudo lsof -i -n -P | grep zookeeper」で確認<br><br></b></li><li>コンソールからkafkaをEMRにインストール<br>今回は、ストリーミングデータをkafkaで取得して、pysparkで読み込んで前処理して、kafkaに戻すシステムなので、まずはkafkaをEMRにインストールする。<br>　kafkaの<a href="https://kafka.apache.org/" target="_blank" class="u-lnk-clr" style="">サイトリンク</a><br>　(1) kafkaのダウンロード(※必ず<b>Binaryをダウンロード</b>すること！！！）<br>　　<b>wget&nbsp;https://archive.apache.org/dist/kafka/2.8.0/kafka_2.12-2.8.0.tgz</b><br>　(2) kafkaの解凍<br>　　<b>tar -xzf&nbsp;kafka_2.12-2.8.0.tgz</b><br>　(3) フォルダ名の変更<br>　　<b>mv kafka_2.12-2.8.0&nbsp;kafka<br>&nbsp;</b></li><li>kafkaの起動<br>&nbsp; &nbsp;kafkaの起動は、メタデータ管理のzookeeperを起動してから、kafka Brokerを起動する。<br>　(1) zookeeperの起動<br>　　kafkaのファルダに入ってから起動<br>　　<b>cd kafka<br>　　bin/zookeeper-server-start.sh config/zookeeper.properties</b><br><br>　(2) Kafka Brokerの起動&nbsp;<br>　　最初のコンソールはzookeeperが起動中なので、別コンソールを開いて起動する。<br>　　kafkaフォルダ内で、<br>　　<b>bin/kafka-server-start.sh config/server.properties</b><br>　(3) テスト用のtopic生成<br>　　別コンソールを開いて、kafkaが正しく起動しているか確認するため、topicを作成してみる<br>　　 <b>bin/kafka-topics.sh --create --zookeeper localhost:2181 --replication-factor 1 --partitions 1 --topic test<br></b>　　<b><i>※ kafkaのversionが3.0.0以上は、 --zookeeperオプションが無くなったので、3.0.0以降をダウンロードしたら、topic作成方法を確認すること！</i></b><br>&nbsp; &nbsp; &nbsp; &nbsp;以下コマンドで、作成したtestトピックの設定状況確認<br>　　<b>bin/kafka-topics.sh --describe --zookeeper localhost:2181 --topic test</b><br></li></ol><p><b>&nbsp; </b>以上までが、EMRの起動とコンソールへのアクセス</p><p><br></p><h3>■sparkによるkafka操作用設定</h3><p><a href="https://mvnrepository.com/artifact/org.apache.spark/spark-streaming-kafka-0-10_2.12/3.1.2" target="_blank" class="u-lnk-clr"><u>repository</u></a>から、Spark Integration For Kafkaをダウンロード</p><p><b>wget&nbsp;https://repo1.maven.org/maven2/org/apache/spark/spark-streaming-kafka-0-10_2.12/3.1.2/spark-streaming-kafka-0-10_2.12-3.1.2.jar</b></p><p><b><br></b></p><h3><b>■kafkaでのストリーミングデータの送受信</b></h3><p><b>送信はコンソールからデータ流す（ストリーミングデータの変わり）</b></p><ol><li>トピックの作成<br><b>bin/kafka-topics.sh --create --zookeeper localhost:2181 --replication-factor 1 --partitions 1 --topic orders_topic</b><br><br>ストリーミングデータ送信用トピック：order_topic<br><br></li><li>ストリーミングデータの送信<br>実際のストリーミングデータの代わりに、s3ファイルのデータを取得して、コンソールから kafka-console-producer.sh でデータをkafkaに送る<br><br>push_orders_data_in_topic.sh</li></ol><p><br></p><h3><b>■sparkによる前処理および、kafkaへの再送信</b></h3><h4>kafkaから受け取ったデータをpysparkで可視化用に前処理した後、その結果を受け取り用kafkaトピックに送る</h4><ol><li>別のEMRコンソール開いて、前処理後用のtopic作成<br><b>bin/kafka-topics.sh --create --zookeeper localhost:2181 --replication-factor 1 --partitions 1 --topic orders_ten_sec_data<br></b><br>前処理後データ送信用トピック：orders_ten_sec_data<br><br></li><li>pykfkaのインストール<br>　pysparkからトピック作るライブラリ<br>pip install pykafka</li></ol><p><br></p><h3>■sparkによる前処理とnode.jsによるストリーミングデータの可視化</h3><ol><li>別のコンソール開く<br></li><li>node.jsのインストール<br>※8系はすでにサポート対象外だが、youtubeの仕様をそのままつかう<br>curl --silent --location https://rpm.nodesource.com/setup_8.x | sudo bash -<br>sudo yum -y install nodejs<br>npm install express<br>npm install socket.io<br>npm install kafka-node<br><br></li><li>csvファイルを読み込んでコンソールからストリーミングデータの代わりとしてkafkaに流す(push_orders_data_in_topic.shスクリプトでストリーミングデータの代わりを送信)<br><b>/bin/bash push_orders_data_in_topic.sh ../data/ordersdata ip--172-xxxx:9092 orders_data</b><br><br></li><li>spark用コンソール開いて、spark-submitで、kafkaからデータ取得して前処理して返すプログラム(spark_streaming_order_status.py)を実行<br><b>spark-submit --jars spark-streaming-kafka-0-10-assembly_2.12-3.0.1.jar spark_streaming_order_status.py localhost:2181 orders_data<br><br></b></li><li>ローカルPCから、emrのurlで見れないか試したら、ssh接続じゃないとダメなの気づいた・・・</li></ol><p>上記YouTubeのプログラムファイル場所：<a href="https://github.com/raghushining/spark-project.git" target="_blank" class="u-lnk-clr"><u>リンク</u></a></p><h4><br></h4><p><br></p><p><br></p><p><br></p>
		</div>
	]]></content></entry><entry><title><![CDATA[sparkによる、IoTデータ収集とDBへの保存の分散処理化]]></title><link rel="alternate" href="https://study-storage.amebaownd.com/posts/20889823/"></link><link rel="enclosure" type="image/png" href="https://cdn.amebaowndme.com/madrid-prd/madrid-web/images/sites/635143/9a0f3d552345acddd150ff97bff8ef60_18d5d8a11fbf970beceaa5791da00652.png"></link><id>https://study-storage.amebaownd.com/posts/20889823</id><summary><![CDATA[以下仕様で、IoTデータの収集とDBへの保存フローを学ぶ学習書籍：『アプリケーションエンジニアのための Apache Spark入門』（秀和システム）]]></summary><author><name>yooooshi</name></author><published>2021-09-04T05:00:25+00:00</published><updated>2021-09-19T02:10:42+00:00</updated><content type="html"><![CDATA[
		<div>
			<h2>以下仕様で、IoTデータの収集とDBへの保存フローを学ぶ</h2><p>学習書籍：『アプリケーションエンジニアのための Apache Spark入門』（秀和システム）</p>
		</div>
	
		<div>
			<img src="https://cdn.amebaowndme.com/madrid-prd/madrid-web/images/sites/635143/9a0f3d552345acddd150ff97bff8ef60_18d5d8a11fbf970beceaa5791da00652.png?width=960" width="100%">
		</div>
		

		<div>
			<p>コードは以下のGitHubに保存<br></p><p><a href="https://github.com/yoshi-cow/IoT-spark-streaming" class="u-lnk-clr"><b><u>https://github.com/yoshi-cow/IoT-spark-streaming</u></b></a></p>
		</div>
	]]></content></entry><entry><title><![CDATA[分散処理の学習(Apache Spark)]]></title><link rel="alternate" href="https://study-storage.amebaownd.com/posts/20668564/"></link><id>https://study-storage.amebaownd.com/posts/20668564</id><summary><![CDATA[pysparkにて、分散処理によるデータ前処理、機械学習のコーディングを学ぶdataframeの基本コードリンク基本的なdataframeの関数コードリンクsparkによるSQL操作コードリンクフィルター、独自定義関数、データベース入出力などコードリンク機械学習_教師有りコードリンク機械学習_決定木系コードリンク機械学習_教師無しコードリンクグリッドサーチ、クロスバリデーションコードリンクPCAによる特徴量数選択コードリンクkafkaとsparkの連携Githubのコードリンク]]></summary><author><name>yooooshi</name></author><published>2021-08-28T07:13:24+00:00</published><updated>2021-09-09T01:58:57+00:00</updated><content type="html"><![CDATA[
		<div>
			<h2>pysparkにて、分散処理によるデータ前処理、機械学習のコーディングを学ぶ</h2><ul><li><b>dataframeの基本</b><a href="https://yoshi-cow.github.io/learning_spark.io/chapter_4_Basic_of_Spark_DataFrame.html" class="u-lnk-clr"><br><u>コードリンク</u></a></li></ul><ul><li><b>基本的なdataframeの関数</b><a href="https://yoshi-cow.github.io/learning_spark.io/chap3_Basic_Function_with_Spark.html" class="u-lnk-clr"><br><u>コードリンク</u></a></li></ul><ul><li><b>sparkによるSQL操作</b><a href="https://yoshi-cow.github.io/learning_spark.io/chap4_Spark_SQL.html" class="u-lnk-clr"><br><u>コードリンク</u></a></li></ul><ul><li><b>フィルター、独自定義関数、データベース入出力など</b><a href="https://yoshi-cow.github.io/learning_spark.io/chap5_UDF_ExternalDasouce_Filter_with_Spark.html" class="u-lnk-clr"><br><u>コードリンク</u></a></li></ul><ul><li><b>機械学習_教師有り</b><a href="https://yoshi-cow.github.io/learning_spark.io/chapter_6_Supervised_Learning_with_Spark.html" class="u-lnk-clr"><br><u>コードリンク</u></a></li></ul><ul><li><b>機械学習_決定木系</b><a href="https://yoshi-cow.github.io/learning_spark.io/chapter_7_Tree_Methods_with_Spark.html" class="u-lnk-clr"><br><u>コードリンク</u></a></li></ul><ul><li><b>機械学習_教師無し<a href="https://yoshi-cow.github.io/learning_spark.io/chapter_8_Un_Supervised_Learning_with_Spark.html" class="u-lnk-clr"><br></a></b><u><a href="https://yoshi-cow.github.io/learning_spark.io/chapter_8_Un_Supervised_Learning_with_Spark.html" target="_blank" class="u-lnk-clr">コードリンク</a></u></li></ul><ul><li><b>グリッドサーチ、クロスバリデーション</b><a href="https://yoshi-cow.github.io/learning_spark.io/cross_valication.html" class="u-lnk-clr"><u><br>コードリンク</u></a></li></ul><ul><li><b>PCAによる特徴量数選択</b><u><a href="https://yoshi-cow.github.io/learning_spark.io/feature_selection_by_PCA.html" class="u-lnk-clr"><br>コードリンク</a></u></li></ul><p><br></p><ul><li><b>kafkaとsparkの連携</b><a href="https://github.com/yoshi-cow/IoT-spark-streaming" class="u-lnk-clr"><u><br>Githubのコードリンク</u></a></li></ul><p><br></p>
		</div>
	]]></content></entry><entry><title><![CDATA[（未）時系列データのクラスタリング方法例]]></title><link rel="alternate" href="https://study-storage.amebaownd.com/posts/18533841/"></link><link rel="enclosure" type="image/png" href="https://cdn.amebaowndme.com/madrid-prd/madrid-web/images/sites/635143/70e889039c850a4f6af93f4729bba3d6_46f3dfeeb66be38dac695f7e42e4f626.png"></link><id>https://study-storage.amebaownd.com/posts/18533841</id><summary><![CDATA[時系列分析にて、傾向抽出の方法で悩んだ時の備忘録1. DTW(動的時間伸縮法)　　特徴　　２つの時系列の各点の距離を総当たりで求め、最短となるパスを見つける　　時系列同同士の長さや周期が違っても類似度を求められる　　総当たりなので、計算コスト高い　　プログラム例　　結果例]]></summary><author><name>yooooshi</name></author><published>2021-06-19T05:31:00+00:00</published><updated>2021-06-20T01:31:39+00:00</updated><content type="html"><![CDATA[
		<div>
			<p>時系列分析にて、傾向抽出の方法で悩んだ時の備忘録</p><p><br></p><h2><b>1. DTW(動的時間伸縮法)</b></h2><p>　　特徴</p><ul><ul><ul><li>　　２つの時系列の各点の距離を総当たりで求め、最短となるパスを見つける</li><li>　　時系列同同士の長さや周期が違っても類似度を求められる</li><li>　　総当たりなので、計算コスト高い</li></ul></ul></ul><p>　　<a href="https://yoshi-cow.github.io/statistics.github.io/dtw.html" target="_blank" class="u-lnk-clr"><b><u>プログラム例</u></b></a></p><p>　　結果例</p>
		</div>
	
		<div>
			<img src="https://cdn.amebaowndme.com/madrid-prd/madrid-web/images/sites/635143/70e889039c850a4f6af93f4729bba3d6_46f3dfeeb66be38dac695f7e42e4f626.png?width=960" width="100%">
		</div>
		

		<div>
			<p><br></p><h2><b>2. 特徴点マッチング</b></h2><ul><ul><ul><li>　　本来は類似画像を求めるのに利用される</li><li>　　時系列データを曜日と時間でヒートマップで可視化した結果をクラスタリングするのに利用した。</li></ul></ul></ul><p>　　プログラム例</p>
		</div>
	]]></content></entry><entry><title><![CDATA[状態空間モデル]]></title><link rel="alternate" href="https://study-storage.amebaownd.com/posts/18585389/"></link><id>https://study-storage.amebaownd.com/posts/18585389</id><summary><![CDATA[状態方程式：予測対象分布　x_t = T_t * x_(t-1) + R_t * ξ_t　　ξ_t～N(0, Q_t) 観測方程式：予測対象の観測値の分布　y_t = Z_t * x_t + ε_t　　ε_t～N(0, H_t)フィルタリング：手に入った観測値で、予測された状態の値を補正平滑化：すべてのデータが手に入った後に、状態の補正を行う（予測精度が上がるわけではないが、補正に使われる情報が増えるので、ノイズの影響を軽減できる）プログラム例１（statsを用いた外生変数入れた予測モデル）プログラム例２（サブクラス作成による予測モデル）ローカルレベルモデル状態方程式：μ_t = μ_(t-1) + ω_t　　ω_t～N(0, σ²_ω)観測方程式：y_t = μ_t + ν_t　　ν_t～N(0, σ²_ν)ローカル線形トレンドモデルトレンド成分：δ_t = δ_(t-1) + ξ_t　　ξ_t～N(0, σ²_ξ)状態方程式：μ_t = μ_(t-1) + δ_(t-1) + ω_t　　ω_t～N(0, σ²_ω)観測方程式： y_t = μ_t + ν_t　　ν_t～N(0, σ²_ν) カルマンフィルタ予測ステップμ_t = μ_(t-1)|(t-1)　　μ_(t-1)|(t-1)：t-1時点のフィルタ化推定量P_t = P_(t-1)|(t-1) + σ²_ω　　P_(t-1)|(t-1)：t-1時点の「状態のフィルタ化推定量μ_(t-1)|(t-1)の推定誤差分散」^y_t = μ_t　　^y_t：t時点の観測値の予測値F_t = P_t + σ²_ν    F_t：t時点の「観測値の予測誤差の分散」フィルタリングK_t = P_t / (P_t + σ²_ν) = P_t / F_t　　K_t：カルマンゲインy_resid,t = y_t - ^y_t　　y_resid,t：観測誤差μ_t|t = μ_t + K_t * y_resid,tP_t|t = (1 - K_t ) * P_t散漫カルマンフィルタ　カルマンフィルタの改良版　状態の初期値への対応を以下のように行う状態の初期値はあきらめるただし、「状態の予測誤差の分散」の初期値を無限大にしておく※散漫カルマンフィルタを入れることで、最初の予測値の精度が上がるが、時間経過とともにカルマンフィルタの値を同じになるので、初期値の精度気にしないなら、いらないと思われる平滑化　省略状態空間モデルのプログラム例１状態空間モデルのプログラム例２（サブクラス作成版）]]></summary><author><name>yooooshi</name></author><published>2021-05-01T01:35:17+00:00</published><updated>2021-06-20T02:40:45+00:00</updated><content type="html"><![CDATA[
		<div>
			<ul><li>状態方程式：予測対象分布　<b>x_t = T_t * x_(t-1) + R_t * ξ_t　　ξ_t～N(0, Q_t)</b>&nbsp;</li><li>観測方程式：予測対象の観測値の分布　<b>y_t = Z_t * x_t + ε_t　　ε_t～N(0, H_t)</b></li><li>フィルタリング：手に入った観測値で、予測された状態の値を補正</li><li>平滑化：すべてのデータが手に入った後に、状態の補正を行う（予測精度が上がるわけではないが、補正に使われる情報が増えるので、ノイズの影響を軽減できる）<a href="https://yoshi-cow.github.io/statistics.github.io/study_state_space_basic.html" class="u-lnk-clr"><br></a></li><li><b><u><a href="https://yoshi-cow.github.io/statistics.github.io/study_state_space_basic.html" target="_blank" class="u-lnk-clr">プログラム例１（statsを用いた外生変数入れた予測モデル）</a></u></b></li><li><b><u><a href="https://yoshi-cow.github.io/statistics.github.io/study_state_space_make_subclass.html" target="_blank" class="u-lnk-clr">プログラム例２（サブクラス作成による予測モデル）</a><br></u></b></li></ul><p><br></p><h2>ローカルレベルモデル</h2><ul><ul><li>状態方程式：<b>μ_t =&nbsp;μ_(t-1) + ω_t　　ω_t～N(0, σ²_ω)</b></li><li>観測方程式：<b>y_t =&nbsp;μ_t + ν_t　　ν_t～N(0, σ²_ν)</b></li></ul></ul><p><br></p><h2>ローカル線形トレンドモデル</h2><ul><ul><li>トレンド成分：<b>δ_t =&nbsp;δ_(t-1) + ξ_t　　ξ_t～N(0, σ²_ξ)</b></li><li>状態方程式：<b>μ_t =&nbsp;μ_(t-1) +&nbsp;δ_(t-1) + ω_t　　ω_t～N(0, σ²_ω)</b></li><li>観測方程式： <b>y_t =&nbsp;μ_t + ν_t　　ν_t～N(0, σ²_ν)&nbsp;</b></li></ul></ul><p><br></p><h2>カルマンフィルタ</h2><ul><ul><li>予測ステップ</li><ul><li><b>μ_t =&nbsp;μ_(t-1)|(t-1)</b>　　μ_(t-1)|(t-1)：t-1時点のフィルタ化推定量</li><li><b>P_t = P_(t-1)|(t-1) + σ²_ω</b>　　P_(t-1)|(t-1)：t-1時点の「状態のフィルタ化推定量μ_(t-1)|(t-1)の推定誤差分散」</li><li><b>^y_t =&nbsp;μ_t</b>　　^y_t：t時点の観測値の予測値</li><li><b>F_t = P_t + σ²_ν&nbsp;</b> &nbsp;&nbsp;F_t：t時点の「観測値の予測誤差の分散」</li></ul><li>フィルタリング</li><ul><li><b>K_t = P_t / (P_t + σ²_ν) = P_t / F_t</b>　　K_t：カルマンゲイン</li><li><b>y_resid,t = y_t - ^y_t</b>　　y_resid,t：観測誤差</li><li><b>μ_t|t =&nbsp;μ_t + K_t *&nbsp;y_resid,t</b><br></li><li><b>P_t|t = (1 - K_t ) * P_t</b><br></li></ul></ul></ul><p><br></p><h2>散漫カルマンフィルタ</h2><p>　カルマンフィルタの改良版</p><p>　状態の初期値への対応を以下のように行う</p><ul><ul><ul><li>状態の初期値はあきらめる</li><li>ただし、「状態の予測誤差の分散」の初期値を無限大にしておく</li></ul></ul></ul><p>※散漫カルマンフィルタを入れることで、最初の予測値の精度が上がるが、時間経過とともにカルマンフィルタの値を同じになるので、初期値の精度気にしないなら、いらないと思われる</p><p><br></p><h2>平滑化</h2><p>　省略</p><p><a href="https://yoshi-cow.github.io/statistics.github.io/study_state_space_basic.html" class="u-lnk-clr"><br></a></p><p><b><u><a href="https://yoshi-cow.github.io/statistics.github.io/study_state_space_basic.html" target="_blank" class="u-lnk-clr">状態空間モデルのプログラム例１</a></u></b></p><p><a href="https://yoshi-cow.github.io/statistics.github.io/study_state_space_make_subclass.html" target="_blank" class="u-lnk-clr"><b><u>状態空間モデルのプログラム例２（サブクラス作成版）</u></b></a><b><u><br></u></b></p>
		</div>
	]]></content></entry><entry><title><![CDATA[時系列分析備忘録]]></title><link rel="alternate" href="https://study-storage.amebaownd.com/posts/10541576/"></link><link rel="enclosure" type="image/png" href="https://cdn.amebaowndme.com/madrid-prd/madrid-web/images/sites/635143/ef96e7027104b8d67527c2df0bfb6d02_7e1b0ddc59e578e2a63341d370e267e2.png"></link><id>https://study-storage.amebaownd.com/posts/10541576</id><summary><![CDATA[ラグ / 確率過程 / 期待値 / 分散、標準偏差 / 自己共分散 / 自己相関説明サイト：時系列分析で登場する統計量・用語を一つずつ解説原系列 / 差分系列、階差系列 / 対数系列 / 対数差分系列 / 季節調整系列説明サイト：時系列分析の基本的なモデルをわかりやすく解説定常性 = 平均回帰性]]></summary><author><name>yooooshi</name></author><published>2021-01-31T12:54:37+00:00</published><updated>2021-06-19T05:31:52+00:00</updated><content type="html"><![CDATA[
		<div>
			<h3>ラグ /&nbsp;確率過程 /&nbsp;期待値 /&nbsp;分散、標準偏差 /&nbsp;自己共分散 /&nbsp;自己相関</h3><p>説明サイト：<u><a href="https://ai-trend.jp/basic-study/time-series-analysis/time-series-analysis-stat/" target="_blank" class="u-lnk-clr">時系列分析で登場する統計量・用語を一つずつ解説</a></u></p><p><br></p><p><br></p><h3>原系列 /&nbsp;差分系列、階差系列 /&nbsp;対数系列 /&nbsp;対数差分系列 /&nbsp;季節調整系列</h3><p>説明サイト：<u><a href="https://ai-trend.jp/basic-study/time-series-analysis/time-series-analysis/" target="_blank" class="u-lnk-clr">時系列分析の基本的なモデルをわかりやすく解説</a></u><br></p><p><br></p><p><br></p><h3>定常性 = 平均回帰性</h3>
		</div>
	
		<div>
			<img src="https://cdn.amebaowndme.com/madrid-prd/madrid-web/images/sites/635143/ef96e7027104b8d67527c2df0bfb6d02_7e1b0ddc59e578e2a63341d370e267e2.png?width=960" width="100%">
		</div>
		

		<div>
			<p>下は、平均回帰性が見られないケース</p>
		</div>
	
		<div>
			<img src="https://cdn.amebaowndme.com/madrid-prd/madrid-web/images/sites/635143/1d664279ac02d9f7dbb08dac340683f2_d4e037da4127a1b57324e40c35d32ad0.png?width=960" width="100%">
		</div>
		

		<div>
			<h3><br></h3><h3>自己相関&nbsp;</h3><h3>=&nbsp;時系列データが自分の過去の値からどれくらい影響を受けているかの指標</h3>
		</div>
	
		<div>
			<img src="https://cdn.amebaowndme.com/madrid-prd/madrid-web/images/sites/635143/3b40ec4bae43f212729bb5f993bef87b_8156a5fb5a1ebfe2e70d71e8082b3403.png?width=960" width="100%">
		</div>
		

		<div>
			<p>上の平均開始しているケースでは、一時点前の値からしか影響を受けていないが、下の平均回帰していないケースは、過去遡って影響を受けている</p>
		</div>
	
		<div>
			<img src="https://cdn.amebaowndme.com/madrid-prd/madrid-web/images/sites/635143/4cabd49628f9fb3693a524e00b34b5d8_11ccf9be51c2e593b6c6b11dd3690b40.png?width=960" width="100%">
		</div>
		

		<div>
			<p class=""><br></p><h3>分散不均一性<br>&nbsp;= 分散が時間軸に沿って一定していない</h3>
		</div>
	
		<div>
			<img src="https://cdn.amebaowndme.com/madrid-prd/madrid-web/images/sites/635143/ccaebd908cd985575693fa148e0f7276_b9334c4b7a3773f699ecd1857d9171d8.png?width=960" width="100%">
		</div>
		

		<div>
			<p>上は、分散が均一っぽいケース。下が、分散が不均一なケース</p>
		</div>
	
		<div>
			<img src="https://cdn.amebaowndme.com/madrid-prd/madrid-web/images/sites/635143/09b89f1dac6133b9785cbc123276b493_0e64cecdc50051dc0ecf609a3df20340.png?width=960" width="100%">
		</div>
		

		<div>
			<p class="">上記画像は、『<u><a href="https://www.slideshare.net/takashijozaki1/code-score150123-tjo" target="_blank" class="u-lnk-clr">なぜ統計学がビジネスの 意思決定において大事なのか？</a></u>』より</p><p class=""><br></p><p class=""><br></p><h3 class="">定常過程</h3><p class="">時間や位置によって確率分布が変化しない確率過程<a href="https://ja.wikipedia.org/wiki/%E5%AE%9A%E5%B8%B8%E9%81%8E%E7%A8%8B#:~:text=%E5%AE%9A%E5%B8%B8%E9%81%8E%E7%A8%8B%EF%BC%88%E3%81%A6%E3%81%84%E3%81%98%E3%82%87%E3%81%86%E3%81%8B,%E3%81%97%E3%81%AA%E3%81%84%E7%A2%BA%E7%8E%87%E9%81%8E%E7%A8%8B%E3%82%92%E6%8C%87%E3%81%99%E3%80%82" class="u-lnk-clr"><br></a></p><ul><li><u><a href="https://ja.wikipedia.org/wiki/%E5%AE%9A%E5%B8%B8%E9%81%8E%E7%A8%8B#:~:text=%E5%AE%9A%E5%B8%B8%E9%81%8E%E7%A8%8B%EF%BC%88%E3%81%A6%E3%81%84%E3%81%98%E3%82%87%E3%81%86%E3%81%8B,%E3%81%97%E3%81%AA%E3%81%84%E7%A2%BA%E7%8E%87%E9%81%8E%E7%A8%8B%E3%82%92%E6%8C%87%E3%81%99%E3%80%82" target="_blank" class="u-lnk-clr">wiki</a></u></li><li><u><a href="https://ai-trend.jp/basic-study/time-series-analysis/time-series-analysis-stationaly-noise/" target="_blank" class="u-lnk-clr">【時系列分析の基本】定常性とホワイトノイズを分かりすく解説</a></u></li></ul><p><br></p><p><br></p><h3>単位根過程</h3><p><u><a href="https://ai-trend.jp/basic-study/time-series-analysis/time_analy_random_walk/" target="_blank" class="u-lnk-clr">時系列分析の単位根過程、ランダムウォークとは？</a></u><br></p><ul><li>定義：ytが非定常過程、また差分系列yt–yt–1=Δytが定常過程である時、ytは単位根過程である。</li><li>経済、金融データが従うランダムウォークは単位根過程の一種です。また、ARIMA、SARIMAモデルも単位根過程のひとつ。</li><li><p>単位根過程に従うxt,yt を回帰分析を行うと、まったく関係のないxt,ytの間に有意な相関を見出してしまう「見せかけの回帰」が行われます。「見せかけの回帰」は、例えば株価と二酸化炭素濃度という関係のない２つの間に相関性を導き出してしまいます。</p><p>そのため時系列データに対して回帰分析を行う時は「見せかけの回帰」に気を付ける必要があります。</p></li><li><p>「見せかけの回帰」を避けるためには、あらかじめ２つの時系列データxt,ytが単位根過程に従っているかどうか確認しなくてはなりません。そんな時は単位根過程であるかをチェックする単位根検定が行われます。</p></li></ul><p><br></p><p><br></p><h3>Ljung-Box検定</h3><p>Ljung-Box検定は、ある時系列の自己相関が存在するかどうかを次の設定で確かめる検定です。</p><p>H0: ラグ1からラグ m までの全てで自己相関が0</p><p>H1: ラグ1から m までの自己相関のうち、少なくとも一つが0でない</p><p>有意水準を5%としたとき、検定統計量の得られる確率が5%未満であれば「有意な（意味のありそうな）自己相関がある」と判断します。 逆に5%以上であれば、「有意な自己相関があるとは言えない（どちらともいえない）」と判断します。 Ljung-Box検定は、時系列モデルをあてはめた後に残差に対して行われ、残差が独立であることを確認するためにも使用されます。 これには、説明しきれなかった部分が本当にノイズであってほしい、というモチベーションがあります。 statsmodelsではacorr_ljungbox()で実装されています。</p><p><br></p><p><br></p><h3>ADF検定</h3><p>拡張Dickey-Fuller (ADF) 検定は、時系列が定常であるかどうかを確かめる検定です。<br></p><p>statsmodelsではadfuller()で実装されています。<a href="https://ai-trend.jp/basic-study/time-series-analysis/hypothesis-testing/" class="u-lnk-clr"><br></a></p><p><a href="https://ai-trend.jp/basic-study/time-series-analysis/hypothesis-testing/" class="u-lnk-clr"><br></a></p><p><u><a href="https://ai-trend.jp/basic-study/time-series-analysis/hypothesis-testing/" target="_blank" class="u-lnk-clr">時系列解析の検証に使われる2つの仮説検定方法</a></u>より<br></p><p><br></p><p><br></p><h3>非定常　-&gt;　定常　への変換</h3><ul><li><b>差分変換</b><br>一時点離れた値との差を取る差分変換により、平均に関して非定常な系列を定常にできる場合があります。<br>　　　　　　　　　Δyt = yt – yt − 1<br>差分変換は、系列が定常であるとみなせるようになるまで複数回行うことがあります。 一度差分をとることは一階差分と呼ばれ、さらにもう一度差分をとることは二階差分と呼ばれます。 周期性のあるデータに対しては、周期分だけ離れた値との差をとる季節差分を行うことがあります。<br><br><p>非負な原系列に対して対数を取る<b>対数変換</b>は、トレンドに比例してバラツキが変化するような系列に対して有効です。これは、対数をとることにより積の構造が和の構造に変わるためです。<br>　　　　　　　　　log(X×Y) = logX + logY<br><br></p></li><li><p><b>対数差分変換</b><br>金融の分野では、元の価格推移のデータを対数変換したのち差分変換する対数差分変換がしばしば行われ、変化後のデータは「対数収益率」とよばれます。 対数収益率を用いることには、「100円の銘柄が1円値上がりする」ことと「1000円の銘柄が1円値上がりする」ことの不平等さを解消できることなど、様々なメリットがあります。<a href="https://ai-trend.jp/basic-study/time-series-analysis/transformation/" class="u-lnk-clr"><br></a></p></li></ul><p><u><a href="https://ai-trend.jp/basic-study/time-series-analysis/transformation/" target="_blank" class="u-lnk-clr">非定常な時系列データを変換して定常性を持たせる解析</a></u>より<br></p>
		</div>
	]]></content></entry><entry><title><![CDATA[正規表現備忘録]]></title><link rel="alternate" href="https://study-storage.amebaownd.com/posts/10093580/"></link><id>https://study-storage.amebaownd.com/posts/10093580</id><summary><![CDATA[〇〇を含まない文字列の抽出参考サイト：http://www-creators.com/archives/1827特定のパターンで開始しない文字列　^(?!PATTERN).*$特定のパターンで終了しない文字列　^.*(?<!PATTERN)$特定のパターンを含まない文字列　^(?!.*PATTERN).*$]]></summary><author><name>yooooshi</name></author><published>2020-09-09T05:29:22+00:00</published><updated>2020-09-09T05:29:22+00:00</updated><content type="html"><![CDATA[
		<div>
			<h2>〇〇を含まない文字列の抽出</h2><p><br></p><p>参考サイト：</p><p><a href="http://www-creators.com/archives/1827" target="_blank" class="u-lnk-clr">http://www-creators.com/archives/1827</a><br></p><p><br></p><ul><li>特定のパターンで開始しない文字列<br>　<b>^(?!PATTERN).*$<br><br></b></li><li>特定のパターンで終了しない文字列<br>　<b>^.*(?&lt;!PATTERN)$</b><br><br></li><li>特定のパターンを含まない文字列<br>　<b>^(?!.*PATTERN).*$</b><br><br></li></ul>
		</div>
	]]></content></entry><entry><title><![CDATA[pandasのdataframeにPostgreSQLのデータを直接読み込むコード]]></title><link rel="alternate" href="https://study-storage.amebaownd.com/posts/10091196/"></link><link rel="enclosure" type="image/png" href="https://cdn.amebaowndme.com/madrid-prd/madrid-web/images/sites/635143/3b5b34cb9382407bdd3a87b8a2d05d2b_ea81e6dae30567ac4c969c82e0612207.png"></link><id>https://study-storage.amebaownd.com/posts/10091196</id><summary><![CDATA[上記は、以下のgithubより、https://github.com/The-Japan-DataScientist-Society/100knocks-preprocess]]></summary><author><name>yooooshi</name></author><published>2020-09-09T00:36:43+00:00</published><updated>2020-09-09T00:37:05+00:00</updated><content type="html"><![CDATA[
		<div>
			<img src="https://cdn.amebaowndme.com/madrid-prd/madrid-web/images/sites/635143/3b5b34cb9382407bdd3a87b8a2d05d2b_ea81e6dae30567ac4c969c82e0612207.png?width=960" width="100%">
		</div>
		

		<div>
			<p>上記は、以下のgithubより、</p><p>https://github.com/The-Japan-DataScientist-Society/100knocks-preprocess<br></p>
		</div>
	]]></content></entry></feed>