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 |
|---|---|---|---|---|---|
Notice the large amplitude excursions in the data at the start and end of our data segment. This is **spectral leakage** caused by filters we applied to the boundaries ringing off the discontinuities where the data suddenly starts and ends (for a time up to the length of the filter).To avoid this we should trim the end... | # Remove 2 seconds of data from both the beginning and end
conditioned = strain.crop(2, 2)
pylab.plot(conditioned.sample_times, conditioned)
pylab.xlabel('Time (s)') | _____no_output_____ | MIT | Session9/Day4/Matched_filter_tutorial.ipynb | jlmciver/LSSTC-DSFP-Sessions |
That's better. Calculating the spectral density of the dataOptimal matched filtering requires *whitening*; weighting the frequency components of the potential signal and data by the estimated noise amplitude.Let's compute the power spectral density (PSD) of our conditioned data. | from pycbc.psd import interpolate, inverse_spectrum_truncation
# Estimate the power spectral density
# We use 4 second samles of our time series in Welch method.
psd = conditioned.psd(4)
# Now that we have the psd we need to interpolate it to match our data
# and then limit the filter length of 1 / PSD. After this, w... | _____no_output_____ | MIT | Session9/Day4/Matched_filter_tutorial.ipynb | jlmciver/LSSTC-DSFP-Sessions |
---- Define a signal model Recall that matched filtering is essentially integrating the inner product between your data and your signal model in frequency or time (after weighting frequencies correctly) as you slide your signal model over your data in time. If there is a signal in the data that matches your 'template',... | m = 36 # Solar masses
hp, hc = get_td_waveform(approximant="SEOBNRv4_opt",
mass1=m,
mass2=m,
delta_t=conditioned.delta_t,
f_lower=20)
# We should resize the vector of our template to match our data
hp.resize(len(conditioned))
pylab.plo... | _____no_output_____ | MIT | Session9/Day4/Matched_filter_tutorial.ipynb | jlmciver/LSSTC-DSFP-Sessions |
Note that the waveform template currently begins at the start of the vector. However, we want our SNR time series (the inner product between our data and our template) to track with the approximate merger time. To do this, we need to shift our template so that the merger is approximately at the first bin of the data.Fo... | template = hp.cyclic_time_shift(hp.start_time)
pylab.plot(template)
pylab.xlabel('Time samples') | _____no_output_____ | MIT | Session9/Day4/Matched_filter_tutorial.ipynb | jlmciver/LSSTC-DSFP-Sessions |
--- Calculate an SNR time seriesNow that we've pre-conditioned our data and defined a signal model, we can compute the output of our matched filter search. | from pycbc.filter import matched_filter
import numpy
snr = matched_filter(template, conditioned,
psd=psd, low_frequency_cutoff=20)
pylab.figure(figsize=[10, 4])
pylab.plot(snr.sample_times, abs(snr))
pylab.xlabel('Time (s)')
pylab.ylabel('SNR') | _____no_output_____ | MIT | Session9/Day4/Matched_filter_tutorial.ipynb | jlmciver/LSSTC-DSFP-Sessions |
Note that as we expect, there is some corruption at the start and end of our SNR time series by the template filter and the PSD filter. To account for this, we can smoothly zero out 4 seconds (the length of the PSD filter) at the beginning and end for the PSD filtering. We should remove an 4 additional seconds at the b... | snr = snr.crop(4 + 4, 4)
pylab.figure(figsize=[10, 4])
pylab.plot(snr.sample_times, abs(snr))
pylab.ylabel('Signal-to-noise')
pylab.xlabel('Time (s)')
pylab.show() | _____no_output_____ | MIT | Session9/Day4/Matched_filter_tutorial.ipynb | jlmciver/LSSTC-DSFP-Sessions |
Finally, now that the output is properly cropped, we can find the peak of our SNR time series and estimate the merger time and associated SNR of any event candidate within the data. | peak = abs(snr).numpy().argmax()
snrp = snr[peak]
time = snr.sample_times[peak]
print("We found a signal at {}s with SNR {}".format(time,
abs(snrp))) | We found a signal at 1126259462.42s with SNR 19.6770890131
| MIT | Session9/Day4/Matched_filter_tutorial.ipynb | jlmciver/LSSTC-DSFP-Sessions |
You found the first gravitational wave detection in LIGO Hanford data! Nice work. --- Exercise 3 How does the SNR change if you re-compute the matched filter result using a signal model with compenent masses that are closer to the current estimates for GW150914, say m1 = 36 Msol and m2 = 31 Msol? | # complete | _____no_output_____ | MIT | Session9/Day4/Matched_filter_tutorial.ipynb | jlmciver/LSSTC-DSFP-Sessions |
Exercise 4 **Network SNR** is the quadrature sum of the single-detector SNR from each contributing detector. GW150914 was detected by H1 and L1. Try calculating the network SNR (you'll need to estimate the SNR in L1 first), and compare your answer to the network PyCBC SNR as reported in the [GWTC-1 catalog](https://ar... | # complete | _____no_output_____ | MIT | Session9/Day4/Matched_filter_tutorial.ipynb | jlmciver/LSSTC-DSFP-Sessions |
--- Estimate the single-detector significance of an event candidateGreat, we found a large spike in SNR! What are the chances this is a real astrophysical signal? How often would detector noise produce this by chance?Let's plot a histogram of SNR values output by our matched filtering analysis for this time and see how... | # import what we need
from scipy.stats import norm
from math import pi
from math import exp
# make a histogram of SNR values
background = (abs(snr))
# plot the histogram to check out any other outliers
pylab.hist(background, bins=50)
pylab.xlabel('SNR')
pylab.semilogy()
# use norm.fit to fit a normal (Gaussian) di... | The fit mean = 1.295883 and the fit std dev = 0.739471
| MIT | Session9/Day4/Matched_filter_tutorial.ipynb | jlmciver/LSSTC-DSFP-Sessions |
Exercise 5 At what single-detector SNR is the significance of a trigger > 5 sigma? Remember that sigma is constant for a normal distribution (read: this should be simple multiplication now that we have estimated what 1 sigma is). | # complete | _____no_output_____ | MIT | Session9/Day4/Matched_filter_tutorial.ipynb | jlmciver/LSSTC-DSFP-Sessions |
--- ChallengeOur match filter analysis assumes the noise is *stationary* and *Gaussian*, which is not a good assumption, and this short data set isn't representative of all the various things that can go bump in the detector (remember the phone?). **The simple significance estimate above won't work as soon as we encoun... | # complete if time | _____no_output_____ | MIT | Session9/Day4/Matched_filter_tutorial.ipynb | jlmciver/LSSTC-DSFP-Sessions |
 | dst = src1 * 0.5 + src2 * 0.2 + (96, 128, 160)
print(dst.max())
dst = dst.clip(0, 255)
print(dst.max())
Image.fromarray(dst.astype(np.uint8)).save('data/dst/numpy_image_alpha_blend_gamma.jpg') | _____no_output_____ | MIT | notebook/numpy_image_alpha_blend.ipynb | puyopop/python-snippets |
RESTRICTED BOLTZMANN MACHINES IntroductionRestricted Boltzmann Machine (RBM): RBMs are shallow neural nets that learn to reconstruct data by themselves in an unsupervised fashion. Why are RBMs important?It can automatically extract meaningful features from a given input.How does it work?RBM is a 2 layer neural networ... | import urllib.request
with urllib.request.urlopen("http://deeplearning.net/tutorial/code/utils.py") as url:
response = url.read()
target = open('utils.py', 'w')
target.write(response.decode('utf-8'))
target.close() | _____no_output_____ | MIT | IBM_AI/5_TensorFlow/ML0120EN-4.1-Review-RBMMNIST.ipynb | merula89/cousera_notebooks |
Now, we load in all the packages that we use to create the net including the TensorFlow package: | import tensorflow as tf
import numpy as np
from tensorflow.examples.tutorials.mnist import input_data
#!pip install pillow
from PIL import Image
from utils import tile_raster_images
import matplotlib.pyplot as plt
%matplotlib inline | _____no_output_____ | MIT | IBM_AI/5_TensorFlow/ML0120EN-4.1-Review-RBMMNIST.ipynb | merula89/cousera_notebooks |
RBM layersAn RBM has two layers. The first layer of the RBM is called the visible (or input layer). Imagine that our toy example, has only vectors with 7 values, so the visible layer must have j=7 input nodes. The second layer is the hidden layer, which possesses i neurons in our case. Each hidden node can have either... | v_bias = tf.placeholder("float", [7])
h_bias = tf.placeholder("float", [2]) | _____no_output_____ | MIT | IBM_AI/5_TensorFlow/ML0120EN-4.1-Review-RBMMNIST.ipynb | merula89/cousera_notebooks |
We have to define weights among the input layer and hidden layer nodes. In the weight matrix, the number of rows are equal to the input nodes, and the number of columns are equal to the output nodes. Let W be the Tensor of 7x2 (7 - number of visible neurons, 2 - number of hidden neurons) that represents weights between... | W = tf.constant(np.random.normal(loc=0.0, scale=1.0, size=(7, 2)).astype(np.float32)) | _____no_output_____ | MIT | IBM_AI/5_TensorFlow/ML0120EN-4.1-Review-RBMMNIST.ipynb | merula89/cousera_notebooks |
What RBM can do after training?Think RBM as a model that has been trained based on images of a dataset of many SUV and Sedan cars. Also, imagine that the RBM network has only two hidden nodes, one for the weight and, and one for the size of cars, which in a sense, their different configurations represent different car... | sess = tf.Session()
X = tf.constant([[1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0]])
v_state = X
print ("Input: ", sess.run(v_state))
h_bias = tf.constant([0.1, 0.1])
print ("hb: ", sess.run(h_bias))
print ("w: ", sess.run(W))
# Calculate the probabilities of turning the hidden units on:
h_prob = tf.nn.sigmoid(tf.matmul(v_stat... | _____no_output_____ | MIT | IBM_AI/5_TensorFlow/ML0120EN-4.1-Review-RBMMNIST.ipynb | merula89/cousera_notebooks |
Phase 2) Backward Pass (Reconstruction):The RBM reconstructs data by making several forward and backward passes between the visible and hidden layers.So, in the second phase (i.e. reconstruction phase), the samples from the hidden layer (i.e. h) play the role of input. That is, h becomes the input in the backward pass.... | vb = tf.constant([0.1, 0.2, 0.1, 0.1, 0.1, 0.2, 0.1])
print ("b: ", sess.run(vb))
v_prob = sess.run(tf.nn.sigmoid(tf.matmul(h_state, tf.transpose(W)) + vb))
print ("p(vi∣h): ", v_prob)
v_state = tf.nn.relu(tf.sign(v_prob - tf.random_uniform(tf.shape(v_prob))))
print ("v probability states: ", sess.run(v_state)) | _____no_output_____ | MIT | IBM_AI/5_TensorFlow/ML0120EN-4.1-Review-RBMMNIST.ipynb | merula89/cousera_notebooks |
RBM learns a probability distribution over the input, and then, after being trained, the RBM can generate new samples from the learned probability distribution. As you know, probability distribution, is a mathematical function that provides the probabilities of occurrence of different possible outcomes in an experiment... | inp = sess.run(X)
print(inp)
print(v_prob[0])
v_probability = 1
for elm, p in zip(inp[0],v_prob[0]) :
if elm ==1:
v_probability *= p
else:
v_probability *= (1-p)
v_probability | _____no_output_____ | MIT | IBM_AI/5_TensorFlow/ML0120EN-4.1-Review-RBMMNIST.ipynb | merula89/cousera_notebooks |
How similar X and V vectors are? Of course, the reconstructed values most likely will not look anything like the input vector because our network has not trained yet. Our objective is to train the model in such a way that the input vector and reconstructed vector to be same. Therefore, based on how different the input ... | mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
trX, trY, teX, teY = mnist.train.images, mnist.train.labels, mnist.test.images, mnist.test.labels | _____no_output_____ | MIT | IBM_AI/5_TensorFlow/ML0120EN-4.1-Review-RBMMNIST.ipynb | merula89/cousera_notebooks |
Lets look at the dimension of the images. | trX[1].shape | _____no_output_____ | MIT | IBM_AI/5_TensorFlow/ML0120EN-4.1-Review-RBMMNIST.ipynb | merula89/cousera_notebooks |
MNIST images have 784 pixels, so the visible layer must have 784 input nodes. For our case, we'll use 50 nodes in the hidden layer, so i = 50. | vb = tf.placeholder("float", [784])
hb = tf.placeholder("float", [50]) | _____no_output_____ | MIT | IBM_AI/5_TensorFlow/ML0120EN-4.1-Review-RBMMNIST.ipynb | merula89/cousera_notebooks |
Let W be the Tensor of 784x50 (784 - number of visible neurons, 50 - number of hidden neurons) that represents weights between the neurons. | W = tf.placeholder("float", [784, 50]) | _____no_output_____ | MIT | IBM_AI/5_TensorFlow/ML0120EN-4.1-Review-RBMMNIST.ipynb | merula89/cousera_notebooks |
Lets define the visible layer: | v0_state = tf.placeholder("float", [None, 784]) | _____no_output_____ | MIT | IBM_AI/5_TensorFlow/ML0120EN-4.1-Review-RBMMNIST.ipynb | merula89/cousera_notebooks |
Now, we can define hidden layer: | h0_prob = tf.nn.sigmoid(tf.matmul(v0_state, W) + hb) #probabilities of the hidden units
h0_state = tf.nn.relu(tf.sign(h0_prob - tf.random_uniform(tf.shape(h0_prob)))) #sample_h_given_X | _____no_output_____ | MIT | IBM_AI/5_TensorFlow/ML0120EN-4.1-Review-RBMMNIST.ipynb | merula89/cousera_notebooks |
Now, we define reconstruction part: | v1_prob = tf.nn.sigmoid(tf.matmul(h0_state, tf.transpose(W)) + vb)
v1_state = tf.nn.relu(tf.sign(v1_prob - tf.random_uniform(tf.shape(v1_prob)))) #sample_v_given_h | _____no_output_____ | MIT | IBM_AI/5_TensorFlow/ML0120EN-4.1-Review-RBMMNIST.ipynb | merula89/cousera_notebooks |
What is objective function?Goal: Maximize the likelihood of our data being drawn from that distributionCalculate error: In each epoch, we compute the "error" as a sum of the squared difference between step 1 and step n,e.g the error shows the difference between the data and its reconstruction.Note: tf.reduce_mean comp... | err = tf.reduce_mean(tf.square(v0_state - v1_state)) | _____no_output_____ | MIT | IBM_AI/5_TensorFlow/ML0120EN-4.1-Review-RBMMNIST.ipynb | merula89/cousera_notebooks |
How to train the model?Warning!! The following part discuss how to train the model which needs some algebra background. Still, you can skip this part and run the next cells.As mentioned, we want to give a high probability to the input data we train on. So, in order to train an RBM, we have to maximize the product of pr... | h1_prob = tf.nn.sigmoid(tf.matmul(v1_state, W) + hb)
h1_state = tf.nn.relu(tf.sign(h1_prob - tf.random_uniform(tf.shape(h1_prob)))) #sample_h_given_X
alpha = 0.01
W_Delta = tf.matmul(tf.transpose(v0_state), h0_prob) - tf.matmul(tf.transpose(v1_state), h1_prob)
update_w = W + alpha * W_Delta
update_vb = vb + alpha * tf.... | _____no_output_____ | MIT | IBM_AI/5_TensorFlow/ML0120EN-4.1-Review-RBMMNIST.ipynb | merula89/cousera_notebooks |
Let's start a session and initialize the variables: | cur_w = np.zeros([784, 50], np.float32)
cur_vb = np.zeros([784], np.float32)
cur_hb = np.zeros([50], np.float32)
prv_w = np.zeros([784, 50], np.float32)
prv_vb = np.zeros([784], np.float32)
prv_hb = np.zeros([50], np.float32)
sess = tf.Session()
init = tf.global_variables_initializer()
sess.run(init) | _____no_output_____ | MIT | IBM_AI/5_TensorFlow/ML0120EN-4.1-Review-RBMMNIST.ipynb | merula89/cousera_notebooks |
Lets look at the error of the first run: | sess.run(err, feed_dict={v0_state: trX, W: prv_w, vb: prv_vb, hb: prv_hb})
#Parameters
epochs = 5
batchsize = 100
weights = []
errors = []
for epoch in range(epochs):
for start, end in zip( range(0, len(trX), batchsize), range(batchsize, len(trX), batchsize)):
batch = trX[start:end]
cur_w = sess.ru... | _____no_output_____ | MIT | IBM_AI/5_TensorFlow/ML0120EN-4.1-Review-RBMMNIST.ipynb | merula89/cousera_notebooks |
What is the final weight after training? | uw = weights[-1].T
print (uw) # a weight matrix of shape (50,784) | _____no_output_____ | MIT | IBM_AI/5_TensorFlow/ML0120EN-4.1-Review-RBMMNIST.ipynb | merula89/cousera_notebooks |
Learned features We can take each hidden unit and visualize the connections between that hidden unit and each element in the input vector. In our case, we have 50 hidden units. Lets visualize those. Let's plot the current weights:tile_raster_images helps in generating an easy to grasp image from a set of samples or we... | tile_raster_images(X=cur_w.T, img_shape=(28, 28), tile_shape=(5, 10), tile_spacing=(1, 1))
import matplotlib.pyplot as plt
from PIL import Image
%matplotlib inline
image = Image.fromarray(tile_raster_images(X=cur_w.T, img_shape=(28, 28) ,tile_shape=(5, 10), tile_spacing=(1, 1)))
### Plot image
plt.rcParams['figure.figs... | _____no_output_____ | MIT | IBM_AI/5_TensorFlow/ML0120EN-4.1-Review-RBMMNIST.ipynb | merula89/cousera_notebooks |
Each tile in the above visualization corresponds to a vector of connections between a hidden unit and visible layer's units. Let's look at one of the learned weights corresponding to one of hidden units for example. In this particular square, the gray color represents weight = 0, and the whiter it is, the more positiv... | from PIL import Image
image = Image.fromarray(tile_raster_images(X =cur_w.T[10:11], img_shape=(28, 28),tile_shape=(1, 1), tile_spacing=(1, 1)))
### Plot image
plt.rcParams['figure.figsize'] = (4.0, 4.0)
imgplot = plt.imshow(image)
imgplot.set_cmap('gray') | _____no_output_____ | MIT | IBM_AI/5_TensorFlow/ML0120EN-4.1-Review-RBMMNIST.ipynb | merula89/cousera_notebooks |
Let's look at the reconstruction of an image now. Imagine that we have a destructed image of figure 3. Lets see if our trained network can fix it:First we plot the image: | !wget -O destructed3.jpg https://ibm.box.com/shared/static/vvm1b63uvuxq88vbw9znpwu5ol380mco.jpg
img = Image.open('destructed3.jpg')
img | _____no_output_____ | MIT | IBM_AI/5_TensorFlow/ML0120EN-4.1-Review-RBMMNIST.ipynb | merula89/cousera_notebooks |
Now let's pass this image through the net: | # convert the image to a 1d numpy array
sample_case = np.array(img.convert('I').resize((28,28))).ravel().reshape((1, -1))/255.0 | _____no_output_____ | MIT | IBM_AI/5_TensorFlow/ML0120EN-4.1-Review-RBMMNIST.ipynb | merula89/cousera_notebooks |
Feed the sample case into the network and reconstruct the output: | hh0_p = tf.nn.sigmoid(tf.matmul(v0_state, W) + hb)
#hh0_s = tf.nn.relu(tf.sign(hh0_p - tf.random_uniform(tf.shape(hh0_p))))
hh0_s = tf.round(hh0_p)
hh0_p_val,hh0_s_val = sess.run((hh0_p, hh0_s), feed_dict={ v0_state: sample_case, W: prv_w, hb: prv_hb})
print("Probability nodes in hidden layer:" ,hh0_p_val)
print("act... | _____no_output_____ | MIT | IBM_AI/5_TensorFlow/ML0120EN-4.1-Review-RBMMNIST.ipynb | merula89/cousera_notebooks |
Here we plot the reconstructed image: | img = Image.fromarray(tile_raster_images(X=rec_prob, img_shape=(28, 28),tile_shape=(1, 1), tile_spacing=(1, 1)))
plt.rcParams['figure.figsize'] = (4.0, 4.0)
imgplot = plt.imshow(img)
imgplot.set_cmap('gray') | _____no_output_____ | MIT | IBM_AI/5_TensorFlow/ML0120EN-4.1-Review-RBMMNIST.ipynb | merula89/cousera_notebooks |
#Confusion matrix is at the bottom!! **************
import pandas as pd
import os
from sklearn.model_selection import train_test_split
train = pd.merge(pd.read_csv(r'C:\Users\Lesley\Downloads\train_features.csv'), pd.read_csv(r'C:\Users\Lesley\Downloads\train_labels.csv'))
test = pd.read_csv(r'C:\Users\Lesley\Dow... | _____no_output_____ | MIT | module4-classification-metrics/Lesley_Rich_224_assignment.ipynb | terrainthesky-hub/DS-Unit-2-Kaggle-Challenge | |
Question 1 Create a function that takes a number as an argument and returns True or False depending on whether the number is symmetrical or not. A number is symmetrical when it is the same as its reverse. Examples is_symmetrical(7227) ➞ True is_symmetrical(12567) ➞ False is_symmetrical(44444444) ➞ True is_symmetrical(... | def is_symmetrical(n):
rev = str(n)[::-1]
#print(rev)
if rev == str(n):
return True
return False
is_symmetrical(7227)
is_symmetrical(12567)
is_symmetrical(44444444)
is_symmetrical(9939)
is_symmetrical(1112111) | _____no_output_____ | MIT | Python Basic Programming/Programming Assignment_23.ipynb | Sayan97/Python |
Question 2 Given a string of numbers separated by a comma and space, return the product of the numbers. Examples multiply_nums("2, 3") ➞ 6 multiply_nums("1, 2, 3, 4") ➞ 24 multiply_nums("54, 75, 453, 0") ➞ 0 multiply_nums("10, -2") ➞ -20 | def multiply_nums(s):
s = s.replace(' ', "")
s = s.split(',')
sum = 1
for i in s:
sum = sum * int(i)
return sum
multiply_nums("2, 3")
multiply_nums("1, 2, 3, 4")
multiply_nums("54, 75, 453, 0")
multiply_nums("10, -2") | _____no_output_____ | MIT | Python Basic Programming/Programming Assignment_23.ipynb | Sayan97/Python |
Question 3 Create a function that squares every digit of a number. Examples square_digits(9119) ➞ 811181 square_digits(2483) ➞ 416649 square_digits(3212) ➞ 9414 Notes The function receives an integer and must return an integer. | def square_digits(n):
sq = ''.join(str(int(i)**2) for i in str(n))
return int(sq)
square_digits(9119)
square_digits(2483)
square_digits(3212) | _____no_output_____ | MIT | Python Basic Programming/Programming Assignment_23.ipynb | Sayan97/Python |
Question 4 Create a function that sorts a list and removes all duplicate items from it. Examples setify([1, 3, 3, 5, 5]) ➞ [1, 3, 5] setify([4, 4, 4, 4]) ➞ [4] setify([5, 7, 8, 9, 10, 15]) ➞ [5, 7, 8, 9, 10, 15] setify([3, 3, 3, 2, 1]) ➞ [1, 2, 3] | def setify(l):
m = []
l.sort()
l = set(l)
for i in l:
m.append(i)
return m
setify([1, 3, 3, 5, 5])
setify([4, 4, 4, 4])
setify([5, 7, 8, 9, 10, 15])
setify([3, 3, 3, 2, 1]) | _____no_output_____ | MIT | Python Basic Programming/Programming Assignment_23.ipynb | Sayan97/Python |
Question 5 Create a function that returns the mean of all digits. Examples mean(42) ➞ 3 mean(12345) ➞ 3 mean(666) ➞ 6 Notes The mean of all digits is the sum of digits / how many digits there are (e.g. mean of digits in 512 is (5+1+2)/3(number of digits) = 8/3=2). The mean will always be an integer. | def mean(n):
sum = 0
lenth = len(str(n))
for i in str(n):
sum = sum+ int(i)
return int(sum/lenth)
mean(42)
mean(12345)
mean(666) | _____no_output_____ | MIT | Python Basic Programming/Programming Assignment_23.ipynb | Sayan97/Python |
Differential Imaging**Warning:** This notebook will likely cause Google Colab to crash. It is advised to run the notebook locally, either by downloading and running through Jupyter or by connecting to a local runtime.**Disclaimer:** Satellite images are not publicly available in the GitHub repository in order to avoid... | import rasterio as rio
import rioxarray as riox
import numpy as np
import xarray as xr
import matplotlib.pyplot as plt
from glob import glob | _____no_output_____ | MIT | Differential_Imaging.ipynb | Max-FM/IAA-Social-Distancing |
Define Filepaths | fdir = '/home/foxleym/Downloads'
filepaths = glob(f'{fdir}/Southsea2020_PSScene4Band_Explorer/files/*_SR_clip.tif') | _____no_output_____ | MIT | Differential_Imaging.ipynb | Max-FM/IAA-Social-Distancing |
Create 4-Band Median Raster | blueList = []
greenList = []
redList = []
nirList = []
for i, file in enumerate(filepaths):
blueList.append(riox.open_rasterio(file)[0,:,:])
greenList.append(riox.open_rasterio(file)[1,:,:])
redList.append(riox.open_rasterio(file)[2,:,:])
nirList.append(riox.open_rasterio(file)[3,:,:])
blue_median... | _____no_output_____ | MIT | Differential_Imaging.ipynb | Max-FM/IAA-Social-Distancing |
Obtain Median RBG Raster and Plot | def normalize(array):
"""Normalizes numpy arrays into scale 0.0 - 1.0"""
array_min, array_max = array.min(), array.max()
return ((array - array_min)/(array_max - array_min))
def make_composite(band_1, band_2, band_3):
"""Converts three raster bands into a composite image"""
return normalize(np.dsta... | _____no_output_____ | MIT | Differential_Imaging.ipynb | Max-FM/IAA-Social-Distancing |
Perform Image Subtractions | subtractions = []
for f in filepaths:
fname = f.split('/')[-1].split('.')[0]
raster = riox.open_rasterio(f)
subtraction = raster - median_raster
subtractions.append(subtraction)
subtraction.rio.to_raster(f'{fdir}/Southsea2020_PSScene4Band_Explorer/files/{fname}_MEDDIFF.tif') | _____no_output_____ | MIT | Differential_Imaging.ipynb | Max-FM/IAA-Social-Distancing |
Convert to RBG and Plot | b_0, g_0, r_0, nir_0 = raster
b_med, g_med, r_med, nir_med = median_raster
b_sub, g_sub, r_sub, nir_sub = subtractions[0]
rgb_0 = make_composite(r_0, g_0, b_0)
rgb_med = make_composite(r_med, g_med, b_med)
rgb_sub = make_composite(r_sub, g_sub, b_sub)
rgb_list = [rgb_0, rgb_med, rgb_sub]
fig, ax = plt.subplots(n... | _____no_output_____ | MIT | Differential_Imaging.ipynb | Max-FM/IAA-Social-Distancing |
oneDPL- Gamma Correction example Sections- [Gamma Correction](Gamma-Correction)- [Why use buffer iterators?](Why-use-buffer-iterators?)- _Lab Exercise:_ [Gamma Correction](Lab-Exercise:-Gamma-Correction)- [Image outputs](Image-outputs) Learning Objectives* Build a sample __DPC++ application__ to perform Image proces... | %%writefile gamma-correction/src/main.cpp
//==============================================================
// Copyright © 2019 Intel Corporation
//
// SPDX-License-Identifier: MIT
// =============================================================
#include <oneapi/dpl/algorithm>
#include <oneapi/dpl/execution>
#include <... | Overwriting gamma-correction/src/main.cpp
| MIT | DirectProgramming/DPC++/Jupyter/oneapi-essentials-training/07_DPCPP_Library/oneDPL_gamma_correction.ipynb | praveenkk123/oneAPI-samples |
Build and RunSelect the cell below and click run ▶ to compile and execute the code: | ! chmod 755 q; chmod 755 run_gamma_correction.sh; if [ -x "$(command -v qsub)" ]; then ./q run_gamma_correction.sh; else ./run_gamma_correction.sh; fi | _____no_output_____ | MIT | DirectProgramming/DPC++/Jupyter/oneapi-essentials-training/07_DPCPP_Library/oneDPL_gamma_correction.ipynb | praveenkk123/oneAPI-samples |
_If the Jupyter cells are not responsive or if they error out when you compile the code samples, please restart the Jupyter Kernel: "Kernel->Restart Kernel and Clear All Outputs" and compile the code samples again_ Image outputsonce you run the program sucessfuly it creates gamma corrected image and the original image... | from IPython.display import display, Image
display(Image(filename='gamma-correction/build/src/fractal_gamma.png')) | _____no_output_____ | MIT | DirectProgramming/DPC++/Jupyter/oneapi-essentials-training/07_DPCPP_Library/oneDPL_gamma_correction.ipynb | praveenkk123/oneAPI-samples |
View the original ImageSelect the cell below and click run ▶ to view the generated image using gamma correction: | from IPython.display import display, Image
display(Image(filename='gamma-correction/build/src/fractal_original.png')) | _____no_output_____ | MIT | DirectProgramming/DPC++/Jupyter/oneapi-essentials-training/07_DPCPP_Library/oneDPL_gamma_correction.ipynb | praveenkk123/oneAPI-samples |
SummaryIn this module you will have learned how to apply gamma correction to Images using Data Parallel C++ Library Reset Notebook Should you be experiencing any issues with your notebook or just want to start fresh run the below cell. | from IPython.display import display, Markdown, clear_output
import ipywidgets as widgets
button = widgets.Button(
description='Reset Notebook',
disabled=False,
button_style='', # 'success', 'info', 'warning', 'danger' or ''
tooltip='This will update this notebook, overwriting any changes.',
icon='ch... | _____no_output_____ | MIT | DirectProgramming/DPC++/Jupyter/oneapi-essentials-training/07_DPCPP_Library/oneDPL_gamma_correction.ipynb | praveenkk123/oneAPI-samples |
DECOMON tutorial 3 Local Robustness to Adversarial Attacks for classification tasks IntroductionAfter training a model, we want to make sure that the model will give the same output for any images "close" to the initial one, showing some robustness to perturbation. In this notebook, we start from a classifier built ... | import os
import tensorflow.keras as keras
import matplotlib.pyplot as plt
import matplotlib.patches as patches
%matplotlib inline
import numpy as np
import tensorflow.keras.backend as K
from tensorflow.keras.models import Sequential, Model, load_model
from tensorflow.keras.layers import Dense
from tensorflow.keras.dat... | > [0;32m/Users/ducoffe/Documents/Code/open_sourcing/Airbus/decomon/decomon/wrapper.py[0m(1065)[0;36msplit[0;34m()[0m
[0;32m 1063 [0;31m [0msplit_value[0m [0;34m=[0m [0mnp[0m[0;34m.[0m[0marray[0m[0;34m([0m[0;34m[[0m[0mmid_x[0m[0;34m[[0m[0mi[0m[0;34m,[0m [0mindex_k[0m[0;34m,[0m ... | MIT | tutorials/tutorial3_adversarial_attack_Gradient.ipynb | airbus/decomon |
load imagesWe load MNIST data from keras datasets. | ara
img_rows, img_cols = 28, 28
(x_train, y_train_), (x_test, y_test_) = mnist.load_data()
x_train = x_train.reshape((-1, 784))
x_test = x_test.reshape((-1, 784))
x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
x_train /= 255
x_test /= 255
y_train = keras.utils.to_categorical(y_train_)
y_test = ke... | _____no_output_____ | MIT | tutorials/tutorial3_adversarial_attack_Gradient.ipynb | airbus/decomon |
learn the model (classifier for MNIST images)For the model, we use a small fully connected network. It is made of 6 layers with 100 units each and ReLU activation functions. **Decomon** is compatible with a large set of Keras layers, so do not hesitate to modify the architecture. | model = Sequential()
model.add(Dense(100, activation='relu', input_dim=784))
model.add(Dense(100, activation='relu'))
model.add(Dense(10, activation='softmax'))
model.compile('adam', 'categorical_crossentropy', metrics='acc')
model.fit(x_train, y_train, batch_size=32, shuffle=True, validation_split=0.2, epochs=5)
mode... | 313/313 [==============================] - 0s 920us/step - loss: 0.1193 - acc: 0.9666
| MIT | tutorials/tutorial3_adversarial_attack_Gradient.ipynb | airbus/decomon |
After training, we see that the assessment of performance of the model on data that was not seen during training shows pretty good results: around 0.97 (maximum value is 1). It means that out of 100 images, the model was able to guess the correct digit for 97 images. But how can we guarantee that we will get this perfo... | import decomon
from decomon.models import convert
from decomon import get_adv_box, get_upper_box, get_lower_box, check_adv_box, get_upper_box | _____no_output_____ | MIT | tutorials/tutorial3_adversarial_attack_Gradient.ipynb | airbus/decomon |
For computational efficiency, we convert the model into its decomon version once and for all.Note that the decomon method will work on the non-converted model. To obtain more refined guarantees, we activate an option denoted **forward**. You can speed up the method by removing this option in the convert method. | decomon_model = convert(model)
from decomon import build_formal_adv_model
adv_model = build_formal_adv_model(decomon_model)
x_=x_train[:1]
eps=1e-2
z = np.concatenate([x_[:, None]-eps, x_[:, None]+eps], 1)
get_adv_box(decomon_model, x_,x_, source_labels=y_train[0].argmax())
adv_model.predict([x_, z, y_train[:1]])
# co... | _____no_output_____ | MIT | tutorials/tutorial3_adversarial_attack_Gradient.ipynb | airbus/decomon |
We offer an interactive visualisation of the basic adversarial robustness method from decomon **get_adv_upper**. We randomly choose 10 test images use **get_adv_upper** to assess their robustness to misclassification pixel perturbations. The magnitude of the noise on each pixel is independent and bounded by the value o... | def frame(epsilon, reset=0, filename='./data/.hidden_index.pkl'):
n_cols = 5
n_rows = 2
n_samples = n_cols*n_rows
if reset:
index = np.random.permutation(len(x_test))[:n_samples]
with closing(open(filename, 'wb')) as f:
pkl.dump(index, f)
# save data
else... | _____no_output_____ | MIT | tutorials/tutorial3_adversarial_attack_Gradient.ipynb | airbus/decomon |
Largest prime factor Problem 3 The prime factors of 13195 are 5, 7, 13 and 29.What is the largest prime factor of the number 600851475143 ? | from math import sqrt
def factorize(n, start=2):
p = start
while p <= sqrt(n):
q, r = divmod(n, p)
if r == 0:
return [p] + factorize(q, p)
p += 1
return [n]
assert factorize(13195) == [5, 7, 13, 29]
def solve():
return max(factorize(600851475143)) | _____no_output_____ | MIT | 003-largest-prime-factor.ipynb | arkeros/projecteuler |
Solution | solve() | _____no_output_____ | MIT | 003-largest-prime-factor.ipynb | arkeros/projecteuler |
High-School Maths Exercise Getting to Know Jupyter Notebook. Python Libraries and Best Practices. Basic Workflow Problem 1. MarkdownJupyter Notebook is a very light, beautiful and convenient way to organize your research and display your results. Let's play with it for a while.First, you can double-click each cell an... | def multiply_by(x, y):
return x * y
res = multiply_by(4, 7.21324)
print(res) | 28.85296
| MIT | MathConceptsForDevelopers/01.InitialExcercise/High-School Maths Exercise.ipynb | LuGeorgiev/Python-SoftUni |
Problem 2. Formulas and LaTeXWriting math formulas has always been hard. But scientists don't like difficulties and prefer standards. So, thanks to Donald Knuth (a very popular computer scientist, who also invented a lot of algorithms), we have a nice typesetting system, called LaTeX (pronounced _lah_-tek). We'll be u... | sp.init_printing()
x = sp.symbols('x')
a,b,c = sp.symbols('a b c')
sp.solve(a*x**2 + b*x + c, x) | _____no_output_____ | MIT | MathConceptsForDevelopers/01.InitialExcercise/High-School Maths Exercise.ipynb | LuGeorgiev/Python-SoftUni |
How about a function that takes $a, b, c$ (assume they are real numbers, you don't need to do additional checks on them) and returns the **real** roots of the quadratic equation?Remember that in order to calculate the roots, we first need to see whether the expression under the square root sign is non-negative.If $b^2 ... | def solve_quadratic_equation(a, b, c):
d = b**2 - 4*a*c
if a ==0 and b != 0:
return [-c/b]
elif a==0:
return []
elif d < 0:
return []
elif d == 0:
return[-b/2*a]
else:
d = math.sqrt(d)
return[(-b - d)/2*a,(-b + d)/2*a ]
# Testing: Execute t... | [-1.0, 2.0]
[4.0]
[]
[-1.0]
[]
| MIT | MathConceptsForDevelopers/01.InitialExcercise/High-School Maths Exercise.ipynb | LuGeorgiev/Python-SoftUni |
**Bonus:** Last time we saw how to solve a linear equation. Remember that linear equations are just like quadratic equations with $a = 0$. In this case, however, division by 0 will throw an error. Extend your function above to support solving linear equations (in the same way we did it last time). Problem 4. Equation ... | k = np.arange(1, 7, 1)
print(k)
x = np.linspace(-3, 5, 1000)
##y = 2 * x + 3
y = [2 * current + 3 for current in x]
plt.plot(x,y)
ax = plt.gca()
ax.spines["bottom"].set_position("zero")
ax.spines["left"].set_position("zero")
ax.spines["top"].set_visible(False)
ax.spines["right"].set_visible(False)
xticks = ax.xaxis... | [1 2 3 4 5 6]
| MIT | MathConceptsForDevelopers/01.InitialExcercise/High-School Maths Exercise.ipynb | LuGeorgiev/Python-SoftUni |
It doesn't look too bad bit we can do much better. See how the axes don't look like they should? Let's move them to zeto. This can be done using the "spines" of the plot (i.e. the borders).All `matplotlib` figures can have many plots (subfigures) inside them. That's why when performing an operation, we have to specify ... | x = np.linspace(-5,5,5000)
y = 0.5 * np.exp(0.5 * x)
plt.plot(x, y)
plt.show
plt.title('exponent') | _____no_output_____ | MIT | MathConceptsForDevelopers/01.InitialExcercise/High-School Maths Exercise.ipynb | LuGeorgiev/Python-SoftUni |
* Problem 6. Generalizing the Plotting FunctionLet's now use the power of Python to generalize the code we created to plot. In Python, you can pass functions as parameters to other functions. We'll utilize this to pass the math function that we're going to plot.Note: We can also pass *lambda expressions* (anonymous fu... | def plot_math_function(f, min_x, max_x, num_points):
x = np.linspace(min_x, max_x, num_points)
f_vectorized = np.vectorize(f)
y = f_vectorized(x)
plt.plot(x,y)
plt.show()
plot_math_function(lambda x: 2 * x + 3, -3, 5, 1000)
plot_math_function(lambda x: -x + 8, -1, 10, 1000)
plot_math_function(l... | _____no_output_____ | MIT | MathConceptsForDevelopers/01.InitialExcercise/High-School Maths Exercise.ipynb | LuGeorgiev/Python-SoftUni |
* Problem 7. Solving Equations GraphicallyNow that we have a general plotting function, we can use it for more interesting things. Sometimes we don't need to know what the exact solution is, just to see where it lies. We can do this by plotting the two functions around the "=" sign ans seeing where they intersect. Tak... | def plot_math_functions(functions, min_x, max_x, num_points):
# Write your code here
pass
plot_math_functions([lambda x: 2 * x + 3, lambda x: 0], -3, 5, 1000)
plot_math_functions([lambda x: 3 * x**2 - 2 * x + 5, lambda x: 3 * x + 7], -2, 3, 1000) | _____no_output_____ | MIT | MathConceptsForDevelopers/01.InitialExcercise/High-School Maths Exercise.ipynb | LuGeorgiev/Python-SoftUni |
This is also a way to plot the solutions of systems of equation, like the one we solved last time. Let's actually try it. | plot_math_functions([lambda x: (-4 * x + 7) / 3, lambda x: (-3 * x + 8) / 5, lambda x: (-x - 1) / -2], -1, 4, 1000) | _____no_output_____ | MIT | MathConceptsForDevelopers/01.InitialExcercise/High-School Maths Exercise.ipynb | LuGeorgiev/Python-SoftUni |
Problem 8. Trigonometric FunctionsWe already saw the graph of the function $y = \sin(x)$. But, how do we define the trigonometric functions once again? Let's quickly review that.The two basic trigonometric functions are defined as the ratio of two sides:$$ \sin(x) = \frac{\text{opposite}}{\text{hypotenuse}} $$$$ \cos(... | x = np.linspace(-10,10)
plt.plot(x, np.arctan(x))
plt.plot(x, np.sin(x))
plt.plot(x, np.cos(x))
plt.show()
x = np.linspace(-10, 10)
plt.plot(x, np.arccosh(x))
plt.show() | C:\Users\lgeorgiev\AppData\Local\Continuum\anaconda3\lib\site-packages\ipykernel_launcher.py:2: RuntimeWarning: invalid value encountered in arccosh
| MIT | MathConceptsForDevelopers/01.InitialExcercise/High-School Maths Exercise.ipynb | LuGeorgiev/Python-SoftUni |
1/14 최초 구현 by 소연
수정 및 테스트 시 본 파일이 아닌 사본 사용을 부탁드립니다. | import os, sys
from google.colab import drive
drive.mount('/content/drive')
%cd /content/drive/Shareddrives/KPMG_Ideation
import warnings
warnings.filterwarnings('ignore')
import numpy as np
import pandas as pd
from pprint import pprint
from krwordrank.word import KRWordRank
from copy import deepcopy
import ... | _____no_output_____ | MIT | Python_Modules/STT.ipynb | Soyeon-ErinLee/KPMG_Ideation |
Networks and Simulation Packages | %%writefile magic_functions.py
from tqdm import tqdm
from multiprocess import Pool
import scipy
import networkx as nx
import random
import pandas as pd
import numpy as np
import rpy2.robjects as robjects
from rpy2.robjects import pandas2ri
from sklearn.metrics.pairwise import cosine_similarity
from tqdm.notebook import... | _____no_output_____ | MIT | build/html/python_scripts1.ipynb | krishna-harsha/Tolerance-to-modern-slavery |
Generating network with desired characteristics | def create_network(N,nr,er,asa,bs_n,m_size):
### Graph generation
## Total organizations
N=N
## region specific N
n_regions_list=[int(0.46*N),int( 0.16*N),int( 0.38*N)]
if (len(n_regions_list[0]*["NrA"]+n_regions_list[1]*["Eur"]+n_regions_list[2]*['Asia'])!=N):
if (len(n_regions_lis... | _____no_output_____ | MIT | build/html/python_scripts1.ipynb | krishna-harsha/Tolerance-to-modern-slavery |
Generate initial attributes Python wrapper | def sample_lab_attr_all_init(N):
# Defining the R script and loading the instance in Python
r = robjects.r
r['source']('sampling_for_attributes_normal.R')
# Loading the function we have defined in R.
sampling_for_attributes_r2 = robjects.globalenv['sampling_for_attributes_normal']
#Invoking the ... | _____no_output_____ | MIT | build/html/python_scripts1.ipynb | krishna-harsha/Tolerance-to-modern-slavery |
R function for beta distributed tolerance | library(bnlearn)
library(stats)
sampling_for_attributes_normal <- function(N){
#' Preprocessing df to filter country
#'
#'
data_orgs<-read.csv('C:/Users/Krishna/OneDrive/Documents/IIM_R1/proj2/cosine_input.csv')
library(bnlearn)
library(stats)
my_model <- readRDS("C:/Users/Krishna/OneDrive/Documents/IIM_R... | _____no_output_____ | MIT | build/html/python_scripts1.ipynb | krishna-harsha/Tolerance-to-modern-slavery |
Generate new attributes Python wrapper | def sample_lab_attr_new_B(N,reg,s_av1,s_av2):
# Defining the R script and loading the instance in Python
r = robjects.r
r['source']('sampling_for_attributes.R')
# Loading the function we have defined in R.
sampling_for_attributes_r = robjects.globalenv['sampling_for_attributes']
#Invoking the R ... | _____no_output_____ | MIT | build/html/python_scripts1.ipynb | krishna-harsha/Tolerance-to-modern-slavery |
R function to sample new attributes |
sampling_for_attributes <- function(N,reg){
#' Preprocessing df to filter country
#'
#'
library(bnlearn)
#my_model <- readRDS("C:/Users/ADMIN/OneDrive/Documents/IIM_R1/proj2/model_fit.rds")
if ( reg==1){
#C:/Users/ADMIN/OneDrive/Documents
my_model <- readRDS("C:/Users/Krishna/OneDrive/Documents... | _____no_output_____ | MIT | build/html/python_scripts1.ipynb | krishna-harsha/Tolerance-to-modern-slavery |
Bayesian Network fit to attributes of an organization | library(bnlearn)
data<-read.csv('C:/Users/ADMIN/OneDrive/Documents/IIM_R1/proj2/cosine_input.csv')
head(data)
data1<-data[data$Region=='North America',]
data2<-data[data$Region=='Europe',]
data3<-data[data$Region=='Asia',]
data<-data[,c(2:8)]
data1<-data1[,c(2:8)]
data2<-data2[,c(2:8)]
data3<-data3[,c(2:8)]
dim(dat... | _____no_output_____ | MIT | build/html/python_scripts1.ipynb | krishna-harsha/Tolerance-to-modern-slavery |
R scripts for cumulative and probability density of a tolerance score | prob_cdf<-function(cur_sc,reg){
data<-read.csv('C:/Users/Krishna/OneDrive/Documents/IIM_R1/proj2/cosine_input.csv')
#head(data)
reg_lt=unique(data$Region)
data<-data[data$Region==reg_lt[reg],]
#hist(data$Tolerance,probability=TRUE)
#lines(density(data$Tolerance),col="red")
ecdff<-ecdf(data$Tolerance... | _____no_output_____ | MIT | build/html/python_scripts1.ipynb | krishna-harsha/Tolerance-to-modern-slavery |
Python scripts for running R scripts | def prob_cdf(cur_sc,reg):
# Defining the R script and loading the instance in Python
r = robjects.r
r['source']('prob_cdf.R')
# Loading the function we have defined in R.
prob_cdf_r = robjects.globalenv['prob_cdf']
#Invoking the R function and getting the result
df_result_p= prob_cdf_r(cur_s... | _____no_output_____ | MIT | build/html/python_scripts1.ipynb | krishna-harsha/Tolerance-to-modern-slavery |
Simulation | def simulation_continous (node_attr,edge_list_df,num_sim,W,bs1,bs2,N,r_on,m_on,p_reg,p_med,probs_mat,probs_mat2,run_iter,alpha1,alpha2,alpha3,Tmp,rgn,mcp):
#nodes and edges
N=N
node_attr = node_attr
edge_list_df = edge_list_df
#P's
blanck_data_tot=np.empty([N,32,num_sim],dtype='object')
... | _____no_output_____ | MIT | build/html/python_scripts1.ipynb | krishna-harsha/Tolerance-to-modern-slavery |
Parallelization of simulation |
def process_func(run_iter):
#print('@@@@@ run iter @@@@@ --' + str(run_iter))
stc=scn_params.iloc[run_iter,20]
Tmp=scn_params.iloc[run_iter,21]
if stc==1:
nr=[0.22,0.35,0.43]
er=[0.38,0.13,0.50]
asa=[0.22,0.06,0.72]
else:
nr=[0.33,0.335,0.335]
er=[0.33,... | Overwriting magic_functions.py
| MIT | build/html/python_scripts1.ipynb | krishna-harsha/Tolerance-to-modern-slavery |
Running simulation | #scenarios
scn_params=pd.read_csv('simulation_log/testscenarios_uniform_parallel_W_alpha_new_sense_simple_new_missing_reg/testscenarios_uniform_parallel_W_alpha_new_sense_simple.csv')
# Organizational data
data_orgs=pd.read_csv('C:/Users/Krishna/OneDrive/Documents/IIM_R1/proj2/cosine_input.csv')
folder_location='simu... | _____no_output_____ | MIT | build/html/python_scripts1.ipynb | krishna-harsha/Tolerance-to-modern-slavery |
I started this competition investigating neural networks with this kernel https://www.kaggle.com/mulargui/keras-nnNow switching to using ensembles in this new kernel. As of today V6 is the most performant version.You can find all my notes and versions at https://github.com/mulargui/kaggle-Classify-forest-types | # This Python 3 environment comes with many helpful analytics libraries installed
# It is defined by the kaggle/python docker image: https://github.com/kaggle/docker-python
# For example, here's several helpful packages to load in
import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O... | _____no_output_____ | MIT | src/Ensemble.ipynb | mulargui/kaggle-Classify-forest-types |
DATASET GENERATION | import numpy as np
import os
from scipy.misc import imread, imresize
import matplotlib.pyplot as plt
%matplotlib inline
cwd = os.getcwd()
print ("PACKAGES LOADED")
print ("CURRENT FOLDER IS [%s]" % (cwd) ) | PACKAGES LOADED
CURRENT FOLDER IS [/home/sj/notebooks/github/deep-learning-cpslab/code]
| MIT | code/basic_gendataset.ipynb | cpslab-snu/deep_learning |
CONFIGURATION | # FOLDER LOCATIONS
paths = ["../../img_dataset/celebs/Arnold_Schwarzenegger"
, "../../img_dataset/celebs/Junichiro_Koizumi"
, "../../img_dataset/celebs/Vladimir_Putin"
, "../../img_dataset/celebs/George_W_Bush"]
categories = ['Terminator', 'Koizumi', 'Putin', 'Bush']
# CONFIGURATIONS
imgsize =... | YOUR IMAGES SHOULD BE AT
[0/4] ../../img_dataset/celebs/Arnold_Schwarzenegger
[1/4] ../../img_dataset/celebs/Junichiro_Koizumi
[2/4] ../../img_dataset/celebs/Vladimir_Putin
[3/4] ../../img_dataset/celebs/George_W_Bush
DATA WILL BE SAVED TO
[/home/sj/notebooks/github/deep-learning-cpslab/code/data/custom_data.npz]... | MIT | code/basic_gendataset.ipynb | cpslab-snu/deep_learning |
RGB2GRAY | def rgb2gray(rgb):
if len(rgb.shape) is 3:
return np.dot(rgb[...,:3], [0.299, 0.587, 0.114])
else:
return rgb | _____no_output_____ | MIT | code/basic_gendataset.ipynb | cpslab-snu/deep_learning |
LOAD IMAGES | nclass = len(paths)
valid_exts = [".jpg",".gif",".png",".tga", ".jpeg"]
imgcnt = 0
for i, relpath in zip(range(nclass), paths):
path = cwd + "/" + relpath
flist = os.listdir(path)
for f in flist:
if os.path.splitext(f)[1].lower() not in valid_exts:
continue
fullpath = os.... | TOTAL 681 IMAGES
| MIT | code/basic_gendataset.ipynb | cpslab-snu/deep_learning |
DIVIDE INTO TRAINING AND TEST | def print_shape(string, x):
print ("SHAPE OF [%s] IS [%s]" % (string, x.shape,))
randidx = np.random.randint(imgcnt, size=imgcnt)
trainidx = randidx[0:int(4*imgcnt/5)]
testidx = randidx[int(4*imgcnt/5):imgcnt]
trainimg = totalimg[trainidx, :]
trainlabel = totallabel[trainidx, :]
testimg = totalimg... | SHAPE OF [totalimg] IS [(681, 4096)]
SHAPE OF [totallabel] IS [(681, 4)]
SHAPE OF [trainimg] IS [(544, 4096)]
SHAPE OF [trainlabel] IS [(544, 4)]
SHAPE OF [testimg] IS [(137, 4096)]
SHAPE OF [testlabel] IS [(137, 4)]
| MIT | code/basic_gendataset.ipynb | cpslab-snu/deep_learning |
SAVE TO NPZ | savepath = cwd + "/data/" + data_name + ".npz"
np.savez(savepath, trainimg=trainimg, trainlabel=trainlabel
, testimg=testimg, testlabel=testlabel
, imgsize=imgsize, use_gray=use_gray, categories=categories)
print ("SAVED TO [%s]" % (savepath)) | SAVED TO [/home/sj/notebooks/github/deep-learning-cpslab/code/data/custom_data.npz]
| MIT | code/basic_gendataset.ipynb | cpslab-snu/deep_learning |
LOAD NPZ | # LOAD
cwd = os.getcwd()
loadpath = cwd + "/data/" + data_name + ".npz"
l = np.load(loadpath)
print (l.files)
# Parse data
trainimg_loaded = l['trainimg']
trainlabel_loaded = l['trainlabel']
testimg_loaded = l['testimg']
testlabel_loaded = l['testlabel']
categories_loaded = l['categories']
print ("[%d] TRAINING... | ['trainlabel', 'imgsize', 'trainimg', 'testimg', 'testlabel', 'use_gray', 'categories']
[544] TRAINING IMAGES
[137] TEST IMAGES
LOADED FROM [/home/sj/notebooks/github/deep-learning-cpslab/code/data/custom_data.npz]
| MIT | code/basic_gendataset.ipynb | cpslab-snu/deep_learning |
PLOT LOADED DATA | ntrain_loaded = trainimg_loaded.shape[0]
batch_size = 5;
randidx = np.random.randint(ntrain_loaded, size=batch_size)
for i in randidx:
currimg = np.reshape(trainimg_loaded[i, :], (imgsize[0], -1))
currlabel_onehot = trainlabel_loaded[i, :]
currlabel = np.argmax(currlabel_onehot)
if use_gray:
c... | _____no_output_____ | MIT | code/basic_gendataset.ipynb | cpslab-snu/deep_learning |
Classifying Fashion-MNISTNow it's your turn to build and train a neural network. You'll be using the [Fashion-MNIST dataset](https://github.com/zalandoresearch/fashion-mnist), a drop-in replacement for the MNIST dataset. MNIST is actually quite trivial with neural networks where you can easily achieve better than 97% ... | import torch
from torchvision import datasets, transforms
import helper
# Define a transform to normalize the data
transform = transforms.Compose([transforms.ToTensor(),
transforms.Normalize((0.5,), (0.5,))])
# Download and load the training data
trainset = datasets.FashionMNIST('~/.pyt... | Downloading http://fashion-mnist.s3-website.eu-central-1.amazonaws.com/train-images-idx3-ubyte.gz to C:\Users\yuxinshi/.pytorch/F_MNIST_data/FashionMNIST\raw\train-images-idx3-ubyte.gz
| MIT | intro-to-pytorch/Part 4 - Fashion-MNIST (Exercises).ipynb | YuxinShi0423/deep-learning-v2-pytorch |
Here we can see one of the images. | image, label = next(iter(trainloader))
helper.imshow(image[0,:]); | _____no_output_____ | MIT | intro-to-pytorch/Part 4 - Fashion-MNIST (Exercises).ipynb | YuxinShi0423/deep-learning-v2-pytorch |
Building the networkHere you should define your network. As with MNIST, each image is 28x28 which is a total of 784 pixels, and there are 10 classes. You should include at least one hidden layer. We suggest you use ReLU activations for the layers and to return the logits or log-softmax from the forward pass. It's up t... | # TODO: Define your network architecture here
from torch import nn, optim
import torch.nn.functional as F
class Classifier(nn.Module):
def __init__(self):
super().__init__()
self.fc1 = nn.Linear(784, 256)
self.fc2 = nn.Linear(256, 128)
self.fc3 = nn.Linear(128, 64)
self.fc4 ... | _____no_output_____ | MIT | intro-to-pytorch/Part 4 - Fashion-MNIST (Exercises).ipynb | YuxinShi0423/deep-learning-v2-pytorch |
Train the networkNow you should create your network and train it. First you'll want to define [the criterion](http://pytorch.org/docs/master/nn.htmlloss-functions) ( something like `nn.CrossEntropyLoss`) and [the optimizer](http://pytorch.org/docs/master/optim.html) (typically `optim.SGD` or `optim.Adam`).Then write t... | # TODO: Create the network, define the criterion and optimizer
model = Classifier()
print(list(model.parameters()))
criterion = nn.NLLLoss()
optimizer = optim.SGD(model.parameters(), lr = 0.003)
# TODO: Train the network here
epochs = 5
for e in range(epochs):
running_loss = 0
for images, labels in t... | _____no_output_____ | MIT | intro-to-pytorch/Part 4 - Fashion-MNIST (Exercises).ipynb | YuxinShi0423/deep-learning-v2-pytorch |
The Adonis architectureQubit connectivity:``` QB1 |QB4 - QB3 - QB2 | QB5```Construct an `IQMDevice` instance representing the Adonis architecture | adonis = Adonis()
print(adonis.NATIVE_GATES)
print(adonis.NATIVE_GATE_INSTANCES)
print(adonis.qubits) | _____no_output_____ | Apache-2.0 | examples/usage.ipynb | nikosavola/cirq-on-iqm |
Creating a quantum circuitCreate a quantum circuit and insert native gates | a, b, c = adonis.qubits[:3]
circuit = cirq.Circuit(device=adonis)
circuit.append(cirq.X(a))
circuit.append(cirq.PhasedXPowGate(phase_exponent=0.3, exponent=0.5)(c))
circuit.append(cirq.CZ(a, c))
circuit.append(cirq.YPowGate(exponent=1.1)(c))
print(circuit) | _____no_output_____ | Apache-2.0 | examples/usage.ipynb | nikosavola/cirq-on-iqm |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.