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
Output image to disk
cam = Camera('location',[0,75,0],'look_at',[0,0,0]) bg = Background("color", "White",'transmit',1.0) lights = [LightSource( [0,80,0], 'color','White','parallel')] #lights.extend([LightSource( [0,75,0], 'color','White shadowless')]) obj = [bg] + lights + sphere + cylinder scene = Scene(camera=cam,objects=obj,included...
_____no_output_____
MIT
src/graphene_adsorbed_phases.ipynb
DelMaestroGroup/papers-code-BoseHubbardModelHeAdsorptionGraphene
Superfluid
import importlib importlib.reload(vapory) # graphene sphere = [Sphere([x[i],0, y[i]], r_C, col_C) for i in range(len(x))] cylinder = [Cylinder([x1[i],0.0,y1[i]],[x2[i],0.0,y2[i]], 0.075,col_bond) for i in range(len(x1))] # Helium atoms = [Sphere([cr[0],1.1, cr[1]], r_He/3.0, col_He_link) for cr in hex_centers] bonds =...
_____no_output_____
MIT
src/graphene_adsorbed_phases.ipynb
DelMaestroGroup/papers-code-BoseHubbardModelHeAdsorptionGraphene
Supersolid
# graphene sphere = [Sphere([x[i],0, y[i]], r_C, col_C) for i in range(len(x))] cylinder = [Cylinder([x1[i],0.0,y1[i]],[x2[i],0.0,y2[i]], 0.075,col_bond) for i in range(len(x1))] # Helium atoms = [Sphere([cr[0],1.1, cr[1]], r_He/4.0, col_He_link) for cr in hex_centers] atoms.extend([Sphere([cr[0],1.1, cr[1]], r_He/2....
_____no_output_____
MIT
src/graphene_adsorbed_phases.ipynb
DelMaestroGroup/papers-code-BoseHubbardModelHeAdsorptionGraphene
Suspended WettingWe first construct the bonds for the larger graphene lattice used in wetting.
bonds_big = np.empty([0,4]) NG_big = len(C_positions_big) for i in range(NG_big): ri = C_positions_big[i] for j in range(i,NG_big): rj = C_positions_big[j] d = np.linalg.norm(ri-rj) if d > 0.1 and d < (aₒ+0.1): bonds_big = np.vstack((bonds_big,[ri[0],rj[0],ri[1],rj[1]])) x_...
_____no_output_____
MIT
src/graphene_adsorbed_phases.ipynb
DelMaestroGroup/papers-code-BoseHubbardModelHeAdsorptionGraphene
USGS Earthquakes with the Mapboxgl-Jupyter Python Libraryhttps://github.com/mapbox/mapboxgl-jupyter
# Python 3.5+ only! import asyncio from aiohttp import ClientSession import json, geojson, os, time import pandas as pd from datetime import datetime, timedelta from mapboxgl.viz import * from mapboxgl.utils import * import pysal.esda.mapclassify as mapclassify # Get Data from the USGS API data = [] async def fetch(ur...
(198308, 9)
MIT
examples/usgs-earthquakes.ipynb
Swanson-Hysell/mapboxgl-jupyter
Set your Mapbox access token.Set a MAPBOX_ACCESS_TOKEN environment variable, or copy your token to use this notebook.If you do not have a Mapbox access token, sign up for an account at https://www.mapbox.com/If you already have an account, you can grab your token at https://www.mapbox.com/account/
token = os.getenv('MAPBOX_ACCESS_TOKEN') # Generate a geojson file from the dataframe df_to_geojson(df, filename='points.geojson', precision=4, lon='longitude', lat='latitude', properties=['mag','timestamp']) # Create the visualization #Calculate the visualization to create color_breaks = mapclassify.Nat...
_____no_output_____
MIT
examples/usgs-earthquakes.ipynb
Swanson-Hysell/mapboxgl-jupyter
Using min and max in another wayJust passing minrange and maxrange r / \ / \ min, r-1 r, max
import queue class BinaryTreeNode: def __init__(self, data): self.data = data self.left = None self.right = None def minTree(root): if root == None: return 1000000 leftMin = minTree(root.left) rightMin = minTree(root.right) return min(leftMin, rightMin, root.data) d...
Enter root 4 Enter left child of 4 2 Enter right child of 4 6 Enter left child of 2 1 Enter right child of 2 3 Enter left child of 6 5 Enter right child of 6 7 Enter left child of 1 -1 Enter right child of 1 -1 Enter left child of 3 -1 Enter right child of 3 -1 Enter left child of 5 -1 Enter right child of ...
Unlicense
15 BST-1/15.7 isBST (Another solution).ipynb
suhassuhas/Coding-Ninjas---Data-Structures-and-Algorithms-in-Python
MLP モデルのKerasによる実装基礎編で使った2次元データを基に、MLPモデルをTensorflow/Kerasで書いてみます。
# 二次元ガウス分布と一様分布 def getDataset2(): state = np.random.get_state() np.random.seed(0) # 今回はデータセットの乱数を固定させます。 nSignal = 100 # 生成するシグナルイベントの数 nBackground = 1000 # 生成するバックグラウンドイベントの数 # データ点の生成 xS = np.random.multivariate_normal([1.0, 0], [[1, 0], [0, 1]], size=nSignal) # 平均(x1,x2) = (1.0, 0.0)...
_____no_output_____
Apache-2.0
advanced/MLP.ipynb
saitoicepp/ppcc2021_DeepLearning
中間層が2層、それぞれの層のノード数がそれぞれ3つ、1つのMLPを構成します。
from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense from tensorflow.keras.optimizers import SGD # データ点の取得 x, t = getDataset2() # モデルの定義 model = Sequential([ Dense(units=3, activation='sigmoid', input_dim=2), # ノード数が3の層を追加。活性化関数はシグモイド関数。 Dense(units=1, activation='sigmoid'...
_____no_output_____
Apache-2.0
advanced/MLP.ipynb
saitoicepp/ppcc2021_DeepLearning
`Dense` は1層の隠れ層を作成する関数です。`Dense`の詳細は[公式のドキュメント](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Dense)を参照することでわかります。ドキュメントを見ると、```pythontf.keras.layers.Dense( units, activation=None, use_bias=True, kernel_initializer='glorot_uniform', bias_initializer='zeros', kernel_regularizer=None, bias_regula...
model.summary()
_____no_output_____
Apache-2.0
advanced/MLP.ipynb
saitoicepp/ppcc2021_DeepLearning
このモデルは、1層目の隠れ層の出力が3, 学習可能なパラメータ数が9, 2層目の隠れ層の出力が1, 学習可能なパラメータ数が4 であることがわかります。"Output Shape"の"None"はサイズが未確定であることを表しています。ここでは、バッチサイズ用の次元になります。 モデルの構成図を作ってくれる便利なAPIも存在します。
from tensorflow.keras.utils import plot_model plot_model(model, to_file='model.png', show_shapes=True)
_____no_output_____
Apache-2.0
advanced/MLP.ipynb
saitoicepp/ppcc2021_DeepLearning
層の数を増やしてみましょう。新たな層を重ねることで層の数を増やすことができます。```pythonmodel = Sequential([ Dense(units=3, activation='sigmoid', input_dim=2), ノード数が3の層を追加。活性化関数はシグモイド関数。 Dense(units=3, activation='sigmoid') ノード数が3の層を追加。活性化関数はシグモイド関数。 Dense(units=3, activation='sigmoid') ノード数が3の層を追加。活性化関数はシグモイド関数。 Dense(units=1, activation=...
model = Sequential([ Dense(units=3, activation='sigmoid', input_dim=2), # ノード数が3の層を追加。活性化関数はシグモイド関数。 Dense(units=3, activation='sigmoid'), # ノード数が3の層を追加。活性化関数はシグモイド関数。 Dense(units=3, activation='sigmoid'), # ノード数が3の層を追加。活性化関数はシグモイド関数。 Dense(units=3, activation='sigmoid'), # ノード数が3の層を追加。活性化関数はシグモイド関数...
_____no_output_____
Apache-2.0
advanced/MLP.ipynb
saitoicepp/ppcc2021_DeepLearning
モデルのパラメータの数が増えていることがわかります。次に、ノードの数を増やしてみましょう。
model = Sequential([ Dense(units=128, activation='sigmoid', input_dim=2), # ノード数が3の層を追加。活性化関数はシグモイド関数。 Dense(units=128, activation='sigmoid'), # ノード数が128の層を追加。活性化関数はシグモイド関数。 Dense(units=128, activation='sigmoid'), # ノード数が128の層を追加。活性化関数はシグモイド関数。 Dense(units=128, activation='sigmoid'), # ノード数が128の層を追加...
_____no_output_____
Apache-2.0
advanced/MLP.ipynb
saitoicepp/ppcc2021_DeepLearning
パラメータの数が大きく増えたことがわかります。MLPにおいては、パラメータの数は、ノード数の2乗で増加します。 このモデルを使って学習させてみましょう。
# 誤差関数としてクロスエントロピーを指定。最適化手法は(確率的)勾配降下法 model.compile(loss='binary_crossentropy', optimizer=SGD(learning_rate=0.01)) # トレーニング model.fit( x=x, y=t, batch_size=len(x), # バッチサイズ。一回のステップで全てのデータを使うようにする。 epochs=3000, # 学習のステップ数 verbose=0, # 1とするとステップ毎に誤差関数の値などが表示される ) # プロット ## パーセプトロンの出力を等高線プロット P...
_____no_output_____
Apache-2.0
advanced/MLP.ipynb
saitoicepp/ppcc2021_DeepLearning
これまでは活性化関数としてシグモイド関数(`sigmoid`)を使っていました。昔はsigmoid関数やtanh関数がよく使われていましたが、最近はReLU関数がよく使われます。$$ ReLU = \begin{cases} x & (x \geq 0) \\ 0 & (x < 0) \end{cases}$$ReLUが好まれる理由については、別の資料を参照してください。ReLUを使って学習がどのようになるか確認してみましょう。
from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense from tensorflow.keras.optimizers import SGD # データ点の取得 x, t = getDataset2() # モデルの定義 model = Sequential([ Dense(units=128, activation='relu', input_dim=2), # ノード数が3の層を追加。活性化関数はReLU。 Dense(units=128, activation='relu'), #...
_____no_output_____
Apache-2.0
advanced/MLP.ipynb
saitoicepp/ppcc2021_DeepLearning
深層学習をトレーニングするにあたって、最適化関数(optimizer)も非常に重要な要素です。確率的勾配降下法(SGD)の他によく使われるアルゴリズムとして adam があります。adamを使ってみると、どのようになるでしょうか。
from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense from tensorflow.keras.optimizers import SGD # データ点の取得 x, t = getDataset2() # モデルの定義 model = Sequential([ Dense(units=128, activation='relu', input_dim=2), # ノード数が3の層を追加。活性化関数はReLU。 Dense(units=128, activation='relu'), #...
_____no_output_____
Apache-2.0
advanced/MLP.ipynb
saitoicepp/ppcc2021_DeepLearning
Keras モデルの定義方法Kerasモデルを定義する方法はいくつかあります。最も簡単なのが`Sequential`を使った方法で、これまでの例では全てこの方法でモデルを定義してきました。一方で、少し複雑なモデルを考えると、`Sequential`モデルで対応できなくなってきます。一例としてResidual Network(ResNet)で使われるskip connectionを考えてみます。skip connectionは$$y = f_2(f_1(x) + x)$$のように、入力を2つの経路に分け、片方はMLP、もう片方はそのまま後ろのレイヤーに接続するつなげ方です。このようなモデルは、途中入出力の分岐があるため、`Seque...
from tensorflow.keras import Input, Model input = Input(shape=(2,)) x = Dense(units=128, activation='relu')(input) x = Dense(units=128, activation='relu')(x) x = Dense(units=128, activation='relu')(x) x = Dense(units=128, activation='relu')(x) x = Dense(units=128, activation='relu')(x) output = Dense(units=1, activatio...
_____no_output_____
Apache-2.0
advanced/MLP.ipynb
saitoicepp/ppcc2021_DeepLearning
入力(`Input`)をモジュールに順々に適用していき、```pythonx = Dense()(x)```最終的な出力(`output`)とはじめの入力を使って`Model`クラスを定義する、という流れになっています。`Functional API`でskip connectionを実装すると、以下のようになります。
from tensorflow.keras import Input, Model from tensorflow.keras.layers import Add input = Input(shape=(2,)) x = Dense(units=128, activation='relu')(input) z = Dense(units=128, activation='relu')(x) x = Add()([x, z]) z = Dense(units=128, activation='relu')(x) x = Add()([x, z]) output = Dense(units=1, activation='sigmoid...
_____no_output_____
Apache-2.0
advanced/MLP.ipynb
saitoicepp/ppcc2021_DeepLearning
Kerasモデルを定義する方法として、`Model`クラスのサブクラスを作る方法もあります。`Model`クラスをカスタマイズすることができるので、特殊な学習をさせたいときなど、高度な深層学習モデルを扱うときに使われることもあります。
# Modelクラスを継承して新しいクラスを作成します from tensorflow.keras import Model class myModel(Model): def __init__(self): super().__init__() self.dense_1 = Dense(units=128, activation='relu') self.dense_2 = Dense(units=128, activation='relu') self.dense_3 = Dense(units=128, activation='relu') ...
_____no_output_____
Apache-2.0
advanced/MLP.ipynb
saitoicepp/ppcc2021_DeepLearning
!nvidia-smi !pip install contractions !pip install textsearch !pip install tqdm import nltk nltk.download('punkt') import pandas as pd import numpy as np # fix random seed for reproducibility seed = 42 np.random.seed(seed) import zipfile from google.colab import drive drive.mount("/content/drive") z= zipfile.ZipFile("...
0%| | 0/1956 [00:00<?, ?it/s]/usr/local/lib/python3.7/dist-packages/bs4/__init__.py:336: UserWarning: "https://twitter.com/GBphotographyGB" looks like a URL. Beautiful Soup is not an HTTP client. You should probably use an HTTP client like requests to get the document behind the URL, and feed that document ...
MIT
FINAL_CODE/Model_LSTM.ipynb
rafsunshuvo/Thesis
PreprocessingTo prepare text data for our deep learning model, we transform each review into a sequence.Every word in the review is mapped to an integer index and thus the sentence turns into a sequence of numbers.To perform this transformation, keras provides the ```Tokenizer```
import tensorflow as tf t = tf.keras.preprocessing.text.Tokenizer(oov_token='<UNK>') # fit the tokenizer on the documents t.fit_on_texts(norm_train_reviews) t.word_index['<PAD>'] = 0 max([(k, v) for k, v in t.word_index.items()], key = lambda x:x[1]), min([(k, v) for k, v in t.word_index.items()], key = lambda x:x[1])...
_____no_output_____
MIT
FINAL_CODE/Model_LSTM.ipynb
rafsunshuvo/Thesis
# pad dataset to a maximum review length in words X_train = tf.keras.preprocessing.sequence.pad_sequences(train_sequences, maxlen=MAX_SEQUENCE_LENGTH) X_test = tf.keras.preprocessing.sequence.pad_sequences(test_sequences, maxlen=MAX_SEQUENCE_LENGTH) X_train.shape, X_test.shape
_____no_output_____
MIT
FINAL_CODE/Model_LSTM.ipynb
rafsunshuvo/Thesis
Encoding Labels
from sklearn.preprocessing import LabelEncoder le = LabelEncoder() num_classes=2 # positive -> 1, negative -> 0 y_train = le.fit_transform(train_sentiments) y_test = le.transform(test_sentiments) VOCAB_SIZE = len(t.word_index)
_____no_output_____
MIT
FINAL_CODE/Model_LSTM.ipynb
rafsunshuvo/Thesis
LSTM Model
EMBEDDING_DIM = 300 # dimension for dense embeddings for each token LSTM_DIM = 128 # total LSTM units model = tf.keras.models.Sequential() model.add(tf.keras.layers.Embedding(input_dim=VOCAB_SIZE, output_dim=EMBEDDING_DIM, input_length=MAX_SEQUENCE_LENGTH)) model.add(tf.keras.layers.SpatialDropout1D(0.1)) model.add(tf...
Model: "sequential_1" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= embedding_1 (Embedding) (None, 1000, 300) 1235400 ...
MIT
FINAL_CODE/Model_LSTM.ipynb
rafsunshuvo/Thesis
Train Model
Metrics = [tf.keras.metrics.BinaryAccuracy(name = 'accuracy'), tf.keras.metrics.Precision(name = 'precision'), tf.keras.metrics.Recall(name = 'recall') ] # compiling our model model.compile(optimizer ='adam', loss = 'binary_crossentropy', metrics = Metrics)...
_____no_output_____
MIT
FINAL_CODE/Model_LSTM.ipynb
rafsunshuvo/Thesis
Saving and loading models for inference in PyTorch==================================================There are two approaches for saving and loading models for inference inPyTorch. The first is saving and loading the ``state_dict``, and thesecond is saving and loading the entire model.Introduction------------Saving the ...
import torch import torch.nn as nn import torch.optim as optim
_____no_output_____
BSD-3-Clause
docs/_downloads/695ce7a76ce07582023a85d63a717ce2/saving_and_loading_models_for_inference.ipynb
Baescott/PyTorch-tutorials-kr
2. Define and intialize the neural network~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~For sake of example, we will create a neural network for trainingimages. To learn more see the Defining a Neural Network recipe.
class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.conv1 = nn.Conv2d(3, 6, 5) self.pool = nn.MaxPool2d(2, 2) self.conv2 = nn.Conv2d(6, 16, 5) self.fc1 = nn.Linear(16 * 5 * 5, 120) self.fc2 = nn.Linear(120, 84) self.fc3 = nn.Linear(84, 1...
_____no_output_____
BSD-3-Clause
docs/_downloads/695ce7a76ce07582023a85d63a717ce2/saving_and_loading_models_for_inference.ipynb
Baescott/PyTorch-tutorials-kr
3. Initialize the optimizer~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~We will use SGD with momentum.
optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9)
_____no_output_____
BSD-3-Clause
docs/_downloads/695ce7a76ce07582023a85d63a717ce2/saving_and_loading_models_for_inference.ipynb
Baescott/PyTorch-tutorials-kr
4. Save and load the model via ``state_dict``~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~Let’s save and load our model using just ``state_dict``.
# Specify a path PATH = "state_dict_model.pt" # Save torch.save(net.state_dict(), PATH) # Load model = Net() model.load_state_dict(torch.load(PATH)) model.eval()
_____no_output_____
BSD-3-Clause
docs/_downloads/695ce7a76ce07582023a85d63a717ce2/saving_and_loading_models_for_inference.ipynb
Baescott/PyTorch-tutorials-kr
A common PyTorch convention is to save models using either a ``.pt`` or``.pth`` file extension.Notice that the ``load_state_dict()`` function takes a dictionaryobject, NOT a path to a saved object. This means that you mustdeserialize the saved state_dict before you pass it to the``load_state_dict()`` function. For exam...
# Specify a path PATH = "entire_model.pt" # Save torch.save(net, PATH) # Load model = torch.load(PATH) model.eval()
_____no_output_____
BSD-3-Clause
docs/_downloads/695ce7a76ce07582023a85d63a717ce2/saving_and_loading_models_for_inference.ipynb
Baescott/PyTorch-tutorials-kr
Autograd: automatic differentiationCentral to all neural networks in PyTorch is the `autograd` package. Let's first briefly visit this, and we will then go to train our first neural network.The `autograd` package provides automatic differentiation for all operation on Tensors. It is a define-by-run framework, which me...
import torch # Create a tensor and set `requires_grad=True` to track computation with it. x = torch.ones(2, 2, requires_grad=True) print(x) # Do a tensor operation: y = x + 2 print(y) # y was created as a result of an operation, so it has a grad_fn print(y.grad_fn) z = y * y * 3 out = z.mean() print(z, out) a = tor...
True False tensor(1, dtype=torch.uint8)
Apache-2.0
DeepLearning/pytorch/Autograd.ipynb
MikoyChinese/learn
Exercise 5.01
import numpy as np import torch from torch import nn, optim from PIL import Image import matplotlib.pyplot as plt from torchvision import transforms, models imsize = 224 loader = transforms.Compose([ transforms.Resize(imsize), transforms.ToTensor(), transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.22...
_____no_output_____
MIT
Chapter05/Exercise5.02/Exercise5.02.ipynb
thoolihan/The-Deep-Learning-with-PyTorch-Workshop
Exercise 5.02
model = models.vgg19(pretrained=True).features for param in model.parameters(): param.requires_grad_(False)
_____no_output_____
MIT
Chapter05/Exercise5.02/Exercise5.02.ipynb
thoolihan/The-Deep-Learning-with-PyTorch-Workshop
Sampling the potential energy surface Introduction This interactive notebook demonstrates how to utilize the Potential Energy Surface (PES) samplers algorithm of qiskit chemistry to generate the dissociation profile of a molecule. We use the Born-Oppenhemier Potential Energy Surface (BOPES)and demonstrate how to exp...
# import common packages import numpy as np import pandas as pd import matplotlib.pyplot as plt from functools import partial # qiskit from qiskit.aqua import QuantumInstance from qiskit import BasicAer from qiskit.aqua.algorithms import NumPyMinimumEigensolver, VQE, IQPE from qiskit.aqua.components.optimizers import ...
_____no_output_____
Apache-2.0
tutorials/chemistry/05_Sampling_potential_energy_surfaces.ipynb
azeemba/qiskit-tutorials
Here, we use the H2 molecule as a model sysem for testing.
ft = FermionicTransformation() driver = PySCFDriver() solver = VQE(quantum_instance= QuantumInstance(backend=BasicAer.get_backend('statevector_simulator'))) me_gsc = GroundStateEigensolver(ft, solver) stretch1 = partial(Molecule.absolute_stretching, atom_pair=(1, 0)) mol = Molecule(geometry=[('H', [0., 0.,...
[('H', [0.0, 0.0, 0.0]), ('H', [0.0, 0.0, 0.3])]
Apache-2.0
tutorials/chemistry/05_Sampling_potential_energy_surfaces.ipynb
azeemba/qiskit-tutorials
Make a perturbation to the molecule along the absolute_stretching dof
mol.perturbations = [0.2] print(mol.geometry) mol.perturbations = [0.6] print(mol.geometry)
[('H', [0.0, 0.0, 0.0]), ('H', [0.0, 0.0, 0.8999999999999999])] [('H', [0.0, 0.0, 0.0]), ('H', [0.0, 0.0, 0.5])]
Apache-2.0
tutorials/chemistry/05_Sampling_potential_energy_surfaces.ipynb
azeemba/qiskit-tutorials
Calculate bond dissociation profile using BOPES SamplerHere, we pass the molecular information and the VQE to a built-in type called the BOPES Sampler. The BOPES Sampler allows the computation of the potential energy surface for a specified set of degrees of freedom/points of interest. First we compare no bootstrappi...
stretch1 = partial(Molecule.absolute_stretching, atom_pair=(1, 0)) mol = Molecule(geometry=[('H', [0., 0., 0.]), ('H', [0., 0., 0.3])], degrees_of_freedom=[stretch1], ) # pass molecule to PSYCF driver driver = PySCFDriver(molecule=mol) # Specify de...
_____no_output_____
Apache-2.0
tutorials/chemistry/05_Sampling_potential_energy_surfaces.ipynb
azeemba/qiskit-tutorials
Compare to classical eigensolver
# define numpy solver solver_numpy = NumPyMinimumEigensolver() me_gsc_numpy = GroundStateEigensolver(ft, solver_numpy) bs_classical = BOPESSampler( gss=me_gsc_numpy ,bootstrap=False ,num_bootstrap=None ,extrapolator=None) # execute res_np = bs_classical.sample...
_____no_output_____
Apache-2.0
tutorials/chemistry/05_Sampling_potential_energy_surfaces.ipynb
azeemba/qiskit-tutorials
Plot results
fig = plt.figure() for value, bootstrap in conditions.items(): plt.plot(results[f'points_{bootstrap}'], results[f'energies_{bootstrap}'], label = f'{bootstrap}') plt.plot(results['points_np'], results['energies_np'], label = 'numpy') plt.legend() plt.title('Dissociation profile') plt.xlabel('Interatomic distance') ...
_____no_output_____
Apache-2.0
tutorials/chemistry/05_Sampling_potential_energy_surfaces.ipynb
azeemba/qiskit-tutorials
Compare number of evaluations
for condition, result_full in results_full.items(): print(condition) print('Total evaluations for ' + condition + ':') sum = 0 for key in result_full: if condition is not 'np': sum += result_full[key]['raw_result']['cost_function_evals'] else: sum = 0 print(su...
no bootstrapping Total evaluations for no bootstrapping: 1714 bootstrapping Total evaluations for bootstrapping: 1266 np Total evaluations for np: 0
Apache-2.0
tutorials/chemistry/05_Sampling_potential_energy_surfaces.ipynb
azeemba/qiskit-tutorials
Extrapolation Here, an extrapolator added that will try to fit each (param,point) set to some specified function and suggest an initial parameter set for the next point (degree of freedom). - Extrapolator is based on an external extrapolator that sets the 'window', that is, the number of previous points to use for ext...
# define different extrapolators degree = 1 extrap_poly = Extrapolator.factory("poly", degree = degree) extrap_diff = Extrapolator.factory("diff_model", degree = degree) extrapolators = {'poly': extrap_poly, 'diff_model': extrap_diff} for key in extrapolators: extrap_internal = extrapolators[key] extrap = Extr...
_____no_output_____
Apache-2.0
tutorials/chemistry/05_Sampling_potential_energy_surfaces.ipynb
azeemba/qiskit-tutorials
Plot results
fig = plt.figure() for value, bootstrap in conditions.items(): plt.plot(results[f'points_{bootstrap}'], results[f'energies_{bootstrap}'], label = f'{bootstrap}') plt.plot(results['points_np'], results['energies_np'], label = 'numpy') for condition in extrapolators.keys(): print(condition) plt.plot(results[f...
poly diff_model
Apache-2.0
tutorials/chemistry/05_Sampling_potential_energy_surfaces.ipynb
azeemba/qiskit-tutorials
Compare number of evaluations
for condition, result_full in results_full.items(): print(condition) print('Total evaluations for ' + condition + ':') sum = 0 for key in results_full[condition].keys(): if condition is not 'np': sum += results_full[condition][key]['raw_result']['cost_function_evals'] els...
_____no_output_____
Apache-2.0
tutorials/chemistry/05_Sampling_potential_energy_surfaces.ipynb
azeemba/qiskit-tutorials
Weight InitializationIn this lesson, you'll learn how to find good initial weights for a neural network. Weight initialization happens once, when a model is created and before it trains. Having good initial weights can place the neural network close to the optimal solution. This allows the neural network to come to th...
import torch import numpy as np from torchvision import datasets import torchvision.transforms as transforms from torch.utils.data.sampler import SubsetRandomSampler # number of subprocesses to use for data loading num_workers = 0 # how many samples per batch to load batch_size = 100 # percentage of training set to us...
_____no_output_____
MIT
weight-initialization/weight_initialization_exercise.ipynb
tengwu27/udacity-deep-learning
Visualize Some Training Data
import matplotlib.pyplot as plt %matplotlib inline # obtain one batch of training images dataiter = iter(train_loader) images, labels = dataiter.next() images = images.numpy() # plot the images in the batch, along with the corresponding labels fig = plt.figure(figsize=(25, 4)) for idx in np.arange(20): ax = f...
/Users/tengwu/opt/anaconda3/envs/deep-learning/lib/python3.7/site-packages/ipykernel_launcher.py:12: MatplotlibDeprecationWarning: Passing non-integers as three-element position specification is deprecated since 3.3 and will be removed two minor releases later. if sys.path[0] == '':
MIT
weight-initialization/weight_initialization_exercise.ipynb
tengwu27/udacity-deep-learning
Define the Model ArchitectureWe've defined the MLP that we'll use for classifying the dataset. Neural Network* A 3 layer MLP with hidden dimensions of 256 and 128. * This MLP accepts a flattened image (784-value long vector) as input and produces 10 class scores as output.---We'll test the effect of different initial ...
import torch.nn as nn import torch.nn.functional as F # define the NN architecture class Net(nn.Module): def __init__(self, hidden_1=256, hidden_2=128, constant_weight=None): super(Net, self).__init__() # linear layer (784 -> hidden_1) self.fc1 = nn.Linear(28 * 28, hidden_1) # linea...
_____no_output_____
MIT
weight-initialization/weight_initialization_exercise.ipynb
tengwu27/udacity-deep-learning
Compare Model BehaviorBelow, we are using `helpers.compare_init_weights` to compare the training and validation loss for the two models we defined above, `model_0` and `model_1`. This function takes in a list of models (each with different initial weights), the name of the plot to produce, and the training and valida...
# initialize two NN's with 0 and 1 constant weights model_0 = Net(constant_weight=0) model_1 = Net(constant_weight=1) import helpers import importlib importlib.reload(helpers) # put them in list form to compare model_list = [(model_0, 'All Zeros'), (model_1, 'All Ones')] # plot the loss over the first ...
_____no_output_____
MIT
weight-initialization/weight_initialization_exercise.ipynb
tengwu27/udacity-deep-learning
As you can see the accuracy is close to guessing for both zeros and ones, around 10%.The neural network is having a hard time determining which weights need to be changed, since the neurons have the same output for each layer. To avoid neurons with the same output, let's use unique weights. We can also randomly selec...
import importlib importlib.reload(helpers) helpers.hist_dist('Random Uniform (low=-3, high=3)', np.random.uniform(-3, 3, [1000]))
_____no_output_____
MIT
weight-initialization/weight_initialization_exercise.ipynb
tengwu27/udacity-deep-learning
The histogram used 500 buckets for the 1000 values. Since the chance for any single bucket is the same, there should be around 2 values for each bucket. That's exactly what we see with the histogram. Some buckets have more and some have less, but they trend around 2.Now that you understand the uniform function, let's...
# takes in a module and applies the specified weight initialization def weights_init_uniform(m): classname = m.__class__.__name__ # for every Linear layer in a model.. if classname.find('Linear') != -1: # apply a uniform distribution to the weights and a bias=0 m.weight.data.uniform_(0.0, 1....
_____no_output_____
MIT
weight-initialization/weight_initialization_exercise.ipynb
tengwu27/udacity-deep-learning
---The loss graph is showing the neural network is learning, which it didn't with all zeros or all ones. We're headed in the right direction! General rule for setting weightsThe general rule for setting the weights in a neural network is to set them to be close to zero without being too small. >Good practice is to star...
# takes in a module and applies the specified weight initialization def weights_init_uniform_center(m): classname = m.__class__.__name__ # for every Linear layer in a model.. if classname.find('Linear') != -1: # apply a centered, uniform distribution to the weights m.weight.data.uniform_(-0....
_____no_output_____
MIT
weight-initialization/weight_initialization_exercise.ipynb
tengwu27/udacity-deep-learning
Then let's create a distribution and model that uses the **general rule** for weight initialization; using the range $[-y, y]$, where $y=1/\sqrt{n}$ .And finally, we'll compare the two models.
# takes in a module and applies the specified weight initialization def weights_init_uniform_rule(m): classname = m.__class__.__name__ # for every Linear layer in a model.. if classname.find('Linear') != -1: # get the number of the inputs n = m.in_features y = 1.0/np.sqrt(n) ...
_____no_output_____
MIT
weight-initialization/weight_initialization_exercise.ipynb
tengwu27/udacity-deep-learning
This behavior is really promising! Not only is the loss decreasing, but it seems to do so very quickly for our uniform weights that follow the general rule; after only two epochs we get a fairly high validation accuracy and this should give you some intuition for why starting out with the right initial weights can real...
helpers.hist_dist('Random Normal (mean=0.0, stddev=1.0)', np.random.normal(0, 2, size=[1000]))
_____no_output_____
MIT
weight-initialization/weight_initialization_exercise.ipynb
tengwu27/udacity-deep-learning
Let's compare the normal distribution against the previous, rule-based, uniform distribution. TODO: Define a weight initialization function that gets weights from a normal distribution > The normal distribution should have a mean of 0 and a standard deviation of $y=1/\sqrt{n}$
## complete this function def weights_init_normal(m): '''Takes in a module and initializes all linear layers with weight values taken from a normal distribution.''' classname = m.__class__.__name__ # for every Linear layer in a model # m.weight.data shoud be taken from a normal distribution ...
_____no_output_____
MIT
weight-initialization/weight_initialization_exercise.ipynb
tengwu27/udacity-deep-learning
The normal distribution gives us pretty similar behavior compared to the uniform distribution, in this case. This is likely because our network is so small; a larger neural network will pick more weight values from each of these distributions, magnifying the effect of both initialization styles. In general, a normal di...
## Instantiate a model with _no_ explicit weight initialization model_no_rule = Net() # create a new model with the rule-based, uniform weights model_uniform_rule = Net() model_uniform_rule.apply(weights_init_uniform_rule) # create a new model with the rule-based, NORMAL weights model_normal_rule = Net() model_norma...
_____no_output_____
MIT
weight-initialization/weight_initialization_exercise.ipynb
tengwu27/udacity-deep-learning
Model$Y = \beta_0 + \beta_1 x_1 + \dots + \beta_k x_k + \epsilon$$\epsilon_i$ i.i.d. $N(0, 1)$$E = Y - \hat{Y}$ Canonical X $Y = 6 + 1.3 x + \epsilon$$\epsilon_i$ i.i.d. $N(0, 1)$
x = x_fix.copy() e = e_fix.copy() y = y_fix.copy() data = pd.DataFrame({"x": x, "e": e, "y": y}) regressor = smf.ols(formula="y ~ x", data=data).fit() print(regressor.summary()) ax = plot_lmreg(data=data) plt.savefig(f"../imgs/simul_model_canonical.png", bbox_inches="tight") plt.show() data["pred"] = predict(regresso...
OLS Regression Results ============================================================================== Dep. Variable: y R-squared: 0.556 Model: OLS Adj. R-squared: 0.555 Meth...
MIT
notebooks/Assumptions.ipynb
victordalla/regression-diagnosis
Model validityNormality: the OLS is `robust`, having its `validity` even when their assumptions are false - hypothesis tests and confidence intervals are approximately correct for **non-normal large samples**.The OLS might not be `efficient`, specially for **heavy-tailed** distributed errors. When the errors have a *...
x = x_fix.copy() / 10 e = e_fix.copy() y = true_params["b0"] + true_params["b1"] * x**2 + e data = pd.DataFrame({"x": x, "e": e, "y": y}) print("Model: y ~ x") regressor = smf.ols(formula="y ~ x", data=data).fit() ax = plot_lmreg(data=data, x="x", y="y", lowess=True) plt.savefig(f"../imgs/simul_model_nonlin_cov_false....
Model: y ~ x
MIT
notebooks/Assumptions.ipynb
victordalla/regression-diagnosis
**Non linearity on response**$Y^2 = 6 + 1.3 x + \epsilon$
setting = "canonical" x = x_fix.copy() e = e_fix.copy() y = 100+true_params["b0"] + true_params["b1"] * x + e y = y**2 data = pd.DataFrame({"x": x, "e": e, "y": y}) print("Model: y ~ x") regressor = smf.ols(formula="y ~ x", data=data).fit() ax = plot_lmreg(data=data, x="x", y="y", lowess=True) plt.savefig(f"../imgs/s...
Model: y ~ x
MIT
notebooks/Assumptions.ipynb
victordalla/regression-diagnosis
**Non independent**Positive-correlated data in a same with independent data between days.
x = x_fix.copy() data = pd.DataFrame({"x": x, "e": None, "y": None}) data["date"] = pd.Series(range(n//5)).sample(n, replace=True, random_state=0).values for idx, [group, df_group] in enumerate(data.groupby("date")): m = len(df_group) cov = np.full((m, m), 0.9 * true_params["scale"]**2) np.fill_diagonal(cov...
_____no_output_____
MIT
notebooks/Assumptions.ipynb
victordalla/regression-diagnosis
**Non-constant variance**
setting = "canonical" x = x_fix.copy() e = e_fix.copy() mu = 100 + true_params["b1"] * x e = (mu)**0.5 * e y = true_params["b0"] + true_params["b1"] * x + e data = pd.DataFrame({"x": x, "e": e, "y": y}) print("Model: y ~ x") regressor = smf.ols(formula="y ~ x", data=data).fit() ax = plot_lmreg(data=data, x="x", y="y"...
_____no_output_____
MIT
notebooks/Assumptions.ipynb
victordalla/regression-diagnosis
實驗:實作InceptionV3網路架構 Run in Google Colab View source on GitHub Import必要套件
import numpy as np import matplotlib.pyplot as plt import tensorflow as tf
_____no_output_____
MIT
Lab8.ipynb
leolinxup6/tf-
--- Keras Applications 創建InceptionV3網路架構- 輸入大小(預設):(299, 299, 3)- 權重(預設):`imagenet`- 輸出類別(預設):1000個類別
model = tf.keras.applications.InceptionV3(include_top=True, weights='imagenet')
Downloading data from https://storage.googleapis.com/tensorflow/keras-applications/inception_v3/inception_v3_weights_tf_dim_ordering_tf_kernels.h5 96116736/96112376 [==============================] - 22s 0us/step
MIT
Lab8.ipynb
leolinxup6/tf-
透過`model.summary`可以察看網路模型的每一層資訊:
model.summary()
Model: "inception_v3" __________________________________________________________________________________________________ Layer (type) Output Shape Param # Connected to ================================================================================================== i...
MIT
Lab8.ipynb
leolinxup6/tf-
將網路模型儲存到TensorBoard上:
model_tb = tf.keras.callbacks.TensorBoard(log_dir='lab8-logs-inceptionv3-keras') model_tb.set_model(model)
_____no_output_____
MIT
Lab8.ipynb
leolinxup6/tf-
資料前處理和輸出解碼 使用別人提供的模型預測,需要注意兩件事情,1)訓練時的資料前處理,2)輸出結果對應到的類別。Keras很貼心的提供每個模型相對應的資料預處理和輸出解碼的函式。- preprocess_input:網路架構的影像前處理(注意:每一個模型在訓練時做的資料正規化並不會相同,例如:VGG、ResNet-50輸入影像為0~255的數值,而inception_v3、xception輸入影像為-1~1的數值)。- decode_predictions:對應網路架構的輸出解碼。 Import資料預處理和輸出解碼的函式:
from tensorflow.keras.applications.inception_v3 import preprocess_input from tensorflow.keras.applications.inception_v3 import decode_predictions
_____no_output_____
MIT
Lab8.ipynb
leolinxup6/tf-
預測輸出結果 創建影像讀取的函式:讀取影像,並將影像大小縮放大299x299x3的尺寸。
def read_img(img_path, resize=(299,299)): img_string = tf.io.read_file(img_path) # 讀取檔案 img_decode = tf.image.decode_image(img_string) # 將檔案以影像格式來解碼 img_decode = tf.image.resize(img_decode, resize) # 將影像resize到網路輸入大小 # 將影像格式增加到4維(batch, height, width, channels),模型預測要求格式 img_decode = tf.expand_dim...
_____no_output_____
MIT
Lab8.ipynb
leolinxup6/tf-
從資料夾中讀取一張影像(elephant.jpg)作為測試:
img_path = 'image/elephant.jpg' img = read_img(img_path) # 透過剛創建的函式讀取影像 plt.imshow(tf.cast(img, tf.uint8)[0]) # 透過matplotlib顯示圖片需將影像轉為Integers
_____no_output_____
MIT
Lab8.ipynb
leolinxup6/tf-
預測結果:
img = preprocess_input(img) # 影像前處理 preds = model.predict(img) # 預測圖片 print("Predicted:", decode_predictions(preds, top=3)[0]) # 輸出預測最高的三個類別
Downloading data from https://storage.googleapis.com/download.tensorflow.org/data/imagenet_class_index.json 40960/35363 [==================================] - 0s 0us/step Predicted: [('n02504458', 'African_elephant', 0.8037864), ('n01871265', 'tusker', 0.121638976), ('n02504013', 'Indian_elephant', 0.0042992695)]
MIT
Lab8.ipynb
leolinxup6/tf-
--- TensorFlow HubInstall:```pip install tensorflow-hub```Search:https://tfhub.dev/
import tensorflow as tf import tensorflow_hub as hub
_____no_output_____
MIT
Lab8.ipynb
leolinxup6/tf-
創建Inception V3模型Model:https://tfhub.dev/google/tf2-preview/inception_v3/classification/2num_classes = 1001 classes of the classification from the original training Image:height x width = 299 x 299 pixels, 3 RGB color values in the range 0~1labels file: https://storage.googleapis.com/download.tensorflow.org/data/ImageN...
# Inception V3預訓練模型的URL module_url = "https://tfhub.dev/google/tf2-preview/inception_v3/classification/4" # 創建一個Sequential Model,網路模型裡面包含了Inception V3網路層 model = tf.keras.Sequential([ # hub.KerasLayer將載入的Inception V3模型封裝成網路層(Keras Layer) hub.KerasLayer(module_url, input_shape=(299, 299, 3), ...
Model: "sequential" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= Inception_v3 (KerasLayer) (None, 1001) 23853833 ====================================...
MIT
Lab8.ipynb
leolinxup6/tf-
資料前處理和輸出解碼 創建資料前處理函式:
def read_img(img_path, resize=(299,299)): img_string = tf.io.read_file(img_path) # 讀取檔案 img_decode = tf.image.decode_image(img_string) # 將檔案以影像格式來解碼 img_decode = tf.image.resize(img_decode, resize) # 將影像resize到網路輸入大小 img_decode = img_decode / 255.0 # 對影像做正規畫,將數值縮放到0~1之間 # 將影像格式增加到4維(batch, heigh...
_____no_output_____
MIT
Lab8.ipynb
leolinxup6/tf-
創建輸出解碼器:
# 下載ImageNet 的標籤檔 labels_path = tf.keras.utils.get_file('ImageNetLabels.txt', 'https://storage.googleapis.com/download.tensorflow.org/data/ImageNetLabels.txt') # 讀取標籤檔中的數據 with open(labels_path) as file: lines = file.read().splitlines() print(lines) # 顯示讀取的標籤 imagenet_labels = np.array(lines) # 將標籤轉成numpy array做...
Downloading data from https://storage.googleapis.com/download.tensorflow.org/data/ImageNetLabels.txt 16384/10484 [==============================================] - 0s 0us/step ['background', 'tench', 'goldfish', 'great white shark', 'tiger shark', 'hammerhead', 'electric ray', 'stingray', 'cock', 'hen', 'ostrich', 'bra...
MIT
Lab8.ipynb
leolinxup6/tf-
預測輸出結果 從資料夾中讀取一張影像(elephant.jpg)作為測試:
img_path = 'image/elephant.jpg' img = read_img(img_path) # 透過剛創建的函式讀取影像 plt.imshow(img[0])
_____no_output_____
MIT
Lab8.ipynb
leolinxup6/tf-
預測結果:
preds = model.predict(img) # 預測圖片 index = np.argmax(preds) # 取得預測結果最大的Index print("Predicted:", imagenet_labels[index]) # 透過解碼器將輸出轉成標籤
Predicted: African elephant
MIT
Lab8.ipynb
leolinxup6/tf-
顯示最好的三個預測:
# 取得預測結果最大的三個indexs top3_indexs = np.argsort(preds)[0, ::-1][:3] print("Predicted:", imagenet_labels[top3_indexs]) # 透過解碼器將輸出轉成標籤
Predicted: ['African elephant' 'tusker' 'Indian elephant']
MIT
Lab8.ipynb
leolinxup6/tf-
Distribuciones de probabilidad
# Importamos librerías a trabajar en todas las simulaciones import matplotlib.pyplot as plt import numpy as np from itertools import cycle # Librería para hacer ciclos import scipy.stats as st # Librería estadística from math import factorial as fac # Importo la operación factorial %matplotlib inline
_____no_output_____
MIT
TEMA-2/Clase12_DistribucionesProbabilidad.ipynb
anehik/SPF-2020-II-G1
1. Distrución de probabilidad uniforme$X\sim U(a,b)$ Parámetros $a,b \rightarrow $ intervalo$$\textbf{Función de densidad de probabilidad}\\f(x)=\begin{cases}\frac{1}{b-a} & a\leq x \leq b\\0& \text{otro caso}\end{cases}$$ $$ \textbf{Función de distribución de probabilidad}\\F(x)=\begin{cases}0& x<a\\\frac{x-a}{b-a} ...
a,b=1,2 # Interval U = np.random.uniform(a,b) U st.uniform.rvs(loc=a, scale=b, size=2)
_____no_output_____
MIT
TEMA-2/Clase12_DistribucionesProbabilidad.ipynb
anehik/SPF-2020-II-G1
2. Distribución normal$X\sim N(\mu,\sigma^2)$ Parámetros: Media=$\mu$ y varianza=$\sigma^2$$$ \textbf{Función de densidad de probabilidad}\\ f(x)= \frac{1}{\sigma\sqrt{2\pi}}e^{\frac{-(x-\mu)^2}{2\sigma^2}}$$$$ \textbf{Función de distribución de probabilidad}\\ F(x)= \frac{1}{\sigma\sqrt(2\pi)}\int_{-\infty}^{x}e^{\fr...
mu, sigma = 0, 0.1 # mean and standard deviation N = np.random.normal(mu, sigma,5) N st.norm.rvs(loc=a, scale=sigma, size=5)
_____no_output_____
MIT
TEMA-2/Clase12_DistribucionesProbabilidad.ipynb
anehik/SPF-2020-II-G1
3. Distribución exponencial$X\sim Exp(\beta)$ Parámetros: Media $\beta>0$ o tasa = $\lambda = 1/\beta$$$\textbf{Función de densidad de probabilidad}\\f(x) = \frac{1}{\beta} e^{-\frac{x}{\beta}}$$$$\textbf{Función de distribución de probabilidad}\\F(x) = 1-e^{-\frac{x}{\beta}}$$![imagen.png](attachment:imagen.png) Ejem...
beta = 4 E = np.random.exponential(beta,1) E st.expon
_____no_output_____
MIT
TEMA-2/Clase12_DistribucionesProbabilidad.ipynb
anehik/SPF-2020-II-G1
4. Distribución erlangParámetros: Tamaño $k \in \mathbb{N}$, escala=$\frac{1}{\beta}$$$\textbf{Función de densidad de probabilidad}\\f(x)=x^{k-1}\frac{e^{-x/\beta}}{\beta^k\Gamma(k)}\equiv x^{k-1}\frac{e^{-x/\beta}}{\beta^k(k-1)!}$$$$\textbf{Función de distribución de probabilidad}\\F(x)=1-\sum_{n=0}^{k-1}\frac{1}{n!}...
N = 10000 # Número de muestras k,scale = 3,1/4 # Parámetros de la distribución E1 = st.erlang.rvs(k,scale=scale,size=N) E2 = np.random.gamma(k,scale,N) # Erlang como caso particular de la distribución gamma plt.figure(1,figsize=[12,4]) plt.subplot(121) plt.hist(E1,50,density=True,label='Usando Lib. scipy') ...
_____no_output_____
MIT
TEMA-2/Clase12_DistribucionesProbabilidad.ipynb
anehik/SPF-2020-II-G1
5. Distribución binomial$X\sim B(n,p)$ Parámetros: $n$ y $p$$$\textbf{Función de densidad de probabilidad}\\p_i=P(X=i)={n \choose i}p^i(1-p)^{n-i}= \frac{n!}{i!(n-i)!}p^i(1-p)^{n-i},\quad i=0,1,\cdots,n$$>Recordar:$$p_{i+1}=\frac{n-i}{i+1}\frac{p}{1-p} p_i $$$$\textbf{Función de distribución de probabilidad}\\F(x)=\su...
# Función que calcula la probabilidad acumulada optimizada def proba_binomial(n:'Cantidad de ensayos',p:'Probabilidad de los eventos', N:'Cantidad de puntos a graficar'): Pr = np.zeros(N) Pr[0] = (1-p)**n def pr(i): nonlocal Pr c = p/(1-p) Pr[i+1]=(c*(n-i)/(i+1))*...
(3, 100)
MIT
TEMA-2/Clase12_DistribucionesProbabilidad.ipynb
anehik/SPF-2020-II-G1
CaracterísticasLa distribución binomial es una distribución de probabilidad discreta que cuenta el número de éxitos en una secuencia de **n ensayos de Bernoulli independientes entre sí**, con una probabilidad `fija` p de ocurrencia del éxito entre los ensayos. A lo que se denomina «éxito», tiene una probabilidad de oc...
n = 51; p=1/6; X=20 print('P(X=20)=',st.binom(n,p).pmf(X))
P(X=20)= 7.444834157690862e-05
MIT
TEMA-2/Clase12_DistribucionesProbabilidad.ipynb
anehik/SPF-2020-II-G1
Relaciones con otras variables aleatoriasSi n tiende a infinito y p es tal que el producto entre ambos parámetros tiende a $\lambda$, entonces la distribución de la variable aleatoria binomial tiende a una distribución de Poisson de parámetro $\lambda$.Por último, se cumple que cuando $p =0.5$ y n es muy grande (usual...
p = .5; n = 50 mu = n*p; sigma = np.sqrt(n*p*(1-p)) # Usando nuetra función creada Bi = proba_binomial(n,p,n) plt.figure(1,figsize=[10,5]) plt.subplot(121) plt.plot(Bi,'o') plt.title('Distribución binomial n=%i,p=%0.2f'%(n,p)) # Usando la función de la librería scipy para graficar la normal x = np.arange(0,n) Bi_norm...
_____no_output_____
MIT
TEMA-2/Clase12_DistribucionesProbabilidad.ipynb
anehik/SPF-2020-II-G1
6. Distribución PoissonParámetros: media=$\lambda>0 \in \mathbb{R}$, N°Ocurrencias = k - k es el número de ocurrencias del evento o fenómeno (la función nos da la probabilidad de que el evento suceda precisamente k veces). - λ es un parámetro positivo que representa el **número de veces que se espera que ocurra el...
k=5; Lamda = 8 print('P(5;8)=',st.poisson(Lamda).pmf(k))
P(5;8)= 0.09160366159257921
MIT
TEMA-2/Clase12_DistribucionesProbabilidad.ipynb
anehik/SPF-2020-II-G1
Usando el paquete estadístico `stats`
# Parámetros Lamda = [8,20] k=np.arange(0,40); # Distribución de probabilidad P = np.array([st.poisson(Lamda[i]).pmf(k) for i in range(len(Lamda))]) # Distribución de probabilidad acumulada P_acum = np.array([st.poisson(Lamda[i]).cdf(k) for i in range(len(Lamda))]) fig,[ax1,ax2] = plt.subplots(1,2,sharey=False,figs...
_____no_output_____
MIT
TEMA-2/Clase12_DistribucionesProbabilidad.ipynb
anehik/SPF-2020-II-G1
Usando las expresiones matemáticas
import scipy.special as sps p = lambda k,l:(l**k*np.exp(-l))/sps.gamma(k+1) k = np.arange(0,50) l = [1,10,20,30] P = np.asmatrix(list(map(lambda x:p(k,x*np.ones(len(k))),l))).T print(P.shape) plt.figure(1,figsize=[12,4]) plt.subplot(121) plt.plot(P,'o',markersize=3) plt.legend(['$\lambda$=%d'%i for i in l]) plt.title...
(50, 4)
MIT
TEMA-2/Clase12_DistribucionesProbabilidad.ipynb
anehik/SPF-2020-II-G1
Load dataThree datasets are included, pNIPAM at 25 °C, 32.5 °C and 40 °C. pNIPAM is thermoresponsive; the 25 °C is a swollen, diffuse layer, whilst the 40 °C data is a collapsed slab.
data = RD("pNIPAM brush in d2o at 25C.dat") # data = RD("pNIPAM brush in d2o at 32C.dat") # data = RD("pNIPAM brush in d2o at 40C.dat")
_____no_output_____
BSD-3-Clause
polymer_brushes/FreeformVFP-example.ipynb
arm61/refnx-models
Define materials and slab componentsFor simplicity some parameters that may normally have been allowed to vary have been set to predetermined optimum values.
si = SLD(2.07, 'si') sio2 = SLD(2.9, 'sio2') d2o = SLD(6.23 , 'd2o') polymer = SLD(0.81, 'polymer') si_l = si(0, 0) sio2_l = sio2(20, 4.8) d2o_l = d2o(0, 0)
_____no_output_____
BSD-3-Clause
polymer_brushes/FreeformVFP-example.ipynb
arm61/refnx-models
Create the freeform component
NUM_KNOTS = 4 #Polymer layer 1 polymer_0 = polymer(2, 0.5) # Polymer-Solvent interface (spline) polymer_vfp = FreeformVFP(adsorbed_amount=120, vff=[0.6] * NUM_KNOTS, dzf=[1/(NUM_KNOTS + 1)] * (NUM_KNOTS + 1), polymer_sld=polymer, ...
_____no_output_____
BSD-3-Clause
polymer_brushes/FreeformVFP-example.ipynb
arm61/refnx-models
Set parameter bounds
sio2.real.setp(vary=True, bounds=(2.8, 3.47)) polymer_0.thick.setp(vary=True, bounds=(2, 20)) polymer_0.vfsolv.setp(vary=True, bounds=(0.1, 0.7)) polymer_vfp.adsorbed_amount.setp(vary=True, bounds=(100, 130)) # We can enforce monotonicity through the bounds we place on the fractional volume fraction changes. enforc...
_____no_output_____
BSD-3-Clause
polymer_brushes/FreeformVFP-example.ipynb
arm61/refnx-models
Create the structure, model, objective
structure = si_l | sio2_l | polymer_0 | polymer_vfp | d2o_l # contracting the slab representation reduces computation time. structure.contract = 1.5 model = ReflectModel(structure) model.bkg.setp(vary=True, bounds=(1e-6, 1e-5)) objective = Objective(model, data) fitter= CurveFitter(objective) fitter.fit('differentia...
_____no_output_____
BSD-3-Clause
polymer_brushes/FreeformVFP-example.ipynb
arm61/refnx-models
Iterative reconstruction of undersampled MR dataThis demonstration shows how to hande undersampled dataand how to write a simple iterative reconstruction algorithm withthe acquisition model.This demo is a 'script', i.e. intended to be run step by step in aPython notebook such as Jupyter. It is organised in 'cells'. Ju...
#%% make sure figures appears inline and animations works %matplotlib notebook # Setup the working directory for the notebook import notebook_setup from sirf_exercises import cd_to_working_dir cd_to_working_dir('MR', 'd_undersampled_reconstructions') __version__ = '0.1.0' # import engine module import sirf.Gadgetron ...
_____no_output_____
Apache-2.0
notebooks/MR/d_undersampled_reconstructions.ipynb
mastergari/SIRF-Exercises
Undersampled Reconstruction Goals of this notebook:- Write a fully sampled reconstruction on your own.- Obtain knowledge of how to deal with undersampled data.- User SIRF and Gadgetron to perform a GRAPPA reconstruction.- Implement an iterative parallel imaging SENSE reconstruction algorithm from scratch.
# This is just an auxiliary function def norm_array( arr ): min_a = abs(arr).min() max_a = abs(arr).max() return (arr - min_a)/(max_a - min_a)
_____no_output_____
Apache-2.0
notebooks/MR/d_undersampled_reconstructions.ipynb
mastergari/SIRF-Exercises
Time to get warmed up again:Since we deal with undersampled data in this last section, we need to compare it to a reference.So we need to reconstruct the fully sampled dataset we encountered before.This is an ideal opportunity to test what we learned and employ the `pMR.FullSampledReconstructor` class from before. Pr...
# YOUR CODE GOES HERE # VALIDATION CELL fs_image_array = fs_image.as_array() fs_image_array = norm_array(fs_image_array) fig = plt.figure() plt.set_cmap('gray') ax = fig.add_subplot(1,1,1) ax.imshow( abs(fs_image_array[0,:,:]), vmin=0, vmax=1) ax.set_title('Fully sampled reconstruction') ax.axis('off') # Soluti...
_____no_output_____
Apache-2.0
notebooks/MR/d_undersampled_reconstructions.ipynb
mastergari/SIRF-Exercises
This looks pretty similar to what we had before, so we should be good.
# we define a quick fft with sos coil combination to do a standard reconstruction. def our_fft( k_array ): image_array = numpy.zeros(k_array.shape, numpy.complex128) for c in range(num_channels): image_array[:,c,:] = numpy.fft.fftshift( numpy.fft.ifft2( numpy.fft.ifftshift(k_array[:,c,:]))) # image_...
_____no_output_____
Apache-2.0
notebooks/MR/d_undersampled_reconstructions.ipynb
mastergari/SIRF-Exercises
Question: Please answer the following question for yourself: - Why is the undersampled reconstruction squeezed, but covers the whole FOV?
# NOW LET'S LOOK WHICH PARTS ARE SAMPLED AND WHICH ARE LEFT OUT # kspace_encode_step_1 gives the phase encoding steps which were performed which_pe = preprocessed_data.get_ISMRMRD_info('kspace_encode_step_1') print('The following Phase Encoding (PE) points were sampled: \n') print(which_pe)
_____no_output_____
Apache-2.0
notebooks/MR/d_undersampled_reconstructions.ipynb
mastergari/SIRF-Exercises
Observation: approximately 3 out of 4 phase encoding steps are missing.
# Fill an array with 1 only if a datapoint was acquired sampling_mask = numpy.zeros([256,256]) for pe in which_pe: sampling_mask[pe,:] = 1 # PLOT THE SAMPLING MASK fig = plt.figure() plt.set_cmap('gray') ax = fig.add_subplot(1,1,1) ax.imshow( sampling_mask, vmin=0, vmax=1) ax.set_title('Sampling pattern of a ...
_____no_output_____
Apache-2.0
notebooks/MR/d_undersampled_reconstructions.ipynb
mastergari/SIRF-Exercises
We notice that $112 = \frac{256}{4} + 48$.This means the around the center of k-space is densely sampled containing 48 readout lines.The outside of k-space is undersampled by a factor of 4. Workaround: 'zero-fill' the k-space dataSince the artifacts seem to be related to the shape of the data, let's just unsqueeze the...
k_shape = [sampling_mask.shape[0], num_channels, sampling_mask.shape[1]] zf_k_array = numpy.zeros(k_shape, numpy.complex128) for i in range(k_array.shape[0]): zf_k_array[which_pe[i],:,:] = k_array[i,:,:] fig = plt.figure() plt.set_cmap('gray') for c in range(num_channels): ax = fig.add_subplot(2,num_channels...
_____no_output_____
Apache-2.0
notebooks/MR/d_undersampled_reconstructions.ipynb
mastergari/SIRF-Exercises
Observation: Bummer. Now the shape is correct, however the artifacts are still present. - What artifacts appear in the zero-filled reconstruction? - Why are they artifacts all fine-lined? - How come they only appear in one direction?To get rid of these we will need some parallel imaging techniques. Coil Sensitivity ...
# WHICH COILMAPS DO WE GET FROM THIS DATASET? csm = pMR.CoilSensitivityData() csm.smoothness = 50 csm.calculate(preprocessed_data) csm_array = numpy.squeeze(csm.as_array()) csm_array = csm_array.transpose([1,0,2]) fig = plt.figure() plt.set_cmap('jet') for c in range(csm_array.shape[1]): ax = fig.add_subplot(2,nu...
_____no_output_____
Apache-2.0
notebooks/MR/d_undersampled_reconstructions.ipynb
mastergari/SIRF-Exercises
Question: In practice we would want to use a weighted sum (WS) coil combination technique so any artifacts in the coilmap would directly translate into the combined image. But we didn't see any of the high frequency artifacts!Please answer the following question:- Why are there are artifacts in the reconstruction but ...
# WE DO A GRAPPA RECONSTRUCTION USING SIRF recon = pMR.CartesianGRAPPAReconstructor() recon.set_input(preprocessed_data) recon.compute_gfactors(False) print('---\n reconstructing...') recon.process() # for undersampled acquisition data GRAPPA computes Gfactor images # in addition to reconstructed ones grappa_images =...
_____no_output_____
Apache-2.0
notebooks/MR/d_undersampled_reconstructions.ipynb
mastergari/SIRF-Exercises
__Well, that was very little code to perform a difficult task!__ That is because we sent our data off to The Gadgetron and they did all the work. Question:In what respect did a GRAPPA reconstruction: * improve the resulting image? * deterioate the resulting image? GREAT! Now we want to develop our own algorithm and be...
# NOW WE GENERATE THE ACQUISITION MODEL E = pMR.AcquisitionModel(preprocessed_data, grappa_images) # We need help again to see what this thing here can do help(E) # to supply coil info to the acquisition model we use the dedicated method E.set_coil_sensitivity_maps(csm) # Now we can hop back from k-space into image sp...
_____no_output_____
Apache-2.0
notebooks/MR/d_undersampled_reconstructions.ipynb
mastergari/SIRF-Exercises