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 |
|---|---|---|---|---|---|
Define a Galactocentric Coordinate FrameWe will start by defining a Galactocentric coordinate system using `astropy.coordinates`. We will adopt the latest parameter set assumptions for the solar Galactocentric position and velocity as implemented in Astropy, but note that these parameters are customizable by passing p... | with coord.galactocentric_frame_defaults.set("v4.0"):
galcen_frame = coord.Galactocentric()
galcen_frame | _____no_output_____ | MIT | 4-Science-case-studies/1-Computing-orbits-for-Gaia-stars.ipynb | CCADynamicsGroup/SummerSchoolWorkshops |
Define the Solar Position and Velocity In this coordinate system, the sun is along the $x$-axis (at a negative $x$ value), and the Galactic rotation at this position is in the $+y$ direction. The 3D position of the sun is therefore given by: | sun_xyz = u.Quantity(
[-galcen_frame.galcen_distance, 0 * u.kpc, galcen_frame.z_sun] # x,y,z
) | _____no_output_____ | MIT | 4-Science-case-studies/1-Computing-orbits-for-Gaia-stars.ipynb | CCADynamicsGroup/SummerSchoolWorkshops |
We can combine this with the solar velocity vector (defined in the `astropy.coordinates.Galactocentric` frame) to define the sun's phase-space position, which we will use as initial conditions shortly to compute the orbit of the Sun: | sun_vxyz = galcen_frame.galcen_v_sun
sun_vxyz
sun_w0 = gd.PhaseSpacePosition(pos=sun_xyz, vel=sun_vxyz) | _____no_output_____ | MIT | 4-Science-case-studies/1-Computing-orbits-for-Gaia-stars.ipynb | CCADynamicsGroup/SummerSchoolWorkshops |
To compute the sun's orbit, we need to specify a mass model for the Galaxy. Here, we will use the default Milky Way mass model implemented in Gala, which is defined in detail in the Gala documentation: [Defining a Milky Way model](define-milky-way-model.html). Here, we will initialize the potential model with default p... | mw_potential = gp.MilkyWayPotential()
mw_potential | _____no_output_____ | MIT | 4-Science-case-studies/1-Computing-orbits-for-Gaia-stars.ipynb | CCADynamicsGroup/SummerSchoolWorkshops |
This potential is composed of four mass components meant to represent simple models of the different structural components of the Milky Way: | for k, pot in mw_potential.items():
print(f"{k}: {pot!r}") | _____no_output_____ | MIT | 4-Science-case-studies/1-Computing-orbits-for-Gaia-stars.ipynb | CCADynamicsGroup/SummerSchoolWorkshops |
With a potential model for the Galaxy and initial conditions for the sun, we can now compute the Sun's orbit using the default integrator (Leapfrog integration): We will compute the orbit for 4 Gyr, which is about 16 orbital periods. | sun_orbit = mw_potential.integrate_orbit(sun_w0, dt=0.5 * u.Myr, t1=0, t2=4 * u.Gyr) | _____no_output_____ | MIT | 4-Science-case-studies/1-Computing-orbits-for-Gaia-stars.ipynb | CCADynamicsGroup/SummerSchoolWorkshops |
Let's plot the Sun's orbit in 3D to get a feel for the geometry of the orbit: | fig, ax = sun_orbit.plot_3d()
lim = (-12, 12)
ax.set(xlim=lim, ylim=lim, zlim=lim) | _____no_output_____ | MIT | 4-Science-case-studies/1-Computing-orbits-for-Gaia-stars.ipynb | CCADynamicsGroup/SummerSchoolWorkshops |
Retrieve Gaia Data for Kepler-444 As a comparison, we will compute the orbit of the exoplanet-hosting star "Kepler-444." To get Gaia data for this star, we first have to retrieve its sky coordinates so that we can do a positional cross-match query on the Gaia catalog. We can retrieve the sky position of Kepler-444 fro... | star_sky_c = coord.SkyCoord.from_name("Kepler-444")
star_sky_c | _____no_output_____ | MIT | 4-Science-case-studies/1-Computing-orbits-for-Gaia-stars.ipynb | CCADynamicsGroup/SummerSchoolWorkshops |
We happen to know a priori that Kepler-444 has a large proper motion, so the sky position reported by Simbad could be off from the Gaia sky position (epoch=2016) by many arcseconds. To run and retrieve the Gaia data, we will use the [pyia](http://pyia.readthedocs.io/) package: We can pass in an ADQL query, which `pyia`... | star_gaia = GaiaData.from_query(
f"""
SELECT TOP 1 * FROM gaiaedr3.gaia_source
WHERE 1=CONTAINS(
POINT('ICRS', {star_sky_c.ra.degree}, {star_sky_c.dec.degree}),
CIRCLE('ICRS', ra, dec, {(15*u.arcsec).to_value(u.degree)})
)
ORDER BY phot_g_mean_mag
"""
)
star_gaia | _____no_output_____ | MIT | 4-Science-case-studies/1-Computing-orbits-for-Gaia-stars.ipynb | CCADynamicsGroup/SummerSchoolWorkshops |
We will assume (and hope!) that this source is Kepler-444, but we know that it is fairly bright compared to a typical Gaia source, so we should be safe.We can now use the returned `pyia.GaiaData` object to retrieve an astropy `SkyCoord` object with all of the position and velocity measurements taken from the Gaia archi... | star_gaia_c = star_gaia.get_skycoord()
star_gaia_c | _____no_output_____ | MIT | 4-Science-case-studies/1-Computing-orbits-for-Gaia-stars.ipynb | CCADynamicsGroup/SummerSchoolWorkshops |
To compute this star's Galactic orbit, we need to convert its observed, Heliocentric (actually solar system barycentric) data into the Galactocentric coordinate frame we defined above. To do this, we will use the `astropy.coordinates` transformation framework using the `.transform_to()` method, and we will pass in the ... | star_galcen = star_gaia_c.transform_to(galcen_frame)
star_galcen | _____no_output_____ | MIT | 4-Science-case-studies/1-Computing-orbits-for-Gaia-stars.ipynb | CCADynamicsGroup/SummerSchoolWorkshops |
Let's print out the Cartesian position and velocity for Kepler-444: | print(star_galcen.cartesian)
print(star_galcen.velocity) | _____no_output_____ | MIT | 4-Science-case-studies/1-Computing-orbits-for-Gaia-stars.ipynb | CCADynamicsGroup/SummerSchoolWorkshops |
Now with Galactocentric position and velocity components for Kepler-444, we can create Gala initial conditions and compute its orbit on the time grid used to compute the Sun's orbit above: | star_w0 = gd.PhaseSpacePosition(star_galcen.data)
star_orbit = mw_potential.integrate_orbit(star_w0, t=sun_orbit.t) | _____no_output_____ | MIT | 4-Science-case-studies/1-Computing-orbits-for-Gaia-stars.ipynb | CCADynamicsGroup/SummerSchoolWorkshops |
We can now compare the orbit of Kepler-444 to the solar orbit we computed above. We will plot the two orbits in two projections: First in the $x$-$y$ plane (Cartesian positions), then in the *meridional plane*, showing the cylindrical $R$ and $z$ position dependence of the orbits: | fig, axes = plt.subplots(1, 2, figsize=(10, 5), constrained_layout=True)
sun_orbit.plot(["x", "y"], axes=axes[0])
star_orbit.plot(["x", "y"], axes=axes[0])
axes[0].set_xlim(-10, 10)
axes[0].set_ylim(-10, 10)
sun_orbit.cylindrical.plot(
["rho", "z"],
axes=axes[1],
auto_aspect=False,
labels=["$R$ [kpc]"... | _____no_output_____ | MIT | 4-Science-case-studies/1-Computing-orbits-for-Gaia-stars.ipynb | CCADynamicsGroup/SummerSchoolWorkshops |
Exercise: How does Kepler-444's orbit differ from the Sun's?- What are the guiding center radii of the two orbits? - What is the maximum $z$ height reached by each orbit? - What are their eccentricities? - Can you guess which star is older based on their kinematics? - Which star do you think has a higher metallicity? ... | # random_stars_g = .. | _____no_output_____ | MIT | 4-Science-case-studies/1-Computing-orbits-for-Gaia-stars.ipynb | CCADynamicsGroup/SummerSchoolWorkshops |
Compute orbits for these stars for the same time grid used above to compute the sun's orbit: | # random_stars_c = ...
# random_stars_galcen = ...
# random_stars_w0 = ...
# random_stars_orbits = ... | _____no_output_____ | MIT | 4-Science-case-studies/1-Computing-orbits-for-Gaia-stars.ipynb | CCADynamicsGroup/SummerSchoolWorkshops |
Plot the initial (present-day) positions of all of these stars in Galactocentric Cartesian coordinates: Now plot the orbits of these stars in the x-y and R-z planes: | fig, axes = plt.subplots(1, 2, figsize=(10, 5), constrained_layout=True)
random_stars_orbits.plot(["x", "y"], axes=axes[0])
axes[0].set_xlim(-15, 15)
axes[0].set_ylim(-15, 15)
random_stars_orbits.cylindrical.plot(
["rho", "z"],
axes=axes[1],
auto_aspect=False,
labels=["$R$ [kpc]", "$z$ [kpc]"],
)
axe... | _____no_output_____ | MIT | 4-Science-case-studies/1-Computing-orbits-for-Gaia-stars.ipynb | CCADynamicsGroup/SummerSchoolWorkshops |
Compute maximum $z$ heights ($z_\textrm{max}$) and eccentricities for all of these orbits. Compare the Sun, Kepler-444, and this random sampling of nearby stars. Where do the Sun and Kepler-444 sit relative to the random sample of nearby stars in terms of $z_\textrm{max}$ and eccentricity? (Hint: plot $z_\textrm{max}$ ... | # rand_zmax = ...
# rand_ecc = ...
fig, ax = plt.subplots(figsize=(8, 6))
ax.scatter(
rand_ecc, rand_zmax, color="k", alpha=0.4, s=14, lw=0, label="random nearby stars"
)
ax.scatter(sun_orbit.eccentricity(), sun_orbit.zmax(), color="tab:orange", label="Sun")
ax.scatter(
star_orbit.eccentricity(), star_orbit.zma... | _____no_output_____ | MIT | 4-Science-case-studies/1-Computing-orbits-for-Gaia-stars.ipynb | CCADynamicsGroup/SummerSchoolWorkshops |
Image Denoising with Autoencoders Introduction and Importing Libraries___Note: If you are starting the notebook from this task, you can run cells from all previous tasks in the kernel by going to the top menu and then selecting Kernel > Restart and Run All___ | import numpy as np
from tensorflow.keras.datasets import mnist
from matplotlib import pyplot as plt
from tensorflow.keras.models import Sequential, Model
from tensorflow.keras.layers import Dense, Input
from tensorflow.keras.callbacks import EarlyStopping, LambdaCallback
from tensorflow.keras.utils import to_categoric... | _____no_output_____ | MIT | Image_Noise_Reduction.ipynb | Hevenicio/Image-Noise-Reduction-with-Auto-encoders-using-TensorFlow |
Data Preprocessing___Note: If you are starting the notebook from this task, you can run cells from all previous tasks in the kernel by going to the top menu and then selecting Kernel > Restart and Run All___ | (x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train = x_train.astype('float')/255.
x_test = x_test.astype('float')/255.
x_train = np.reshape(x_train, (60000, 784))
x_test = np.reshape(x_test, (10000, 784)) | Downloading data from https://storage.googleapis.com/tensorflow/tf-keras-datasets/mnist.npz
11493376/11490434 [==============================] - 0s 0us/step
| MIT | Image_Noise_Reduction.ipynb | Hevenicio/Image-Noise-Reduction-with-Auto-encoders-using-TensorFlow |
Adding Noise___Note: If you are starting the notebook from this task, you can run cells from all previous tasks in the kernel by going to the top menu and then selecting Kernel > Restart and Run All___ | x_train_noisy = x_train + np.random.rand(60000, 784)*0.9
x_test_noisy = x_test + np.random.rand(10000, 784)*0.9
x_train_noisy = np.clip(x_train_noisy, 0., 1.)
x_test_noisy = np.clip(x_test_noisy, 0., 1.)
def Plot(x, p, labels = False):
plt.figure(figsize = (20, 2))
for i in range(10):
plt.subplot(1, 1... | _____no_output_____ | MIT | Image_Noise_Reduction.ipynb | Hevenicio/Image-Noise-Reduction-with-Auto-encoders-using-TensorFlow |
Building and Training a Classifier___Note: If you are starting the notebook from this task, you can run cells from all previous tasks in the kernel by going to the top menu and then selecting Kernel > Restart and Run All___ | classifier = Sequential([
Dense(256, activation = 'relu', input_shape = (784,)),
Dense(256, activation = 'relu'),
Dense(256, activation = 'softmax')
])
classifier.compile(optimizer = 'adam',
loss = 'sparse_categorical_crossentropy',
metrics = ['accuracy'])
classifier.fi... | 313/313 [==============================] - 0s 1ms/step - loss: 11.9475 - accuracy: 0.1621
0.16210000216960907
| MIT | Image_Noise_Reduction.ipynb | Hevenicio/Image-Noise-Reduction-with-Auto-encoders-using-TensorFlow |
Building the Autoencoder___Note: If you are starting the notebook from this task, you can run cells from all previous tasks in the kernel by going to the top menu and then selecting Kernel > Restart and Run All___ | input_image = Input(shape = (784,))
encoded = Dense(64, activation = 'relu')(input_image)
decoded = Dense(784, activation = 'sigmoid')(encoded)
autoencoder = Model(input_image, decoded)
autoencoder.compile(loss = 'binary_crossentropy', optimizer = 'adam') | _____no_output_____ | MIT | Image_Noise_Reduction.ipynb | Hevenicio/Image-Noise-Reduction-with-Auto-encoders-using-TensorFlow |
Training the Autoencoder___Note: If you are starting the notebook from this task, you can run cells from all previous tasks in the kernel by going to the top menu and then selecting Kernel > Restart and Run All___ | autoencoder.fit(
x_train_noisy,
x_train,
epochs = 100,
batch_size = 512,
validation_split = 0.2,
verbose = False,
callbacks = [
EarlyStopping(monitor = 'val_loss', patience = 5),
LambdaCallback(on_epoch_end = lambda e,l: print('{:.3f}'.format(l['val_loss']), end = ' _ '))
... | 0.261 _ 0.236 _ 0.204 _ 0.187 _ 0.176 _ 0.166 _ 0.158 _ 0.151 _ 0.146 _ 0.141 _ 0.138 _ 0.134 _ 0.132 _ 0.129 _ 0.127 _ 0.125 _ 0.123 _ 0.122 _ 0.121 _ 0.119 _ 0.118 _ 0.117 _ 0.117 _ 0.116 _ 0.115 _ 0.115 _ 0.114 _ 0.114 _ 0.113 _ 0.113 _ 0.113 _ 0.113 _ 0.112 _ 0.112 _ 0.112 _ 0.112 _ 0.112 _ 0.112 _ 0.112 _ 0.112 _ ... | MIT | Image_Noise_Reduction.ipynb | Hevenicio/Image-Noise-Reduction-with-Auto-encoders-using-TensorFlow |
Denoised Images___Note: If you are starting the notebook from this task, you can run cells from all previous tasks in the kernel by going to the top menu and then selecting Kernel > Restart and Run All___ | preds = autoencoder.predict(x_test_noisy)
Plot(x_test_noisy, None)
Plot(preds, None)
loss, acc = classifier.evaluate(preds, y_test)
print(acc) | 313/313 [==============================] - 0s 2ms/step - loss: 0.2170 - accuracy: 0.9334
0.9333999752998352
| MIT | Image_Noise_Reduction.ipynb | Hevenicio/Image-Noise-Reduction-with-Auto-encoders-using-TensorFlow |
Composite Model___Note: If you are starting the notebook from this task, you can run cells from all previous tasks in the kernel by going to the top menu and then selecting Kernel > Restart and Run All___ | input_image=Input(shape=(784,))
x=autoencoder(input_image)
y=classifier(x)
denoise_and_classfiy = Model(input_image, y)
predictions=denoise_and_classfiy.predict(x_test_noisy)
Plot(x_test_noisy, predictions, True)
Plot(x_test, to_categorical(y_test), True) | _____no_output_____ | MIT | Image_Noise_Reduction.ipynb | Hevenicio/Image-Noise-Reduction-with-Auto-encoders-using-TensorFlow |
Text Annotation Example | %pip install transformers==4.17.0 -qq
!git clone https://github.com/AMontgomerie/bulgarian-nlp
%cd bulgarian-nlp | Cloning into 'bulgarian-nlp'...
remote: Enumerating objects: 141, done.[K
remote: Counting objects: 100% (141/141), done.[K
remote: Compressing objects: 100% (126/126), done.[K
remote: Total 141 (delta 62), reused 9 (delta 2), pack-reused 0[K
Receiving objects: 100% (141/141), 70.39 KiB | 1.68 MiB/s, done.
Resolvin... | MIT | examples/text_annotator_example.ipynb | iarfmoose/bulgarian-nlp |
First we create an instance of the annotator. | from annotation.annotators import TextAnnotator
annotator = TextAnnotator() | _____no_output_____ | MIT | examples/text_annotator_example.ipynb | iarfmoose/bulgarian-nlp |
Next we create an example input and pass it as an argument to the annotator. | example_input = 'България е член на ЕС.'
annotations = annotator(example_input)
annotations | _____no_output_____ | MIT | examples/text_annotator_example.ipynb | iarfmoose/bulgarian-nlp |
As you can see, the raw output is a dictionary of tokens and corresponding tags. To make it more readable, let's display the tag level output as a dataframe. | import pandas as pd
tokens = [t["text"] for t in annotations["tokens"]]
pos_tags = [t["pos"] for t in annotations["tokens"]]
entity_tags = [t["entity"] for t in annotations["tokens"]]
df = pd.DataFrame({"token": tokens, "pos": pos_tags, "entity": entity_tags})
df | _____no_output_____ | MIT | examples/text_annotator_example.ipynb | iarfmoose/bulgarian-nlp |
For more information about the meanings of the POS tags, see https://universaldependencies.org/u/pos/The sentence level entities are also available in `annotations["entities"]`: | for entity in annotations["entities"]:
print(f"{entity['text']}: {entity['type']}") | България: LOCATION
ЕС: ORGANISATION
| MIT | examples/text_annotator_example.ipynb | iarfmoose/bulgarian-nlp |
Lab 04 : Train vanilla neural network -- solution Training a one-layer net on FASHION-MNIST | # For Google Colaboratory
import sys, os
if 'google.colab' in sys.modules:
from google.colab import drive
drive.mount('/content/gdrive')
file_name = 'train_vanilla_nn_solution.ipynb'
import subprocess
path_to_file = subprocess.check_output('find . -type f -name ' + str(file_name), shell=True).decode... | _____no_output_____ | MIT | codes/labs_lecture03/lab04_train_vanilla_nn/train_vanilla_nn_solution.ipynb | alanwuha/CE7454_2019 |
Download the TRAINING SET (data+labels) | from utils import check_fashion_mnist_dataset_exists
data_path=check_fashion_mnist_dataset_exists()
train_data=torch.load(data_path+'fashion-mnist/train_data.pt')
train_label=torch.load(data_path+'fashion-mnist/train_label.pt')
print(train_data.size())
print(train_label.size()) | torch.Size([60000, 28, 28])
torch.Size([60000])
| MIT | codes/labs_lecture03/lab04_train_vanilla_nn/train_vanilla_nn_solution.ipynb | alanwuha/CE7454_2019 |
Download the TEST SET (data only) | test_data=torch.load(data_path+'fashion-mnist/test_data.pt')
print(test_data.size()) | torch.Size([10000, 28, 28])
| MIT | codes/labs_lecture03/lab04_train_vanilla_nn/train_vanilla_nn_solution.ipynb | alanwuha/CE7454_2019 |
Make a one layer net class | class one_layer_net(nn.Module):
def __init__(self, input_size, output_size):
super(one_layer_net , self).__init__()
self.linear_layer = nn.Linear( input_size, output_size , bias=False)
def forward(self, x):
y = self.linear_layer(x)
prob = F.softmax(y, dim=1)
ret... | _____no_output_____ | MIT | codes/labs_lecture03/lab04_train_vanilla_nn/train_vanilla_nn_solution.ipynb | alanwuha/CE7454_2019 |
Build the net | net=one_layer_net(784,10)
print(net) | one_layer_net(
(linear_layer): Linear(in_features=784, out_features=10, bias=False)
)
| MIT | codes/labs_lecture03/lab04_train_vanilla_nn/train_vanilla_nn_solution.ipynb | alanwuha/CE7454_2019 |
Take the 4th image of the test set: | im=test_data[4]
utils.show(im) | _____no_output_____ | MIT | codes/labs_lecture03/lab04_train_vanilla_nn/train_vanilla_nn_solution.ipynb | alanwuha/CE7454_2019 |
And feed it to the UNTRAINED network: | p = net( im.view(1,784))
print(p) | tensor([[0.1320, 0.0970, 0.0802, 0.0831, 0.1544, 0.0777, 0.1040, 0.1219, 0.0820,
0.0678]], grad_fn=<SoftmaxBackward>)
| MIT | codes/labs_lecture03/lab04_train_vanilla_nn/train_vanilla_nn_solution.ipynb | alanwuha/CE7454_2019 |
Display visually the confidence scores | utils.show_prob_fashion_mnist(p) | _____no_output_____ | MIT | codes/labs_lecture03/lab04_train_vanilla_nn/train_vanilla_nn_solution.ipynb | alanwuha/CE7454_2019 |
Train the network (only 5000 iterations) on the train set | criterion = nn.NLLLoss()
optimizer=torch.optim.SGD(net.parameters() , lr=0.01 )
for iter in range(1,5000):
# choose a random integer between 0 and 59,999
# extract the corresponding picture and label
# and reshape them to fit the network
idx=randint(0, 60000-1)
input=train_data[idx].view(1,78... | _____no_output_____ | MIT | codes/labs_lecture03/lab04_train_vanilla_nn/train_vanilla_nn_solution.ipynb | alanwuha/CE7454_2019 |
Take the 34th image of the test set: | im=test_data[34]
utils.show(im) | _____no_output_____ | MIT | codes/labs_lecture03/lab04_train_vanilla_nn/train_vanilla_nn_solution.ipynb | alanwuha/CE7454_2019 |
Feed it to the TRAINED net: | p = net( im.view(1,784))
print(p) | tensor([[2.3781e-04, 8.4407e-06, 6.5949e-03, 6.4070e-03, 5.8398e-03, 3.5421e-02,
5.3267e-03, 5.8309e-04, 9.3951e-01, 6.6500e-05]],
grad_fn=<SoftmaxBackward>)
| MIT | codes/labs_lecture03/lab04_train_vanilla_nn/train_vanilla_nn_solution.ipynb | alanwuha/CE7454_2019 |
Display visually the confidence scores | utils.show_prob_fashion_mnist(prob) | _____no_output_____ | MIT | codes/labs_lecture03/lab04_train_vanilla_nn/train_vanilla_nn_solution.ipynb | alanwuha/CE7454_2019 |
Choose image at random from the test set and see how good/bad are the predictions | # choose a picture at random
idx=randint(0, 10000-1)
im=test_data[idx]
# diplay the picture
utils.show(im)
# feed it to the net and display the confidence scores
prob = net( im.view(1,784))
utils.show_prob_fashion_mnist(prob) | _____no_output_____ | MIT | codes/labs_lecture03/lab04_train_vanilla_nn/train_vanilla_nn_solution.ipynb | alanwuha/CE7454_2019 |
#https://machinelearningmastery.com/how-to-develop-a-convolutional-neural-network-from-scratch-for-mnist-handwritten-digit-classification/
#https://towardsdatascience.com/convolutional-neural-networks-for-beginners-using-keras-and-tensorflow-2-c578f7b3bf25
#https://github.com/jorditorresBCN/python-deep-learning/blob/ma... | train imagens original shape: (60000, 28, 28)
train labels original shape: (60000,)
| MIT | IA_ConvNN_classificacao_MNIST.ipynb | TerradasExatas/Introdu-o-IA-e-Machine-Learning | |
Note: Notebook was updated July 2, 2019 with bug fixes. If you were working on the older version:* Please click on the "Coursera" icon in the top right to open up the folder directory. * Navigate to the folder: Week 3/ Planar data classification with one hidden layer. You can see your prior work in version 5: Planar ... | # Package imports
import numpy as np
import matplotlib.pyplot as plt
from testCases_v2 import *
import sklearn
import sklearn.datasets
import sklearn.linear_model
from planar_utils import plot_decision_boundary, sigmoid, load_planar_dataset, load_extra_datasets
%matplotlib inline
np.random.seed(1) # set a seed so tha... | _____no_output_____ | MIT | neural_networks_and_deep_learning/Week 3/Planar data classification with one hidden layer/Planar_data_classification_with_onehidden_layer_v6b.ipynb | shengfeng/coursera_deep_learning |
2 - Dataset First, let's get the dataset you will work on. The following code will load a "flower" 2-class dataset into variables `X` and `Y`. | X, Y = load_planar_dataset() | _____no_output_____ | MIT | neural_networks_and_deep_learning/Week 3/Planar data classification with one hidden layer/Planar_data_classification_with_onehidden_layer_v6b.ipynb | shengfeng/coursera_deep_learning |
Visualize the dataset using matplotlib. The data looks like a "flower" with some red (label y=0) and some blue (y=1) points. Your goal is to build a model to fit this data. In other words, we want the classifier to define regions as either red or blue. | # Visualize the data:
plt.scatter(X[0, :], X[1, :], c=Y, s=40, cmap=plt.cm.Spectral); | _____no_output_____ | MIT | neural_networks_and_deep_learning/Week 3/Planar data classification with one hidden layer/Planar_data_classification_with_onehidden_layer_v6b.ipynb | shengfeng/coursera_deep_learning |
You have: - a numpy-array (matrix) X that contains your features (x1, x2) - a numpy-array (vector) Y that contains your labels (red:0, blue:1).Lets first get a better sense of what our data is like. **Exercise**: How many training examples do you have? In addition, what is the `shape` of the variables `X` and `Y`... | ### START CODE HERE ### (≈ 3 lines of code)
shape_X = None
shape_Y = None
m = X.shape[1] # training set size
### END CODE HERE ###
print ('The shape of X is: ' + str(shape_X))
print ('The shape of Y is: ' + str(shape_Y))
print ('I have m = %d training examples!' % (m)) | The shape of X is: (2, 400)
The shape of Y is: (1, 400)
I have m = 400 training examples!
| MIT | neural_networks_and_deep_learning/Week 3/Planar data classification with one hidden layer/Planar_data_classification_with_onehidden_layer_v6b.ipynb | shengfeng/coursera_deep_learning |
**Expected Output**: **shape of X** (2, 400) **shape of Y** (1, 400) **m** 400 3 - Simple Logistic RegressionBefore building a full neural network, lets first see how logistic regression performs on this problem. You can use sklearn's built-in functions to do that... | # Train the logistic regression classifier
clf = sklearn.linear_model.LogisticRegressionCV();
clf.fit(X.T, Y.T); | _____no_output_____ | MIT | neural_networks_and_deep_learning/Week 3/Planar data classification with one hidden layer/Planar_data_classification_with_onehidden_layer_v6b.ipynb | shengfeng/coursera_deep_learning |
You can now plot the decision boundary of these models. Run the code below. | # Plot the decision boundary for logistic regression
plot_decision_boundary(lambda x: clf.predict(x), X, Y)
plt.title("Logistic Regression")
# Print accuracy
LR_predictions = clf.predict(X.T)
print ('Accuracy of logistic regression: %d ' % float((np.dot(Y,LR_predictions) + np.dot(1-Y,1-LR_predictions))/float(Y.size)*1... | Accuracy of logistic regression: 47 % (percentage of correctly labelled datapoints)
| MIT | neural_networks_and_deep_learning/Week 3/Planar data classification with one hidden layer/Planar_data_classification_with_onehidden_layer_v6b.ipynb | shengfeng/coursera_deep_learning |
**Expected Output**: **Accuracy** 47% **Interpretation**: The dataset is not linearly separable, so logistic regression doesn't perform well. Hopefully a neural network will do better. Let's try this now! 4 - Neural Network modelLogistic regression did not work well on the "flower dataset". You are goi... | # GRADED FUNCTION: layer_sizes
def layer_sizes(X, Y):
"""
Arguments:
X -- input dataset of shape (input size, number of examples)
Y -- labels of shape (output size, number of examples)
Returns:
n_x -- the size of the input layer
n_h -- the size of the hidden layer
n_y -- the size o... | The size of the input layer is: n_x = 5
The size of the hidden layer is: n_h = 4
The size of the output layer is: n_y = 2
| MIT | neural_networks_and_deep_learning/Week 3/Planar data classification with one hidden layer/Planar_data_classification_with_onehidden_layer_v6b.ipynb | shengfeng/coursera_deep_learning |
**Expected Output** (these are not the sizes you will use for your network, they are just used to assess the function you've just coded). **n_x** 5 **n_h** 4 **n_y** 2 4.2 - Initialize the model's parameters **Exercise**: Implement the function `initialize_parameters()`... | # GRADED FUNCTION: initialize_parameters
def initialize_parameters(n_x, n_h, n_y):
"""
Argument:
n_x -- size of the input layer
n_h -- size of the hidden layer
n_y -- size of the output layer
Returns:
params -- python dictionary containing your parameters:
W1 -- wei... | W1 = [[-0.00416758 -0.00056267]
[-0.02136196 0.01640271]
[-0.01793436 -0.00841747]
[ 0.00502881 -0.01245288]]
b1 = [[ 0.]
[ 0.]
[ 0.]
[ 0.]]
W2 = [[-0.01057952 -0.00909008 0.00551454 0.02292208]]
b2 = [[ 0.]]
| MIT | neural_networks_and_deep_learning/Week 3/Planar data classification with one hidden layer/Planar_data_classification_with_onehidden_layer_v6b.ipynb | shengfeng/coursera_deep_learning |
**Expected Output**: **W1** [[-0.00416758 -0.00056267] [-0.02136196 0.01640271] [-0.01793436 -0.00841747] [ 0.00502881 -0.01245288]] **b1** [[ 0.] [ 0.] [ 0.] [ 0.]] **W2** [[-0.01057952 -0.00909008 0.00551454 0.02292208]] **b2** [[ 0.]] 4.3 - The Loop **Qu... | # GRADED FUNCTION: forward_propagation
def forward_propagation(X, parameters):
"""
Argument:
X -- input data of size (n_x, m)
parameters -- python dictionary containing your parameters (output of initialization function)
Returns:
A2 -- The sigmoid output of the second activation
cache ... | 0.262818640198 0.091999045227 -1.30766601287 0.212877681719
| MIT | neural_networks_and_deep_learning/Week 3/Planar data classification with one hidden layer/Planar_data_classification_with_onehidden_layer_v6b.ipynb | shengfeng/coursera_deep_learning |
**Expected Output**: 0.262818640198 0.091999045227 -1.30766601287 0.212877681719 Now that you have computed $A^{[2]}$ (in the Python variable "`A2`"), which contains $a^{[2](i)}$ for every example, you can compute the cost function as follows:$$J = - \frac{1}{m} \sum\limits_{i = 1}^{m} \large{(} \small y^{(i)... | # GRADED FUNCTION: compute_cost
def compute_cost(A2, Y, parameters):
"""
Computes the cross-entropy cost given in equation (13)
Arguments:
A2 -- The sigmoid output of the second activation, of shape (1, number of examples)
Y -- "true" labels vector of shape (1, number of examples)
paramete... | cost = 0.6930587610394646
| MIT | neural_networks_and_deep_learning/Week 3/Planar data classification with one hidden layer/Planar_data_classification_with_onehidden_layer_v6b.ipynb | shengfeng/coursera_deep_learning |
**Expected Output**: **cost** 0.693058761... Using the cache computed during forward propagation, you can now implement backward propagation.**Question**: Implement the function `backward_propagation()`.**Instructions**:Backpropagation is usually the hardest (most mathematical) part in deep learning. To ... | # GRADED FUNCTION: backward_propagation
def backward_propagation(parameters, cache, X, Y):
"""
Implement the backward propagation using the instructions above.
Arguments:
parameters -- python dictionary containing our parameters
cache -- a dictionary containing "Z1", "A1", "Z2" and "A2".
... | dW1 = [[ 0.00301023 -0.00747267]
[ 0.00257968 -0.00641288]
[-0.00156892 0.003893 ]
[-0.00652037 0.01618243]]
db1 = [[ 0.00176201]
[ 0.00150995]
[-0.00091736]
[-0.00381422]]
dW2 = [[ 0.00078841 0.01765429 -0.00084166 -0.01022527]]
db2 = [[-0.16655712]]
| MIT | neural_networks_and_deep_learning/Week 3/Planar data classification with one hidden layer/Planar_data_classification_with_onehidden_layer_v6b.ipynb | shengfeng/coursera_deep_learning |
**Expected output**: **dW1** [[ 0.00301023 -0.00747267] [ 0.00257968 -0.00641288] [-0.00156892 0.003893 ] [-0.00652037 0.01618243]] **db1** [[ 0.00176201] [ 0.00150995] [-0.00091736] [-0.00381422]] **dW2** [[ 0.00078841 0.01765429 -0.00084166 -0.01022527]] **db2** ... | # GRADED FUNCTION: update_parameters
def update_parameters(parameters, grads, learning_rate = 1.2):
"""
Updates parameters using the gradient descent update rule given above
Arguments:
parameters -- python dictionary containing your parameters
grads -- python dictionary containing your gradie... | W1 = [[-0.00643025 0.01936718]
[-0.02410458 0.03978052]
[-0.01653973 -0.02096177]
[ 0.01046864 -0.05990141]]
b1 = [[ 1.21732533e-05]
[ 2.12263977e-05]
[ 1.36755874e-05]
[ 1.05251698e-05]]
W2 = [[-0.01041081 -0.04463285 0.01758031 0.04747113]]
b2 = [[ 0.00010457]]
| MIT | neural_networks_and_deep_learning/Week 3/Planar data classification with one hidden layer/Planar_data_classification_with_onehidden_layer_v6b.ipynb | shengfeng/coursera_deep_learning |
**Expected Output**: **W1** [[-0.00643025 0.01936718] [-0.02410458 0.03978052] [-0.01653973 -0.02096177] [ 0.01046864 -0.05990141]] **b1** [[ -1.02420756e-06] [ 1.27373948e-05] [ 8.32996807e-07] [ -3.20136836e-06]] **W2** [[-0.01041081 -0.04463285 0.01758031 0.04747113]] ... | # GRADED FUNCTION: nn_model
def nn_model(X, Y, n_h, num_iterations = 10000, print_cost=False):
"""
Arguments:
X -- dataset of shape (2, number of examples)
Y -- labels of shape (1, number of examples)
n_h -- size of the hidden layer
num_iterations -- Number of iterations in gradient descent loo... | Cost after iteration 0: 0.692739
Cost after iteration 1000: 0.000218
Cost after iteration 2000: 0.000107
Cost after iteration 3000: 0.000071
Cost after iteration 4000: 0.000053
Cost after iteration 5000: 0.000042
Cost after iteration 6000: 0.000035
Cost after iteration 7000: 0.000030
Cost after iteration 8000: 0.000026... | MIT | neural_networks_and_deep_learning/Week 3/Planar data classification with one hidden layer/Planar_data_classification_with_onehidden_layer_v6b.ipynb | shengfeng/coursera_deep_learning |
**Expected Output**: **cost after iteration 0** 0.692739 $\vdots$ $\vdots$ **W1** [[-0.65848169 1.21866811] [-0.76204273 1.39377573] [ 0.5792005 -1.10397703] [ 0.76773391 -1.41477129]] **b1** [[ 0.287592 ] [ 0.3511264 ] [-0... | # GRADED FUNCTION: predict
def predict(parameters, X):
"""
Using the learned parameters, predicts a class for each example in X
Arguments:
parameters -- python dictionary containing your parameters
X -- input data of size (n_x, m)
Returns
predictions -- vector of predictions of o... | predictions mean = 0.666666666667
| MIT | neural_networks_and_deep_learning/Week 3/Planar data classification with one hidden layer/Planar_data_classification_with_onehidden_layer_v6b.ipynb | shengfeng/coursera_deep_learning |
**Expected Output**: **predictions mean** 0.666666666667 It is time to run the model and see how it performs on a planar dataset. Run the following code to test your model with a single hidden layer of $n_h$ hidden units. | # Build a model with a n_h-dimensional hidden layer
parameters = nn_model(X, Y, n_h = 4, num_iterations = 10000, print_cost=True)
# Plot the decision boundary
plot_decision_boundary(lambda x: predict(parameters, x.T), X, Y)
plt.title("Decision Boundary for hidden layer size " + str(4)) | Cost after iteration 0: 0.693048
Cost after iteration 1000: 0.288083
Cost after iteration 2000: 0.254385
Cost after iteration 3000: 0.233864
Cost after iteration 4000: 0.226792
Cost after iteration 5000: 0.222644
Cost after iteration 6000: 0.219731
Cost after iteration 7000: 0.217504
Cost after iteration 8000: 0.219471... | MIT | neural_networks_and_deep_learning/Week 3/Planar data classification with one hidden layer/Planar_data_classification_with_onehidden_layer_v6b.ipynb | shengfeng/coursera_deep_learning |
**Expected Output**: **Cost after iteration 9000** 0.218607 | # Print accuracy
predictions = predict(parameters, X)
print ('Accuracy: %d' % float((np.dot(Y,predictions.T) + np.dot(1-Y,1-predictions.T))/float(Y.size)*100) + '%') | Accuracy: 90%
| MIT | neural_networks_and_deep_learning/Week 3/Planar data classification with one hidden layer/Planar_data_classification_with_onehidden_layer_v6b.ipynb | shengfeng/coursera_deep_learning |
**Expected Output**: **Accuracy** 90% Accuracy is really high compared to Logistic Regression. The model has learnt the leaf patterns of the flower! Neural networks are able to learn even highly non-linear decision boundaries, unlike logistic regression. Now, let's try out several hidden layer sizes. 4.6... | # This may take about 2 minutes to run
plt.figure(figsize=(16, 32))
hidden_layer_sizes = [1, 2, 3, 4, 5, 20, 50]
for i, n_h in enumerate(hidden_layer_sizes):
plt.subplot(5, 2, i+1)
plt.title('Hidden Layer of size %d' % n_h)
parameters = nn_model(X, Y, n_h, num_iterations = 5000)
plot_decision_boundary(... | Accuracy for 1 hidden units: 67.5 %
Accuracy for 2 hidden units: 67.25 %
Accuracy for 3 hidden units: 90.75 %
Accuracy for 4 hidden units: 90.5 %
Accuracy for 5 hidden units: 91.25 %
Accuracy for 20 hidden units: 90.0 %
Accuracy for 50 hidden units: 90.25 %
| MIT | neural_networks_and_deep_learning/Week 3/Planar data classification with one hidden layer/Planar_data_classification_with_onehidden_layer_v6b.ipynb | shengfeng/coursera_deep_learning |
**Interpretation**:- The larger models (with more hidden units) are able to fit the training set better, until eventually the largest models overfit the data. - The best hidden layer size seems to be around n_h = 5. Indeed, a value around here seems to fits the data well without also incurring noticeable overfitting.-... | # Datasets
noisy_circles, noisy_moons, blobs, gaussian_quantiles, no_structure = load_extra_datasets()
datasets = {"noisy_circles": noisy_circles,
"noisy_moons": noisy_moons,
"blobs": blobs,
"gaussian_quantiles": gaussian_quantiles}
### START CODE HERE ### (choose your dataset)
dat... | _____no_output_____ | MIT | neural_networks_and_deep_learning/Week 3/Planar data classification with one hidden layer/Planar_data_classification_with_onehidden_layer_v6b.ipynb | shengfeng/coursera_deep_learning |
I get the data | server = ECMWFDataServer(url = "https://api.ecmwf.int/v1",
key = "XXXXXXXXXXXXXXXX",
email = "Sylvie.Lamy-Thepaut@ecmwf.int")
request = {
"dataset": "geff_reanalysis",
"date": "2016-12-01/to/2016-12-31",
"origin": "fwis",
"param": "fwi",
"step": "00",
"t... | _____no_output_____ | ECL-2.0 | notebook/GEFF Access.ipynb | EduardRosert/magics |
__Standardize timestamps__ | #temp = pd.DatetimeIndex(articles['timeStamp']) # Gather all datetime objects
#articles['date'] = temp.date # Pull out the date from the datetime objects and assign to Date column
#articles['time'] = temp.time # Pull out the time from the datetime objects and assign to Time column
pr... | _____no_output_____ | MIT | past-team-code/Fall2018Team1/News Articles Data/1119_article_and_bitcoin.ipynb | shun-lin/project-paradigm-chatbot |
__Preprocess text for NLP formulations__ | articles.head()
#Clean the articles - Remove stopwords, remove punctuation, all lowercase
import re
for i in articles.index:
text = articles.loc[i, 'contents']
if pd.isnull(text):
pass
else:
text = re.sub(r"[^a-zA-Z]", " ", text)
text = [word for word in text.split() if not word in e... | _____no_output_____ | MIT | past-team-code/Fall2018Team1/News Articles Data/1119_article_and_bitcoin.ipynb | shun-lin/project-paradigm-chatbot |
__Combine cleaned articles with "Markers" from Time Series event detection__ | df=articles
df.to_csv("1119_article_data_and_price_labeled_publisher.csv") | _____no_output_____ | MIT | past-team-code/Fall2018Team1/News Articles Data/1119_article_and_bitcoin.ipynb | shun-lin/project-paradigm-chatbot |
2D Numpy in Python Welcome! This notebook will teach you about using Numpy in the Python Programming Language. By the end of this lab, you'll know what Numpy is and the Numpy operations. Table of Contents Create a 2D Numpy Array Accessing different elements of a Numpy Array Basic Operation... | # Import the libraries
import numpy as np
import matplotlib.pyplot as plt | _____no_output_____ | MIT | Python for Data Science and AI/w5/PY0101EN-5-2-Numpy2D.ipynb | Carlosriosch/IBM-Data-Science |
Consider the list a, the list contains three nested lists **each of equal size**. | # Create a list
a = [[11, 12, 13], [21, 22, 23], [31, 32, 33]]
a | _____no_output_____ | MIT | Python for Data Science and AI/w5/PY0101EN-5-2-Numpy2D.ipynb | Carlosriosch/IBM-Data-Science |
We can cast the list to a Numpy Array as follow | # Convert list to Numpy Array
# Every element is the same type
A = np.array(a)
A | _____no_output_____ | MIT | Python for Data Science and AI/w5/PY0101EN-5-2-Numpy2D.ipynb | Carlosriosch/IBM-Data-Science |
We can use the attribute ndim to obtain the number of axes or dimensions referred to as the rank. | # Show the numpy array dimensions
A.ndim | _____no_output_____ | MIT | Python for Data Science and AI/w5/PY0101EN-5-2-Numpy2D.ipynb | Carlosriosch/IBM-Data-Science |
Attribute shape returns a tuple corresponding to the size or number of each dimension. | # Show the numpy array shape
A.shape | _____no_output_____ | MIT | Python for Data Science and AI/w5/PY0101EN-5-2-Numpy2D.ipynb | Carlosriosch/IBM-Data-Science |
The total number of elements in the array is given by the attribute size. | # Show the numpy array size
A.size | _____no_output_____ | MIT | Python for Data Science and AI/w5/PY0101EN-5-2-Numpy2D.ipynb | Carlosriosch/IBM-Data-Science |
Accessing different elements of a Numpy Array We can use rectangular brackets to access the different elements of the array. The correspondence between the rectangular brackets and the list and the rectangular representation is shown in the following figure for a 3x3 array: We can access the 2nd-row 3rd column as s... | # Access the element on the second row and third column
A[1, 2] | _____no_output_____ | MIT | Python for Data Science and AI/w5/PY0101EN-5-2-Numpy2D.ipynb | Carlosriosch/IBM-Data-Science |
We can also use the following notation to obtain the elements: | # Access the element on the second row and third column
A[1][2] | _____no_output_____ | MIT | Python for Data Science and AI/w5/PY0101EN-5-2-Numpy2D.ipynb | Carlosriosch/IBM-Data-Science |
Consider the elements shown in the following figure We can access the element as follows | # Access the element on the first row and first column
A[0][0] | _____no_output_____ | MIT | Python for Data Science and AI/w5/PY0101EN-5-2-Numpy2D.ipynb | Carlosriosch/IBM-Data-Science |
We can also use slicing in numpy arrays. Consider the following figure. We would like to obtain the first two columns in the first row This can be done with the following syntax | # Access the element on the first row and first and second columns
A[0][0:2] | _____no_output_____ | MIT | Python for Data Science and AI/w5/PY0101EN-5-2-Numpy2D.ipynb | Carlosriosch/IBM-Data-Science |
Similarly, we can obtain the first two rows of the 3rd column as follows: | # Access the element on the first and second rows and third column
A[0:2, 2] | _____no_output_____ | MIT | Python for Data Science and AI/w5/PY0101EN-5-2-Numpy2D.ipynb | Carlosriosch/IBM-Data-Science |
Corresponding to the following figure: Basic Operations We can also add arrays. The process is identical to matrix addition. Matrix addition of X and Y is shown in the following figure: The numpy array is given by X and Y | # Create a numpy array X
X = np.array([[1, 0], [0, 1]])
X
# Create a numpy array Y
Y = np.array([[2, 1], [1, 2]])
Y | _____no_output_____ | MIT | Python for Data Science and AI/w5/PY0101EN-5-2-Numpy2D.ipynb | Carlosriosch/IBM-Data-Science |
We can add the numpy arrays as follows. | # Add X and Y
Z = X + Y
Z | _____no_output_____ | MIT | Python for Data Science and AI/w5/PY0101EN-5-2-Numpy2D.ipynb | Carlosriosch/IBM-Data-Science |
Multiplying a numpy array by a scaler is identical to multiplying a matrix by a scaler. If we multiply the matrix Y by the scaler 2, we simply multiply every element in the matrix by 2 as shown in the figure. We can perform the same operation in numpy as follows | # Create a numpy array Y
Y = np.array([[2, 1], [1, 2]])
Y
# Multiply Y with 2
Z = 2 * Y
Z | _____no_output_____ | MIT | Python for Data Science and AI/w5/PY0101EN-5-2-Numpy2D.ipynb | Carlosriosch/IBM-Data-Science |
Multiplication of two arrays corresponds to an element-wise product or Hadamard product. Consider matrix X and Y. The Hadamard product corresponds to multiplying each of the elements in the same position, i.e. multiplying elements contained in the same color boxes together. The result is a new matrix that is the same s... | # Create a numpy array Y
Y = np.array([[2, 1], [1, 2]])
Y
# Create a numpy array X
X = np.array([[1, 0], [0, 1]])
X
# Multiply X with Y
Z = X * Y
Z | _____no_output_____ | MIT | Python for Data Science and AI/w5/PY0101EN-5-2-Numpy2D.ipynb | Carlosriosch/IBM-Data-Science |
We can also perform matrix multiplication with the numpy arrays A and B as follows: First, we define matrix A and B: | # Create a matrix A
A = np.array([[0, 1, 1], [1, 0, 1]])
A
# Create a matrix B
B = np.array([[1, 1], [1, 1], [-1, 1]])
B | _____no_output_____ | MIT | Python for Data Science and AI/w5/PY0101EN-5-2-Numpy2D.ipynb | Carlosriosch/IBM-Data-Science |
We use the numpy function dot to multiply the arrays together. | # Calculate the dot product
Z = np.dot(A,B)
Z
# Calculate the sine of Z
np.sin(Z) | _____no_output_____ | MIT | Python for Data Science and AI/w5/PY0101EN-5-2-Numpy2D.ipynb | Carlosriosch/IBM-Data-Science |
We use the numpy attribute T to calculate the transposed matrix | # Create a matrix C
C = np.array([[1,1],[2,2],[3,3]])
C
# Get the transposed of C
C.T | _____no_output_____ | MIT | Python for Data Science and AI/w5/PY0101EN-5-2-Numpy2D.ipynb | Carlosriosch/IBM-Data-Science |
Hill-Langmuir Bayesian Regression Goals similar to: https://www.ncbi.nlm.nih.gov/pmc/articles/PMC3773943/pdf/nihms187302.pdf However, they use a different paramerization that does not include Emax Bayesian Hill Model Regression The Hill model is defined as: $$ F(c, E_{max}, E_0, EC_{50}, H) = E_0 + \frac{E_{max} - E_... | # https://ipywidgets.readthedocs.io/en/latest/examples/Using%20Interact.html
def f(E0=2.5, Emax=0, log_EC50=-2, H=1):
EC50 = 10**log_EC50
plt.figure(2, figsize=(10,5))
xx = np.logspace(-4, 1, 100)
yy = E0 + (Emax - E0)/(1+(EC50/xx)**H)
plt.plot(np.log10(xx),yy, 'r-')
plt.ylim(-0.2, 3)
... | _____no_output_____ | MIT | Trematinib-Combo-CI/python/Hill-Equation-Bayesian-Regression.ipynb | nathanieljevans/HNSCC_functional_data_pipeline |
Define Model + Guide | class plotter:
def __init__(self, params, figsize=(20,10), subplots = (2,7)):
'''
'''
assert len(params) <= subplots[0]*subplots[1], 'wrong number of subplots for given params to report'
self.fig, self.axes = plt.subplots(*subplots,figsize=figsize, sharex='col', sharey='row')
... | _____no_output_____ | MIT | Trematinib-Combo-CI/python/Hill-Equation-Bayesian-Regression.ipynb | nathanieljevans/HNSCC_functional_data_pipeline |
choosing priors $E_0$The upper bound or maximum value of our function, $E_0$ should be centered at 1, although it's possible to be a little above or below that, we'll model this with a Normal distribution and a fairly tight variance around 1. $$ E_0 \propto N(1, \sigma_{E_0}) $$ $E_{max}$ $E_{max}$ is the lower boun... | def f(E0_std):
plt.figure(2)
xx = np.linspace(-2, 4, 50)
rv = norm(1, E0_std)
yy = rv.pdf(xx)
plt.ylim(0,1)
plt.title('E0 parameter')
plt.xlabel('E0')
plt.ylabel('probability')
plt.plot(xx, yy, 'r-')
plt.show()
interactive_plot = interactive(f, E0_std=(0.1,4,0.1))
outp... | _____no_output_____ | MIT | Trematinib-Combo-CI/python/Hill-Equation-Bayesian-Regression.ipynb | nathanieljevans/HNSCC_functional_data_pipeline |
Expecation, Variance to Alpha,Beta for Gamma | def gamma_modes_to_params(E, S):
'''
'''
beta = E/S
alpha = E**2/S
return alpha, beta
| _____no_output_____ | MIT | Trematinib-Combo-CI/python/Hill-Equation-Bayesian-Regression.ipynb | nathanieljevans/HNSCC_functional_data_pipeline |
Emax Prior | # TODO: Have inputs be E[] and Var[] rather than a,b... more useful for setting up priors.
def f(emax_mean=1, emax_var=3):
a_emax, b_emax = gamma_modes_to_params(emax_mean, emax_var)
plt.figure(2)
xx = np.linspace(0, 1.2, 100)
rv = gamma(a_emax, scale=1/b_emax, loc=0)
yy = rv.pdf(xx)... | _____no_output_____ | MIT | Trematinib-Combo-CI/python/Hill-Equation-Bayesian-Regression.ipynb | nathanieljevans/HNSCC_functional_data_pipeline |
Define Priors | ############ PRIORS ###############
E0_std = 0.05
# uniform
# 50,100 -> example if we have strong support for Emax around 0.5
a_emax = 50. #2.
b_emax = 100. #8.
# H gamma prior
alpha_H = 1
beta_H = 1
#EC50
# this is in logspace, so in uM -> 10**mu_ec50
mu_ec50 = -2.
std_ec50 = 3.
# obs error
a_obs = 1
b_obs = 1... | _____no_output_____ | MIT | Trematinib-Combo-CI/python/Hill-Equation-Bayesian-Regression.ipynb | nathanieljevans/HNSCC_functional_data_pipeline |
Define DataWe'll use fake data for now. | Y = torch.tensor([1., 1., 1., 0.9, 0.7, 0.6, 0.5], dtype=torch.float)
X = torch.tensor([10./3**i for i in range(7)][::-1], dtype=torch.float).unsqueeze(-1) | _____no_output_____ | MIT | Trematinib-Combo-CI/python/Hill-Equation-Bayesian-Regression.ipynb | nathanieljevans/HNSCC_functional_data_pipeline |
Fit model with MCMChttps://forum.pyro.ai/t/need-help-with-very-simple-model/600https://pyro.ai/examples/bayesian_regression_ii.html | torch.manual_seed(99999)
nuts_kernel = NUTS(model, adapt_step_size=True)
mcmc_run = MCMC(nuts_kernel, num_samples=400, warmup_steps=100, num_chains=1)
mcmc_run.run(X,Y) | Sample: 100%|██████████| 500/500 [00:32, 15.43it/s, step size=2.56e-01, acc. prob=0.949]
| MIT | Trematinib-Combo-CI/python/Hill-Equation-Bayesian-Regression.ipynb | nathanieljevans/HNSCC_functional_data_pipeline |
visualize results | samples = {k: v.detach().cpu().numpy() for k, v in mcmc_run.get_samples().items()}
f, axes = plt.subplots(3,2, figsize=(10,5))
for ax, key in zip(axes.flat, samples.keys()):
ax.set_title(key)
ax.hist(samples[key], bins=np.linspace(min(samples[key]), max(samples[key]), 50), density=True)
ax.set_xlabe... | _____no_output_____ | MIT | Trematinib-Combo-CI/python/Hill-Equation-Bayesian-Regression.ipynb | nathanieljevans/HNSCC_functional_data_pipeline |
plot fitted hill f-n | plt.figure(figsize=(7,7))
xx = np.logspace(-7, 6, 200)
for i,s in pd.DataFrame(samples).iterrows():
yy = s.E0 + (s.Emax - s.E0)/(1+(10**s.log_EC50/xx)**s.H)
plt.plot(np.log10(xx), yy, 'ro', alpha=0.01)
plt.plot(np.log10(X), Y, 'b.', label='data')
plt.xlabel('log10 Concentration')
plt.ylabel('cell_v... | _____no_output_____ | MIT | Trematinib-Combo-CI/python/Hill-Equation-Bayesian-Regression.ipynb | nathanieljevans/HNSCC_functional_data_pipeline |
Deprecated EC50 example - gamma in concentration space | def f(alpha_ec50=1, beta_ec50=0.5):
f, axes = plt.subplots(1,2,figsize=(8,4))
xx = np.logspace(-5, 2, 100)
g = gamma(alpha_ec50, scale=1/beta_ec50, loc=0)
yy = g.pdf(xx)
g_samples = g.rvs(1000)
axes[0].plot(xx,yy, 'r-')
axes[1].plot(np.log10(xx), yy, 'b-')
plt.tight_l... | _____no_output_____ | MIT | Trematinib-Combo-CI/python/Hill-Equation-Bayesian-Regression.ipynb | nathanieljevans/HNSCC_functional_data_pipeline |
Fit Model with `stochastic variational inference` | adam = optim.Adam({"lr": 1e-1})
svi = SVI(model, guide, adam, loss=Trace_ELBO())
tic = time.time()
STEPS = 2500
pyro.clear_param_store()
myplotter = plotter(['_alpha_H', '_beta_H', '_a_emax', '_b_emax', '_a_obs', '_b_obs', '_mu_ec50', '_std_ec50'], figsize=(12, 8), subplots=(2,5))
_losses = []
last=0
loss = 0
n = 10... | _____no_output_____ | MIT | Trematinib-Combo-CI/python/Hill-Equation-Bayesian-Regression.ipynb | nathanieljevans/HNSCC_functional_data_pipeline |
ライブラリのインポートとバージョン表示 | import pandas as pd
import numpy as np
import cesiumpy
cesiumpy.__version__ | _____no_output_____ | Apache-2.0 | Cesium_Advent_Calendar_3rd.ipynb | tkama/hello_cesiumpy |
CSVファイルの読み込み | filename = '07hoikuennyoutien-asakashi_utf8.csv'
df = pd.read_csv( filename ) | _____no_output_____ | Apache-2.0 | Cesium_Advent_Calendar_3rd.ipynb | tkama/hello_cesiumpy |
バブルチャートの表示 | v = cesiumpy.Viewer()
for i, row in df.iterrows():
l = row['施設_収容人数[総定員]人数']
p = cesiumpy.Point(position=[row['施設_経度'], row['施設_緯度'], 0]
, pixelSize=l/5, color='blue')
v.entities.add(p)
v | _____no_output_____ | Apache-2.0 | Cesium_Advent_Calendar_3rd.ipynb | tkama/hello_cesiumpy |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.