Juliaで作って学ぶベイズ統計学のJulia コードを実行してみた結果を,GItHubで公開してみています.
Jupyter Notebookが完成し次第,随時アップロードしていく予定です.
アップデートなので,すでにJuliaがインストールされている前提です.
Homebrewを使います.まずはターミナルから,以下のようしてJuliaをアップデートします.
% brew install julia --cask
% brew cask install julia
Error: `brew cask` is no longer a `brew` command. Use `brew <command> --cask` instead.
% brew cask install julia
その上で,"]"キーを押してパッケージモードに切り替えて,以下のように(add IJulia)IJuliaパッケージを追加します.
/Applications/Julia-1.8.app/Contents/Resources/julia/bin/julia ; exit;
% /Applications/Julia-1.8.app/Contents/Resources/julia/bin/julia ; exit;
_
_ _ _(_)_ | Documentation: https://docs.julialang.org
(_) | (_) (_) |
_ _ _| |_ __ _ | Type "?" for help, "]?" for Pkg help.
| | | | | | |/ _` | |
| | |_| | | | (_| | | Version 1.8.1 (2022-09-06)
_/ |\__'_|_|_|\__'_| | Official https://julialang.org/ release
|__/ |
(@v1.8) pkg> add IJulia
この↑例では省略していますが,add IJuliaを実行すると,ずらずらとインストールが始まります.
IJuliaパッケージの追加が終わった段階で,Available kernelsを確認すると,julia-1.8 が現れます.
% jupyter kernelspec list
Available kernels:
julia-1.0 /Users/hide/Library/Jupyter/kernels/julia-1.0
julia-1.8 /Users/hide/Library/Jupyter/kernels/julia-1.8
python3 /usr/local/share/jupyter/kernels/python3
Jupyter Notebookを立ち上げて,インストールしたJuliaを使えるかどうか確認しておきます.
Julia(今回は1.8.1)が使えるようになっていれば成功です.
使わないカーネルや,存在しないカーネル(今回の例では,Julia 1.0.5)を削除するにはターミナルから以下のように入力します.なお,"KERNEL_NAME"には使わなくなった,もしくは存在しないカーネルの名前を書きます.
% jupyter kernelspec uninstall KERNEL_NAME
% jupyter kernelspec uninstall julia-1.0
Kernel specs to remove:
julia-1.0 /Users/xxx/Library/Jupyter/kernels/julia-1.0
Remove 1 kernel specs [y/N]: y
[RemoveKernelSpec] Removed /Users/xxx/Library/Jupyter/kernels/julia-1.0
(@v1.8) pkg> add CSV
(@v1.8) pkg> add Combinatorics
(@v1.8) pkg> add DataFrames
(@v1.8) pkg> add Distributions
(@v1.8) pkg> add JuMP
(@v1.8) pkg> add Plots
(@v1.8) pkg> add PyCall
(@v1.8) pkg> add PyPlot
(@v1.8) pkg> add RDatasets
(@v1.8) pkg> add StatsBase
(@v1.8) pkg> add StatsPlots
(@v1.8) pkg> add SumOfSquares
(@v1.8) pkg> add Statistics
(@v1.8) pkg> add Gadfly
(@v1.8) pkg> add LinearAlgebra
(@v1.8) pkg> add Optim
(@v1.8) pkg> status
Status `~/.julia/environments/v1.8/Project.toml`
[336ed68f] CSV v0.10.4
[861a8166] Combinatorics v1.0.2
[a93c6f00] DataFrames v1.3.5
⌅ [31c24e10] Distributions v0.23.4
[c91e804a] Gadfly v1.3.4
[7073ff75] IJulia v1.23.3
[4076af6c] JuMP v1.3.0
[5424a776] Mamba v0.12.5
[429524aa] Optim v1.7.2
[91a5bcdd] Plots v1.32.1
[438e738f] PyCall v1.94.1
[d330b81b] PyPlot v2.11.0
[ce6b1742] RDatasets v0.7.7
[2913bbd2] StatsBase v0.33.21
⌃ [f3b207a7] StatsPlots v0.15.1
[4b9e565b] SumOfSquares v0.6.2
[37e2e46d] LinearAlgebra
[10745b16] Statistics
Info Packages marked with ⌃ and ⌅ have new versions available, but those with ⌅ cannot be upgraded. To see why use `status --outdated`
Pythonによるベイズ統計学入門に掲載されているコードを実行してみた際のメモです.
ベータ分布を描画するPythonのコード.
Pythonによるベイズ統計学入門に掲載されているコードを実行してみた際のメモです.
ベルヌーイ分布の成功確率の事前分布(一様分布とベルヌーイ分布)を描画するPythonのコード.
これを実行すると,以下の図が表示されます.
コードの簡単な解説は以下の通りです.
macOSに付属していたPython 2では NumPy, SciPy, matplotlib がプリインストールされていました.一方で,Python 3にはそれらがインストールされていないため,別途インストールが必要です.
インストールする際には,ターミナルで以下のようなコマンドを実行します.
まずは,NumPyのインストールです.
% python3 -m pip install --upgrade numpy
Requirement already satisfied: numpy in /usr/local/lib/python3.9/site-packages (1.20.2)
Collecting numpy
Downloading numpy-1.21.5-cp39-cp39-macosx_10_9_x86_64.whl (17.0 MB)
|████████████████████████████████| 17.0 MB 915 kB/s
Installing collected packages: numpy
Attempting uninstall: numpy
Found existing installation: numpy 1.20.2
Uninstalling numpy-1.20.2:
Successfully uninstalled numpy-1.20.2
Successfully installed numpy-1.21.5
次にSciPyのインストールです.実行するコマンドは以下です.
% python3 -m pip install --upgrade scipy
すると,以下のようにインストールが実行されます.
Collecting scipy
Downloading scipy-1.7.3-cp39-cp39-macosx_10_9_x86_64.whl (33.2 MB)
|████████████████████████████████| 33.2 MB 1.2 MB/s
Requirement already satisfied: numpy<1.23.0,>=1.16.5 in /usr/local/lib/python3.9/site-packages (from scipy) (1.21.5)
Installing collected packages: scipy
Successfully installed scipy-1.7.3
最後にmatplotlibのインストールです.実行するコマンドは以下です.
% python3 -m pip install --upgrade matplotlib
そうすると,インストールが始まります.
Requirement already satisfied: matplotlib in /usr/local/lib/python3.9/site-packages (3.4.2)
Collecting matplotlib
Downloading matplotlib-3.5.1-cp39-cp39-macosx_10_9_x86_64.whl (7.3 MB)
|████████████████████████████████| 7.3 MB 1.2 MB/s
Collecting fonttools>=4.22.0
Downloading fonttools-4.28.5-py3-none-any.whl (890 kB)
|████████████████████████████████| 890 kB 1.2 MB/s
Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.9/site-packages (from matplotlib) (0.10.0)
Requirement already satisfied: packaging>=20.0 in /usr/local/lib/python3.9/site-packages (from matplotlib) (20.9)
Requirement already satisfied: pyparsing>=2.2.1 in /usr/local/lib/python3.9/site-packages (from matplotlib) (2.4.7)
Requirement already satisfied: python-dateutil>=2.7 in /usr/local/lib/python3.9/site-packages (from matplotlib) (2.8.1)
Requirement already satisfied: numpy>=1.17 in /usr/local/lib/python3.9/site-packages (from matplotlib) (1.21.5)
Requirement already satisfied: pillow>=6.2.0 in /usr/local/lib/python3.9/site-packages (from matplotlib) (8.2.0)
Requirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.9/site-packages (from matplotlib) (1.3.1)
Requirement already satisfied: six in /usr/local/lib/python3.9/site-packages (from cycler>=0.10->matplotlib) (1.15.0)
Installing collected packages: fonttools, matplotlib
Attempting uninstall: matplotlib
Found existing installation: matplotlib 3.4.2
Uninstalling matplotlib-3.4.2:
Successfully uninstalled matplotlib-3.4.2
Successfully installed fonttools-4.28.5 matplotlib-3.5.1
hide@MBP ~ % pip3 install seaborn
Collecting seaborn
Using cached seaborn-0.11.2-py3-none-any.whl (292 kB)
Requirement already satisfied: pandas>=0.23 in /usr/local/lib/python3.9/site-packages (from seaborn) (1.2.4)
Requirement already satisfied: numpy>=1.15 in /usr/local/lib/python3.9/site-packages (from seaborn) (1.21.5)
Requirement already satisfied: matplotlib>=2.2 in /usr/local/lib/python3.9/site-packages (from seaborn) (3.5.1)
Requirement already satisfied: scipy>=1.0 in /usr/local/lib/python3.9/site-packages (from seaborn) (1.7.3)
Requirement already satisfied: python-dateutil>=2.7 in /usr/local/lib/python3.9/site-packages (from matplotlib>=2.2->seaborn) (2.8.1)
Requirement already satisfied: pillow>=6.2.0 in /usr/local/lib/python3.9/site-packages (from matplotlib>=2.2->seaborn) (8.2.0)
Requirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.9/site-packages (from matplotlib>=2.2->seaborn) (1.3.1)
Requirement already satisfied: packaging>=20.0 in /usr/local/lib/python3.9/site-packages (from matplotlib>=2.2->seaborn) (20.9)
Requirement already satisfied: pyparsing>=2.2.1 in /usr/local/lib/python3.9/site-packages (from matplotlib>=2.2->seaborn) (2.4.7)
Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.9/site-packages (from matplotlib>=2.2->seaborn) (0.10.0)
Requirement already satisfied: fonttools>=4.22.0 in /usr/local/lib/python3.9/site-packages (from matplotlib>=2.2->seaborn) (4.28.5)
Requirement already satisfied: six in /usr/local/lib/python3.9/site-packages (from cycler>=0.10->matplotlib>=2.2->seaborn) (1.15.0)
Requirement already satisfied: pytz>=2017.3 in /usr/local/lib/python3.9/site-packages (from pandas>=0.23->seaborn) (2021.1)
Installing collected packages: seaborn
Successfully installed seaborn-0.11.2
WARNING: You are using pip version 21.0.1; however, version 21.3.1 is available.
You should consider upgrading via the '/opt/homebrew/opt/python@3.9/bin/python3.9 -m pip install --upgrade pip' command.
% /opt/homebrew/opt/python@3.9/bin/python3.9 -m pip install --upgrade pip
Requirement already satisfied: pip in /opt/homebrew/lib/python3.9/site-packages (21.0.1)
Collecting pip
Downloading pip-21.3.1-py3-none-any.whl (1.7 MB)
|████████████████████████████████| 1.7 MB 4.7 MB/s
Installing collected packages: pip
Attempting uninstall: pip
Found existing installation: pip 21.0.1
Uninstalling pip-21.0.1:
Successfully uninstalled pip-21.0.1
Successfully installed pip-21.3.1
Pythonで予約語や組み込み関数を表示する際のメモです.
Pythonで予約語を表示するには"__import__('keyword').kwlist"というコマンドを用います.
>>> # 予約語を表示するコマンド
>>> __import__('keyword').kwlist
['False', 'None', 'True', '__peg_parser__', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
>>>
>>> # 組み込み関数を表示するコマンド
>>> dir(__builtins__)
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'ModuleNotFoundError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError', 'RecursionError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopAsyncIteration', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'ZeroDivisionError', '_', '__build_class__', '__debug__', '__doc__', '__import__', '__loader__', '__name__', '__package__', '__spec__', 'abs', 'all', 'any', 'ascii', 'bin', 'bool', 'breakpoint', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip']
>>>
Pythonで大量のテキストデータをマージする際のメモです.
大量のテキストデータをマージするPythonのコードを作成した際のメモです.
用途としては,Hi-netのダウンロードデータ(1分間)をマージすることを想定しています.
ダウンロードしたテキストデータは以下のような名前だとします(当然,これはこの例の場合なので,読み替えて下さい).
201412071000_Daimon_4b33
201412071000_Daimon_4b34
201412071000_Daimon_4b35
…
201412071059_Daimon_4b33
201412071059_Daimon_4b34
201412071059_Daimon_4b35
データの名前の末尾が"4b33","4b34","4b35"になっていますが,この末尾別にマージしたいとします.
コードは以下のようになります.
# Settiung では(マージして)作成するファイル名を設定します.ファイルを実行する際には,作成したいファイル名に設定します.この部分は必須ではなく,後述の "# Create new file "のところで設定しても良いのですが,プログラムの実行の際に書き換えたりする場所を限定したかったために,このような形式にしています.
# Import modules では,必要となるモジュール "glob" を読み込みます.
# Data append function では,以下の関数を定義しています.