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 |
|---|---|---|---|---|---|
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 | M6_Python_for_Data_Science_AI_Development/Week4/files/PY0101EN-5-2-Numpy2D.ipynb | cmaroblesg/IBM_DevOps-_and_Software_Engineering |
Quiz on 2D Numpy Array Consider the following list a, convert it to Numpy Array. | # Write your code below and press Shift+Enter to execute
a = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]] | _____no_output_____ | MIT | M6_Python_for_Data_Science_AI_Development/Week4/files/PY0101EN-5-2-Numpy2D.ipynb | cmaroblesg/IBM_DevOps-_and_Software_Engineering |
Click here for the solution```pythonA = np.array(a)A``` Calculate the numpy array size. | # Write your code below and press Shift+Enter to execute
| _____no_output_____ | MIT | M6_Python_for_Data_Science_AI_Development/Week4/files/PY0101EN-5-2-Numpy2D.ipynb | cmaroblesg/IBM_DevOps-_and_Software_Engineering |
Click here for the solution```pythonA.size``` Access the element on the first row and first and second columns. | # Write your code below and press Shift+Enter to execute
| _____no_output_____ | MIT | M6_Python_for_Data_Science_AI_Development/Week4/files/PY0101EN-5-2-Numpy2D.ipynb | cmaroblesg/IBM_DevOps-_and_Software_Engineering |
Click here for the solution```pythonA[0][0:2]``` Perform matrix multiplication with the numpy arrays A and B. | # Write your code below and press Shift+Enter to execute
B = np.array([[0, 1], [1, 0], [1, 1], [-1, 0]]) | _____no_output_____ | MIT | M6_Python_for_Data_Science_AI_Development/Week4/files/PY0101EN-5-2-Numpy2D.ipynb | cmaroblesg/IBM_DevOps-_and_Software_Engineering |
Plotting and Functions This notebook will work trough how to plot data and how to define functions. Throughout the lecture we will take a few moments to plot different functions and see how they depend on their parameters Plotting in Python: Matplot | import matplotlib.pyplot as plt
import numpy as np
import scipy as sp | _____no_output_____ | MIT | 9-19-2019 - Lecture Notebook.ipynb | sju-chem264-2019/9-19-2019-lecture-deannapatti |
Pyplot is a powerful plotting library that can be used to make publication quaility plots. It is also useful for quikly plotting the results of a calcualtion. This is a quick demonstration of its useNote: when you call al library `import matplotlib.pyplot as plt` the way that use it is to do the following `plt.function... | # Define x and y values for some function
x = [i for i in range(20)]
y1 = [i**2 for i in x]
y2 = [i**3 for i in x] | _____no_output_____ | MIT | 9-19-2019 - Lecture Notebook.ipynb | sju-chem264-2019/9-19-2019-lecture-deannapatti |
The methods used above to make the lists is considered very *pythonic*. It works the same as a loop, but outputs all the results into a list. The left-hand most argument is what the list elements will be and the right hand side is the the way the loop will work. When you use pyplot to make a plot, you can add more than... | plt.plot(x,y1)
plt.plot(x,y2)
plt.xlabel('X', fontsize=24)
plt.ylabel('Y', fontsize=24)
plt.legend(['Quadratic', 'Cubic'], loc=0)
plt.show() | _____no_output_____ | MIT | 9-19-2019 - Lecture Notebook.ipynb | sju-chem264-2019/9-19-2019-lecture-deannapatti |
We can call also use numpy fucntions to make our plots. Numpy is a very powerful math library | # linspace will make a list of values from initial to final with however many increments you want
# this example goes from 0-2.5 with 20 increments
x=numpy.linspace(0,1.0,20)
print(x)
exp_func=np.exp(-2*np.pi*x)
print(exp_func)
plt.plot(x,exp_func, color="black")
plt.xlabel('x', fontsize=24)
plt.ylabel("y(x)", fontsize... | _____no_output_____ | MIT | 9-19-2019 - Lecture Notebook.ipynb | sju-chem264-2019/9-19-2019-lecture-deannapatti |
All aspects of the plot can be changed. The best way to figure out what you want to do is to go to the Matplotlib gallery and choose an image that looks like what you are trying to do.https://matplotlib.org/gallery/index.html Example: Scatter plot with histograms | import numpy as np
#Fixing random state for reproducibility
np.random.seed(19680801)
# the random data
x = np.random.randn(1000)
y = np.random.randn(1000)
# definitions for the axes
left, width = 0.1, 0.65
bottom, height = 0.1, 0.65
spacing = 0.005
rect_scatter = [left, bottom, width, height]
rect_histx = [left, b... | _____no_output_____ | MIT | 9-19-2019 - Lecture Notebook.ipynb | sju-chem264-2019/9-19-2019-lecture-deannapatti |
I don't have to be an expert in making that kind of plot. I just have to understand and guess enough to figure out. I also google things I don't knowhttps://www.google.com/search?client=firefox-b-1-d&q=pyplot+histogram+change+colorhttps://stackoverflow.com/questions/42172440/python-matplotlib-histogram-color?rq=1https:... | #Fixing random state for reproducibility
np.random.seed(19680801)
# the random data
x = np.random.randn(1000)
y = np.random.randn(1000)
# definitions for the axes
left, width = 0.1, 0.65
bottom, height = 0.1, 0.65
spacing = 0.005
rect_scatter = [left, bottom, width, height]
rect_histx = [left, bottom + height + spa... | _____no_output_____ | MIT | 9-19-2019 - Lecture Notebook.ipynb | sju-chem264-2019/9-19-2019-lecture-deannapatti |
Notice how I changed the colors on the plot based off of what I found on the stack exchange. The way to solve issues in the course and computational work is to google them. Plotting Exersice 1 Find a plot from the gallery that you like. Then make some sort of noticable change to it. | import numpy as np
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
points = np.ones(5) # Draw 5 points for each line
marker_style = dict(color='tab:blue', linestyle=':', marker='o',
markersize=15, markerfacecoloralt='tab:red')
fig, ax = plt.subplots()
# Plot all fill styles.... | _____no_output_____ | MIT | 9-19-2019 - Lecture Notebook.ipynb | sju-chem264-2019/9-19-2019-lecture-deannapatti |
Plotting Exersice 2 Plot a the following functions on the same plot from $ -2\pi $ to $2\pi$$$ \sin(2\pi x+\pi)$$$$ \cos(2\pi x+\pi)$$$$\sin(2\pi x+\pi)+\cos(2\pi x+\pi)$$ This might be useful:https://docs.scipy.org/doc/numpy/reference/generated/numpy.sin.htmlhttps://docs.scipy.org/doc/numpy/reference/generated/numpy.... | np.sin(np.pi/2.)
np.sin(np.array((0., 30., 45., 60., 90.)) * np.pi / 180. )
import matplotlib.pylab as plt
x = np.linspace(-np.pi, np.pi, 201)
plt.plot(x, np.sin(x))
plt.xlabel('Angle [rad]')
plt.ylabel('sin(x)')
plt.axis('tight')
plt.show()
import matplotlib.pylab as plt
x = np.linspace(-2*np.pi, 2*np.pi, 201)
plt.p... | _____no_output_____ | MIT | 9-19-2019 - Lecture Notebook.ipynb | sju-chem264-2019/9-19-2019-lecture-deannapatti |
Lecture plots Periodically during lecture we will take a pause to plot some of the interesting functions that we use in class. Classical wavefunctionsThe following plot shows the the spacial component of the standard wavefunction with a wavelength of $\lambda=\text{1.45 m}$ and a relative amplitude of $A=1$ when the ... | x=np.linspace(0,3.0,100)
sinx=np.sin(2*np.pi*x+0+1)
plt.plot(x,sinx, color="black")
plt.xlabel('x', fontsize=24)
plt.ylabel("y(x)", fontsize=24)
plt.show() | _____no_output_____ | MIT | 9-19-2019 - Lecture Notebook.ipynb | sju-chem264-2019/9-19-2019-lecture-deannapatti |
Make a new figure where you plot the same wave function at three time points in the future. Assume the frequency is $\nu=.1 \text{ ms / s} $ Use a different color for each plot Orthogonality Graphically show that the the following two functions are orthogonal on the interval $-3\pi$ to $3\pi$$$ \sin(x) \text{ and } \c... | import matplotlib.pylab as plt
x = np.linspace(-3*np.pi, 3*np.pi, 201)
plt.plot(x, np.sin(x))
plt.xlabel('Angle [rad]')
plt.ylabel('sin(x)')
plt.axis('tight')
plt.show()
import matplotlib.pylab as plt
x = np.linspace(-3*np.pi, 3*np.pi, 201)
plt.plot(x, np.sin(x))
plt.plot(x, np.cos(3*x))
plt.xlabel('Angle [rad]')
plt.y... | _____no_output_____ | MIT | 9-19-2019 - Lecture Notebook.ipynb | sju-chem264-2019/9-19-2019-lecture-deannapatti |
Use the numpy trapezoid rule integrator to show the the two functions are orthogonal`np.trapz(y,x)`https://docs.scipy.org/doc/numpy/reference/generated/numpy.trapz.html | # Example code
x=numpy.linspace(0,1.0,20)
exp_func=np.exp(-2*np.pi*x)
np.trapz(exp_func,x)
# Your code here | _____no_output_____ | MIT | 9-19-2019 - Lecture Notebook.ipynb | sju-chem264-2019/9-19-2019-lecture-deannapatti |
Approach | params, data = sio.read_dat(AFM_FOLDER6 + "HistoryData001.dat")
amplitude = data["Amplitude (m)"].values
fig, ax = plt.subplots()
ax.plot(amplitude*1e9)
ax.set_ylabel("Amplitude (nm)")
ax.set_xlabel("Time (a.u.)")
#plt.savefig("snap.jpg", dpi=600) | _____no_output_____ | MIT | notebooks/20200818_Akiyama_AFM.ipynb | dineshpinto/qudiamond-analysis |
20200721_Akiyama_AFM | params, data = sio.read_dat(AFM_FOLDER1 + "frq-sweep002.dat")
freq_shift = data["Frequency Shift (Hz)"].values
amplitude = data["Amplitude (m)"].values
phase = data["Phase (deg)"].values
amp_freq_sweep = sft.fit_fano(freq_shift, amplitude, linear_offset=True)
phase_freq_sweep = sft.fit_fano(freq_shift, phase)
%matplotl... | _____no_output_____ | MIT | notebooks/20200818_Akiyama_AFM.ipynb | dineshpinto/qudiamond-analysis |
Quality factor can be calculated as $ Q = \frac{f_R}{\Delta f} $ | print(f'Q-factor= {params["f_res (Hz)"] / amp_freq_sweep.params["fwhm"].value}') | _____no_output_____ | MIT | notebooks/20200818_Akiyama_AFM.ipynb | dineshpinto/qudiamond-analysis |
20200818_Akiyama_AFM | params, data = sio.read_dat(AFM_FOLDER + "frq-sweep001.dat")
#pprint(params, sort_dicts=False)
freq_shift = data["Frequency Shift (Hz)"]
amplitude = data["Amplitude (m)"]
phase = data["Phase (deg)"]
fano = sft.fit_fano(freq_shift, amplitude)
lorentzian = sft.fit_fano(freq_shift, phase)
params | _____no_output_____ | MIT | notebooks/20200818_Akiyama_AFM.ipynb | dineshpinto/qudiamond-analysis |
Equations for calculating Q factor$$ Q = \frac{f_R}{\Delta f} $$$$ Q = \frac{A(\omega_0)}{A_{in}} $$ | f_res = 44379.7064
sigma = 62.2841355
print(f_res/sigma)
A_drive = 50e-3
A_res = 28.3e-6 * 1 / 500e-6
print(A_res/A_drive)
# Calibration
A_drive = 50e-3
osc_amp = 50e-9
print(osc_amp/A_drive) | 712.5362830154398
1.132
1e-06
| MIT | notebooks/20200818_Akiyama_AFM.ipynb | dineshpinto/qudiamond-analysis |
Plot frequency sweep curves | fig, (ax1, ax2) = plt.subplots(nrows=2, sharex=True)
ax1.plot(freq_shift, amplitude)
ax1.plot(freq_shift, fano.best_fit)
ax1.set_ylabel(data.columns[2])
ax2.plot(freq_shift, phase)
ax2.plot(freq_shift, lorentzian.best_fit)
ax2.set_ylabel(data.columns[3])
ax2.set_xlabel(data.columns[1]) | _____no_output_____ | MIT | notebooks/20200818_Akiyama_AFM.ipynb | dineshpinto/qudiamond-analysis |
Extract fit values | print("{} = {:.1f} +- {:.1f}".format(fano.params["sigma"].name, fano.params["sigma"].value, fano.params["sigma"].stderr))
print("{} = {:.2e} +- {:.0e}".format(fano.params["amplitude"].name, fano.params["amplitude"].value, fano.params["amplitude"].stderr)) | _____no_output_____ | MIT | notebooks/20200818_Akiyama_AFM.ipynb | dineshpinto/qudiamond-analysis |
20200824_Akiyama_AFM Automatically read files from diskReads all files stored in **AFM_FOLDER2 = "20200824_Akiyama_AFM/"** and plots the amplitude and phase data.Optionally, the data can be fit to Fano resonances by setting the variable```pythonfit = True```The Q-factor is calculated as:$$ Q = \frac{f_R}{\Delta f} = \... | %matplotlib inline
fit = False # Setting to True will take slightly longer due to the fitting protocols
files = []
for file in os.listdir(AFM_FOLDER2):
if file.endswith(".dat"):
files.append(file)
fig, ax = plt.subplots(nrows=len(files), ncols=2)
for idx, file in enumerate(files):
params, data =... | _____no_output_____ | MIT | notebooks/20200818_Akiyama_AFM.ipynb | dineshpinto/qudiamond-analysis |
20200826_TFSC_Preamp_AFM 11613_Tip_5 | %matplotlib inline
fit = False # Setting to True will take slightly longer due to the fitting protocols
files = []
for file in os.listdir(AFM_FOLDER4):
if file.endswith(".dat"):
files.append(file)
fig, ax = plt.subplots(nrows=len(files), ncols=2)
for idx, file in enumerate(files):
params, data =... | _____no_output_____ | MIT | notebooks/20200818_Akiyama_AFM.ipynb | dineshpinto/qudiamond-analysis |
Calibration from Thermal Noise densityFrom Atomic Force Microscopy, Second Edition by Bert VoigtländerSection 11.6.5 Experimental Determination of the Sensitivity and Spring Constant in AFM Without Tip-Sample ContactEq. 11.28 and 11.26 | %matplotlib widget
file = "SignalAnalyzer_Spectrum001"
params, data = sio.read_dat(AFM_FOLDER4 + file)
calibration_params = sft.find_afm_calibration_parameters(data, frequency_range=[40000, 48000], Q=1000, f_0_guess=44000)
fig, ax = plt.subplots()
ax.plot(calibration_params["Frequency (Hz)"], calibration_params["PSD s... | _____no_output_____ | MIT | notebooks/20200818_Akiyama_AFM.ipynb | dineshpinto/qudiamond-analysis |
import matplotlib.pyplot as plt
import numpy as np
import os
import tensorflow as tf
from tensorflow.keras.preprocessing import image_dataset_from_directory
_URL = 'https://storage.googleapis.com/mledu-datasets/cats_and_dogs_filtered.zip'
path_to_zip = tf.keras.utils.get_file('cats_and_dogs.zip', origin=_URL, extract=... | _____no_output_____ | MIT | cat_vs_dog_0_0_2.ipynb | yarusx/cat_vs_dogo | |
Download Latest Data | data_dir = "/Users/dhruvbalwada/work_root/sogos/data/raw/climatology/" | _____no_output_____ | MIT | notebooks/0.0_db_RG_climatology.ipynb | dhruvbalwada/sogos |
FTP ADDRESS: ftp://kakapo.ucsd.edu/pub/gilson/argo_climatology/ Data prior to 2017 (till Dec 2016) is in a single file | # download the big climatology files
wget.download(
"ftp://kakapo.ucsd.edu/pub/gilson/argo_climatology/RG_ArgoClim_Salinity_2017.nc.gz",
data_dir,
)
wget.download(
"ftp://kakapo.ucsd.edu/pub/gilson/argo_climatology/RG_ArgoClim_Temperature_2017.nc.gz",
data_dir,
)
from ftplib import FTP
ftp_address = "ft... | DownloadingRG_ArgoClim_201701.nc.gz
DownloadingRG_ArgoClim_201702.nc.gz
DownloadingRG_ArgoClim_201703.nc.gz
DownloadingRG_ArgoClim_201704.nc.gz
DownloadingRG_ArgoClim_201705.nc.gz
DownloadingRG_ArgoClim_201706.nc.gz
DownloadingRG_ArgoClim_201707.nc.gz
DownloadingRG_ArgoClim_201708.nc.gz
DownloadingRG_ArgoClim_201709.nc... | MIT | notebooks/0.0_db_RG_climatology.ipynb | dhruvbalwada/sogos |
Load some data | Tclim = xr.open_dataset(data_dir + "RG_ArgoClim_Temperature_2017.nc", decode_times=False)
Sclim = xr.open_dataset(data_dir + "RG_ArgoClim_Salinity_2017.nc", decode_times=False)
Climextra = xr.open_mfdataset(data_dir+ 'RG_ArgoClim_201*', decode_times=False)
RG_clim = xr.merge([Tclim, Sclim, Climextra])
# Calendar type w... | /Users/dhruvbalwada/code/miniconda/envs/sogos/lib/python3.7/site-packages/dask/array/numpy_compat.py:40: RuntimeWarning: divide by zero encountered in true_divide
x = np.divide(x1, x2, out)
/Users/dhruvbalwada/code/miniconda/envs/sogos/lib/python3.7/site-packages/dask/array/numpy_compat.py:40: RuntimeWarning: invalid... | MIT | notebooks/0.0_db_RG_climatology.ipynb | dhruvbalwada/sogos |
Some Climatological Mean Sections | dens_section30 = RG_clim.SIGMA0.sel(LONGITUDE=30, method='nearest').sel(LATITUDE=slice(-70,-40)).load()
dens_section40 = RG_clim.SIGMA0.sel(LONGITUDE=40, method='nearest').sel(LATITUDE=slice(-70,-40)).load()
glider = {"start_month": 4.99, "end_month":7.8, "start_lat": -51.5, "end_lat": -53, "max_depth": 1000}
plt.figu... | _____no_output_____ | MIT | notebooks/0.0_db_RG_climatology.ipynb | dhruvbalwada/sogos |
N2\begin{equation}N^2 = db/dz\end{equation}$b = -\frac{g}{\rho_0} \rho'$$b = g(\alpha \triangle T - \beta \triangle S)$ | RG_clim
RG_clim = generate_grid_ds(RG_clim,
{'Z':'PRESSURE', 'X':'LONGITUDE', 'Y':'LATITUDE'})
grid = Grid(RG_clim, periodic='X')
g = 9.81
rho0 = 1000
dens_clim_monthly = RG_clim.SIGMA0.groupby('TIME.month').mean()
dens_clim_monthly
N2_clim_monthly = grid.interp(-g/rho0* grid.diff(dens_clim_monthly, 'Z', bound... | /Users/dhruvbalwada/code/miniconda/envs/sogos/lib/python3.7/site-packages/dask/core.py:119: RuntimeWarning: divide by zero encountered in true_divide
return func(*args2)
/Users/dhruvbalwada/code/miniconda/envs/sogos/lib/python3.7/site-packages/dask/core.py:119: RuntimeWarning: invalid value encountered in true_divide... | MIT | notebooks/0.0_db_RG_climatology.ipynb | dhruvbalwada/sogos |
The apply ufunc way, not working yet. | CT_clim = CT.groupby('TIME.month').mean()
SA_clim = SA.groupby('TIME.month').mean()
CT_clim_region = CT_clim.sel(LATITUDE=slice(-65,-35), LONGITUDE=slice(20,50)).load()
SA_clim_region = SA_clim.sel(LATITUDE=slice(-65,-35), LONGITUDE=slice(20,50)).load()
(N2, pmid) = xr.apply_ufunc(gsw.Nsquared, SA_clim_region, CT_clim_... | /Users/dhruvbalwada/code/miniconda/envs/sogos/lib/python3.7/site-packages/gsw/stability.py:85: RuntimeWarning: divide by zero encountered in true_divide
N2 = ((g_local**2) / (specvol_mid * db_to_pa * dp))
| MIT | notebooks/0.0_db_RG_climatology.ipynb | dhruvbalwada/sogos |
Gestrophic Velocities | psi = xr.apply_ufunc(gsw.geo_strf_dyn_height, SA, CT , RG_clim.PRESSURE,
dask='parallelized', output_dtypes=[float,]).rename('psi')
psi
vels = xr.apply_ufunc(gsw.geostrophic_velocity, psi, psi.LONGITUDE, psi.LATITUDE,
dask='parallelized', output_core_dims=[4,4], output_dtypes=... | _____no_output_____ | MIT | notebooks/0.0_db_RG_climatology.ipynb | dhruvbalwada/sogos |
Mixed Layer DepthEnded up going with Holte's climatology for MLD work | delta_dens = RG_clim.SIGMA0 - RG_clim.SIGMA0.isel(PRESSURE=0)
import nc_time_axis
RG_clim.SIGMA0.sel(LONGITUDE=30, method='nearest').sel( LATITUDE=slice(-63,-45)).isel(TIME=-1).plot.contourf()
plt.gca().invert_yaxis()
RG_clim.SIGMA0.sel(LONGITUDE=30, LATITUDE=-50, method='nearest').isel(TIME=-1).plot()
RG_clim.SIGMA0.s... | _____no_output_____ | MIT | notebooks/0.0_db_RG_climatology.ipynb | dhruvbalwada/sogos |
Mecanismo de manivela-biela corredera | import numpy as np
import matplotlib.pyplot as plt
from numpy import pi,cos,sin,tan
%matplotlib inline
def plotvector(p0,u,color="r"):
"""
Gráfica un vector, dados su punto inicial
y sus componentes rectangulares
"""
plt.plot([p0[0],p0[0]+u[0]],[p0[1],p0[1]+u[1]], color=color, ls="-", marker='o')
... | _____no_output_____ | MIT | nbooks/Slider-Crank.ipynb | JorgeDeLosSantos/mem-upgto-1703 |
FTP - Get file **Tags:** ftp file naas_drivers operations snippet naas **Author:** [Jeremy Ravenel](https://www.linkedin.com/in/ACoAAAJHE7sB5OxuKHuzguZ9L6lfDHqw--cdnJg/) Input Import library | from naas_drivers import ftp | _____no_output_____ | BSD-3-Clause | FTP/FTP_Get_file.ipynb | techthiyanes/awesome-notebooks |
Variables | path = "/path/to/file/in/ftp"
user = "my user"
passwd = "my passwd" | _____no_output_____ | BSD-3-Clause | FTP/FTP_Get_file.ipynb | techthiyanes/awesome-notebooks |
Model Connect to ftp | ftp = ftp.connect(user, passwd) | _____no_output_____ | BSD-3-Clause | FTP/FTP_Get_file.ipynb | techthiyanes/awesome-notebooks |
Output Get the path | ftp = ftp.connect(user, passwd)
ftp.get(path) | _____no_output_____ | BSD-3-Clause | FTP/FTP_Get_file.ipynb | techthiyanes/awesome-notebooks |
User testing for for Scikit-Yellowbrick Using data that was recorded from sensors during Data Science Certificate Program at GWhttps://github.com/georgetown-analytics/classroom-occupancy Data consist of temperature, humidity, CO2 levels, light, of bluetooth devices, noise levels and count of people in the room. | import pandas as pd
%matplotlib inline
dataset = pd.read_csv('dataset.csv')
dataset.head(5)
dataset.count_total.describe()
#add a new column to create a binary class for room occupancy
countmed = dataset.count_total.median()
dataset['room_occupancy'] = dataset['count_total'].apply(lambda x: 'occupied' if x > 4 else 'e... | _____no_output_____ | Apache-2.0 | examples/exbald/data/testing.ipynb | doc22940/yellowbrick |
Feature Analysis Feature analysis visualizers are designed to visualize instances in data space in order to detect features or targets that might impact downstream fitting. Because ML operates on high-dimensional data sets (usually at least 35), the visualizers focus on aggregation, optimization, and other techniques ... | from yellowbrick.features.rankd import Rank2D
from yellowbrick.features.radviz import RadViz
from yellowbrick.features.pcoords import ParallelCoordinates | _____no_output_____ | Apache-2.0 | examples/exbald/data/testing.ipynb | doc22940/yellowbrick |
Rank2DRank1D and Rank2D evaluate single features or pairs of features using a variety of metrics that score the features on the scale [-1, 1] or [0, 1] allowing them to be ranked. A similar concept to SPLOMs, the scores are visualized on a lower-left triangle heatmap so that patterns between pairs of features can be e... | # Load the classification data set
data = dataset
# Specify the features of interest
features = ['temperature','humidity','co2','light','noise','bluetooth_devices']
# Extract the numpy arrays from the data frame
X = data[features].as_matrix()
y = data['count_total'].as_matrix()
# Instantiate the visualizer with the C... | _____no_output_____ | Apache-2.0 | examples/exbald/data/testing.ipynb | doc22940/yellowbrick |
RadVizRadViz is a multivariate data visualization algorithm that plots each feature dimension uniformely around the circumference of a circle then plots points on the interior of the circle such that the point normalizes its values on the axes from the center to each arc. This meachanism allows as many dimensions as w... | # Specify the features of interest and the classes of the target
features = ['temperature','humidity','co2','light','noise','bluetooth_devices']
classes = ['empty', 'occupied']
# Extract the numpy arrays from the data frame
X = data[features].as_matrix()
y = data.room_occupancy_num.as_matrix()
# Instantiate the visu... | _____no_output_____ | Apache-2.0 | examples/exbald/data/testing.ipynb | doc22940/yellowbrick |
For regression, the RadViz visualizer should use a color sequence to display the target information, as opposed to discrete colors. Parallel Coordinates !!! On this step notebook crashes and has to be restarted | # Specify the features of interest and the classes of the target
#features = ['temperature','humidity','co2','light','noise','bluetooth_devices']
#classes = ['empty', 'occupied']
# Extract the numpy arrays from the data frame
#X = data[features].as_matrix()
#y = data.room_occupancy_num.as_matrix()
# Instantiate the ... | _____no_output_____ | Apache-2.0 | examples/exbald/data/testing.ipynb | doc22940/yellowbrick |
Regressor Evaluation Regression models attempt to predict a target in a continuous space. Regressor score visualizers display the instances in model space to better understand how the model is making predictions. We currently have implemented two regressor evaluations:Residuals Plot: plot the difference between the ex... | # Regression Evaluation Imports
from sklearn.linear_model import Ridge, Lasso
from sklearn.model_selection import train_test_split
from yellowbrick.regressor import PredictionError, ResidualsPlot | _____no_output_____ | Apache-2.0 | examples/exbald/data/testing.ipynb | doc22940/yellowbrick |
Residuals PlotA residual plot shows the residuals on the vertical axis and the independent variable on the horizontal axis. If the points are randomly dispersed around the horizontal axis, a linear regression model is appropriate for the data; otherwise, a non-linear model is more appropriate. | # Load the data
df = data
feature_names = ['temperature','humidity','co2','light','noise','bluetooth_devices']
target_name = 'count_total'
# Get the X and y data from the DataFrame
X = df[feature_names].as_matrix()
y = df[target_name].as_matrix()
# Create the train and test data
X_train, X_test, y_train, y_test = ... | _____no_output_____ | Apache-2.0 | examples/exbald/data/testing.ipynb | doc22940/yellowbrick |
Prediction Error PlotPlots the actual targets from the dataset against the predicted values generated by our model. This allows us to see how much variance is in the model. Data scientists diagnose this plot by comparing against the 45 degree line, where the prediction exactly matches the model. | # Load the data
df = data
feature_names = ['temperature','humidity','co2','light','noise','bluetooth_devices']
target_name = 'count_total'
# Get the X and y data from the DataFrame
X = df[feature_names].as_matrix()
y = df[target_name].as_matrix()
# Create the train and test data
X_train, X_test, y_train, y_test = ... | _____no_output_____ | Apache-2.0 | examples/exbald/data/testing.ipynb | doc22940/yellowbrick |
Classifier EvaluationClassification models attempt to predict a target in a discrete space, that is assign an instance of dependent variables one or more categories. Classification score visualizers display the differences between classes as well as a number of classifier-specific visual evaluations. We currently have... | # Classifier Evaluation Imports
from sklearn.naive_bayes import GaussianNB
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from yellowbrick.classifier import ClassificationReport, ROCAUC, ClassBalance | _____no_output_____ | Apache-2.0 | examples/exbald/data/testing.ipynb | doc22940/yellowbrick |
Classification reportThe classification report visualizer displays the precision, recall, and F1 scores for the model. Integrates numerical scores as well color-coded heatmap in order for easy interpretation and detection. | # Load the classification data set
data = dataset
# Specify the features of interest and the classes of the target
features = ['temperature','humidity','co2','light','noise','bluetooth_devices']
classes = ['empty', 'occupied']
# Extract the numpy arrays from the data frame
X = data[features].as_matrix()
y = data.ro... | _____no_output_____ | Apache-2.0 | examples/exbald/data/testing.ipynb | doc22940/yellowbrick |
ROCAUCPlot the ROC to visualize the tradeoff between the classifier's sensitivity and specificity. | # Instantiate the classification model and visualizer
logistic = LogisticRegression()
visualizer = ROCAUC(logistic)
visualizer.fit(X_train, y_train) # Fit the training data to the visualizer
visualizer.score(X_test, y_test) # Evaluate the model on the test data
g = visualizer.show() # Draw/show/show th... | _____no_output_____ | Apache-2.0 | examples/exbald/data/testing.ipynb | doc22940/yellowbrick |
ClassBalanceClass balance chart that shows the support for each class in the fitted classification model. | # Instantiate the classification model and visualizer
forest = RandomForestClassifier()
visualizer = ClassBalance(forest, classes=classes)
visualizer.fit(X_train, y_train) # Fit the training data to the visualizer
visualizer.score(X_test, y_test) # Evaluate the model on the test data
g = visualizer.show() ... | _____no_output_____ | Apache-2.0 | examples/exbald/data/testing.ipynb | doc22940/yellowbrick |
5. Putting it all together**Bring together all of the skills you acquired in the previous chapters to work on a real-life project. From connecting to a database and populating it, to reading and querying it.** It's time to put all your effort so far to good use on a census case study. Census case studyThe case study i... | # Import create_engine, MetaData
from sqlalchemy import create_engine, MetaData
# Define an engine to connect to chapter5.sqlite: engine
engine = create_engine('sqlite:///chapter5.sqlite')
# Initialize MetaData: metadata
metadata = MetaData() | _____no_output_____ | FSFAP | Data Analyst with Python/18_Introduction_to_Databases_in_Python/18_5_Putting it all together.ipynb | brendensong/DataCamp |
Create the table to the databaseHaving setup the engine and initialized the metadata, you will now define the `census` table object and then create it in the database using the `metadata` and `engine` from the previous exercise. To create it in the database, you will have to use the `.create_all()` method on the `meta... | # Import Table, Column, String, and Integer
from sqlalchemy import Table, Column, String, Integer
# Build a census table: census
census = Table('census', metadata,
Column('state', String(30)),
Column('sex', String(1)),
Column('age', Integer),
Column('pop2000'... | _____no_output_____ | FSFAP | Data Analyst with Python/18_Introduction_to_Databases_in_Python/18_5_Putting it all together.ipynb | brendensong/DataCamp |
--- Populating the databaseWith our table in place, we can now load the data into it. The US Census Agency gave us a CSV file full of data that we need to load into the table. Part 2: populating the databaseWe'll start that by building a `values_list` like we did in chapter 4 with this exercise. ```pythonvalues_list = ... | import csv
csv_reader = csv.reader(open('census.csv'))
# Create an empty list: values_list
values_list = []
# Iterate over the rows
for row in csv_reader:
# Create a dictionary with the values
data = {'state': row[0], 'sex': row[1], 'age': row[2],
'pop2000': row[3], 'pop2008': row[4]}
# Appe... | _____no_output_____ | FSFAP | Data Analyst with Python/18_Introduction_to_Databases_in_Python/18_5_Putting it all together.ipynb | brendensong/DataCamp |
Load data from a list into the TableUsing the multiple insert pattern, in this exercise, you will load the data from `values_list` into the table. - Import `insert` from `sqlalchemy`.- Build an insert statement for the `census` table.- Execute the statement `stmt` along with `values_list`. You will need to pass them b... | # Import insert
from sqlalchemy import insert
# Build insert statement: stmt
stmt = insert(census)
# Use values_list to insert data: results
results = connection.execute(stmt, values_list)
# Print rowcount
print(results.rowcount) | 8772
| FSFAP | Data Analyst with Python/18_Introduction_to_Databases_in_Python/18_5_Putting it all together.ipynb | brendensong/DataCamp |
--- Querying the database Part 3: answering data science questions with queriesHere is an example of how we calculated an average in an exercise from Chapter 3. We began by importing the select statement. Next we built a select statement that creates a weighted average. We do this by summing the result of multiplying t... | # Import select and func
from sqlalchemy import select, func
# Select the average of age weighted by pop2000
stmt = select([func.sum(census.columns.pop2000 *
census.columns.age) /
func.sum(census.columns.pop2000)]) | _____no_output_____ | FSFAP | Data Analyst with Python/18_Introduction_to_Databases_in_Python/18_5_Putting it all together.ipynb | brendensong/DataCamp |
- Modify the select statement to alias the new column with weighted average as `'average_age'` using `.label()`. |
# Import select and func
from sqlalchemy import select, func
# Relabel the new column as average_age
stmt = select([(func.sum(census.columns.pop2000 *
census.columns.age) /
func.sum(census.columns.pop2000)).label('average_age')
]) | _____no_output_____ | FSFAP | Data Analyst with Python/18_Introduction_to_Databases_in_Python/18_5_Putting it all together.ipynb | brendensong/DataCamp |
- Modify the select statement to select the `sex` column of `census` in addition to the weighted average, with the `sex` column coming first.- Group by the `sex` column of `census`. | # Import select and func
from sqlalchemy import select, func
# Add the sex column to the select statement
stmt = select([census.columns.sex,
(func.sum(census.columns.pop2000 *
census.columns.age) /
func.sum(census.columns.pop2000)).label('average_age'), ... | _____no_output_____ | FSFAP | Data Analyst with Python/18_Introduction_to_Databases_in_Python/18_5_Putting it all together.ipynb | brendensong/DataCamp |
- Execute the statement on the `connection` and fetch all the results.- Loop over the results and print the values in the `sex` and `average_age` columns for each record in the results. |
# Import select and func
from sqlalchemy import select, func
# Select sex and average age weighted by 2000 population
stmt = select([census.columns.sex,
(func.sum(census.columns.pop2000 *
census.columns.age) /
func.sum(census.columns.pop2000)).label('average_a... | F 37
M 34
| FSFAP | Data Analyst with Python/18_Introduction_to_Databases_in_Python/18_5_Putting it all together.ipynb | brendensong/DataCamp |
Determine the percentage of population by gender and stateIn this exercise, you will write a query to determine the percentage of the population in 2000 that comprised of women. You will group this query by state. - Import `case`, `cast` and `Float` from `sqlalchemy`.- Define a statement to select `state` and the perc... |
# import case, cast and Float from sqlalchemy
from sqlalchemy import case, cast, Float, desc
# Build a query to calculate the percentage of women in 2000: stmt
stmt = select([census.columns.state,
(func.sum(
case([
(census.columns.sex == 'F',
... | District of Columbia 53.129626141738385
Rhode Island 52.07343391902215
Maryland 51.93575549972231
Mississippi 51.92229481794672
Massachusetts 51.843023571316785
New York 51.83453865150073
Alabama 51.832407770179465
Louisiana 51.75351596554121
Pennsylvania 51.74043473051053
South Carolina 51.73072129765755
Connecticut 5... | FSFAP | Data Analyst with Python/18_Introduction_to_Databases_in_Python/18_5_Putting it all together.ipynb | brendensong/DataCamp |
*Interestingly, the District of Columbia had the highest percentage of women in 2000, while Alaska had the highest percentage of males.* Determine the difference by state from the 2000 and 2008 censusesIn this final exercise, you will write a query to calculate the states that changed the most in population. You will ... | # Build query to return state name and population difference from 2008 to 2000
stmt = select([census.columns.state,
(census.columns.pop2008-
census.columns.pop2000).label('pop_change')
])
# Group by State
stmt = stmt.group_by(census.columns.state)
# Order by Population Change
stmt = st... | Texas:40137
California:35406
Florida:21954
Arizona:14377
Georgia:13357
North Carolina:11574
Virginia:6639
Colorado:6425
Utah:5934
Illinois:5412
Nevada:5367
Washington:4666
Tennessee:4621
Missouri:4547
Minnesota:3763
Oklahoma:3677
Pennsylvania:3384
South Carolina:3360
Wisconsin:2945
Oregon:2817
Maryland:2551
Arkansas:25... | FSFAP | Data Analyst with Python/18_Introduction_to_Databases_in_Python/18_5_Putting it all together.ipynb | brendensong/DataCamp |
Prepare environment | !pip install git+https://github.com/katarinagresova/ensembl_scraper.git@6d3bba8e6be7f5ead58a3bbaed6a4e8cd35e62fd | Collecting git+https://github.com/katarinagresova/ensembl_scraper.git@6d3bba8e6be7f5ead58a3bbaed6a4e8cd35e62fd
Cloning https://github.com/katarinagresova/ensembl_scraper.git (to revision 6d3bba8e6be7f5ead58a3bbaed6a4e8cd35e62fd) to /tmp/pip-req-build-fz97hoif
Running command git clone --filter=blob:none -q https://... | Apache-2.0 | docs/human_ensembl_regulatory/create_datasets.ipynb | ML-Bioinfo-CEITEC/genomic_benchmarks |
Create config file | import yaml
config = {
"root_dir": "../../datasets/",
"organisms": {
"homo_sapiens": {
"regulatory_feature"
}
}
}
user_config = 'user_config.yaml'
with open(user_config, 'w') as handle:
yaml.dump(config, handle) | _____no_output_____ | Apache-2.0 | docs/human_ensembl_regulatory/create_datasets.ipynb | ML-Bioinfo-CEITEC/genomic_benchmarks |
Prepare directories | from pathlib import Path
BASE_FILE_PATH = Path("../../datasets/human_ensembl_regulatory/")
# copied from https://stackoverflow.com/a/57892171
def rm_tree(pth: Path):
for child in pth.iterdir():
if child.is_file():
child.unlink()
else:
rm_tree(child)
pth.rmdir()
if BASE... | _____no_output_____ | Apache-2.0 | docs/human_ensembl_regulatory/create_datasets.ipynb | ML-Bioinfo-CEITEC/genomic_benchmarks |
Run tool | !python -m scraper.ensembl_scraper -c user_config.yaml | Processing organisms: 0%| | 0/1 [00:00<?, ?it/s]
Processing feature files: 0%| | 0/1 [00:00<?, ?it/s][AINFO:root:download_file(): Going to download file from path ftp://ftp.ensembl.org/pub/release-100/mysql/regulation_mart_100/hsapiens_regulatory_feature__reg... | Apache-2.0 | docs/human_ensembl_regulatory/create_datasets.ipynb | ML-Bioinfo-CEITEC/genomic_benchmarks |
Reformating | !mkdir -p ../../datasets/human_ensembl_regulatory/train
!mkdir -p ../../datasets/human_ensembl_regulatory/test
!mv ../../datasets/homo_sapiens_regulatory_feature_open_chromatin_region/train/positive.csv ../../datasets/human_ensembl_regulatory/train/ocr.csv
!mv ../../datasets/homo_sapiens_regulatory_feature_open_chromat... | _____no_output_____ | Apache-2.0 | docs/human_ensembl_regulatory/create_datasets.ipynb | ML-Bioinfo-CEITEC/genomic_benchmarks |
Cleaning | !rm user_config.yaml
!rm -rf ../../datasets/tmp/
!rm -rf ../../datasets/homo_sapiens_regulatory_feature_CTCF_binding_site
!rm -rf ../../datasets/homo_sapiens_regulatory_feature_enhancer
!rm -rf ../../datasets/homo_sapiens_regulatory_feature_promoter
!rm -rf ../../datasets/homo_sapiens_regulatory_feature_promoter_flank... | _____no_output_____ | Apache-2.0 | docs/human_ensembl_regulatory/create_datasets.ipynb | ML-Bioinfo-CEITEC/genomic_benchmarks |
Testing | from genomic_benchmarks.loc2seq import download_dataset
download_dataset("human_ensembl_regulatory", local_repo=True)
from genomic_benchmarks.data_check import info
info("human_ensembl_regulatory", 0, local_repo=True) | Dataset `human_ensembl_regulatory` has 3 classes: enhancer, ocr, promoter.
The length of genomic intervals ranges from 71 to 802, with average 429.91753643694585 and median 401.0.
Totally 289061 sequences have been found, 231348 for training and 57713 for testing.
| Apache-2.0 | docs/human_ensembl_regulatory/create_datasets.ipynb | ML-Bioinfo-CEITEC/genomic_benchmarks |
Source detection with Gammapy ContextThe first task in a source catalogue production is to identify significant excesses in the data that can be associated to unknown sources and provide a preliminary parametrization in term of position, extent, and flux. In this notebook we will use Fermi-LAT data to illustrate how t... | %matplotlib inline
import matplotlib.pyplot as plt
import matplotlib.cm as cm
from gammapy.maps import Map
from gammapy.detect import (
ASmooth,
TSMapEstimator,
find_peaks,
compute_lima_image,
)
from gammapy.catalog import SOURCE_CATALOGS
from gammapy.cube import PSFKernel
from gammapy.stats import sign... | _____no_output_____ | BSD-3-Clause | tutorials/detect.ipynb | QRemy/gammapy |
Read in input imagesWe first read in the counts cube and sum over the energy axis: | counts = Map.read("$GAMMAPY_DATA/fermi-3fhl-gc/fermi-3fhl-gc-counts.fits.gz")
background = Map.read(
"$GAMMAPY_DATA/fermi-3fhl-gc/fermi-3fhl-gc-background.fits.gz"
)
exposure = Map.read(
"$GAMMAPY_DATA/fermi-3fhl-gc/fermi-3fhl-gc-exposure.fits.gz"
)
maps = {"counts": counts, "background": background, "exposure... | _____no_output_____ | BSD-3-Clause | tutorials/detect.ipynb | QRemy/gammapy |
Adaptive smoothingFor visualisation purpose it can be nice to look at a smoothed counts image. This can be performed using the adaptive smoothing algorithm from [Ebeling et al. (2006)](https://ui.adsabs.harvard.edu/abs/2006MNRAS.368...65E/abstract).In the following example the `threshold` argument gives the minimum si... | %%time
scales = u.Quantity(np.arange(0.05, 1, 0.05), unit="deg")
smooth = ASmooth(threshold=3, scales=scales)
images = smooth.run(**maps)
plt.figure(figsize=(15, 5))
images["counts"].plot(add_cbar=True, vmax=10); | _____no_output_____ | BSD-3-Clause | tutorials/detect.ipynb | QRemy/gammapy |
TS map estimationThe Test Statistic, TS = 2 ∆ log L ([Mattox et al. 1996](https://ui.adsabs.harvard.edu/abs/1996ApJ...461..396M/abstract)), compares the likelihood function L optimized with and without a given source.The TS map is computed by fitting by a single amplitude parameter on each pixel as described in Append... | %%time
estimator = TSMapEstimator()
images = estimator.run(maps, kernel.data) | _____no_output_____ | BSD-3-Clause | tutorials/detect.ipynb | QRemy/gammapy |
Plot resulting images | plt.figure(figsize=(15, 5))
images["sqrt_ts"].plot(add_cbar=True);
plt.figure(figsize=(15, 5))
images["flux"].plot(add_cbar=True, stretch="sqrt", vmin=0);
plt.figure(figsize=(15, 5))
images["niter"].plot(add_cbar=True); | _____no_output_____ | BSD-3-Clause | tutorials/detect.ipynb | QRemy/gammapy |
Source candidatesLet's run a peak finder on the `sqrt_ts` image to get a list of point-sources candidates (positions and peak `sqrt_ts` values).The `find_peaks` function performs a local maximun search in a sliding window, the argument `min_distance` is the minimum pixel distance between peaks (smallest possible value... | sources = find_peaks(images["sqrt_ts"], threshold=8, min_distance=1)
nsou = len(sources)
sources
# Plot sources on top of significance sky image
plt.figure(figsize=(15, 5))
_, ax, _ = images["sqrt_ts"].plot(add_cbar=True)
ax.scatter(
sources["ra"],
sources["dec"],
transform=plt.gca().get_transform("icrs")... | _____no_output_____ | BSD-3-Clause | tutorials/detect.ipynb | QRemy/gammapy |
Note that we used the instrument point-spread-function (PSF) as kernel, so the hypothesis we test is the presence of a point source. In order to test for extended sources we would have to use as kernel an extended template convolved by the PSF. Alternatively, we can compute the significance of an extended excess using ... | %%time
radius = np.array([0.05, 0.1, 0.15, 0.2, 0.25, 0.3, 0.4, 0.5])
pixsize = counts.geom.pixel_scales[0].value
nr = len(radius)
signi = np.zeros((nsou, nr))
excess = np.zeros((nsou, nr))
for kr in range(nr):
npixel = radius[kr] / pixsize
kernel = Tophat2DKernel(npixel)
result = compute_lima_image(counts,... | _____no_output_____ | BSD-3-Clause | tutorials/detect.ipynb | QRemy/gammapy |
For simplicity we saved the significance and excess at the position of the candidates found previously on the TS map, but we could aslo have applied the peak finder on these significances maps for each scale, or alternatively implemented a 3D peak detection (in longitude, latitude, radius). Now let's look at the signif... | plt.figure()
for ks in range(nsou):
plt.plot(radius, signi[ks, :], color=colors[ks])
plt.xlabel("Radius")
plt.ylabel("Li & Ma Significance")
plt.title("Guessing optimal radius of each candidate"); | _____no_output_____ | BSD-3-Clause | tutorials/detect.ipynb | QRemy/gammapy |
We can add the optimal radius guessed and the corresdponding excess to the source candidate properties table. | # rename the value key to sqrt(TS)_PS
sources.rename_column("value", "sqrt(TS)_PS")
index = np.argmax(signi, axis=1)
sources["significance"] = signi[range(nsou), index]
sources["radius"] = radius[index]
sources["excess"] = excess[range(nsou), index]
sources
# Plot candidates sources on top of significance sky image wi... | _____no_output_____ | BSD-3-Clause | tutorials/detect.ipynb | QRemy/gammapy |
Quasi-Laplace approximation for Poisson data- toc: true - badges: true- comments: true- categories: [jupyter] AboutThe [quasi-Laplace approximation]({% post_url 2020-06-22-intuition-for-quasi-Laplace %}) may be extended to approximate the posterior of a Poisson distribution with a Gaussian, as we will see here.We app... | #collapse_hide
import numpy as np
np.set_printoptions(precision = 4, suppress=True)
from scipy import optimize
from scipy.special import gammaln
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib import ticker as plticker
from mpl_toolkits.axes_grid1 import make_axes_locatable
import sys
sys.p... | _____no_output_____ | Apache-2.0 | _notebooks/2020-07-08-poisson-quasi-Laplace-posterior.ipynb | banskt/glm-ash-notes |
Generate toy dataLet us consider a Poisson model with sparse coefficients, so that the number of causal variables `ncausal` is much less than the number of variables `nvar` in the model. This is ensured by sampling the betas from a Gaussian mixture prior of `nGcomp` components with variances given by $\sigma_k^2$ (`si... | nsample = 20
nvar = 30
nGcomp = 3
sparsity = 0.8
prior_strength = 20
num_inf = 1e4 # a large number for 1/sigma_k^2 when sigma_k^2 = 0
probk = np.zeros(nGcomp)
probk[0] = sparsity
probk[1:(nGcomp - 1)] = (1 - sparsity) / (nGcomp - 1)
probk[nGcomp - 1] = 1 - np.sum(probk)
sigmak2 = np.array([prior_strength * np.square(... | _____no_output_____ | Apache-2.0 | _notebooks/2020-07-08-poisson-quasi-Laplace-posterior.ipynb | banskt/glm-ash-notes |
We use the exponential link function $\lambda_i = \exp\left(\mathbf{X}_i\boldsymbol{\beta}\right)$ to generate the response variable $y_i$ for $i = 1, \ldots, N$ samples using the Poisson probability distribution\begin{equation*}p\left(y_i \mid \mathbf{X}_i, \boldsymbol{\beta}\right) = \frac{\lambda_i^{y_i}e^{-\lambda_... | # collapse-hide
def standardize(X):
Xnorm = (X - np.mean(X, axis = 0))
Xstd = Xnorm / np.std(Xnorm, axis = 0)
return Xstd
def poisson_data(X, beta):
Xbeta = np.dot(X, beta)
pred = np.exp(Xbeta)
Y = np.random.poisson(pred)
return Y
X = np.random.rand(nsample * nvar).reshape(nsample, nva... | _____no_output_____ | Apache-2.0 | _notebooks/2020-07-08-poisson-quasi-Laplace-posterior.ipynb | banskt/glm-ash-notes |
Let us have a look at the generated data. | # collapse-hide
print(f'There are {ncausal} non-zero coefficients with variance {betavar:.4f}')
fig = plt.figure(figsize = (12,6))
ax1 = fig.add_subplot(121)
ax2 = fig.add_subplot(122)
Xbeta = np.dot(X, beta)
ax1.scatter(Xbeta, np.log(Y+1), s = 10)
ax2.hist(Y)
ax1.set_xlabel(r'$\sum_i X_{ni} \beta_i$')
ax1.set_ylab... | There are 5 non-zero coefficients with variance 3.2003
| Apache-2.0 | _notebooks/2020-07-08-poisson-quasi-Laplace-posterior.ipynb | banskt/glm-ash-notes |
True posterior vs quasi-Laplace posteriorWe select two causal variables (with maximum effect size) and fix all the others to optimum values to understand how the likelihood and posterior depends on these two chosen variables. To avoid the sum over the indicator variables, we use the joint prior $p\left(\boldsymbol{\be... | # collapse-hide
def get_log_likelihood(Y, X, beta):
Xbeta = np.dot(X, beta)
logL = np.sum(Y * Xbeta - np.exp(Xbeta))# - gammaln(Y+1))
return logL
def get_log_prior(beta, gammajk, probk, sigmak2):
logprior = 0
for j, b in enumerate(beta):
k = np.where(gammajk[j, :] == 1)[0][0]
logpr... | _____no_output_____ | Apache-2.0 | _notebooks/2020-07-08-poisson-quasi-Laplace-posterior.ipynb | banskt/glm-ash-notes |
We calculate the likelihood, prior, *true* posterior and the quasi-Laplace posterior. Note that the posteriors are not normalized. We apply quasi-Laplace (QL) approximation with some $\mathbf{\Lambda}$ and show QL posterior distribution, which is given by\begin{equation*}p\left(\mathbf{y} \mid \mathbf{X}, \boldsymbol{\... | np.max(beta)
# collapse-hide
bchoose = np.argsort(abs(beta))[-2:]
nplotx = 20
nploty = 20
b1min = -0.5
b1max = 4
b2min = -4
b2max = 0.5
beta1 = np.linspace(b1min, b1max, nplotx)
beta2 = np.linspace(b2min, b2max, nploty)
logL = np.zeros((nploty, nplotx))
logPr = np.zeros((nploty, nplotx))
logPs = np.zeros((nploty, np... | _____no_output_____ | Apache-2.0 | _notebooks/2020-07-08-poisson-quasi-Laplace-posterior.ipynb | banskt/glm-ash-notes |
Here, we plot the contour maps. The x and y-axis show the two coefficients $\beta_1$ and $\beta_2$, which we chose to vary. The blue dot shows the coordinates of the true values of $\{\beta_1, \beta_2\}$ and the black dot shows the maximum of the log probabilities. Note how the non-Gaussian *true* posterior is now appr... | fig = plt.figure(figsize = (12, 8))
ax1 = fig.add_subplot(221)
ax2 = fig.add_subplot(222)
ax3 = fig.add_subplot(223)
ax4 = fig.add_subplot(224)
norm = cm.colors.Normalize(vmin=np.min(logPs), vmax=np.max(logPs))
plot_contours(ax1, beta1, beta2, logL, beta[bchoose], None, cstep = 5000, zlabel = "Log Likelihood")
plot_... | _____no_output_____ | Apache-2.0 | _notebooks/2020-07-08-poisson-quasi-Laplace-posterior.ipynb | banskt/glm-ash-notes |
Effect of regularizerLet us assume that we do not know $\mathbf{\Lambda}$ and all $\lambda_j$'s are equal. Here we look at how the QL posterior changes with varying $\beta_2$ for different values of $\lambda_j$.Here we define a function for calculating the QL posterior and true posterior for changing the coefficients ... | # collapse-hide
def get_logQL_logPs_single_variable(X, Y, beta, regvar, betavar, bidx,
regL, gammajk, probk, sigmak2):
nvar = beta.shape[0]
nplotrv = regvar.shape[0]
nplotx = betavar.shape[0]
logL = np.zeros(nplotx)
logPr = np.zeros(nplotx)
logPs = np.z... | _____no_output_____ | Apache-2.0 | _notebooks/2020-07-08-poisson-quasi-Laplace-posterior.ipynb | banskt/glm-ash-notes |
And then look at the posteriors for $\beta_2$. | #collapse-hide
nplotx_rv = 200
nplotrv = 4
bmin = -4
bmax = 0
rvmin = 1
rvmax = 100
bidx = bchoose[1]
fig = plt.figure(figsize = (8, 8))
ax1 = fig.add_subplot(111)
betavals = np.linspace(bmin, bmax, nplotx_rv)
regvals = np.linspace(rvmin, rvmax, nplotrv)
logPs_rv, logQL_rv = get_logQL_logPs_single_variable(X, Y... | _____no_output_____ | Apache-2.0 | _notebooks/2020-07-08-poisson-quasi-Laplace-posterior.ipynb | banskt/glm-ash-notes |
What happens to the QL posterior for other variables? Let us look at every $\beta_j$ and their individual maximum posterior, while all others are kept fixed at optimum values. Here, we have arranged the $\beta_j$ in ascending order. | #collapse-hide
bmin = -5
bmax = 5
bidx_sorted = np.argsort(beta)
bidx_sorted_nz = bidx_sorted #bidx_sorted[beta[bidx_sorted]!=0]
betavals = np.linspace(bmin, bmax, nplotx_rv)
regvals = np.linspace(rvmin, rvmax, nplotrv)
maxQL = np.zeros((nplotrv, len(bidx_sorted_nz)))
maxPs = np.zeros(len(bidx_sorted_nz))
for i, b... | _____no_output_____ | Apache-2.0 | _notebooks/2020-07-08-poisson-quasi-Laplace-posterior.ipynb | banskt/glm-ash-notes |
Modelo Ciclo de Carnot Importar librerias | import numpy as np
import matplotlib.pyplot as plt | _____no_output_____ | MIT | 05 - Ciclo de Carnot.ipynb | StarBrand/IQ3201-Ciclos |
Definir funcionesPara la presión de un gas ideal isotérmico y adiabático | # Valores dados para que calce el gráfico
R = 1
gamma = 10
def pressure_ideal(T, v):
return R*T / v
def pressure_adiabatic(v, P1, v1):
return P1*np.power(v1/v, gamma) | _____no_output_____ | MIT | 05 - Ciclo de Carnot.ipynb | StarBrand/IQ3201-Ciclos |
Definir valores a gráficar | Th = 850
Tc = 310
delta_v = 0.05 | _____no_output_____ | MIT | 05 - Ciclo de Carnot.ipynb | StarBrand/IQ3201-Ciclos |
Proceso Isotérmico | vC = 2.5
vD = 2.0 | _____no_output_____ | MIT | 05 - Ciclo de Carnot.ipynb | StarBrand/IQ3201-Ciclos |
Calculo de vA y vB | PC = pressure_ideal(Tc, vC)
PD = pressure_ideal(Tc, vD)
vA = ((PD*(vD**gamma))/(R*Th))**(1/(gamma-1))
vB = ((PC*(vC**gamma))/(R*Th))**(1/(gamma-1))
v = np.linspace(vA-delta_v, vC+delta_v) # v1, 3 | _____no_output_____ | MIT | 05 - Ciclo de Carnot.ipynb | StarBrand/IQ3201-Ciclos |
Proceso adiabático | v_2 = np.linspace(vB-delta_v, vC+delta_v)
v_4 = np.linspace(vA-delta_v, vD+delta_v)
_, ax = plt.subplots(figsize=(8, 6))
ax.plot(v, pressure_ideal(Tc, v), '--b', label="Isoterma")
ax.plot(v, pressure_ideal(Th, v), '--b')
ax.plot(v_2, pressure_adiabatic(v_2, PC, vC), '-.r', label="Adiabática")
ax.plot(v_4, pressure_adi... | _____no_output_____ | MIT | 05 - Ciclo de Carnot.ipynb | StarBrand/IQ3201-Ciclos |
App and Process ControllerThis notebook is used to start client-Processes | # from subprocess import call
# import os | _____no_output_____ | MIT | src/App_Process_Controller.ipynb | Dustin-dusTir/Python-Projekt-Setup |
Test if this notebook works | ! start powershell python ./test/testConsoleScript.py | _____no_output_____ | MIT | src/App_Process_Controller.ipynb | Dustin-dusTir/Python-Projekt-Setup |
Start a server | ! start powershell python ./server.py | _____no_output_____ | MIT | src/App_Process_Controller.ipynb | Dustin-dusTir/Python-Projekt-Setup |
Phase Proportions Over TimeGoal is to create a figure like that in Paul et al. [1].[1] Michael J. Paul, Ryen W. White, and Eric Horvitz. 2015. Diagnoses, Decisions, and Outcomes: Web Search as Decision Support for Cancer. In Proceedings of the 24th International Conference on World Wide Web - WWW ’15 (WWW’15), 831–841... | %reload_ext autoreload
%autoreload 2
%matplotlib inline
import sys
sys.path.append("../../annotation_data")
from phase import *
import pandas as pd
import numpy as np
import sklearn
import sklearn.metrics
import subprocess
from tqdm import tqdm
import matplotlib.pyplot as plt
import matplotlib.dates as md
import matplo... | _____no_output_____ | MIT | classification/phases/phase-proportion-figure.ipynb | levon003/icwsm-cancer-journeys |
Load VW phase labels | all_predictions_filepath = os.path.join(vw_working_dir, "vw_all_preds.pkl")
pred_df = pd.read_pickle(all_predictions_filepath)
len(pred_df)
pred_df.head()
for site_id, site_preds in tqdm(pred_df.groupby(by='site_id', sort=False)):
journal_creation_times = site_preds.loc[:, 'created_at']
journal_labels = site_pr... | 100%|██████████| 4977/4977 [00:05<00:00, 950.92it/s]
| MIT | classification/phases/phase-proportion-figure.ipynb | levon003/icwsm-cancer-journeys |
Loading data | #dataframe = pd.read_csv('all_essaysets.csv', encoding = 'latin-1')
dataframe = pd.read_csv('training.tsv', encoding = 'latin-1', sep='\t')
dataframe.describe()
dataframe.head() | _____no_output_____ | MIT | autoEssayGrader4.ipynb | ogozuacik/automated_essay_scoring |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.