markdown
stringlengths
0
1.02M
code
stringlengths
0
832k
output
stringlengths
0
1.02M
license
stringlengths
3
36
path
stringlengths
6
265
repo_name
stringlengths
6
127
上と下のコードセルでリストの連結を行っているが、++/2 演算子を用いている。 この `++/2` という表記は `++` が演算子自体で `/2` がアリティ (引数の数) を表す。 ---質問 $\quad$ アリティとはなにか。---質問 $\quad$ リストの連結に `++` で文字列の連結 `` なのはなぜか。 オーバーライディングはあるのか。 文字列 string はリストではないのか。 長さを測る関数も別々なのか。
# リストの連結 !elixir -e 'IO.inspect [1, 2] ++ [3, 4, 1]' # リストの減算 # --/2 演算子は存在しない値を引いてしまってもオッケー !elixir -e 'IO.inspect ["foo", :bar, 42] -- [42, "bar"]' # 重複した値の場合、右辺の要素のそれぞれに対し、左辺の要素のうち初めて登場した同じ値が順次削除 !elixir -e 'IO.inspect [1,2,2,3,2,3] -- [1,2,3,2]' # リストの減算の値のマッチには strict comparison が使われている !elixir -e 'IO.inspect ...
3.14 [:pie, "Apple"]
MIT
learnelixir.ipynb
kalz2q/myjupyternotebooks
---リストを頭部と尾部に分けるのに* パターンマッチング* cons 演算子( `|` )を使うこともできる。
!elixir -e '[head | tail] = [3.14, :pie, "Apple"]; IO.inspect head; IO.inspect tail'
3.14 [:pie, "Apple"]
MIT
learnelixir.ipynb
kalz2q/myjupyternotebooks
キーワードリストキーワードリストとマップは elixir の連想配列である。キーワードリストは最初の要素がアトムのタプルからなる特別なリストで、リストと同様の性能になる。
# キーワードリスト !elixir -e 'IO.inspect [foo: "bar", hello: "world"]' # タプルのリストとしても同じ !elixir -e 'IO.inspect [{:foo, "bar"}, {:hello, "world"}]' !elixir -e 'IO.inspect [foo: "bar", hello: "world"] == [{:foo, "bar"}, {:hello, "world"}]'
[foo: "bar", hello: "world"] [foo: "bar", hello: "world"] true
MIT
learnelixir.ipynb
kalz2q/myjupyternotebooks
キーワードリストの 3 つの特徴* キーはアトムである。* キーは順序付けされている。* キーの一意性は保証されない。こうした理由から、キーワードリストは関数にオプションを渡すためによく用いられる。
# 実験 リストの角括弧は省略できる !elixir -e 'IO.inspect foo: "bar", hello: "world"' # 実験 !elixir -e 'IO.inspect [1, fred: 1, dave: 2]' !elixir -e 'IO.inspect {1, fred: 1, dave: 2}' !elixir -e 'IO.inspect {1, [{:fred,1},{:dave, 2}]}'
[1, {:fred, 1}, {:dave, 2}] {1, [fred: 1, dave: 2]} {1, [fred: 1, dave: 2]}
MIT
learnelixir.ipynb
kalz2q/myjupyternotebooks
マップ* キーワードリストとは違ってどんな型のキーも使える。* 順序付けされない。* キーの一意性が保証されている。重複したキーが追加された場合は、前の値が置き換えられる。* 変数をマップのキーにできる。* `%{}` 構文で定義する。
!elixir -e 'IO.inspect %{:foo => "bar", "hello" => :world}' !elixir -e 'map = %{:foo => "bar", "hello" => :world}; IO.inspect map[:foo]' !elixir -e 'map = %{:foo => "bar", "hello" => :world}; IO.inspect map["hello"]' !echo !elixir -e 'key = "hello"; IO.inspect %{key => "world"}' !echo !elixir -e 'IO.inspect %{:foo => "...
%{:foo => "bar", "hello" => :world} "bar" :world %{"hello" => "world"} warning: key :foo will be overridden in map nofile:1 %{foo: "hello world"}
MIT
learnelixir.ipynb
kalz2q/myjupyternotebooks
アトムのキーだけを含んだマップには特別な構文がある。
!elixir -e 'IO.inspect %{foo: "bar", hello: "world"} == %{:foo => "bar", :hello => "world"}' # 加えて、アトムのキーにアクセスするための特別な構文がある。 !elixir -e 'map = %{foo: "bar", hello: "world"}; IO.inspect map.hello' !elixir -e 'map = %{foo: "bar", hello: "world"}; IO.inspect map[:hello]' !elixir -e 'map = %{:foo => "bar", :hello => "worl...
"world" "world" "world"
MIT
learnelixir.ipynb
kalz2q/myjupyternotebooks
---質問 map の特別な構文1. `=>` の代わりにコロン `:` を使う2. 要素を取り出すのに `[]` の代わりにピリオド `.` を使うは不要ではないか。不要だが見かけが良くなる、ということか。普通はどっちを使うのか。無駄に構文を複雑にするだけのような気がする。多分まず Python の dict でコロン `:` を使うこと、Ruby は `=>` を使うが糖衣構文としてコロン `:` が使えてその形が主流であることから、見かけ大切ということでこうなったのではないか。キーにアトムを使うことが前提ならば生産性が上がるかもしれない。キーであることを示すコロンが不要になる。fat arrow よりコロンの方が短い。map ...
# マップの更新のための構文がある (新しい map が作成される) # この構文は、マップに既に存在するキーを更新する場合にのみ機能する !elixir -e 'map = %{foo: "bar", hello: "world"}; IO.inspect %{map | foo: "baz"}' # 新しいキーを作成するには、`Map.put/3` を使用 !elixir -e 'map = %{hello: "world"}; IO.inspect Map.put(map, :foo, "baz")'
%{foo: "baz", hello: "world"}
MIT
learnelixir.ipynb
kalz2q/myjupyternotebooks
---質問 binary については良くわからないので別途。 バイナリ binary
# binaries !elixir -e 'IO.inspect <<1,2>>' !elixir -e 'IO.inspect <<1,10>>' !elixir -e 'bin = <<1,10>>; IO.inspect byte_size bin' !elixir -e 'bin = <<3::size(2),5::size(4),1::size(2)>>; IO.inspect bin' !elixir -e 'IO.puts Integer.to_string(213,2)' !elixir -e 'IO.puts 0b11' !elixir -e 'IO.puts 0b0101' !echo !elixir -e ...
<<1, 2, 3>>
MIT
learnelixir.ipynb
kalz2q/myjupyternotebooks
----** Date and Time 日付 **
# Date and Time !elixir -e 'IO.inspect Date.new(2021,6,2)' !elixir -e '{:ok, d1}=Date.new(2021,6,2); IO.inspect d1' !elixir -e '{:ok, d1}=Date.new(2021,6,2); IO.inspect Date.day_of_week(d1)' !elixir -e '{:ok, d1}=Date.new(2021,6,2); IO.inspect Date.add(d1,7)' !elixir -e '{:ok, d1}=Date.new(2021,6,2); IO.inspect d1, str...
~D[2021-06-02] 3 ~D[2021-06-09] %{__struct__: Date, calendar: Calendar.ISO, day: 2, month: 6, year: 2021}
MIT
learnelixir.ipynb
kalz2q/myjupyternotebooks
`~D[...]` や `~T[...]` は elixir の シギル sigil である。 文字列とバイナリーのところで説明する。 help についてメモ $\quad$ 関数の調べ方Helper の使い方。 help, type, info, information とか。下のコードセルにあるように、対象のモジュールの関数名を調べ、そのヘルプを見ればけっこうくわしくわかる。コメントアウトしてあるのは出力が大きいので、とりあえずコメントアウトして出力を抑制してある。具体的には、Enum にあたるところにモジュール名を入れて関数のリストを出す。 Ctrl+A Ctrl+C でコピーして vscode などでペーストして読む。 調...
# !elixir -e 'Enum.__info__(:functions) |> Enum.each(fn({function, arity}) -> IO.puts "#{function}/#{arity}" end)' # !elixir -e 'require IEx.Helpers;IEx.Helpers.h Enum.all?/1' # h 単独のドキュメントを見たい # !elixir -e 'require IEx.Helpers;IEx.Helpers.h' # i というのもある # !elixir -e 'x = [3,2]; require IEx.Helpers;IEx.Helpers.i x' # !...
_____no_output_____
MIT
learnelixir.ipynb
kalz2q/myjupyternotebooks
Enum モジュールEnum はリストなどコレクションを列挙するための一連のアルゴリズム。* all?、any?* chunk_every、chunk_by、map_every* each* map、filter、reduce* min、max* sort、uniq、uniq_by* キャプチャ演算子 `(&)`
# all? 関数を引数で受け取り、リストの全体が true の時、true を返す !elixir -e 'IO.puts Enum.all?(["foo", "bar", "hello"], fn(s) -> String.length(s) == 3 end)' !elixir -e 'IO.puts Enum.all?(["foo", "bar", "hello"], fn(s) -> String.length(s) >1 end)' # any? 少なくとも1つの要素が true と評価された場合に true を返す !elixir -e 'IO.puts Enum.any?(["foo", "bar", "hello"...
[1, 2, 3] [%{x: 1, y: 1}, %{x: 3, y: 3}]
MIT
learnelixir.ipynb
kalz2q/myjupyternotebooks
キャプチャ演算子 `&` を使用した Enum と無名関数 elixir の Enum モジュール内の多くの関数は、引数として無名関数を取る。これらの無名関数は、多くの場合、キャプチャ演算子 `&` を使用して省略形で記述される。
# 無名関数でのキャプチャ演算子の使用 !elixir -e 'IO.inspect Enum.map([1,2,3], fn number -> number + 3 end)' !elixir -e 'IO.inspect Enum.map([1,2,3], &(&1 + 3))' !elixir -e 'plus_three = &(&1 + 3);IO.inspect Enum.map([1,2,3], plus_three)' # Enum.all? でもキャプチャ演算子が使えるか # all? 関数を引数で受け取り、リストの全体が true の時、true を返す # !elixir -e 'IO.puts Enum....
false true
MIT
learnelixir.ipynb
kalz2q/myjupyternotebooks
--- パターンマッチングパターンマッチングでは、値、データ構造、関数をマッチすることができる。* マッチ演算子* ピン演算子
# マッチ演算子 `=` はマッチ演算子である。 マッチ演算子を通して値を代入し、 # その後、マッチさせることができる。マッチすると、方程式の結果が返され、 # 失敗すると、エラーになる !elixir -e 'IO.puts x = 1' !elixir -e 'x = 1;IO.puts 1 = x' # !elixir -e 'x = 1;IO.puts 2 = x' #=> (MatchError) no match of right hand side value: 1 # リストでのマッチ演算子 !elixir -e 'IO.inspect list = [1, 2, 3]' !elixir -e 'list = [1...
{:ok, "Successful!"} "Successful!"
MIT
learnelixir.ipynb
kalz2q/myjupyternotebooks
---**ピン演算子**マッチ演算子は左辺に変数が含まれている時に代入操作を行う。 この変数を再び束縛するという挙動は望ましくない場合がある。 そうした状況のために、ピン演算子 `^` がある。ピン演算子で変数を固定すると、新しく再束縛するのではなく既存の値とマッチする。
# ピン演算子 !elixir -e 'IO.inspect x = 1' # !elixir -e 'x = 1; IO.inspect ^x = 2' #=> ** (MatchError) no match of right hand side value: 2 !elixir -e 'x = 1; IO.inspect {x, ^x} = {2, 1}' !elixir -e 'x = 1;{x, ^x} = {2, 1}; IO.inspect x' !echo !elixir -e 'IO.inspect key = "hello"' !elixir -e 'key = "hello"; IO.inspect %{^ke...
"Hello" #Function<43.65746770/2 in :erl_eval.expr/5> "Hi Sean" "Mornin,Sean"
MIT
learnelixir.ipynb
kalz2q/myjupyternotebooks
制御構造 control structure* if と unless* case* cond* with if と unless elixir の if と unless は ruby と同じ。elixir は if と unless はマクロとして定義されている。この実装は kernel module で知ることができる。elixir では偽とみなされる値は nil と真理値の false だけだということに留意。
%%writefile temp.exs IO.puts ( if String.valid?("Hello") do "Valid string!" else "Invalid string." end) !elixir temp.exs %%writefile temp.exs if "a string value" do IO.puts "Truthy" end !elixir temp.exs # unless/2 は if/2 の逆で、条件が否定される時だけ作用する %%writefile temp.exs unless is_integer("hello") d...
Will match
MIT
learnelixir.ipynb
kalz2q/myjupyternotebooks
---ガード節とは何か?公式ドキュメントの Expressions allowed in guard clauses を参照
# cond !elixir -e 'IO.puts (cond do 2+2==5 -> "This will not be true"; 2*2==3 -> "Nor this"; 1+1 == 2 -> "But this will" end)' # cond も case と同様マッチしない場合にエラーになるので、true になる条件を定義する !elixir -e 'IO.puts (cond do 7+1==0 -> "Incorrect"; true -> "Catch all" end)' # with # 特殊形式の with/1 はネストされた case/2 文やきれいにパイプできない状況に便利 # with/1...
We don't have this item in map :error
MIT
learnelixir.ipynb
kalz2q/myjupyternotebooks
関数 Function
# 関数型言語では、関数は第一級オブジェクト first class object である # ここでは無名関数、名前付き関数、アリティ、パターンマッチング、プライベート関数、ガード、デフォルト引数について学ぶ # 無名関数 anonymous function # fn end のキーワードを用い、 引数 `->` 関数定義 の形で定義する %%writefile temp.exs sum = fn (a, b) -> a + b end IO.puts sum.(2, 3) !elixir temp.exs # シェルワンライナーで書いてみる !elixir -e 'sum=fn(a,b)->a+b end;IO.puts ...
5
MIT
learnelixir.ipynb
kalz2q/myjupyternotebooks
---質問 無名関数に引数を渡して結果を得るのはどうやるのか&(&1 + &2).(2, 3) として出来なかった。 => 出来た。!elixir -e 'IO.puts ((&(&1 + &2)).(2,3))'
!elixir -e 'IO.puts ((fn (a,b) -> a + b end).(2,3))' !elixir -e 'IO.puts ((&(&1 + &2)).(2,3))' # 関数定義にパターンマッチングが使える %%writefile temp.exs handle_result = fn {:ok, _result} -> IO.puts "Handling result..." {:ok, _} -> IO.puts "This would be never run as previous will be matched beforehand." {:error} -> IO.puts "An e...
Hello, Fred %{age: "95", favorite_color: "Taupe", name: "Fred"} Hello, Fred %{name: "Fred"}
MIT
learnelixir.ipynb
kalz2q/myjupyternotebooks
# %{name: person_name} と person の順序を入れ替えても、それぞれがfredとマッチングするので同じ結果となる # 変数とマップを入れ替えてみる # それぞれがパターンマッチしているので結果は同じになる %%writefile temp.exs defmodule Greeter3 do def hello(person = %{name: person_name}) do IO.puts "Hello, " <> person_name IO.inspect person end end fred = %{ name: "Fred", age: "95", ...
Hello, Sean, Steve Hello, Bill
MIT
learnelixir.ipynb
kalz2q/myjupyternotebooks
---質問 Elixir のガードは Haskell のガードと同じか?
# デフォルト引数 # デフォルト値が欲しい場合、引数 \\ デフォルト値の記法を用いる %%writefile temp.exs defmodule Greeter do def hello(name, language_code \\ "en") do phrase(language_code) <> name end defp phrase("en"), do: "Hello, " defp phrase("es"), do: "Hola, " end IO.puts Greeter.hello("Sean", "en") IO.puts Greeter.hello("Sean") IO.puts ...
true
MIT
learnelixir.ipynb
kalz2q/myjupyternotebooks
モジュール ---質問 いままで IO.puts とか一々モジュール名を付けていたが、elixir ではこれが普通なのか?関数を作る際に一々モジュールを作成していたがあれで既存のモジュールに付け加えられているのか?
# モジュールの基本的な例 %%writefile temp.exs defmodule Example do def greeting(name) do "Hello #{name}." end end IO.puts Example.greeting "Sean" !elixir temp.exs # モジュールはネストする事ができる %%writefile temp.exs defmodule Example.Greetings do def morning(name) do "Good morning #{name}." end def evening(name) do "Go...
Hola, Sean
MIT
learnelixir.ipynb
kalz2q/myjupyternotebooks
Mix
# mixとは Ruby の Bundler, RubyGems, Rake が組み合わさったようなもの # colab の環境でやってみる !mix new example #=> # * creating README.md # * creating .formatter.exs # * creating .gitignore # * creating mix.exs # * creating lib # * creating lib/example.ex # * creating test # * creating test/test_helper.exs # * creating test/example_test.exs...
_____no_output_____
MIT
learnelixir.ipynb
kalz2q/myjupyternotebooks
シギル sigil
# シギル sigil とは elixir で文字列リテラルを取り扱うための特別の構文 # チルダ ~ で始まる # シギルのリスト # ~C エスケープや埋め込みを含まない文字のリストを生成する # ~c エスケープや埋め込みを含む文字のリストを生成する # ~R エスケープや埋め込みを含まない正規表現を生成する # ~r エスケープや埋め込みを含む正規表現を生成する # ~S エスケープや埋め込みを含まない文字列を生成する # ~s エスケープや埋め込みを含む文字列を生成する # ~W エスケープや埋め込みを含まない単語のリストを生成する # ~w エスケープや埋め込みを含む単語のリストを生成する # ~N NaiveDat...
ELIXIR SCHOOL
MIT
learnelixir.ipynb
kalz2q/myjupyternotebooks
**ドキュメント** **インラインドキュメント用の属性*** @moduledoc - モジュールレベルのドキュメント用* @doc - 関数レベルのドキュメント用省略 **テスト**ExUnit省略 内包表記
# 内包表記 list comprehension # 内包表記は列挙体 enumerable をループするための糖衣構文である !elixir -e 'list=[1,2,3,4,5];IO.inspect for x <- list, do: x*x' # for とジェネレータの使い方に留意する # ジェネレータとは `x <- list` の部分 # Haskell だと [x * x | x <- list] と書き、数学の集合での表記に近いが Elixir ではこのように書く # 内包表記はリストに限定されない # キーワードリスト !elixir -e 'IO.inspect for {_key, val} <- ...
"Hello"
MIT
learnelixir.ipynb
kalz2q/myjupyternotebooks
文字列
# 文字列 string # elixir の文字列はバイトのシーケンスである !elixir -e 'string = <<104,101,108,108,111>>;IO.puts string' !elixir -e 'string = <<104,101,108,108,111>>;IO.inspect string' !elixir -e 'IO.inspect <<104,101,108,108,111>>' !echo # 文字列に 0 バイトを追加するとバイナリとして表示される !elixir -e 'IO.inspect <<104,101,108,108,111,0>>' # 質問 文字列をバイナリ表示するにはど...
_____no_output_____
MIT
learnelixir.ipynb
kalz2q/myjupyternotebooks
日付と時間
# 日付と時間 # 現在時刻の取得 !elixir -e 'IO.puts Time.utc_now' # シギルで Time 構造体を作る !elixir -e 'IO.puts ~T[21:00:27.472988]' # hour, minute, second !elixir -e 't = ~T[21:00:27.472988];IO.puts t.hour' !elixir -e 't = ~T[21:00:27.472988];IO.puts t.minute' !elixir -e 't = ~T[21:00:27.472988];IO.puts t.second' # Date !elixir -e 'IO.pu...
Overwriting temp.exs
MIT
learnelixir.ipynb
kalz2q/myjupyternotebooks
カスタムMixタスク 省略 いまここ IEx Helpers 省略
_____no_output_____
MIT
learnelixir.ipynb
kalz2q/myjupyternotebooks
NeuroTorch Tutorial**NeuroTorch** is a framework for reconstructing neuronal morphology fromoptical microscopy images. It interfaces PyTorch with differentautomated neuron tracing algorithms for fast, accurate, scalableneuronal reconstructions. It uses deep learning to generate an initialsegmentation of neurons in opt...
from neurotorch.datasets.specification import JsonSpec import os IMAGE_PATH = '../../tests/images/' json_spec = JsonSpec() # Initialize the JSON specification # Create a dataset containing the inputs inputs = json_spec.open(os.path.join(IMAGE_PATH, "inputs_spec.json")) # Create...
_____no_output_____
BSD-3-Clause
docs/tutorials/neurotorch-tutorial.ipynb
jgornet/NeuroTorch
Augmenting datasetsWith the image datasets, it is possible to augment data on-the-fly. To implement an augmentation–such as branch occlusion—instantiate an aligned volume and specify the augmentation with the aligned volume.
from neurotorch.datasets.dataset import AlignedVolume from neurotorch.augmentations.occlusion import Occlusion from neurotorch.augmentations.blur import Blur from neurotorch.augmentations.brightness import Brightness from neurotorch.augmentations.dropped import Drop from neurotorch.augmentations.duplicate import Duplic...
_____no_output_____
BSD-3-Clause
docs/tutorials/neurotorch-tutorial.ipynb
jgornet/NeuroTorch
Training with the image datasetsTo train a neural network using these image datasets, load the neural network architecture and initialize a `Trainer`. To savetraining checkpoints, add a `CheckpointWriter` to the `Trainer` object.Lastly, call the `Trainer` object to run training.
from neurotorch.core.trainer import Trainer from neurotorch.nets.RSUNet import RSUNet from neurotorch.training.checkpoint import CheckpointWriter from neurotorch.training.logging import ImageWriter, LossWriter net = RSUNet() # Initialize the U-Net architecture # Setup the trainer trainer = Trainer(net, augmented_volu...
_____no_output_____
BSD-3-Clause
docs/tutorials/neurotorch-tutorial.ipynb
jgornet/NeuroTorch
Predicting using NeuroTorchOnce training has completed, we can use the training checkpointsto predict on image datasets. We first have to load the neural network architecture and image volume.We then have to initialize a `Predictor` object and an output volume.Once these have been specified, we can begin prediction.
from neurotorch.nets.RSUNet import RSUNet from neurotorch.core.predictor import Predictor from neurotorch.datasets.filetypes import TiffVolume from neurotorch.datasets.dataset import Array from neurotorch.datasets.datatypes import (BoundingBox, Vector) import numpy as np import tifffile as tif import os IMAGE_PATH = '...
_____no_output_____
BSD-3-Clause
docs/tutorials/neurotorch-tutorial.ipynb
jgornet/NeuroTorch
Displaying the predictionPredictions are output in logits form. To map this to aprobability distribution, we need to apply a sigmoid functionto the prediction. We can then evaluate the prediction and ground-truth.
# Apply sigmoid function probability_map = 1/(1+np.exp(-output_volume.getArray())) # Plot prediction and ground-truth plt.subplot(2, 1, 1) plt.title('Prediction') plt.imshow(output_volume.getArray()[25]) plt.axis('off') plt.subplot(2, 1, 2) plt.title('Ground-Truth') plt.imshow(labels.get( BoundingBox(Vector(0, 0,...
_____no_output_____
BSD-3-Clause
docs/tutorials/neurotorch-tutorial.ipynb
jgornet/NeuroTorch
This IPython Notebook introduces the use of the `openmc.mgxs` module to calculate multi-group cross sections for an infinite homogeneous medium. In particular, this Notebook introduces the the following features:* **General equations** for scalar-flux averaged multi-group cross sections* Creation of multi-group cross s...
from IPython.display import Image Image(filename='images/mgxs.png', width=350)
_____no_output_____
MIT
examples/jupyter/mgxs-part-i.ipynb
cchaugen/temp_openmc_for_Sterling
A variety of tools employing different methodologies have been developed over the years to compute multi-group cross sections for certain applications, including NJOY (LANL), MC$^2$-3 (ANL), and Serpent (VTT). The `openmc.mgxs` Python module is designed to leverage OpenMC's tally system to calculate multi-group cross s...
%matplotlib inline import numpy as np import matplotlib.pyplot as plt import openmc import openmc.mgxs as mgxs
_____no_output_____
MIT
examples/jupyter/mgxs-part-i.ipynb
cchaugen/temp_openmc_for_Sterling
We being by creating a material for the homogeneous medium.
# Instantiate a Material and register the Nuclides inf_medium = openmc.Material(name='moderator') inf_medium.set_density('g/cc', 5.) inf_medium.add_nuclide('H1', 0.028999667) inf_medium.add_nuclide('O16', 0.01450188) inf_medium.add_nuclide('U235', 0.000114142) inf_medium.add_nuclide('U238', 0.006886019) inf_medium.add...
_____no_output_____
MIT
examples/jupyter/mgxs-part-i.ipynb
cchaugen/temp_openmc_for_Sterling
With our material, we can now create a `Materials` object that can be exported to an actual XML file.
# Instantiate a Materials collection and export to XML materials_file = openmc.Materials([inf_medium]) materials_file.export_to_xml()
_____no_output_____
MIT
examples/jupyter/mgxs-part-i.ipynb
cchaugen/temp_openmc_for_Sterling
Now let's move on to the geometry. This problem will be a simple square cell with reflective boundary conditions to simulate an infinite homogeneous medium. The first step is to create the outer bounding surfaces of the problem.
# Instantiate boundary Planes min_x = openmc.XPlane(boundary_type='reflective', x0=-0.63) max_x = openmc.XPlane(boundary_type='reflective', x0=0.63) min_y = openmc.YPlane(boundary_type='reflective', y0=-0.63) max_y = openmc.YPlane(boundary_type='reflective', y0=0.63)
_____no_output_____
MIT
examples/jupyter/mgxs-part-i.ipynb
cchaugen/temp_openmc_for_Sterling
With the surfaces defined, we can now create a cell that is defined by intersections of half-spaces created by the surfaces.
# Instantiate a Cell cell = openmc.Cell(cell_id=1, name='cell') # Register bounding Surfaces with the Cell cell.region = +min_x & -max_x & +min_y & -max_y # Fill the Cell with the Material cell.fill = inf_medium
_____no_output_____
MIT
examples/jupyter/mgxs-part-i.ipynb
cchaugen/temp_openmc_for_Sterling
OpenMC requires that there is a "root" universe. Let us create a root universe and add our square cell to it.
# Create root universe root_universe = openmc.Universe(name='root universe', cells=[cell])
_____no_output_____
MIT
examples/jupyter/mgxs-part-i.ipynb
cchaugen/temp_openmc_for_Sterling
We now must create a geometry that is assigned a root universe and export it to XML.
# Create Geometry and set root Universe openmc_geometry = openmc.Geometry(root_universe) # Export to "geometry.xml" openmc_geometry.export_to_xml()
_____no_output_____
MIT
examples/jupyter/mgxs-part-i.ipynb
cchaugen/temp_openmc_for_Sterling
Next, we must define simulation parameters. In this case, we will use 10 inactive batches and 40 active batches each with 2500 particles.
# OpenMC simulation parameters batches = 50 inactive = 10 particles = 2500 # Instantiate a Settings object settings_file = openmc.Settings() settings_file.batches = batches settings_file.inactive = inactive settings_file.particles = particles settings_file.output = {'tallies': True} # Create an initial uniform spatia...
_____no_output_____
MIT
examples/jupyter/mgxs-part-i.ipynb
cchaugen/temp_openmc_for_Sterling
Now we are ready to generate multi-group cross sections! First, let's define a 2-group structure using the built-in `EnergyGroups` class.
# Instantiate a 2-group EnergyGroups object groups = mgxs.EnergyGroups() groups.group_edges = np.array([0., 0.625, 20.0e6])
_____no_output_____
MIT
examples/jupyter/mgxs-part-i.ipynb
cchaugen/temp_openmc_for_Sterling
We can now use the `EnergyGroups` object, along with our previously created materials and geometry, to instantiate some `MGXS` objects from the `openmc.mgxs` module. In particular, the following are subclasses of the generic and abstract `MGXS` class:* `TotalXS`* `TransportXS`* `AbsorptionXS`* `CaptureXS`* `FissionXS`*...
# Instantiate a few different sections total = mgxs.TotalXS(domain=cell, groups=groups) absorption = mgxs.AbsorptionXS(domain=cell, groups=groups) scattering = mgxs.ScatterXS(domain=cell, groups=groups) # Note that if we wanted to incorporate neutron multiplication in the # scattering cross section we would write the ...
_____no_output_____
MIT
examples/jupyter/mgxs-part-i.ipynb
cchaugen/temp_openmc_for_Sterling
Each multi-group cross section object stores its tallies in a Python dictionary called `tallies`. We can inspect the tallies in the dictionary for our `Absorption` object as follows.
absorption.tallies
_____no_output_____
MIT
examples/jupyter/mgxs-part-i.ipynb
cchaugen/temp_openmc_for_Sterling
The `Absorption` object includes tracklength tallies for the 'absorption' and 'flux' scores in the 2-group structure in cell 1. Now that each `MGXS` object contains the tallies that it needs, we must add these tallies to a `Tallies` object to generate the "tallies.xml" input file for OpenMC.
# Instantiate an empty Tallies object tallies_file = openmc.Tallies() # Add total tallies to the tallies file tallies_file += total.tallies.values() # Add absorption tallies to the tallies file tallies_file += absorption.tallies.values() # Add scattering tallies to the tallies file tallies_file += scattering.tallies...
/home/romano/openmc/openmc/mixin.py:61: IDWarning: Another CellFilter instance already exists with id=3. warn(msg, IDWarning) /home/romano/openmc/openmc/mixin.py:61: IDWarning: Another EnergyFilter instance already exists with id=4. warn(msg, IDWarning)
MIT
examples/jupyter/mgxs-part-i.ipynb
cchaugen/temp_openmc_for_Sterling
Now we a have a complete set of inputs, so we can go ahead and run our simulation.
# Run OpenMC openmc.run()
%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%...
MIT
examples/jupyter/mgxs-part-i.ipynb
cchaugen/temp_openmc_for_Sterling
Tally Data Processing Our simulation ran successfully and created statepoint and summary output files. We begin our analysis by instantiating a `StatePoint` object.
# Load the last statepoint file sp = openmc.StatePoint('statepoint.50.h5')
_____no_output_____
MIT
examples/jupyter/mgxs-part-i.ipynb
cchaugen/temp_openmc_for_Sterling
In addition to the statepoint file, our simulation also created a summary file which encapsulates information about the materials and geometry. By default, a `Summary` object is automatically linked when a `StatePoint` is loaded. This is necessary for the `openmc.mgxs` module to properly process the tally data. The sta...
# Load the tallies from the statepoint into each MGXS object total.load_from_statepoint(sp) absorption.load_from_statepoint(sp) scattering.load_from_statepoint(sp)
_____no_output_____
MIT
examples/jupyter/mgxs-part-i.ipynb
cchaugen/temp_openmc_for_Sterling
Voila! Our multi-group cross sections are now ready to rock 'n roll! Extracting and Storing MGXS Data Let's first inspect our total cross section by printing it to the screen.
total.print_xs()
Multi-Group XS Reaction Type = total Domain Type = cell Domain ID = 1 Cross Sections [cm^-1]: Group 1 [0.625 - 20000000.0eV]: 6.81e-01 +/- 2.69e-01% Group 2 [0.0 - 0.625 eV]: 1.40e+00 +/- 5.93e-01%
MIT
examples/jupyter/mgxs-part-i.ipynb
cchaugen/temp_openmc_for_Sterling
Since the `openmc.mgxs` module uses [tally arithmetic](http://openmc.readthedocs.io/en/latest/examples/tally-arithmetic.html) under-the-hood, the cross section is stored as a "derived" `Tally` object. This means that it can be queried and manipulated using all of the same methods supported for the `Tally` class in the ...
df = scattering.get_pandas_dataframe() df.head(10)
_____no_output_____
MIT
examples/jupyter/mgxs-part-i.ipynb
cchaugen/temp_openmc_for_Sterling
Each multi-group cross section object can be easily exported to a variety of file formats, including CSV, Excel, and LaTeX for storage or data processing.
absorption.export_xs_data(filename='absorption-xs', format='excel')
_____no_output_____
MIT
examples/jupyter/mgxs-part-i.ipynb
cchaugen/temp_openmc_for_Sterling
The following code snippet shows how to export all three `MGXS` to the same HDF5 binary data store.
total.build_hdf5_store(filename='mgxs', append=True) absorption.build_hdf5_store(filename='mgxs', append=True) scattering.build_hdf5_store(filename='mgxs', append=True)
_____no_output_____
MIT
examples/jupyter/mgxs-part-i.ipynb
cchaugen/temp_openmc_for_Sterling
Comparing MGXS with Tally Arithmetic Finally, we illustrate how one can leverage OpenMC's [tally arithmetic](http://openmc.readthedocs.io/en/latest/examples/tally-arithmetic.html) data processing feature with `MGXS` objects. The `openmc.mgxs` module uses tally arithmetic to compute multi-group cross sections with auto...
# Use tally arithmetic to compute the difference between the total, absorption and scattering difference = total.xs_tally - absorption.xs_tally - scattering.xs_tally # The difference is a derived tally which can generate Pandas DataFrames for inspection difference.get_pandas_dataframe()
_____no_output_____
MIT
examples/jupyter/mgxs-part-i.ipynb
cchaugen/temp_openmc_for_Sterling
Similarly, we can use tally arithmetic to compute the ratio of `AbsorptionXS` and `ScatterXS` to the `TotalXS`.
# Use tally arithmetic to compute the absorption-to-total MGXS ratio absorption_to_total = absorption.xs_tally / total.xs_tally # The absorption-to-total ratio is a derived tally which can generate Pandas DataFrames for inspection absorption_to_total.get_pandas_dataframe() # Use tally arithmetic to compute the scatter...
_____no_output_____
MIT
examples/jupyter/mgxs-part-i.ipynb
cchaugen/temp_openmc_for_Sterling
Lastly, we sum the derived scatter-to-total and absorption-to-total ratios to confirm that they sum to unity.
# Use tally arithmetic to ensure that the absorption- and scattering-to-total MGXS ratios sum to unity sum_ratio = absorption_to_total + scattering_to_total # The sum ratio is a derived tally which can generate Pandas DataFrames for inspection sum_ratio.get_pandas_dataframe()
_____no_output_____
MIT
examples/jupyter/mgxs-part-i.ipynb
cchaugen/temp_openmc_for_Sterling
Bungee Characterization Lab PH 211 COCC Bruce Emerson 1/20/2021This notebook is meant to provide tools and discussion to support data analysis and presentation as you generate your lab reports. [Bungee Characterization (Bungee I)](http://coccweb.cocc.edu/bemerson/PhysicsGlobal/Courses/PH211/PH211Materials/PH211Labs/PH...
import numpy as np import matplotlib as mplot import matplotlib.pyplot as plt
_____no_output_____
MIT
Bungee/.ipynb_checkpoints/BungeeCharacLab-checkpoint.ipynb
JNichols-19/PH211
Data Entry (Lists/Vectors)As we learned last week we can manually enter our data in as lists. See last weeks lab for reminders if needed. In this lab we are working with data pairs (x,y data). There are a number of ways of doing this but the most conceptually direct approach is to create an ordered list of the xdata a...
# this is the actual data from your experiment xdata1 = [3.23961446, 12.3658087, 27.08638038, 36.88808393, 48.5373278, 43.90496472, 75.81073494, 105.42389529, 123.53497036, 158.87537602] ydata1 = [0.62146893, 1.53513096, 3.97591135, 4.54284862, 6.23415512, 5.12951366, 6.1733864, 7.95...
stretch data: [3.23961446, 12.3658087, 27.08638038, 36.88808393, 48.5373278, 43.90496472, 75.81073494, 105.42389529, 123.53497036, 158.87537602] force data: [0.62146893, 1.53513096, 3.97591135, 4.54284862, 6.23415512, 5.12951366, 6.1733864, 7.9524996, 8.90050684, 10.29383595]
MIT
Bungee/.ipynb_checkpoints/BungeeCharacLab-checkpoint.ipynb
JNichols-19/PH211
Number of Data Points:Because we are scatter plotting the data we need to be sure that every x value has a related y value or the plotting routines will complain. Previously we learned to use the ```len()``` function to determine the number of data points in a list. We do that again here. Extra: Conditional Statements...
# determine the lengths of the data lists xdata1length = len(xdata1) ydata1length = len(ydata1) # print out the lengths- visually check that they are the same print("number of data points (x):", xdata1length) print("number of data points (y):", ydata1length) if (xdata1length == ydata1length): print("Looks good:)"...
number of data points (x): 10 number of data points (y): 10 Looks good:)
MIT
Bungee/.ipynb_checkpoints/BungeeCharacLab-checkpoint.ipynb
JNichols-19/PH211
Scatter Plots Most data that we will want to analyze in physics is (x,y) data. For this type of data the typical plot type is called a scatter plot which is just what you think of when you plot individual data points.To begin the process in python we need to create a container for the multiple plots we will be creatin...
# create a figure with a set of axes as we did with histograms fig1, ax1 = plt.subplots() # scatter plot data set 1 ax1.scatter(xdata1, ydata1) # set up labels and titles for the plot and turn on the grid lines ax1.set(xlabel='independent variable (units)', ylabel='dependent variable (units)', title='My Data f...
_____no_output_____
MIT
Bungee/.ipynb_checkpoints/BungeeCharacLab-checkpoint.ipynb
JNichols-19/PH211
Adding more dataWhen I want to add more data I just make another plot on a new set of axes. I have to start a new container (fig) because the ```plt.show()``` call blocks me from adding more information to the plot (there is something in this that is still not clear to me and perhaps soon I will
# a new set of axes fig2, ax2 = plt.subplots() ax2.scatter(xdata1, ydata1, color = 'blue') ax2.scatter(xdata2, ydata2, color = 'red') ax2.set(xlabel='independent variable (units)', ylabel='dependent variable (units)', title='My Data from Lab') ax2.grid() # Set the size of my plot for better visibility fig2.set...
_____no_output_____
MIT
Bungee/.ipynb_checkpoints/BungeeCharacLab-checkpoint.ipynb
JNichols-19/PH211
Discussion: Deliverable 2The second deliverable asks you to consider the data from your plot(s) and describe whether it has features that are consistent with an ideal physics spring (Hooke's Law). Are some regions linear? ....sort of? Is the spring stiffer at the beginning or at the end of data? Explain your answer. D...
# actual model parameters - slope and intercept model1slope = .12 model2slope = .045 model1int = 0. model2int = 3. # range of x values -- choose lower and upper limits of range model1x = np.linspace(0.,50.,20) model2x = np.linspace(30.,170.,20) # in case you want to check how many values are generated # modellength =...
_____no_output_____
MIT
Bungee/.ipynb_checkpoints/BungeeCharacLab-checkpoint.ipynb
JNichols-19/PH211
Plotting ReferencesThere are a range of different marks that you can use to plot your data points on the scatter plot. Here is the link... [marker types for scatter plot](https://matplotlib.org/3.1.0/api/markers_api.htmlmodule-matplotlib.markers)There are also a range of colors that you can use for all plots. I am no...
fig3, ax3 = plt.subplots() # scatter plot of the data ax3.scatter(xdata1, ydata1, marker = 'x', color = 'black', label = "82 cm Bungee") # draw the two lines that represent my model ax3.plot(model1x, model1y, color = 'red', linestyle = ':', linewidth = 3., label = "initial") ax3.plot(model2x, model2y, color = 'green',...
_____no_output_____
MIT
Bungee/.ipynb_checkpoints/BungeeCharacLab-checkpoint.ipynb
JNichols-19/PH211
Discussion: Deliverable IIISo what does your plot above mean? What explanation of the behavior of the bungee is suggested by the two line fit? NormalizationNormalization is the process of trying to see if a particular feature of the data has a simple dependence. In this case each bungee is a different length but othe...
length1 = 75. xdata1norm = np.true_divide(xdata1,length1) fig, axn = plt.subplots() axn.scatter(xdata1norm, ydata1) axn.set(xlabel='independent variable (units)', ylabel='dependent variable (units)', title='My Data from Lab') axn.grid() #fig.savefig("myplot.png") plt.show()
_____no_output_____
MIT
Bungee/.ipynb_checkpoints/BungeeCharacLab-checkpoint.ipynb
JNichols-19/PH211
Data SimilarityPrevious experiments have had some strange results, with models occasionally performing abnormally well (or badly) on the out of sample set. To make sure that there are no duplicate samples or abnormally similar studies, I made this notebook
import json import matplotlib.pyplot as plt import numpy as np import pandas as pd import yaml from plotnine import * from sklearn.metrics.pairwise import euclidean_distances from saged import utils, datasets, models
_____no_output_____
BSD-3-Clause
notebook/debugging/data_similarity.ipynb
ben-heil/saged
Load the data
dataset_config_file = '../../dataset_configs/refinebio_labeled_dataset.yml' dataset_config_str = """name: "RefineBioMixedDataset" compendium_path: "../../data/subset_compendium.pkl" metadata_path: "../../data/aggregated_metadata.json" label_path: "../../data/sample_classifications.pkl" """ dataset_config = yaml.safe_lo...
_____no_output_____
BSD-3-Clause
notebook/debugging/data_similarity.ipynb
ben-heil/saged
Look for samples that are very similar to each other despite having different IDs
sample_names = all_data.get_samples() assert len(sample_names) == len(set(sample_names)) sample_names[:5] expression = all_data.get_all_data() print(len(sample_names)) print(expression.shape) sample_distance_matrix = euclidean_distances(expression, expression) # This is unrelated to debugging the data, I'm just curio...
_____no_output_____
BSD-3-Clause
notebook/debugging/data_similarity.ipynb
ben-heil/saged
Since there are as many zeros as elements in the diagonal, there are no duplicate samples with different IDs (unless noise was added somewhere) Get all distancesBecause we know there aren't any zeros outside of the diagonal, we can zero out the lower diagonal and use the the non-zero entries of the upper diagonal to v...
triangle = np.triu(sample_distance_matrix, k=0) triangle distances = triangle.flatten() nonzero_distances = distances[distances != 0] nonzero_distances.shape plt.hist(nonzero_distances, bins=20)
_____no_output_____
BSD-3-Clause
notebook/debugging/data_similarity.ipynb
ben-heil/saged
Distribution looks bimodal, probably due to different platforms having different distances from each other?
plt.hist(nonzero_distances[nonzero_distances < 200]) plt.hist(nonzero_distances[nonzero_distances < 100])
_____no_output_____
BSD-3-Clause
notebook/debugging/data_similarity.ipynb
ben-heil/saged
Looks like there may be some samples that are abnormally close to each other. I wonder whether they're in the same study Correspondence between distance and study
# There is almost certainly a vectorized way of doing this but oh well distances = [] first_samples = [] second_samples = [] for row_index in range(sample_distance_matrix.shape[0]): for col_index in range(sample_distance_matrix.shape[0]): distance = sample_distance_matrix[row_index, col_index] if d...
104723274
BSD-3-Clause
notebook/debugging/data_similarity.ipynb
ben-heil/saged
For some reason my computer didn't want me to make a figure with 50 million points. We'll work with means instead
means_df = distance_df.groupby(['study_1', 'same_study']).mean() means_df means_df = means_df.unstack(level='same_study') means_df = means_df.reset_index() means_df.head() # Get rid of the multilevel confusion means_df.columns = means_df.columns.droplevel() means_df.columns = ['study_name', 'distance_to_other', 'dista...
_____no_output_____
BSD-3-Clause
notebook/debugging/data_similarity.ipynb
ben-heil/saged
These results indicate that most of the data is behaving as expected (the distance between pairs of samples from different studies is less than the distance between pairs of samples within the same study).The outliers are mostly bead-chip, which makes sense (though they shouldn't be in the dataset and I'll need to look...
%reset -f # Calling reset because the notebook runs out of memory otherwise import json import matplotlib.pyplot as plt import numpy as np import pandas as pd import yaml from plotnine import * from sklearn.metrics.pairwise import euclidean_distances from saged import utils, datasets, models dataset_config_file = '.....
_____no_output_____
BSD-3-Clause
notebook/debugging/data_similarity.ipynb
ben-heil/saged
Look for samples that are very similar to each other despite having different IDs
sample_names = all_data.get_samples() assert len(sample_names) == len(set(sample_names)) sample_names[:5] expression = all_data.get_all_data() print(len(sample_names)) print(expression.shape) sample_distance_matrix = euclidean_distances(expression, expression) # This is unrelated to debugging the data, I'm just curio...
_____no_output_____
BSD-3-Clause
notebook/debugging/data_similarity.ipynb
ben-heil/saged
Since there are as many zeros as elements in the diagonal, there are no duplicate samples with different IDs (unless noise was added somewhere) Get all distancesBecause we know there aren't any zeros outside of the diagonal, we can zero out the lower diagonal and use the the non-zero entries of the upper diagonal to v...
triangle = np.triu(sample_distance_matrix, k=0) triangle distances = triangle.flatten() nonzero_distances = distances[distances != 0] nonzero_distances.shape plt.hist(nonzero_distances, bins=20)
_____no_output_____
BSD-3-Clause
notebook/debugging/data_similarity.ipynb
ben-heil/saged
Distribution looks bimodal, probably due to different platforms having different distances from each other?
plt.hist(nonzero_distances[nonzero_distances < 200]) plt.hist(nonzero_distances[nonzero_distances < 100])
_____no_output_____
BSD-3-Clause
notebook/debugging/data_similarity.ipynb
ben-heil/saged
Looks like there may be some samples that are abnormally close to each other. I wonder whether they're in the same study Correspondence between distance and study
# There is almost certainly a vectorized way of doing this but oh well distances = [] first_samples = [] second_samples = [] for row_index in range(sample_distance_matrix.shape[0]): for col_index in range(sample_distance_matrix.shape[0]): distance = sample_distance_matrix[row_index, col_index] if d...
104724522
BSD-3-Clause
notebook/debugging/data_similarity.ipynb
ben-heil/saged
For some reason my computer didn't want me to make a figure with 50 million points. We'll work with means instead
means_df = distance_df.groupby(['study_1', 'same_study']).mean() means_df means_df = means_df.unstack(level='same_study') means_df = means_df.reset_index() means_df.head() # Get rid of the multilevel confusion means_df.columns = means_df.columns.droplevel() means_df.columns = ['study_name', 'distance_to_other', 'dista...
_____no_output_____
BSD-3-Clause
notebook/debugging/data_similarity.ipynb
ben-heil/saged
Data Preprocessing Notebook
import pandas as pd # import modin.pandas as pd import numpy as np import os import re import warnings warnings.filterwarnings("ignore") # os.environ["MODIN_ENGINE"] = "ray" # Modin will use Ray # os.environ["MODIN_ENGINE"] = "dask" # Modin will use Dask from sklearn.model_selection import train_test_split from arg...
_____no_output_____
MIT
chapter_4/Surname-MLP/SurName-Dataset.ipynb
ManuLasker/nlp-with-pytorch
Define Args
args = Namespace( raw_dataset_csv="data/surnames/surnames.csv", train_proportion=0.7, val_proportion=0.15, test_proportion=0.15, output_munged_csv="data/surnames/surnames_with_splits.csv", seed=1337 )
_____no_output_____
MIT
chapter_4/Surname-MLP/SurName-Dataset.ipynb
ManuLasker/nlp-with-pytorch
Load Data suing modin ray backend
surnames = pd.read_csv(args.raw_dataset_csv, header=0) surnames.head()
_____no_output_____
MIT
chapter_4/Surname-MLP/SurName-Dataset.ipynb
ManuLasker/nlp-with-pytorch
Data Insights
surnames.describe() set(surnames.nationality.unique())
_____no_output_____
MIT
chapter_4/Surname-MLP/SurName-Dataset.ipynb
ManuLasker/nlp-with-pytorch
Split data Train/Test/Val
train_surnames, val_surnames = train_test_split(surnames, train_size=args.train_proportion, stratify=surnames.nationality.values) val_surnames, test_surnames = train_test_split(val_surnames, train_size=0.5, stratify=val_surnames.n...
_____no_output_____
MIT
chapter_4/Surname-MLP/SurName-Dataset.ipynb
ManuLasker/nlp-with-pytorch
Save Data
final_surnames.to_csv(args.output_munged_csv, index=False)
_____no_output_____
MIT
chapter_4/Surname-MLP/SurName-Dataset.ipynb
ManuLasker/nlp-with-pytorch
Getting started in scikit-learn with the famous iris dataset*From the video series: [Introduction to machine learning with scikit-learn](https://github.com/justmarkham/scikit-learn-videos)*
#environment setup with watermark %load_ext watermark %watermark -a 'Gopala KR' -u -d -v -p watermark,numpy,pandas,matplotlib,nltk,sklearn,tensorflow,theano,mxnet,chainer
WARNING (theano.tensor.blas): Using NumPy C-API based implementation for BLAS functions.
MIT
tests/scikit-learn/03_getting_started_with_iris.ipynb
gopala-kr/ds-notebooks
Agenda- What is the famous iris dataset, and how does it relate to machine learning?- How do we load the iris dataset into scikit-learn?- How do we describe a dataset using machine learning terminology?- What are scikit-learn's four key requirements for working with data? Introducing the iris dataset ![Iris](images/0...
from IPython.display import IFrame IFrame('http://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data', width=300, height=200)
_____no_output_____
MIT
tests/scikit-learn/03_getting_started_with_iris.ipynb
gopala-kr/ds-notebooks
Machine learning on the iris dataset- Framed as a **supervised learning** problem: Predict the species of an iris using the measurements- Famous dataset for machine learning because prediction is **easy**- Learn more about the iris dataset: [UCI Machine Learning Repository](http://archive.ics.uci.edu/ml/datasets/Iris)...
# import load_iris function from datasets module from sklearn.datasets import load_iris # save "bunch" object containing iris dataset and its attributes iris = load_iris() type(iris) # print the iris data print(iris.data)
[[ 5.1 3.5 1.4 0.2] [ 4.9 3. 1.4 0.2] [ 4.7 3.2 1.3 0.2] [ 4.6 3.1 1.5 0.2] [ 5. 3.6 1.4 0.2] [ 5.4 3.9 1.7 0.4] [ 4.6 3.4 1.4 0.3] [ 5. 3.4 1.5 0.2] [ 4.4 2.9 1.4 0.2] [ 4.9 3.1 1.5 0.1] [ 5.4 3.7 1.5 0.2] [ 4.8 3.4 1.6 0.2] [ 4.8 3. 1.4 0.1] [ 4.3 3. 1.1 0.1...
MIT
tests/scikit-learn/03_getting_started_with_iris.ipynb
gopala-kr/ds-notebooks
Machine learning terminology- Each row is an **observation** (also known as: sample, example, instance, record)- Each column is a **feature** (also known as: predictor, attribute, independent variable, input, regressor, covariate)
# print the names of the four features print(iris.feature_names) # print integers representing the species of each observation print(iris.target) # print the encoding scheme for species: 0 = setosa, 1 = versicolor, 2 = virginica print(iris.target_names)
['setosa' 'versicolor' 'virginica']
MIT
tests/scikit-learn/03_getting_started_with_iris.ipynb
gopala-kr/ds-notebooks
- Each value we are predicting is the **response** (also known as: target, outcome, label, dependent variable)- **Classification** is supervised learning in which the response is categorical- **Regression** is supervised learning in which the response is ordered and continuous Requirements for working with data in sci...
# check the types of the features and response print(type(iris.data)) print(type(iris.target)) # check the shape of the features (first dimension = number of observations, second dimensions = number of features) print(iris.data.shape) # check the shape of the response (single dimension matching the number of observatio...
_____no_output_____
MIT
tests/scikit-learn/03_getting_started_with_iris.ipynb
gopala-kr/ds-notebooks
Resources- scikit-learn documentation: [Dataset loading utilities](http://scikit-learn.org/stable/datasets/)- Jake VanderPlas: Fast Numerical Computing with NumPy ([slides](https://speakerdeck.com/jakevdp/losing-your-loops-fast-numerical-computing-with-numpy-pycon-2015), [video](https://www.youtube.com/watch?v=EEUXKG9...
from IPython.core.display import HTML def css_styling(): styles = open("styles/custom.css", "r").read() return HTML(styles) css_styling() test complete; Gopal
_____no_output_____
MIT
tests/scikit-learn/03_getting_started_with_iris.ipynb
gopala-kr/ds-notebooks
How to Use Forecasters in MerlionThis notebook will guide you through using all the key features of forecasters in Merlion. Specifically, we will explain1. Initializing a forecasting model (including ensembles and automatic model selectors)1. Training the model1. Producing a forecast with the model1. Visualizing the m...
import matplotlib.pyplot as plt import numpy as np from merlion.utils.time_series import TimeSeries from ts_datasets.forecast import M4 # Load the time series # time_series is a time-indexed pandas.DataFrame # trainval is a time-indexed pandas.Series indicating whether each timestamp is for training or testing time_s...
100%|██████████| 414/414 [00:00<00:00, 513.64it/s]
BSD-3-Clause
examples/forecast/1_ForecastFeatures.ipynb
ankitakashyap05/Merlion
Model InitializationIn this notebook, we will use three different forecasting models:1. ARIMA (a classic stochastic process model)2. Prophet (Facebook's popular time series forecasting model)3. MSES (the Multi-Scale Exponential Smoothing model, developed in-house)Let's start by initializing each of them.
# Import models & configs from merlion.models.forecast.arima import Arima, ArimaConfig from merlion.models.forecast.prophet import Prophet, ProphetConfig from merlion.models.forecast.smoother import MSES, MSESConfig # Import data pre-processing transforms from merlion.transform.base import Identity from merlion.transf...
_____no_output_____
BSD-3-Clause
examples/forecast/1_ForecastFeatures.ipynb
ankitakashyap05/Merlion
Now that we have initialized the individual models, we will also combine them in two different ensembles: `ensemble` simply takes the mean prediction of each individual model, and `selector` selects the best individual model based on its sMAPE (symmetric Mean Average Precision Error). The sMAPE is a metric used to eval...
from merlion.evaluate.forecast import ForecastMetric from merlion.models.ensemble.combine import Mean, ModelSelector from merlion.models.ensemble.forecast import ForecasterEnsemble, ForecasterEnsembleConfig # The ForecasterEnsemble is a forecaster, and we treat it as a first-class model. # Its config takes a combiner ...
_____no_output_____
BSD-3-Clause
examples/forecast/1_ForecastFeatures.ipynb
ankitakashyap05/Merlion
Model TrainingAll forecasting models (and ensembles) share the same API for training. The `train()` method returns the model's predictions and standard error of those predictions on the training data. Note that the standard error is just `None` if the model doesn't support uncertainty estimation (this is the case for ...
print(f"Training {type(model1).__name__}...") forecast1, stderr1 = model1.train(train_data) print(f"\nTraining {type(model2).__name__}...") forecast2, stderr2 = model2.train(train_data) print(f"\nTraining {type(model3).__name__}...") forecast3, stderr3 = model3.train(train_data) print("\nTraining ensemble...") forec...
Training Arima...
BSD-3-Clause
examples/forecast/1_ForecastFeatures.ipynb
ankitakashyap05/Merlion
Model InferenceTo obtain a forecast from a trained model, we simply call `model.forecast()` with the Unix timestamps at which we the model to generate a forecast. In many cases, you may obtain these directly from a time series as shown below.
# Truncate the test data to ensure that we are within each model's maximum # forecast horizon. sub_test_data = test_data[:50] # Obtain the time stamps corresponding to the test data time_stamps = sub_test_data.univariates[sub_test_data.names[0]].time_stamps # Get the forecast & standard error of each model. These are...
_____no_output_____
BSD-3-Clause
examples/forecast/1_ForecastFeatures.ipynb
ankitakashyap05/Merlion
Model Visualization and Quantitative EvaluationIt is fairly transparent to visualize a model's forecast and also quantitatively evaluate the forecast, using standard metrics like sMAPE. We show examples for all five models below.Below, we quantitatively evaluate the models using the sMAPE metric. However, the `Forecas...
from merlion.evaluate.forecast import ForecastMetric # We begin by computing the sMAPE of ARIMA's forecast (scale is 0 to 100) smape1 = ForecastMetric.sMAPE.value(ground_truth=sub_test_data, predict=forecast1) print(f"{type(model1).__name__} sMAPE is {smape1:.3f}") # Next, we can v...
Selector sMAPE is 3.768
BSD-3-Clause
examples/forecast/1_ForecastFeatures.ipynb
ankitakashyap05/Merlion
Saving & Loading ModelsAll models have a `save()` method and `load()` class method. Models may also be loaded with the assistance of the `ModelFactory`, which works for arbitrary models. The `save()` method creates a new directory at the specified path, where it saves a `json` file representing the model's config, as ...
import json import os import pprint from merlion.models.factory import ModelFactory # Save the model os.makedirs("models", exist_ok=True) path = os.path.join("models", "prophet") model2.save(path) # Print the config saved pp = pprint.PrettyPrinter() with open(os.path.join(path, "config.json")) as f: print(f"{type...
Prophet Config {'add_seasonality': 'auto', 'daily_seasonality': 'auto', 'dim': 1, 'max_forecast_steps': None, 'model_path': '/Users/abhatnagar/Desktop/Merlion_public/examples/forecast/models/prophet/model.pkl', 'target_seq_index': 0, 'transform': {'name': 'Identity'}, 'uncertainty_samples': 100, 'weekly_seasona...
BSD-3-Clause
examples/forecast/1_ForecastFeatures.ipynb
ankitakashyap05/Merlion
We can do the same exact thing with ensembles! Note that the ensemble saves each of its sub-models in a different sub-directory, which it tracks manually. Additionally, the combiner (which is saved in the `ForecasterEnsembleConfig`), keeps track of the sMAPE achieved by each model (the `metric_values` key).
# Save the selector path = os.path.join("models", "selector") selector.save(path) # Print the config saved. Note that we've saved all individual models, # and their paths are specified under the model_paths key. pp = pprint.PrettyPrinter() with open(os.path.join(path, "config.json")) as f: print(f"Selector Config"...
Selector Config {'combiner': {'abs_score': False, 'metric': 'ForecastMetric.sMAPE', 'metric_values': [5.479063255045728, 8.611665684950744, 17.72980301555831], 'n_models': 3, 'name': 'ModelSelector'},...
BSD-3-Clause
examples/forecast/1_ForecastFeatures.ipynb
ankitakashyap05/Merlion
Simulating Live Model DeploymentA typical model deployment scenario is as follows:1. Train an initial model on some recent historical data1. At a regular interval `cadence`, obtain the model's forecast for a certain `horizon`1. At a regular interval `retrain_freq`, retrain the entire model on the most recent data1. Op...
from merlion.evaluate.forecast import ForecastEvaluator, ForecastEvaluatorConfig, ForecastMetric def create_evaluator(model): # Re-initialize the model, so we can re-train it from scratch model.reset() # Create an evaluation pipeline for the model, where we # -- get the model's forecast every hour ...
_____no_output_____
BSD-3-Clause
examples/forecast/1_ForecastFeatures.ipynb
ankitakashyap05/Merlion
First, let's evaluate ARIMA.
# Obtain the results of running the evaluation pipeline for ARIMA. # These result objects are to be treated as a black box, and should be # passed directly to the evaluator's evaluate() method. model1_evaluator = create_evaluator(model1) model1_train_result, model1_test_result = model1_evaluator.get_predict( train_...
Arima sMAPE: 2.015 Arima RMSE: 143.416
BSD-3-Clause
examples/forecast/1_ForecastFeatures.ipynb
ankitakashyap05/Merlion
Next, we will evaluate the ensemble (taking the mean prediction of ARIMA, Prophet, and MSES every time the models are called).
# Obtain the results of running the evaluation pipeline for the ensemble. # These result objects are to be treated as a black box, and should be # passed directly to the evaluator's evaluate() method. ensemble_evaluator = create_evaluator(ensemble) ensemble_train_result, ensemble_test_result = ensemble_evaluator.get_pr...
Ensemble sMAPE: 2.893 Ensemble RMSE: 210.927
BSD-3-Clause
examples/forecast/1_ForecastFeatures.ipynb
ankitakashyap05/Merlion
Strings
name = "Robin"
_____no_output_____
Apache-2.0
Lecture-Notes/2018/Day2.ipynb
unmeshvrije/python-for-beginners