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
Blobs and GMM
X, y = make_blobs(n_samples=10000, n_features=2, centers=4, random_state=2) plt.figure(figsize=(7,7)) plt.scatter(X[:, 0],X[:, 1]) plt.xlabel('Weight') plt.ylabel('Height') plt.title('Data Distribution') plt.show() gmm = GaussianMixture(n_components=4) gmm.fit(X, y) labels = gmm.predict(X) frame = pd.DataFrame(X, y) fr...
_____no_output_____
MIT
Gaussian Mixture Model Assignment/Gaussian Mixture Model.ipynb
tusharsaxena250/AIML_Course
Deutsch-Jozsa Algorithm In this section, we first introduce the Deutsch-Jozsa problem, and classical and quantum algorithms to solve it. We then implement the quantum algorithm using Qiskit, and run it on a simulator and device. Contents1. [Introduction](introduction) 1.1 [Deutsch-Jozsa Problem](djproblem) ...
from qiskit_textbook.widgets import dj_widget dj_widget(size="small", case="balanced")
_____no_output_____
Apache-2.0
content/ch-algorithms/deutsch-jozsa.ipynb
muneerqu/qiskit-textbook
3. Creating Quantum Oracles Let's see some different ways we can create a quantum oracle. For a constant function, it is simple:$\qquad$ 1. if f(x) = 0, then apply the $I$ gate to the qubit in register 2. $\qquad$ 2. if f(x) = 1, then apply the $X$ gate to the qubit in register 2.For a balanced function, there are m...
# initialization import numpy as np # importing Qiskit from qiskit import IBMQ, BasicAer from qiskit.providers.ibmq import least_busy from qiskit import QuantumCircuit, execute # import basic plot tools from qiskit.visualization import plot_histogram
_____no_output_____
Apache-2.0
content/ch-algorithms/deutsch-jozsa.ipynb
muneerqu/qiskit-textbook
Next, we set the size of the input register for our oracle:
# set the length of the n-bit input string. n = 3
_____no_output_____
Apache-2.0
content/ch-algorithms/deutsch-jozsa.ipynb
muneerqu/qiskit-textbook
4.1 Constant Oracle Let's start by creating a constant oracle, in this case the input has no effect on the ouput so we just randomly set the output qubit to be 0 or 1:
# set the length of the n-bit input string. n = 3 const_oracle = QuantumCircuit(n+1) output = np.random.randint(2) if output == 1: const_oracle.x(n) const_oracle.draw()
_____no_output_____
Apache-2.0
content/ch-algorithms/deutsch-jozsa.ipynb
muneerqu/qiskit-textbook
4.2 Balanced Oracle
balanced_oracle = QuantumCircuit(n+1)
_____no_output_____
Apache-2.0
content/ch-algorithms/deutsch-jozsa.ipynb
muneerqu/qiskit-textbook
Next, we create a balanced oracle. As we saw in section 1b, we can create a balanced oracle by performing CNOTs with each input qubit as a control and the output bit as the target. We can vary the input states that give 0 or 1 by wrapping some of the controls in X-gates. Let's first choose a binary string of length `n`...
b_str = "101"
_____no_output_____
Apache-2.0
content/ch-algorithms/deutsch-jozsa.ipynb
muneerqu/qiskit-textbook
Now we have this string, we can use it as a key to place our X-gates. For each qubit in our circuit, we place an X-gate if the corresponding digit in `b_str` is `1`, or do nothing if the digit is `0`.
balanced_oracle = QuantumCircuit(n+1) b_str = "101" # Place X-gates for qubit in range(len(b_str)): if b_str[qubit] == '1': balanced_oracle.x(qubit) balanced_oracle.draw()
_____no_output_____
Apache-2.0
content/ch-algorithms/deutsch-jozsa.ipynb
muneerqu/qiskit-textbook
Next, we do our controlled-NOT gates, using each input qubit as a control, and the output qubit as a target:
balanced_oracle = QuantumCircuit(n+1) b_str = "101" # Place X-gates for qubit in range(len(b_str)): if b_str[qubit] == '1': balanced_oracle.x(qubit) # Use barrier as divider balanced_oracle.barrier() # Controlled-NOT gates for qubit in range(n): balanced_oracle.cx(qubit, n) balanced_oracle.barrier()...
_____no_output_____
Apache-2.0
content/ch-algorithms/deutsch-jozsa.ipynb
muneerqu/qiskit-textbook
Finally, we repeat the code from two cells up to finish wrapping the controls in X-gates:
balanced_oracle = QuantumCircuit(n+1) b_str = "101" # Place X-gates for qubit in range(len(b_str)): if b_str[qubit] == '1': balanced_oracle.x(qubit) # Use barrier as divider balanced_oracle.barrier() # Controlled-NOT gates for qubit in range(n): balanced_oracle.cx(qubit, n) balanced_oracle.barrier()...
_____no_output_____
Apache-2.0
content/ch-algorithms/deutsch-jozsa.ipynb
muneerqu/qiskit-textbook
We have just created a balanced oracle! All that's left to do is see if the Deutsch-Joza algorithm can solve it. 4.3 The Full Algorithm Let's now put everything together. This first step in the algorithm is to initialise the input qubits in the state $|{+}\rangle$ and the output qubit in the state $|{-}\rangle$:
dj_circuit = QuantumCircuit(n+1, n) # Apply H-gates for qubit in range(n): dj_circuit.h(qubit) # Put qubit in state |-> dj_circuit.x(n) dj_circuit.h(n) dj_circuit.draw()
_____no_output_____
Apache-2.0
content/ch-algorithms/deutsch-jozsa.ipynb
muneerqu/qiskit-textbook
Next, let's apply the oracle. Here we apply the `balanced_oracle` we created above:
dj_circuit = QuantumCircuit(n+1, n) # Apply H-gates for qubit in range(n): dj_circuit.h(qubit) # Put qubit in state |-> dj_circuit.x(n) dj_circuit.h(n) # Add oracle dj_circuit += balanced_oracle dj_circuit.draw()
_____no_output_____
Apache-2.0
content/ch-algorithms/deutsch-jozsa.ipynb
muneerqu/qiskit-textbook
Finally, we perform H-gates on the $n$-input qubits, and measure our input register:
dj_circuit = QuantumCircuit(n+1, n) # Apply H-gates for qubit in range(n): dj_circuit.h(qubit) # Put qubit in state |-> dj_circuit.x(n) dj_circuit.h(n) # Add oracle dj_circuit += balanced_oracle # Repeat H-gates for qubit in range(n): dj_circuit.h(qubit) dj_circuit.barrier() # Measure for i in range(n): ...
_____no_output_____
Apache-2.0
content/ch-algorithms/deutsch-jozsa.ipynb
muneerqu/qiskit-textbook
Let's see the output:
# use local simulator backend = BasicAer.get_backend('qasm_simulator') shots = 1024 results = execute(dj_circuit, backend=backend, shots=shots).result() answer = results.get_counts() plot_histogram(answer)
_____no_output_____
Apache-2.0
content/ch-algorithms/deutsch-jozsa.ipynb
muneerqu/qiskit-textbook
We can see from the results above that we have a 0% chance of measuring `000`. This correctly predicts the function is balanced. 4.4 Generalised Circuits Below, we provide a generalised function that creates Deutsch-Joza oracles and turns them into quantum gates. It takes the `case`, (either `'balanced'` or '`constant...
def dj_oracle(case, n): # We need to make a QuantumCircuit object to return # This circuit has n+1 qubits: the size of the input, # plus one output qubit oracle_qc = QuantumCircuit(n+1) # First, let's deal with the case in which oracle is balanced if case == "balanced": # First gene...
_____no_output_____
Apache-2.0
content/ch-algorithms/deutsch-jozsa.ipynb
muneerqu/qiskit-textbook
Let's also create a function that takes this oracle gate and performs the Deutsch-Joza algorithm on it:
def dj_algorithm(oracle, n): dj_circuit = QuantumCircuit(n+1, n) # Set up the output qubit: dj_circuit.x(n) dj_circuit.h(n) # And set up the input register: for qubit in range(n): dj_circuit.h(qubit) # Let's append the oracle gate to our circuit: dj_circuit.append(oracle, range(n...
_____no_output_____
Apache-2.0
content/ch-algorithms/deutsch-jozsa.ipynb
muneerqu/qiskit-textbook
Finally, let's use these functions to play around with the algorithm:
n = 4 oracle_gate = dj_oracle('balanced', n) dj_circuit = dj_algorithm(oracle_gate, n) dj_circuit.draw()
_____no_output_____
Apache-2.0
content/ch-algorithms/deutsch-jozsa.ipynb
muneerqu/qiskit-textbook
And see the results of running this circuit:
results = execute(dj_circuit, backend=backend, shots=1024).result() answer = results.get_counts() plot_histogram(answer)
_____no_output_____
Apache-2.0
content/ch-algorithms/deutsch-jozsa.ipynb
muneerqu/qiskit-textbook
5. Experiment with Real Devices We can run the circuit on the real device as shown below. We first look for the least-busy device that can handle our circuit.
# Load our saved IBMQ accounts and get the least busy backend device with greater than or equal to (n+1) qubits IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q') backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= (n+1) and not x.configur...
_____no_output_____
Apache-2.0
content/ch-algorithms/deutsch-jozsa.ipynb
muneerqu/qiskit-textbook
As we can see, the most likely result is `1111`. The other results are due to errors in the quantum computation. 6. Problems 1. Are you able to create a balanced or constant oracle of a different form?
from qiskit_textbook.problems import dj_problem_oracle oracle = dj_problem_oracle(1)
_____no_output_____
Apache-2.0
content/ch-algorithms/deutsch-jozsa.ipynb
muneerqu/qiskit-textbook
2. The function `dj_problem_oracle` (shown above) returns a Deutsch-Joza oracle for `n = 4` in the form of a gate. The gate takes 5 qubits as input where the final qubit (`q_4`) is the output qubit (as with the example oracles above). You can get different oracles by giving `dj_problem_oracle` different integers betwee...
import qiskit qiskit.__qiskit_version__
_____no_output_____
Apache-2.0
content/ch-algorithms/deutsch-jozsa.ipynb
muneerqu/qiskit-textbook
Residual NetworksWelcome to the second assignment of this week! You will learn how to build very deep convolutional networks, using Residual Networks (ResNets). In theory, very deep networks can represent very complex functions; but in practice, they are hard to train. Residual Networks, introduced by [He et al.](http...
import numpy as np from keras import layers from keras.layers import Input, Add, Dense, Activation, ZeroPadding2D, BatchNormalization, Flatten, Conv2D, AveragePooling2D, MaxPooling2D, GlobalMaxPooling2D from keras.models import Model, load_model from keras.preprocessing import image from keras.utils import layer_utils ...
Using TensorFlow backend.
MIT
Convolutional Neural Networks/Residual Networks.ipynb
LuketheDukeBates/Deep-Learning-Coursera-Andrew-Ng-
1 - The problem of very deep neural networksLast week, you built your first convolutional neural network. In recent years, neural networks have become deeper, with state-of-the-art networks going from just a few layers (e.g., AlexNet) to over a hundred layers.The main benefit of a very deep network is that it can repr...
# GRADED FUNCTION: identity_block def identity_block(X, f, filters, stage, block): """ Implementation of the identity block as defined in Figure 3 Arguments: X -- input tensor of shape (m, n_H_prev, n_W_prev, n_C_prev) f -- integer, specifying the shape of the middle CONV's window for the main pat...
out = [ 0.94822985 0. 1.16101444 2.747859 0. 1.36677003]
MIT
Convolutional Neural Networks/Residual Networks.ipynb
LuketheDukeBates/Deep-Learning-Coursera-Andrew-Ng-
**Expected Output**: **out** [ 0.94822985 0. 1.16101444 2.747859 0. 1.36677003] 2.2 - The convolutional blockYou've implemented the ResNet identity block. Next, the ResNet "convolutional block" is the other type of block. You can use t...
# GRADED FUNCTION: convolutional_block def convolutional_block(X, f, filters, stage, block, s=2): """ Implementation of the convolutional block as defined in Figure 4 Arguments: X -- input tensor of shape (m, n_H_prev, n_W_prev, n_C_prev) f -- integer, specifying the shape of the middle CONV's win...
out = [ 0.09018463 1.23489773 0.46822017 0.0367176 0. 0.65516603]
MIT
Convolutional Neural Networks/Residual Networks.ipynb
LuketheDukeBates/Deep-Learning-Coursera-Andrew-Ng-
**Expected Output**: **out** [ 0.09018463 1.23489773 0.46822017 0.0367176 0. 0.65516603] 3 - Building your first ResNet model (50 layers)You now have the necessary blocks to build a very deep ResNet. The following figure describes in detail the...
# GRADED FUNCTION: ResNet50 def ResNet50(input_shape=(64, 64, 3), classes=6): """ Implementation of the popular ResNet50 the following architecture: CONV2D -> BATCHNORM -> RELU -> MAXPOOL -> CONVBLOCK -> IDBLOCK*2 -> CONVBLOCK -> IDBLOCK*3 -> CONVBLOCK -> IDBLOCK*5 -> CONVBLOCK -> IDBLOCK*2 -> AVGPOOL ...
_____no_output_____
MIT
Convolutional Neural Networks/Residual Networks.ipynb
LuketheDukeBates/Deep-Learning-Coursera-Andrew-Ng-
Run the following code to build the model's graph. If your implementation is not correct you will know it by checking your accuracy when running `model.fit(...)` below.
model = ResNet50(input_shape=(64, 64, 3), classes=6)
_____no_output_____
MIT
Convolutional Neural Networks/Residual Networks.ipynb
LuketheDukeBates/Deep-Learning-Coursera-Andrew-Ng-
As seen in the Keras Tutorial Notebook, prior training a model, you need to configure the learning process by compiling the model.
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
_____no_output_____
MIT
Convolutional Neural Networks/Residual Networks.ipynb
LuketheDukeBates/Deep-Learning-Coursera-Andrew-Ng-
The model is now ready to be trained. The only thing you need is a dataset. Let's load the SIGNS Dataset. **Figure 6** : **SIGNS dataset**
X_train_orig, Y_train_orig, X_test_orig, Y_test_orig, classes = load_dataset() # Normalize image vectors X_train = X_train_orig / 255. X_test = X_test_orig / 255. # Convert training and test labels to one hot matrices Y_train = convert_to_one_hot(Y_train_orig, 6).T Y_test = convert_to_one_hot(Y_test_orig, 6).T print...
number of training examples = 1080 number of test examples = 120 X_train shape: (1080, 64, 64, 3) Y_train shape: (1080, 6) X_test shape: (120, 64, 64, 3) Y_test shape: (120, 6)
MIT
Convolutional Neural Networks/Residual Networks.ipynb
LuketheDukeBates/Deep-Learning-Coursera-Andrew-Ng-
Run the following cell to train your model on 2 epochs with a batch size of 32. On a CPU it should take you around 5min per epoch.
model.fit(X_train, Y_train, epochs = 2, batch_size = 32)
Epoch 1/2 1080/1080 [==============================] - 313s - loss: 2.9895 - acc: 0.2426 Epoch 2/2 1080/1080 [==============================] - 317s - loss: 2.1304 - acc: 0.3278
MIT
Convolutional Neural Networks/Residual Networks.ipynb
LuketheDukeBates/Deep-Learning-Coursera-Andrew-Ng-
**Expected Output**: ** Epoch 1/2** loss: between 1 and 5, acc: between 0.2 and 0.5, although your results can be different from ours. ** Epoch 2/2** loss: between 1 and 5, acc: between 0.2 and 0.5, you should ...
preds = model.evaluate(X_test, Y_test) print("Loss = " + str(preds[0])) print("Test Accuracy = " + str(preds[1]))
120/120 [==============================] - 11s Loss = 2.15092230638 Test Accuracy = 0.166666666667
MIT
Convolutional Neural Networks/Residual Networks.ipynb
LuketheDukeBates/Deep-Learning-Coursera-Andrew-Ng-
**Expected Output**: **Test Accuracy** between 0.16 and 0.25 For the purpose of this assignment, we've asked you to train the model only for two epochs. You can see that it achieves poor performances. Please go ahead and submit your assignment; to check corre...
model = load_model('ResNet50.h5') preds = model.evaluate(X_test, Y_test) print("Loss = " + str(preds[0])) print("Test Accuracy = " + str(preds[1]))
120/120 [==============================] - 13s Loss = 0.530178320408 Test Accuracy = 0.866666662693
MIT
Convolutional Neural Networks/Residual Networks.ipynb
LuketheDukeBates/Deep-Learning-Coursera-Andrew-Ng-
ResNet50 is a powerful model for image classification when it is trained for an adequate number of iterations. We hope you can use what you've learnt and apply it to your own classification problem to perform state-of-the-art accuracy.Congratulations on finishing this assignment! You've now implemented a state-of-the-a...
img_path = 'images/my_image.jpg' img = image.load_img(img_path, target_size=(64, 64)) x = image.img_to_array(img) x = np.expand_dims(x, axis=0) x = preprocess_input(x) print('Input image shape:', x.shape) my_image = scipy.misc.imread(img_path) imshow(my_image) print("class prediction vector [p(0), p(1), p(2), p(3), p(4...
Input image shape: (1, 64, 64, 3) class prediction vector [p(0), p(1), p(2), p(3), p(4), p(5)] = [[ 1. 0. 0. 0. 0. 0.]]
MIT
Convolutional Neural Networks/Residual Networks.ipynb
LuketheDukeBates/Deep-Learning-Coursera-Andrew-Ng-
You can also print a summary of your model by running the following code.
model.summary()
____________________________________________________________________________________________________ Layer (type) Output Shape Param # Connected to ==================================================================================================== input_1 (InputLay...
MIT
Convolutional Neural Networks/Residual Networks.ipynb
LuketheDukeBates/Deep-Learning-Coursera-Andrew-Ng-
Finally, run the code below to visualize your ResNet50. You can also download a .png picture of your model by going to "File -> Open...-> model.png".
plot_model(model, to_file='model.png') SVG(model_to_dot(model).create(prog='dot', format='svg'))
_____no_output_____
MIT
Convolutional Neural Networks/Residual Networks.ipynb
LuketheDukeBates/Deep-Learning-Coursera-Andrew-Ng-
Python statistics essential training - 05_03_fitgoodness Standard imports
import math import numpy as np import pandas as pd import matplotlib import matplotlib.pyplot as pp %matplotlib inline import statsmodels import statsmodels.api as sm import statsmodels.formula.api as smf
_____no_output_____
MIT
Vallisneri Courses/Python Statistics Essential Training/Exercise Files/chapter5/05_03/05_03_fitgoodness_begin.ipynb
samisaf/Learning-Data-Science
Loading gapminder data for year 1985 (Live Aid!) and setting up plot as in chapter 3
gapminder = pd.read_csv('gapminder.csv') gdata = gapminder.query('year == 1985') size = 1e-6 * gdata.population colors = gdata.region.map({'Africa': 'skyblue', 'Europe': 'gold', 'America': 'palegreen', 'Asia': 'coral'}) def plotdata(): gdata.plot.scatter('age5_surviving','babies_per_woman', ...
_____no_output_____
MIT
Vallisneri Courses/Python Statistics Essential Training/Exercise Files/chapter5/05_03/05_03_fitgoodness_begin.ipynb
samisaf/Learning-Data-Science
Setting up model plot
def plotfit(fit): plotdata() pp.scatter(gdata.age5_surviving,fit.predict(gdata), c=colors,s=30,linewidths=0.5,edgecolor='k',marker='D')
_____no_output_____
MIT
Vallisneri Courses/Python Statistics Essential Training/Exercise Files/chapter5/05_03/05_03_fitgoodness_begin.ipynb
samisaf/Learning-Data-Science
Three models from last video
groupmeans = smf.ols(formula='babies_per_woman ~ -1 + region', data=gdata).fit() surviving = smf.ols(formula='babies_per_woman ~ -1 + region + age5_surviving', data=gdata).fit() surviving_byregion_population = smf.ols( formula='babies_per_woman ~ -1 + region + age5_surviving' '+ age5_surviving:region - ...
_____no_output_____
MIT
Vallisneri Courses/Python Statistics Essential Training/Exercise Files/chapter5/05_03/05_03_fitgoodness_begin.ipynb
samisaf/Learning-Data-Science
Interpreting your pruning and regularization experimentsThis notebook contains code to be included in your own notebooks by adding this line at the top of your notebook:```%run distiller_jupyter_helpers.ipynb```
# Relative import of code from distiller, w/o installing the package import os import sys import distiller.utils import distiller import distiller.apputils.checkpoint import torch import torchvision import os import collections import matplotlib.pyplot as plt import numpy as np def to_np(x): return x.cpu().numpy(...
_____no_output_____
Apache-2.0
jupyter/distiller_jupyter_helpers.ipynb
HWT-WalterHu/distiller
Confounding Example: Finding causal effects from observed dataSuppose you are given some data with treatment and outcome. Can you determine whether the treatment causes the outcome, or is the correlation purely due to another common cause?
import os, sys sys.path.append(os.path.abspath("../../")) import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import math import datasets
_____no_output_____
MIT
docs/source/do_why_confounder_example.py.ipynb
hgrif/dowhy
Let's create a mystery dataset. Need to find if there is a causal effect.Creating the dataset. It is generated from either of two models:* **Model 1**: Treatment does cause outcome. * **Model 2**: Treatment does not cause outcome. All observed correlation is due to a common cause.
rvar = 1 if np.random.uniform() >0.5 else 0 data_dict = datasets.xy_dataset(10000, effect=rvar, sd_error=0.2) df = data_dict['df'] print(df[["Treatment", "Outcome", "w0"]].head()) ...
_____no_output_____
MIT
docs/source/do_why_confounder_example.py.ipynb
hgrif/dowhy
Using DoWhy to resolve the mystery: *Does Treatment cause Outcome variable?* STEP 1: Model the problem as a causal graphInitializing the causal model.
model= CausalModel( data=df, treatment=data_dict["treatment_name"...
WARNING:dowhy.do_why:WARN: Causal Graph not provided. DoWhy will construct a graph based on data inputs.
MIT
docs/source/do_why_confounder_example.py.ipynb
hgrif/dowhy
STEP 2: Identify causal effect using properties of the formal causal graphIdentify the causal effect using properties of the causal graph.
identified_estimand = model.identify_effect() print(identified_estimand)
INFO:dowhy.causal_identifier:Common causes of treatment and outcome:{'w0', 'U'}
MIT
docs/source/do_why_confounder_example.py.ipynb
hgrif/dowhy
STEP 3: Estimate the causal effectOnce we have the identified estimand, can use any statistical method to estimate the causal effect. Let's use Linear Regression for simplicity.
estimate = model.estimate_effect(identified_estimand, method_name="backdoor.linear_regression") print("Causal Estimate is " + str(estimate.value)) # Plot Slope of line between treamtent and outcome =causal effect d...
LinearRegressionEstimator
MIT
docs/source/do_why_confounder_example.py.ipynb
hgrif/dowhy
Checking if the estimate is correct
print("DoWhy estimate is " + str(estimate.value)) print ("Actual true causal effect was {0}".format(rvar))
DoWhy estimate is 0.004553072035180647 Actual true causal effect was 0
MIT
docs/source/do_why_confounder_example.py.ipynb
hgrif/dowhy
Step 4: Refuting the estimateWe can also refute the estimate to check its robustness to assumptions (*aka* sensitivity analysis, but on steroids). Adding a random common cause variable
res_random=model.refute_estimate(identified_estimand, estimate, method_name="random_common_cause") print(res_random)
INFO:dowhy.causal_estimator:INFO: Using Linear Regression Estimator INFO:dowhy.causal_estimator:b: Outcome~Treatment+w0+w_random
MIT
docs/source/do_why_confounder_example.py.ipynb
hgrif/dowhy
Replacing treatment with a random (placebo) variable
res_placebo=model.refute_estimate(identified_estimand, estimate, method_name="placebo_treatment_refuter", placebo_type="permute") print(res_placebo)
INFO:dowhy.causal_estimator:INFO: Using Linear Regression Estimator INFO:dowhy.causal_estimator:b: Outcome~placebo+w0
MIT
docs/source/do_why_confounder_example.py.ipynb
hgrif/dowhy
Removing a random subset of the data
res_subset=model.refute_estimate(identified_estimand, estimate, method_name="data_subset_refuter", subset_fraction=0.9) print(res_subset)
INFO:dowhy.causal_estimator:INFO: Using Linear Regression Estimator INFO:dowhy.causal_estimator:b: Outcome~Treatment+w0
MIT
docs/source/do_why_confounder_example.py.ipynb
hgrif/dowhy
Identify calibration targetsAttempt to automatically locate the calibration target in each scene. If this fails for any images then the target can be located manually. Note that the automated method only works for scenes containing a single target!Calibration spectra ( measured radiance vs known reflectance ) are then...
import os import glob import numpy as np from tqdm.auto import tqdm import hylite import hylite.io as io from hylite.correct import Panel
_____no_output_____
MIT
template_notebooks/Processing/Terrestrial/3_identify_calibration_targets.ipynb
sandralorenz268/hylite
Define data directories
# input directory containing images to locate (these should all be captured from about the same location) path = '/Users/thiele67/Documents/Data/SPAIN/2020_Sierra_Bullones/20200309_sun/elc' image_paths = glob.glob( os.path.join(path,"*.hdr"), recursive=True ) print("Found %d images:" % len(image_paths)) for p in image_...
Found 4 images: /Users/thiele67/Documents/Data/SPAIN/2020_Sierra_Bullones/20200309_sun/elc/0066ELC.hdr /Users/thiele67/Documents/Data/SPAIN/2020_Sierra_Bullones/20200309_sun/elc/0068ELC.hdr /Users/thiele67/Documents/Data/SPAIN/2020_Sierra_Bullones/20200309_sun/elc/0067ELC.hdr /Users/thiele67/Documents/Data/SPAIN/2020_S...
MIT
template_notebooks/Processing/Terrestrial/3_identify_calibration_targets.ipynb
sandralorenz268/hylite
Define calibration panel material
from hylite.reference.spectra import R90, R50, PVC_Red, PVC_White, PVC_Grey # load calibration material spectra M = R90 # define calibration panel material
_____no_output_____
MIT
template_notebooks/Processing/Terrestrial/3_identify_calibration_targets.ipynb
sandralorenz268/hylite
Attempt to automatically identify targets
for i,p in enumerate(tqdm(image_paths)): image = io.loadWithGDAL( p ) #load image image.set_as_nan(0) # set nans target = Panel(M,image,method='auto', bands=hylite.RGB) # look for panel #plot target fig,ax = target.quick_plot() fig.suptitle("%d: %s" % (i,p)) fig.show() #add ...
_____no_output_____
MIT
template_notebooks/Processing/Terrestrial/3_identify_calibration_targets.ipynb
sandralorenz268/hylite
If necessary, manually pick some targets
assert False, "Pause here and turn your brain on! ツ" incorrect = [0,1,2,3] # choose incorrectly identified targets to manually select
_____no_output_____
MIT
template_notebooks/Processing/Terrestrial/3_identify_calibration_targets.ipynb
sandralorenz268/hylite
First, clear incorrectly set targets from header file.
for i in incorrect: image = io.loadWithGDAL( image_paths[i] ) image.header.remove_panel(None) # remove panels outpath = io.matchHeader(image_paths[i])[0] io.saveHeader(outpath, image.header)
_____no_output_____
MIT
template_notebooks/Processing/Terrestrial/3_identify_calibration_targets.ipynb
sandralorenz268/hylite
If targets do exist in scene, manually select them. Skip this step if no targets exist.
targets = [] for i in incorrect: image = io.loadWithGDAL( image_paths[i] ) #load image target = Panel(M,image,method='manual',bands=hylite.RGB) # select panel #add to header image.header.add_panel(target) #save outpath = io.matchHeader(image_paths[i])[0] io.saveHeader(outpath, ima...
_____no_output_____
MIT
template_notebooks/Processing/Terrestrial/3_identify_calibration_targets.ipynb
sandralorenz268/hylite
Neural Transfer Using PyTorch=============================**Author**: `Alexis Jacq `_ **Edited by**: `Winston Herring `_**Re-implemented by:** `Shubhajit Das `Introduction------------This tutorial explains how to implement the `Neural-Style algorithm `__developed by Leon A. Gatys, Alexander S. Ecker and Matthias Bethg...
from google.colab import files uploaded = files.upload() for fn in uploaded.keys(): print('User uploaded file "{name}" with length {length} bytes'.format( name=fn, length=len(uploaded[fn]))) !ls from __future__ import print_function import torch import torch.nn as nn import torch.nn.functional as F import to...
_____no_output_____
Apache-2.0
pytorch-examples/Image/Style_Transfer/neural_style_tutorial.ipynb
shubhajitml/neurCodes
Next, we need to choose which device to run the network on and import thecontent and style images. Running the neural transfer algorithm on largeimages takes longer and will go much faster when running on a GPU. We canuse ``torch.cuda.is_available()`` to detect if there is a GPU available.Next, we set the ``torch.devic...
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
_____no_output_____
Apache-2.0
pytorch-examples/Image/Style_Transfer/neural_style_tutorial.ipynb
shubhajitml/neurCodes
Loading the Images------------------Now we will import the style and content images. The original PIL images have values between 0 and 255, but whentransformed into torch tensors, their values are converted to be between0 and 1. The images also need to be resized to have the same dimensions.An important detail to note ...
# desired size of the output image imsize = 512 if torch.cuda.is_available() else 128 # use small size if no gpu loader = transforms.Compose([ transforms.Resize(imsize), # scale imported image transforms.ToTensor()]) # transform it into a torch tensor def image_loader(image_name): image = Image.open(i...
_____no_output_____
Apache-2.0
pytorch-examples/Image/Style_Transfer/neural_style_tutorial.ipynb
shubhajitml/neurCodes
Now, let's create a function that displays an image by reconverting a copy of it to PIL format and displaying the copy using ``plt.imshow``. We will try displaying the content and style images to ensure they were imported correctly.
unloader = transforms.ToPILImage() # reconvert into PIL image plt.ion() def imshow(tensor, title=None): image = tensor.cpu().clone() # we clone the tensor to not do changes on it image = image.squeeze(0) # remove the fake batch dimension image = unloader(image) plt.imshow(image) if title is...
_____no_output_____
Apache-2.0
pytorch-examples/Image/Style_Transfer/neural_style_tutorial.ipynb
shubhajitml/neurCodes
Loss Functions--------------Content Loss~~~~~~~~~~~~The content loss is a function that represents a weighted version of thecontent distance for an individual layer. The function takes the featuremaps $F_{XL}$ of a layer $L$ in a network processing input $X$ and returns theweighted content distance $w_{CL}.D_C^L(X,C)$ ...
class ContentLoss(nn.Module): def __init__(self, target,): super(ContentLoss, self).__init__() # we 'detach' the target content from the tree used # to dynamically compute the gradient: this is a stated value, # not a variable. Otherwise the forward method of the criterion #...
_____no_output_____
Apache-2.0
pytorch-examples/Image/Style_Transfer/neural_style_tutorial.ipynb
shubhajitml/neurCodes
.. Note:: **Important detail**: although this module is named ``ContentLoss``, it is not a true PyTorch Loss function. If you want to define your content loss as a PyTorch Loss function, you have to create a PyTorch autograd function to recompute/implement the gradient manually in the ``backward`` method. St...
def gram_matrix(input): a, b, c, d = input.size() # a=batch size(=1) # b=number of feature maps # (c,d)=dimensions of a f. map (N=c*d) features = input.view(a * b, c * d) # resise F_XL into \hat F_XL G = torch.mm(features, features.t()) # compute the gram product # we 'normalize' the value...
_____no_output_____
Apache-2.0
pytorch-examples/Image/Style_Transfer/neural_style_tutorial.ipynb
shubhajitml/neurCodes
Now the style loss module looks almost exactly like the content lossmodule. The style distance is also computed using the mean squareerror between $G_{XL}$ and $G_{SL}$.
class StyleLoss(nn.Module): def __init__(self, target_feature): super(StyleLoss, self).__init__() self.target = gram_matrix(target_feature).detach() def forward(self, input): G = gram_matrix(input) self.loss = F.mse_loss(G, self.target) return input
_____no_output_____
Apache-2.0
pytorch-examples/Image/Style_Transfer/neural_style_tutorial.ipynb
shubhajitml/neurCodes
Importing the Model-------------------Now we need to import a pre-trained neural network. We will use a 19layer VGG network like the one used in the paper.PyTorch’s implementation of VGG is a module divided into two child``Sequential`` modules: ``features`` (containing convolution and pooling layers),and ``classifier``...
cnn = models.vgg19(pretrained=True).features.to(device).eval()
Downloading: "https://download.pytorch.org/models/vgg19-dcbb9e9d.pth" to /root/.torch/models/vgg19-dcbb9e9d.pth 100%|██████████| 574673361/574673361 [00:08<00:00, 70914944.30it/s]
Apache-2.0
pytorch-examples/Image/Style_Transfer/neural_style_tutorial.ipynb
shubhajitml/neurCodes
Additionally, VGG networks are trained on images with each channelnormalized by mean=[0.485, 0.456, 0.406] and std=[0.229, 0.224, 0.225].We will use them to normalize the image before sending it into the network.
cnn_normalization_mean = torch.tensor([0.485, 0.456, 0.406]).to(device) cnn_normalization_std = torch.tensor([0.229, 0.224, 0.225]).to(device) # create a module to normalize input image so we can easily put it in a # nn.Sequential class Normalization(nn.Module): def __init__(self, mean, std): super(Normali...
_____no_output_____
Apache-2.0
pytorch-examples/Image/Style_Transfer/neural_style_tutorial.ipynb
shubhajitml/neurCodes
A ``Sequential`` module contains an ordered list of child modules. Forinstance, ``vgg19.features`` contains a sequence (Conv2d, ReLU, MaxPool2d,Conv2d, ReLU…) aligned in the right order of depth. We need to add ourcontent loss and style loss layers immediately after the convolutionlayer they are detecting. To do this w...
# desired depth layers to compute style/content losses : content_layers_default = ['conv_4'] style_layers_default = ['conv_1', 'conv_2', 'conv_3', 'conv_4', 'conv_5'] def get_style_model_and_losses(cnn, normalization_mean, normalization_std, style_img, content_img, ...
_____no_output_____
Apache-2.0
pytorch-examples/Image/Style_Transfer/neural_style_tutorial.ipynb
shubhajitml/neurCodes
Next, we select the input image. You can use a copy of the content imageor white noise.
input_img = content_img.clone() # if you want to use white noise instead uncomment the below line: # input_img = torch.randn(content_img.data.size(), device=device) # add the original input image to the figure: plt.figure() imshow(input_img, title='Input Image')
_____no_output_____
Apache-2.0
pytorch-examples/Image/Style_Transfer/neural_style_tutorial.ipynb
shubhajitml/neurCodes
Gradient Descent----------------As Leon Gatys, the author of the algorithm, suggested `here `__, we will useL-BFGS algorithm to run our gradient descent. Unlike training a network,we want to train the input image in order to minimise the content/stylelosses. We will create a PyTorch L-BFGS optimizer ``optim.LBFGS`` and...
def get_input_optimizer(input_img): # this line to show that input is a parameter that requires a gradient optimizer = optim.LBFGS([input_img.requires_grad_()]) return optimizer
_____no_output_____
Apache-2.0
pytorch-examples/Image/Style_Transfer/neural_style_tutorial.ipynb
shubhajitml/neurCodes
Finally, we must define a function that performs the neural transfer. Foreach iteration of the networks, it is fed an updated input and computesnew losses. We will run the ``backward`` methods of each loss module todynamicaly compute their gradients. The optimizer requires a “closure”function, which reevaluates the mod...
def run_style_transfer(cnn, normalization_mean, normalization_std, content_img, style_img, input_img, num_steps=500, style_weight=1000000, content_weight=1): """Run the style transfer.""" print('Building the style transfer model..') model, style_losses, content_...
_____no_output_____
Apache-2.0
pytorch-examples/Image/Style_Transfer/neural_style_tutorial.ipynb
shubhajitml/neurCodes
Finally, we can run the algorithm.
output = run_style_transfer(cnn, cnn_normalization_mean, cnn_normalization_std, content_img, style_img, input_img) plt.figure() imshow(output, title='Output Image') # sphinx_gallery_thumbnail_number = 4 plt.ioff() plt.show()
Building the style transfer model..
Apache-2.0
pytorch-examples/Image/Style_Transfer/neural_style_tutorial.ipynb
shubhajitml/neurCodes
Linear Regression PyTorch Model Designing Steps 1. **Design your model using class with Variables** 2. **Construct loss and optimizer (select from PyTorch API)** 3. **Training cycle (forward, backward, update)** Step 1 : Design your model using class with Variables
from torch import nn import torch from torch import tensor import matplotlib.pyplot as plt x_data = tensor([[1.0], [2.0], [3.0], [4.0], [5.0], [6.0]]) y_data = tensor([[2.0], [4.0], [6.0], [8.0], [10.0], [12.0]]) # Hyper-parameters input_size = 1 output_size = 1 num_epochs = 100 learning_rate = 0.01 pri...
1.7.0+cu101 Tesla T4
MIT
Class Notebooks/Lab 02 - Linear Regression (PyTorch).ipynb
fesabelilla/SoftComputingLab
Using GPU for the PyTorch Models Remember always 2 things must be on GPU - model - tensors
class Model(nn.Module): def __init__(self): """ In the constructor we instantiate nn.Linear module """ super().__init__() self.linear = torch.nn.Linear(input_size, output_size) # One in and one out def forward(self, x): """ In the forward funct...
_____no_output_____
MIT
Class Notebooks/Lab 02 - Linear Regression (PyTorch).ipynb
fesabelilla/SoftComputingLab
Explanations:- `torch.nn.Linear(in_features, out_features, bias=True)` Applies a linear transformation to the incoming data: $y = W^T * x + b$ **Parameters:** - `in_features `– size of each input sample (i.e. size of x) - `out_features` – size of each output sample (i.e. size of y) - `bias` – If set to False, the...
# Construct our loss function and an Optimizer. The call to model.parameters() # in the SGD constructor will contain the learnable parameters criterion = torch.nn.MSELoss(reduction='sum') optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate)
_____no_output_____
MIT
Class Notebooks/Lab 02 - Linear Regression (PyTorch).ipynb
fesabelilla/SoftComputingLab
Explanations:- MSE Loss: Mean Squared Error (**Default: 'mean'**) - $\hat y$ : prediction - $y$ : true value $MSE \ (sum) = \sum_{i=1}^n(\hat y_i - y_i)^2$ $MSE \ (mean) = \frac{1}{n} \sum_{i=1}^n(\hat y_i - y_i)^2$ Step 3 : Training: forward, loss, backward, step
# Credit: https://github.com/jcjohnson/pytorch-examples # Training loop for epoch in range(num_epochs): # 1) Forward pass: Compute predicted y by passing x to the model y_pred = model(x_data.to(device)) # 2) Compute and print loss loss = criterion(y_pred, y_data.to(device)) print(f'Epoch:...
Epoch: 0 | Loss: 0.04414632171392441 Epoch: 1 | Loss: 0.037211932241916656 Epoch: 2 | Loss: 0.03136666119098663 Epoch: 3 | Loss: 0.02643958479166031 Epoch: 4 | Loss: 0.022286424413323402 Epoch: 5 | Loss: 0.01878545433282852 Epoch: 6 | Loss: 0.015834316611289978 Epoch: 7 | Loss: 0.013346947729587555 Epoch: 8 | L...
MIT
Class Notebooks/Lab 02 - Linear Regression (PyTorch).ipynb
fesabelilla/SoftComputingLab
Explanations:- - Calling `.backward()` mutiple times accumulates the gradient (**by addition**) for each parameter. - This is why you should call `optimizer.zero_grad()` after each .step() call. - Note that following the first `.backward` call, a second call is only possible after you have performed another **fo...
# Clear figure plt.clf() # Get predictions predictions = model(x_data.to(device)).cpu().detach().numpy() # Plot true data plt.plot(x_data, y_data, 'go', label='True data', alpha=0.5) # Plot predictions plt.plot(x_data, predictions, '--', label='Predictions', alpha=0.5) # Legend and plot plt.legend(loc=...
_____no_output_____
MIT
Class Notebooks/Lab 02 - Linear Regression (PyTorch).ipynb
fesabelilla/SoftComputingLab
Saving Model to Directory
from google.colab import drive drive.mount('/content/gdrive') root_path = '/content/gdrive/My Drive/AUST Docs/AUST Teaching Docs/AUST Spring 2020/CSE 4238/Lab 02/'
Drive already mounted at /content/gdrive; to attempt to forcibly remount, call drive.mount("/content/gdrive", force_remount=True).
MIT
Class Notebooks/Lab 02 - Linear Regression (PyTorch).ipynb
fesabelilla/SoftComputingLab
Save Model
save_model = True if save_model is True: # Saves only parameters # wights & biases torch.save(model.state_dict(), root_path + 'linear_regression.pkl') # Save the model checkpoint # torch.save(model.state_dict(), root_path + 'linear_regression.ckpt')
_____no_output_____
MIT
Class Notebooks/Lab 02 - Linear Regression (PyTorch).ipynb
fesabelilla/SoftComputingLab
Load Model
load_model = True if load_model is True: model.load_state_dict(torch.load(root_path + 'linear_regression.pkl'))
_____no_output_____
MIT
Class Notebooks/Lab 02 - Linear Regression (PyTorch).ipynb
fesabelilla/SoftComputingLab
**Blockchain Analytics**Analysis of Bitcoin blockchain data (transaction graph) to find potential indicators of incidents_by Dhruv Chopra and Siddhant Pathak_ **Import all the necessary libraries**
import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sb import networkx as nx import time import requests sb.set()
_____no_output_____
MIT
Analysis.ipynb
siddhantpathakk/Blockchain-Analytics
**Query the data from the Blockchain API and organize it**
response = requests.get("https://blockchain.info/rawtx/0e3e2357e806b6cdb1f70b54c3a3a17b6714ee1f0e68bebb44a74b1efd512098") jason = response.json() #response = requests.get("https://blockchain.info/q/getreceivedbyaddress/12c6DSiU4Rq3P4ZxziKxzrL5LmMBrzjrJX") jason new = jason['out'][0]['addr'] new response = requests.get(...
_____no_output_____
MIT
Analysis.ipynb
siddhantpathakk/Blockchain-Analytics
**Creating the graph**
stack1 = [] stack2 = [] g = nx.MultiDiGraph() address='12c6DSiU4Rq3P4ZxziKxzrL5LmMBrzjrJX' stack1 stack1.append(address) color=[] edge_color=[] completed = [] level = 0 LEVEL = 10 while(level < LEVEL): address = stack1.pop() response = requests.get("https://blockchain.info/rawaddr/"+address) address_info...
_____no_output_____
MIT
Analysis.ipynb
siddhantpathakk/Blockchain-Analytics
**Store the graph**
nx.write_edgelist(g, path = "graph.csv", delimiter=":") plt.figure(4, figsize=(50,50)) pos = nx.spring_layout(g, center=None, dim=2) nx.draw_networkx(g,pos=pos, node_size=99, edge_color=edge_color, node_color=color, width=2.5, with_labels=False) #labels = nx.get_edge_attributes(g,'weight') #nx.draw_networkx_edge_labels...
_____no_output_____
MIT
Analysis.ipynb
siddhantpathakk/Blockchain-Analytics
**Centrality** **VoteRank Algorithm**VoteRank computes a ranking of the nodes in a graph G based on a voting scheme. With VoteRank, all nodes vote for each of its in-neighbours and the node with the highest votes is elected iteratively. The voting ability of out-neighbors of elected nodes is decreased in subsequent t...
node_voterank = nx.algorithms.centrality.voterank(g) node_voterank
_____no_output_____
MIT
Analysis.ipynb
siddhantpathakk/Blockchain-Analytics
**Percolation Centrality** (error)Percolation centrality of a node v, at a given time, is defined as the proportion of ‘percolated paths’ that go through that node. This measure quantifies relative impact of nodes based on their topological connectivity, as well as their percolation states. Percolation states of nodes...
node_percolation = nx.algorithms.centrality.percolation_centrality(g) node_percolation
_____no_output_____
MIT
Analysis.ipynb
siddhantpathakk/Blockchain-Analytics
**PageRank Algorithm** (error)PageRank is an algorithm used by Google Search to rank web pages in their search engine results. PageRank is a way of measuring the importance of website pages.
node_pagerank = nx.algorithms.link_analysis.pagerank_alg.pagerank(g) node_pagerank
_____no_output_____
MIT
Analysis.ipynb
siddhantpathakk/Blockchain-Analytics
**Degree of Nodes**`degree_centrality(G)` : Compute the degree centrality for nodes.`in_degree_centrality(G)` : Compute the in-degree centrality for nodes.`out_degree_centrality(G)` : Compute the out-degree centrality for nodes.
node_degree = nx.degree_centrality(g) node_deg_in = nx.in_degree_centrality(g) node_deg_out = nx.out_degree_centrality(g) node_degree node_deg_in node_deg_out
_____no_output_____
MIT
Analysis.ipynb
siddhantpathakk/Blockchain-Analytics
**Eigenvector and Katz Centrality** (error)Katz centrality is a generalization of degree centrality. Degree centrality measures the number of direct neighbors, and Katz centrality measures the number of all nodes that can be connected through a path, while the contributions of distant nodes are penalized.
node_eigen = nx.eigenvector_centrality(g) node_eigen node_katz = nx.katz_centrality(g) node_katz
_____no_output_____
MIT
Analysis.ipynb
siddhantpathakk/Blockchain-Analytics
**Closeness**`closeness_centrality(G[, u, distance, …])` : Compute closeness centrality for nodes.`incremental_closeness_centrality(G, edge[, …])`: Incremental closeness centrality for nodes.Notice that higher values of closeness indicate higher centrality.
node_close = nx.closeness_centrality(g) node_close node_close_inc = nx.incremental_closeness_centrality(g, edge = ('1Ep8AVZx89qmBzzeu1zPpKLF8pxHfkZaJc', '56484b549f42a4485fb79b2838c7829805d025a28a46248eec677aaba78e4b70') )
_____no_output_____
MIT
Analysis.ipynb
siddhantpathakk/Blockchain-Analytics
**Current Flow Closeness** (error)Compute current-flow closeness centrality for nodes.
node_cur = nx.current_flow_closeness_centrality(g) node_cur_info = nx.information_centrality(g)
_____no_output_____
MIT
Analysis.ipynb
siddhantpathakk/Blockchain-Analytics
**Dispersion**Calculate dispersion between u and v in G.A link between two actors (u and v) has a high dispersion when their mutual ties (s and t) are not well connected with each other.If u (v) is specified, returns a dictionary of nodes with dispersion score for all “target” (“source”) nodes. If neither u nor v is s...
dispersion = nx.dispersion(g) dispersion
_____no_output_____
MIT
Analysis.ipynb
siddhantpathakk/Blockchain-Analytics
**Harmonic Centrality**Harmonic centrality of a node u is the sum of the reciprocal of the shortest path distances from all other nodes to u.
harmonic = nx.harmonic_centrality(g) harmonic
_____no_output_____
MIT
Analysis.ipynb
siddhantpathakk/Blockchain-Analytics
**Reaching**`local_reaching_centrality(G, v[, paths, …])` : Returns the local reaching centrality of a node in a directed graph. The local reaching centrality of a node in a directed graph is the proportion of other nodes reachable from that node`global_reaching_centrality(G[, weight, …]`) : Returns the global reachin...
global_reach = nx.global_reaching_centrality(g) global_reach
_____no_output_____
MIT
Analysis.ipynb
siddhantpathakk/Blockchain-Analytics
**Second Order Centrality** (error)The second order centrality of a given node is the standard deviation of the return times to that node of a perpetual random walk on G:
node_2nd_order = nx.second_order_centrality(g) node_2nd_order
_____no_output_____
MIT
Analysis.ipynb
siddhantpathakk/Blockchain-Analytics
**Trophic** (2 error)`trophic_levels(G[, weight])` : Compute the trophic levels of nodes.`trophic_differences(G[, weight])` : Compute the trophic differences of the edges of a directed graph.`trophic_incoherence_parameter(G[, weight, …])` : Compute the trophic incoherence parameter of a graph.
trophic = nx.trophic_levels(g) trophic trophic_differences = nx.trophic_differences(g) incoherence = nx.trophic_incoherence_parameter(g)
_____no_output_____
MIT
Analysis.ipynb
siddhantpathakk/Blockchain-Analytics
**Subgraph** (error)`subgraph_centrality(G)` : Returns subgraph centrality for each node in G.`subgraph_centrality_exp(G)` : Returns the subgraph centrality for each node of G.`estrada_index(G) `: Returns the Estrada index of a the graph G.
subgraph = nx.subgraph_centrality(g) subgraph sub_exp = nx.subgraph_centrality_exp(g) sub_exp estrada = nx.estrada_index(g)
_____no_output_____
MIT
Analysis.ipynb
siddhantpathakk/Blockchain-Analytics
**Load** The load centrality of a node is the fraction of all shortest paths that pass through that node.
load = nx.load_centrality(g) load edge_load = nx.edge_load_centrality(g) edge_load
_____no_output_____
MIT
Analysis.ipynb
siddhantpathakk/Blockchain-Analytics
**Group Centrality** (error)`group_betweenness_centrality(G, C[, …])`: Compute the group betweenness centrality for a group of nodes.`group_closeness_centrality(G, S[, weight])`: Compute the group closeness centrality for a group of nodes.`group_degree_centrality(G, S)`: Compute the group degree centrality for a group...
gp_btw = nx.group_betweenness_centrality(g, C=g.nodes) gp_btw gp_close = nx.group_closeness_centrality(g,S=g.nodes) gp_close gp_deg = nx.group_degree_centrality(g, g.nodes) gp_in = nx.group_in_degree_centrality(g, g.nodes) gp_in gp_out = nx.group_out_degree_centrality(g, g.nodes) gp_out
_____no_output_____
MIT
Analysis.ipynb
siddhantpathakk/Blockchain-Analytics
**Communicability Betweenness** (error)Communicability betweenness measure makes use of the number of walks connecting every pair of nodes as the basis of a betweenness centrality measure.
comm_btw = nx.communicability_betweenness_centrality(g)
_____no_output_____
MIT
Analysis.ipynb
siddhantpathakk/Blockchain-Analytics
Training a Graph Convolution ModelNow that we have the data appropriately formatted, we can use this data to train a Graph Convolution model. First we need to import the necessary libraries.
import deepchem as dc from deepchem.models import GraphConvModel import numpy as np import sys import pandas as pd import seaborn as sns from rdkit.Chem import PandasTools from tqdm.auto import tqdm
_____no_output_____
MIT
Chapter11/chapter_11_02_erk2_graph_conv.ipynb
deepchem/DeepLearningLifeSciences
Now let's define a function to create a GraphConvModel. In this case we will be creating a classification model. Since we will be apply the model later on a different dataset, it's a good idea to create a directory in which to store the model.
def generate_graph_conv_model(): batch_size = 128 model = GraphConvModel(1, batch_size=batch_size, mode='classification', model_dir="./model_dir") return model
_____no_output_____
MIT
Chapter11/chapter_11_02_erk2_graph_conv.ipynb
deepchem/DeepLearningLifeSciences
Now we will read in the dataset that we just created.
dataset_file = "dude_erk2_mk01.csv" tasks = ["is_active"] featurizer = dc.feat.ConvMolFeaturizer() loader = dc.data.CSVLoader(tasks=tasks, feature_field="SMILES", featurizer=featurizer) dataset = loader.create_dataset(dataset_file, shard_size=8192)
_____no_output_____
MIT
Chapter11/chapter_11_02_erk2_graph_conv.ipynb
deepchem/DeepLearningLifeSciences