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 |
|---|---|---|---|---|---|
1-part latent predictive model | class LaPred1P(nn.Module):
def __init__(self, latent_features, input_features=None, timesteps=None,
data=None, bias=True):
super().__init__()
if data:
input_features = input_features or data.n_vars
timesteps = timesteps or data.n_timesteps
elif input_... | _____no_output_____ | MIT | notebooks/03-framing-models.ipynb | sflippl/patches |
2-part latent predictive model | class LaPred2P(nn.Module):
def __init__(self, latent_features, input_features=None, timesteps=None,
data=None, bias=True):
super().__init__()
if data:
input_features = input_features or data.n_vars
timesteps = timesteps or data.n_timesteps
elif input_... | _____no_output_____ | MIT | notebooks/03-framing-models.ipynb | sflippl/patches |
Contrastive predictive model | cts = patches.data.Contrastive1DTimeSeries(data=cbm.to_array())
ce = patches.networks.LinearScaffold(latent_features=1, data=cts)
criterion = patches.losses.ContrastiveLoss(loss=nn.MSELoss())
optimizer = optim.Adam(ce.parameters())
angles = []
loss_traj = []
running_loss = 0
for epoch in tqdm(range(10)):
for i, dat... | _____no_output_____ | MIT | notebooks/03-framing-models.ipynb | sflippl/patches |
Sampling bias | def moving_average(array):
"""Moving average over axis 0."""
cumsum = array.cumsum(axis=0)
length = cumsum.shape[0]
rng = np.arange(1, length+1)
if cumsum.ndim>1:
rng = rng.reshape(length, 1).repeat(cumsum.shape[1], 1)
return cumsum/rng
exposure = moving_average(np.abs(cbm.to_array()))
(... | _____no_output_____ | MIT | notebooks/03-framing-models.ipynb | sflippl/patches |
**Data Visualization** Estimated time needed: **30** minutes In this lab, you will learn how to visualize and interpret data Objectives * Import Libraries* Lab Exercises * Identifying duplicates * Plotting Scatterplots * Plotting Boxplots *** Import Libraries All Libraries required for this l... | # !pip install pandas
# !pip install numpy
# !pip install matplotlib
# !pip install seaborn | _____no_output_____ | MIT | IBM-statistics/2-Visualizing_Data.ipynb | brndnaxr/brndnaxr-micro-projects |
Import the libraries we need for the lab | import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt | _____no_output_____ | MIT | IBM-statistics/2-Visualizing_Data.ipynb | brndnaxr/brndnaxr-micro-projects |
Read in the csv file from the url using the request library | ratings_url = 'https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-ST0151EN-SkillsNetwork/labs/teachingratings.csv'
ratings_df = pd.read_csv(ratings_url) | _____no_output_____ | MIT | IBM-statistics/2-Visualizing_Data.ipynb | brndnaxr/brndnaxr-micro-projects |
Lab Exercises Identify all duplicate cases using prof. Using all observations, find the average and standard deviation for age. Repeat the analysis by first filtering the data set to include one observation for each instructor with a total number of observations restricted to 94. Identify all duplicate cases using pr... | ratings_df.prof.unique() | _____no_output_____ | MIT | IBM-statistics/2-Visualizing_Data.ipynb | brndnaxr/brndnaxr-micro-projects |
Print out the number of unique values in the prof variable | ratings_df.prof.nunique() | _____no_output_____ | MIT | IBM-statistics/2-Visualizing_Data.ipynb | brndnaxr/brndnaxr-micro-projects |
Using all observations, Find the average and standard deviation for age | ratings_df['age'].mean()
ratings_df['age'].std() | _____no_output_____ | MIT | IBM-statistics/2-Visualizing_Data.ipynb | brndnaxr/brndnaxr-micro-projects |
Repeat the analysis by first filtering the data set to include one observation for each instructor with a total number of observations restricted to 94.> first we drop duplicates using prof as a subset and assign it a new dataframe name called no_duplicates_ratings_df | no_duplicates_ratings_df = ratings_df.drop_duplicates(subset =['prof'])
no_duplicates_ratings_df.head() | _____no_output_____ | MIT | IBM-statistics/2-Visualizing_Data.ipynb | brndnaxr/brndnaxr-micro-projects |
> Use the new dataset to get the mean of age | no_duplicates_ratings_df['age'].mean()
no_duplicates_ratings_df['age'].std() | _____no_output_____ | MIT | IBM-statistics/2-Visualizing_Data.ipynb | brndnaxr/brndnaxr-micro-projects |
Using a bar chart, demonstrate if instructors teaching lower-division courses receive higher average teaching evaluations. | ratings_df.head() | _____no_output_____ | MIT | IBM-statistics/2-Visualizing_Data.ipynb | brndnaxr/brndnaxr-micro-projects |
Find the average teaching evaluation in both groups of upper and lower-division | division_eval = ratings_df.groupby('division')[['eval']].mean().reset_index() | _____no_output_____ | MIT | IBM-statistics/2-Visualizing_Data.ipynb | brndnaxr/brndnaxr-micro-projects |
Plot the barplot using the seaborn library | sns.set(style="whitegrid")
ax = sns.barplot(x="division", y="eval", data=division_eval) | _____no_output_____ | MIT | IBM-statistics/2-Visualizing_Data.ipynb | brndnaxr/brndnaxr-micro-projects |
Plot the relationship between age and teaching evaluation scores. Create a scatterplot with the scatterplot function in the seaborn library | ax = sns.scatterplot(x='age', y='eval', data=ratings_df) | _____no_output_____ | MIT | IBM-statistics/2-Visualizing_Data.ipynb | brndnaxr/brndnaxr-micro-projects |
Using gender-differentiated scatter plots, plot the relationship between age and teaching evaluation scores. Create a scatterplot with the scatterplot function in the seaborn library this time add the hue argument | ax = sns.scatterplot(x='age', y='eval', hue='gender',
data=ratings_df) | _____no_output_____ | MIT | IBM-statistics/2-Visualizing_Data.ipynb | brndnaxr/brndnaxr-micro-projects |
Create a box plot for beauty scores differentiated by credits. We use the boxplot() function from the seaborn library | ax = sns.boxplot(x='credits', y='beauty', data=ratings_df) | _____no_output_____ | MIT | IBM-statistics/2-Visualizing_Data.ipynb | brndnaxr/brndnaxr-micro-projects |
What is the number of courses taught by gender? We use the catplot() function from the seaborn library | sns.catplot(x='gender', kind='count', data=ratings_df) | _____no_output_____ | MIT | IBM-statistics/2-Visualizing_Data.ipynb | brndnaxr/brndnaxr-micro-projects |
Create a group histogram of taught by gender and tenure We will add the hue = Tenure argument | sns.catplot(x='gender', hue = 'tenure', kind='count', data=ratings_df) | _____no_output_____ | MIT | IBM-statistics/2-Visualizing_Data.ipynb | brndnaxr/brndnaxr-micro-projects |
Add division as another factor to the above histogram We add another argument named row and use the division variable as the row | sns.catplot(x='gender', hue = 'tenure', row = 'division',
kind='count', data=ratings_df,
height = 3, aspect = 2) | _____no_output_____ | MIT | IBM-statistics/2-Visualizing_Data.ipynb | brndnaxr/brndnaxr-micro-projects |
Create a scatterplot of age and evaluation scores, differentiated by gender and tenure Use the relplot() function for complex scatter plots | sns.relplot(x="age", y="eval", hue="gender",
row="tenure",
data=ratings_df, height = 3, aspect = 2) | _____no_output_____ | MIT | IBM-statistics/2-Visualizing_Data.ipynb | brndnaxr/brndnaxr-micro-projects |
Create a distribution plot of teaching evaluation scores We use the distplot() function from the seaborn library, set kde = false because we don'e need the curve | ax = sns.distplot(ratings_df['eval'], kde = False) | D:\anaconda3\lib\site-packages\seaborn\distributions.py:2557: FutureWarning: `distplot` is a deprecated function and will be removed in a future version. Please adapt your code to use either `displot` (a figure-level function with similar flexibility) or `histplot` (an axes-level function for histograms).
warnings.wa... | MIT | IBM-statistics/2-Visualizing_Data.ipynb | brndnaxr/brndnaxr-micro-projects |
Create a distribution plot of teaching evaluation score with gender as a factor | ## use the distplot function from the seaborn library
sns.distplot(ratings_df[ratings_df['gender'] == 'female']['eval'], color='green', kde=False)
sns.distplot(ratings_df[ratings_df['gender'] == 'male']['eval'], color="orange", kde=False)
plt.show() | _____no_output_____ | MIT | IBM-statistics/2-Visualizing_Data.ipynb | brndnaxr/brndnaxr-micro-projects |
Create a box plot - age of the instructor by gender | ax = sns.boxplot(x="gender", y="age", data=ratings_df) | _____no_output_____ | MIT | IBM-statistics/2-Visualizing_Data.ipynb | brndnaxr/brndnaxr-micro-projects |
Compare age along with tenure and gender | ax = sns.boxplot(x="tenure", y="age", hue="gender",
data=ratings_df) | _____no_output_____ | MIT | IBM-statistics/2-Visualizing_Data.ipynb | brndnaxr/brndnaxr-micro-projects |
Practice Questions Question 1: Create a distribution plot of beauty scores with Native English speaker as a factor* Make the color of the native English speakers plot - orange and non - native English speakers - blue | ## insert code
| _____no_output_____ | MIT | IBM-statistics/2-Visualizing_Data.ipynb | brndnaxr/brndnaxr-micro-projects |
Double-click **here** for the solution.<!-- The answer is below:sns.distplot(ratings_df[ratings_df['native'] == 'yes']['beauty'], color="orange", kde=False) sns.distplot(ratings_df[ratings_df['native'] == 'no']['beauty'], color="blue", kde=False) plt.show()--> Question 2: Create a Horizontal box plot of the age of the... | ## insert code
| _____no_output_____ | MIT | IBM-statistics/2-Visualizing_Data.ipynb | brndnaxr/brndnaxr-micro-projects |
Double-click **here** for a hint.<!-- The hint is below:Remember that the positions of the argument determine whether it will be vertical or horizontal--> Double-click **here** for the solution.<!-- The answer is below:ax = sns.boxplot(x="age", y="minority", data=ratings_df)--> Question 3: Create a group histogram of ... | ## insert code | _____no_output_____ | MIT | IBM-statistics/2-Visualizing_Data.ipynb | brndnaxr/brndnaxr-micro-projects |
Double-click **here** for the solution.<!-- The answer is below:sns.catplot(x='tenure', hue = 'minority', row = 'gender', kind='count', data=ratings_df, height = 3, aspect = 2)--> Question 4: Create a boxplot of the age variable | ## insert code | _____no_output_____ | MIT | IBM-statistics/2-Visualizing_Data.ipynb | brndnaxr/brndnaxr-micro-projects |
An analysis of the dataset presented in [this technical comment](https://arxiv.org/abs/2004.06601), but with our quality cuts appliedAs a response to our paper [Dessert et al. _Science_ 2020](https://science.sciencemag.org/content/367/6485/1465) (DRS20), we received [a technical comment](https://arxiv.org/abs/2004.066... | # Import required modules
%matplotlib inline
%load_ext autoreload
%autoreload 2
import sys,os
import numpy as np
from scipy.stats import chi2 as chi2_scipy
from scipy.optimize import dual_annealing
from scipy.optimize import minimize
import matplotlib.pyplot as plt
from matplotlib import rc
from matplotlib import ... | _____no_output_____ | MIT | Jupyter/BMRS20_mos_our_cuts.ipynb | bsafdi/BlankSkyfor3p5 |
**NB**: In this notebook, we minimize with `scipy` so that it is easy to run for the interested reader. For scientific analysis, we recommend [Minuit](https://iminuit.readthedocs.io/en/latest/) as a minimizer. In our paper, we used Minuit. Define signal line energyBy default we will look for an anomalous line at 3.48 ... | EUXL = 3.48 # [keV] | _____no_output_____ | MIT | Jupyter/BMRS20_mos_our_cuts.ipynb | bsafdi/BlankSkyfor3p5 |
**NB:** changing EUXL will of course vary the results below, and values in the surrounding discussion will not necessarily be reflective. Load in the data and modelsFirst we will load in the data products that we will use in the analysis. These include the stacked MOS data, associated energy bins, and uncertainties. W... | ## Signal Region (20-35 degrees)
data = np.load("../data/data_mos_boyarsky_ROI_our_cuts.npy") # [cts/s/keV]
data_yerrs = np.load("../data/data_yerrs_mos_boyarsky_ROI_our_cuts.npy") # [cts/s/keV]
QPB = np.load("../data/QPB_mos_boyarsky_ROI_our_cuts.npy") # [cts/s/keV]
# Exposure time
Exp = 8.49e6 # [s]
# D-factor aver... | _____no_output_____ | MIT | Jupyter/BMRS20_mos_our_cuts.ipynb | bsafdi/BlankSkyfor3p5 |
Load in the ModelsNext we use the models that will be used in fitting the above data.There are a sequence of models corresponding to physical line fluxes at the energies specified by `Es_line`. That is, `mod_UXL` gives the detectors counts as a function of energy after forward modeling a physical line at EUXL keV wit... | # Load the forward-modeled lines and energies
mods = np.load("../data/mos_mods.npy")
Es_line = np.load("../data/mos_mods_line_energies.npy")
# Load the detector response
det_res = np.load("../data/mos_det_res.npy")
arg_UXL = np.argmin((Es_line-EUXL)**2)
mod_UXL = mods[arg_UXL]
print "The energy of our "+str(EUXL)+" ... | The energy of our 3.48 keV line example will be: 3.4824707846410687 keV
| MIT | Jupyter/BMRS20_mos_our_cuts.ipynb | bsafdi/BlankSkyfor3p5 |
Visualize the dataData in the signal region, where the dashed vertical line denotes the location of a putative signal line. Note in particular the flux is similar to that in Fig. 2 of DRS20, indicating that the included observations are low-background. | fig = plt.figure(figsize=(10,8))
plt.errorbar(Energies,data,yerr=data_yerrs,xerr=(Energies[1]-Energies[0])/2.,
color="black",label="data",marker="o", fmt='none',capsize=4)
plt.axvline(EUXL,color="black",linestyle="dashed")
plt.xlim(EUXL-0.25,EUXL+0.25)
plt.ylim(7.9e-2,0.1)
plt.xticks(fontsize=22)
plt.ytick... | /sw/lsa/centos7/python-anaconda2/2019.03/lib/python2.7/site-packages/matplotlib/font_manager.py:1331: UserWarning: findfont: Font family [u'serif'] not found. Falling back to DejaVu Sans
(prop.get_family(), self.defaultFamily[fontext]))
| MIT | Jupyter/BMRS20_mos_our_cuts.ipynb | bsafdi/BlankSkyfor3p5 |
Statistical analysisNow, let's perform a rigorous statistical analysis, using profile likelihood. As we operate in the large counts limit for the stacked data, we can perform a simple $\chi^2$ analysis rather than a full joint likelihood analysis as used by default in Dessert et al. 2020. | ## Define the functions we will use
class chi2:
""" A set offunctions for calculation the chisq associated with different hypotheses
"""
def __init__(self,ens,dat,err,null_mod,sig_template):
self._ens = ens
self._dat = dat
self._err = err
self._null_mod = null_mod
se... | _____no_output_____ | MIT | Jupyter/BMRS20_mos_our_cuts.ipynb | bsafdi/BlankSkyfor3p5 |
Fit within $E_{\rm UXL} \pm 0.25$ keVFirst, we will fit the models from $[E_{\rm UXL}-0.25,\,E_{\rm UXL}+0.25]$ keV. Later in this notebook, we broaden this range to 3.0 to 4.0 keV. For the default $E_{\rm UXL} = 3.48$ keV, this corresponds to $3.23~{\rm keV} < E < 3.73~{\rm keV}$.To begin with then, let's reduce the ... | whs_reduced = np.where((Energies >= EUXL-0.25) & (Energies <= EUXL+0.25))[0]
Energies_reduced = Energies[whs_reduced]
data_reduced = data[whs_reduced]
data_yerrs_reduced = data_yerrs[whs_reduced]
data_bkg_reduced = data_bkg[whs_reduced]
data_yerrs_bkg_reduced = data_yerrs_bkg[whs_reduced]
mod_UXL_reduced = mod_UXL[whs_... | _____no_output_____ | MIT | Jupyter/BMRS20_mos_our_cuts.ipynb | bsafdi/BlankSkyfor3p5 |
Let's fit this data with the background only hypothesis and consider the quality of fit. A polynomial background modelHere we model the continuum background as a quadratic. In addition, we add degrees of freedom associated with the possible background lines at 3.3 keV and 3.7 keV. | arg_3p3 = np.argmin((Es_line-3.32)**2)
mod_3p3 = mods[arg_3p3]
arg_3p7 = np.argmin((Es_line-3.68)**2)
mod_3p7 = mods[arg_3p7]
def mod_poly_two_lines(ens,x):
"An extended background model to include two additional lines"
A, B, C, S1, S2 = x
return A+B*ens + C*ens**2 + S1*mod_3p3[whs_reduced] + S2*mod_3p7[... | The Delta chi^2 between signal and null model is: 0.18286814612878288
The chi^2/DOF of the null-model fit is: 0.9413439893438815
Expected 68% containment for the chi^2/DOF: [0.85614219 1.14370943]
Expected 99% containment for the chi^2/DOF: [0.66578577 1.41312157]
| MIT | Jupyter/BMRS20_mos_our_cuts.ipynb | bsafdi/BlankSkyfor3p5 |
The null model is a good fit to the data, and the best-fit signal strength is still consistent with zero at 1$\sigma$.Next we plot the best fit signal and background model, in particular we see the model is almost identical in the two cases, emphasizing the lack of preference for a new emission line at 3.48 keV in this... | fig = plt.figure(figsize=(10,8))
plt.errorbar(Energies,data,yerr=data_yerrs,xerr=(Energies[1]-Energies[0])/2.,
color="black",label="data",marker="o", fmt='none',capsize=4)
plt.plot(Energies_reduced,mod_poly_two_lines(Energies_reduced,mn_null_line.x),'k-',label =r"Null model")
plt.plot(Energies_reduced,mod_... | _____no_output_____ | MIT | Jupyter/BMRS20_mos_our_cuts.ipynb | bsafdi/BlankSkyfor3p5 |
Finally let's compute the associated limit via profile likelihood. | A_sig_array = np.linspace(mn_line.x[0],0.05,100)
chi2_sig_array = np.zeros(len(A_sig_array))
bf = mn_line.x[1:]
for i in range(len(A_sig_array)):
chi2_instance.fix_signal_strength(A_sig_array[i])
mn_profile = minimize(chi2_instance.chi2_fixed_signal,bf,method='Nelder-Mead',
options={'f... | The 95% upper limit on the signal flux is 0.02664201119758925 cts/cm^2/s/sr
This corresponds to a limit on sin^2(2theta) of 2.382479159553265e-11
| MIT | Jupyter/BMRS20_mos_our_cuts.ipynb | bsafdi/BlankSkyfor3p5 |
Power law background model Now let's try a power law for the continuum background model (along with the two lines) as done in BMRS. Given that the stacked data is the sum of power laws, we would not expect the stacked data to be a power law itself, although in our relatively clean dataset we find it to be a reasonable... | def mod_power_two_lines(ens,x):
"An extended background model to include two additional lines"
A, n, S1, S2 = x
return A*ens**n + S1*mod_3p3[whs_reduced] + S2*mod_3p7[whs_reduced]
chi2_instance = chi2(Energies_reduced,data_reduced,data_yerrs_reduced,mod_power_two_lines,mod_UXL_reduced)
mn_null_line = mi... | The 95% upper limit on the signal flux is 0.020575238409308062 cts/cm^2/s/sr
This corresponds to a limit on sin^2(2theta) of 1.8399540616307525e-11
| MIT | Jupyter/BMRS20_mos_our_cuts.ipynb | bsafdi/BlankSkyfor3p5 |
The power law continuum background does not substantively change the results: we still find no evidence for a line. Note this is the same procedure as in BMRS's test color-coded red in their Fig. 1 and Tab. 1. In that analysis, they find marginal 1.3$\sigma$ evidence for a line, although on our cleaner dataset we found... | whs_reduced = np.where((Energies >= 3.0) & (Energies <= 4.0))[0]
Energies_reduced = Energies[whs_reduced]
data_reduced = data[whs_reduced]
data_yerrs_reduced = data_yerrs[whs_reduced]
data_bkg_reduced = data_bkg[whs_reduced]
data_yerrs_bkg_reduced = data_yerrs_bkg[whs_reduced]
mod_UXL_reduced = mod_UXL[whs_reduced]
ar... | Best fit background parameters: [ 0.1807753 -0.58187775 0.02547398 0.01436228 0.09052193 0.03304785]
Best fit signal+background parameters: [ 0.0015216 0.18110231 -0.58372105 0.02608541 0.0154532 0.0911047
0.03434406]
The Delta chi^2 between signal and null model is: 0.03379302143113705
The chi^2/DOF of th... | MIT | Jupyter/BMRS20_mos_our_cuts.ipynb | bsafdi/BlankSkyfor3p5 |
We find no evidence for a 3.5 keV line when we expand the energy window. Although the best-fit signal strength is positive, the $\Delta \chi^2 \sim 0.03$, which is entirely negligable significance. Let's have a look at the best fit signal and background models in this case. There are subtle difference between the two, ... | flux_ill = 4.8e-11 / return_sin_theta_lim(EUXL,1.,D_signal)
print "Flux [cts/cm^2/s/sr] and sin^(2theta) for illustration: ", flux_ill, return_sin_theta_lim(EUXL,flux_ill,D_signal)
chi2_instance.fix_signal_strength(flux_ill)
mn_f = dual_annealing(chi2_instance.chi2_fixed_signal,x0=x0,bounds=bounds,local_search_option... | _____no_output_____ | MIT | Jupyter/BMRS20_mos_our_cuts.ipynb | bsafdi/BlankSkyfor3p5 |
**NB:** In the plot above we averaged the data solely for presentation purposes, no averaging was performed in the analysis.Finally, we compute the limit in this case using the by now familiar procedure. | A_sig_array = np.linspace(mn.x[0],0.05,100)
chi2_sig_array = np.zeros(len(A_sig_array))
bf = mn.x[1:]
for i in range(len(A_sig_array)):
chi2_instance.fix_signal_strength(A_sig_array[i])
mn_profile = minimize(chi2_instance.chi2_fixed_signal,bf,method='Nelder-Mead')
bf = mn_profile.x
chi2_sig_array[i] = m... | The 95% upper limit on the signal flux is 0.015232665842012591 cts/cm^2/s/sr
This corresponds to a limit on sin^2(2theta) of 1.362191038952712e-11
| MIT | Jupyter/BMRS20_mos_our_cuts.ipynb | bsafdi/BlankSkyfor3p5 |
Now with a polynomial background Here we repeat the earlier analysis but with a polynomial background model, as used in the stacked analysis in DRS20 Supplementary Material Sec. 2.9. | whs_reduced = np.where((Energies >= 3.0) & (Energies <= 4.0))[0]
Energies_reduced = Energies[whs_reduced]
data_reduced = data[whs_reduced]
data_yerrs_reduced = data_yerrs[whs_reduced]
data_bkg_reduced = data_bkg[whs_reduced]
data_yerrs_bkg_reduced = data_yerrs_bkg[whs_reduced]
mod_UXL_reduced = mod_UXL[whs_reduced]
ar... | The 95% upper limit on the signal flux is 0.02781422393515111 cts/cm^2/s/sr
This corresponds to a limit on sin^2(2theta) of 2.487305045147695e-11
| MIT | Jupyter/BMRS20_mos_our_cuts.ipynb | bsafdi/BlankSkyfor3p5 |
This change to the background continuum model does not change any conclusions. The 3.5 keV line is in tension with these limits. Subtract the background dataNow, we subtract off the data taken far away from the Galactic Center. We use a folded powerlaw for the background continuum under the assumption that the residu... | # A folded powerlaw function
def folded_PL(A,n):
mod_F = np.matmul(det_res,A*Energies**n)
return mod_F
def mod_folded_power_four_lines(ens,x):
A, n,S1, S2, S3, S4 = x
return folded_PL(A,n)[whs_reduced] + S1*mod_3p3[whs_reduced] + S2*mod_3p7[whs_reduced]+ S3*mod_3p1[whs_reduced] + S4*mod_3p9[whs_reduce... | The 95% upper limit on the signal flux is 0.01567112720512729 cts/cm^2/s/sr
This corresponds to a limit on sin^2(2theta) of 2.476370769990894e-11
| MIT | Jupyter/BMRS20_mos_our_cuts.ipynb | bsafdi/BlankSkyfor3p5 |
In this version of the analysis, too, we see no evidence for a 3.5 keV line and obtain comparable limits as in the stacked analyses in the previous sections. Include the Quiescent Particle Background (QPB)Now we will do a joint likelihood including the QPB data. The QPB data is complicated because the data is correlat... | # We are going to fix a powerlaw to the QPB data and then renormalize the chi^2 function
def PL(A,n,ens):
return A*ens**n
def chi2_QPB_UN(x):
A,n = x
mod = PL(A,n,Energies_reduced)
return np.sum((mod-QPB[whs_reduced])**2)
mn_QPB = minimize(chi2_QPB_UN,[0.084,-0.20],method="Nelder-Mead")
bf_QPB=mn_QPB.... | The 95% upper limit on the signal flux is 0.019016670961038363 cts/cm^2/s/sr
This corresponds to a limit on sin^2(2theta) of 1.700578155032655e-11
| MIT | Jupyter/BMRS20_mos_our_cuts.ipynb | bsafdi/BlankSkyfor3p5 |
Multi-ConvNet Sentiment Classifier In this notebook, we concatenate the outputs of *multiple, parallel convolutional layers* to classify IMDB movie reviews by their sentiment. Load dependencies | import tensorflow
from tensorflow.keras.datasets import imdb
from tensorflow.keras.preprocessing.sequence import pad_sequences
from tensorflow.keras.models import Model # new!
from tensorflow.keras.layers import Input, concatenate # new!
from tensorflow.keras.layers import Dense, Dropout, Embedding, SpatialDropout1D, ... | _____no_output_____ | MIT | notebooks/multi_convnet_sentiment_classifier.ipynb | ewbolme/DLTFpT |
Set hyperparameters | # output directory name:
output_dir = 'model_output/multiconv'
# training:
epochs = 4
batch_size = 128
# vector-space embedding:
n_dim = 64
n_unique_words = 5000
max_review_length = 400
pad_type = trunc_type = 'pre'
drop_embed = 0.2
# convolutional layer architecture:
n_conv_1 = n_conv_2 = n_conv_3 = 256
k_conv_... | _____no_output_____ | MIT | notebooks/multi_convnet_sentiment_classifier.ipynb | ewbolme/DLTFpT |
Load data | (x_train, y_train), (x_valid, y_valid) = imdb.load_data(num_words=n_unique_words) | _____no_output_____ | MIT | notebooks/multi_convnet_sentiment_classifier.ipynb | ewbolme/DLTFpT |
Preprocess data | x_train = pad_sequences(x_train, maxlen=max_review_length, padding=pad_type, truncating=trunc_type, value=0)
x_valid = pad_sequences(x_valid, maxlen=max_review_length, padding=pad_type, truncating=trunc_type, value=0) | _____no_output_____ | MIT | notebooks/multi_convnet_sentiment_classifier.ipynb | ewbolme/DLTFpT |
Design neural network architecture | input_layer = Input(shape=(max_review_length,),
dtype='int16', name='input')
# embedding:
embedding_layer = Embedding(n_unique_words, n_dim,
name='embedding')(input_layer)
drop_embed_layer = SpatialDropout1D(drop_embed,
name='drop... | _____no_output_____ | MIT | notebooks/multi_convnet_sentiment_classifier.ipynb | ewbolme/DLTFpT |
Configure model | model.compile(loss='binary_crossentropy', optimizer='nadam', metrics=['accuracy'])
modelcheckpoint = ModelCheckpoint(filepath=output_dir+"/weights.{epoch:02d}.hdf5")
if not os.path.exists(output_dir):
os.makedirs(output_dir) | _____no_output_____ | MIT | notebooks/multi_convnet_sentiment_classifier.ipynb | ewbolme/DLTFpT |
Train! | model.fit(x_train, y_train, batch_size=batch_size, epochs=epochs, verbose=1, validation_data=(x_valid, y_valid), callbacks=[modelcheckpoint]) | _____no_output_____ | MIT | notebooks/multi_convnet_sentiment_classifier.ipynb | ewbolme/DLTFpT |
Evaluate | model.load_weights(output_dir+"/weights.02.hdf5")
y_hat = model.predict(x_valid)
plt.hist(y_hat)
_ = plt.axvline(x=0.5, color='orange')
"{:0.2f}".format(roc_auc_score(y_valid, y_hat)*100.0) | _____no_output_____ | MIT | notebooks/multi_convnet_sentiment_classifier.ipynb | ewbolme/DLTFpT |
工厂规划等级:中级 目的和先决条件此模型和Factory Planning II都是生产计划问题的示例。在生产计划问题中,必须选择要生产哪些产品,要生产多少产品以及要使用哪些资源,以在满足一系列限制的同时最大化利润或最小化成本。这些问题在广泛的制造环境中都很常见。 What You Will Learn在此特定示例中,我们将建模并解决生产组合问题:在每个阶段中,我们可以制造一系列产品。每种产品在不同的机器上生产需要不同的时间,并产生不同的利润。目的是创建最佳的多周期生产计划,以使利润最大化。由于维护,某些机器在特定时期内不可用。由于市场限制,每个产品每个月的销售量都有上限,并且存储容量也受到限制。In Factory Planni... | import gurobipy as gp
import numpy as np
import pandas as pd
from gurobipy import GRB
# tested with Python 3.7.0 & Gurobi 9.0 | _____no_output_____ | Apache-2.0 | documents/Intermediate/FactoryPlanning1&2/factory_planning_1.ipynb | biancaitian/gurobi-official-examples |
Input DataWe define all the input data of the model. | # Parameters
products = ["Prod1", "Prod2", "Prod3", "Prod4", "Prod5", "Prod6", "Prod7"]
machines = ["grinder", "vertDrill", "horiDrill", "borer", "planer"]
months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun"]
profit = {"Prod1":10, "Prod2":6, "Prod3":8, "Prod4":4, "Prod5":11, "Prod6":9, "Prod7":3}
time_req = {
"gr... | _____no_output_____ | Apache-2.0 | documents/Intermediate/FactoryPlanning1&2/factory_planning_1.ipynb | biancaitian/gurobi-official-examples |
Model DeploymentWe create a model and the variables. For each product (seven kinds of products) and each time period (month), we will create variables for the amount of which products get manufactured, held, and sold. In each month, there is an upper limit on the amount of each product that can be sold. This is due to... | factory = gp.Model('Factory Planning I')
make = factory.addVars(months, products, name="Make") # quantity manufactured
store = factory.addVars(months, products, ub=max_inventory, name="Store") # quantity stored
sell = factory.addVars(months, products, ub=max_sales, name="Sell") # quantity sold | Using license file c:\gurobi\gurobi.lic
Set parameter TokenServer to value SANTOS-SURFACE-
| Apache-2.0 | documents/Intermediate/FactoryPlanning1&2/factory_planning_1.ipynb | biancaitian/gurobi-official-examples |
Next, we insert the constraints. The balance constraints ensure that the amount of product that is in storage in the prior month plus the amount that gets manufactured equals the amount that is sold and held for each product in the current month. This ensures that all products in the model are manufactured in some mon... | #1. Initial Balance
Balance0 = factory.addConstrs((make[months[0], product] == sell[months[0], product]
+ store[months[0], product] for product in products), name="Initial_Balance")
#2. Balance
Balance = factory.addConstrs((store[months[months.index(month) -1], product] +
make[m... | _____no_output_____ | Apache-2.0 | documents/Intermediate/FactoryPlanning1&2/factory_planning_1.ipynb | biancaitian/gurobi-official-examples |
The Inventory Target constraints force that at the end of the last month the storage contains the specified amount of each product. | #3. Inventory Target
TargetInv = factory.addConstrs((store[months[-1], product] == store_target for product in products), name="End_Balance") | _____no_output_____ | Apache-2.0 | documents/Intermediate/FactoryPlanning1&2/factory_planning_1.ipynb | biancaitian/gurobi-official-examples |
The capacity constraints ensure that, for each month, the time all products require on a certain kind of machine is less than or equal to the available hours for that type of machine in that month multiplied by the number of available machines in that period. Each product requires some machine hours on different machin... | #4. Machine Capacity
MachineCap = factory.addConstrs((gp.quicksum(time_req[machine][product] * make[month, product]
for product in time_req[machine])
<= hours_per_month * (installed[machine] - down.get((month, machine), 0))
for machine in machines fo... | _____no_output_____ | Apache-2.0 | documents/Intermediate/FactoryPlanning1&2/factory_planning_1.ipynb | biancaitian/gurobi-official-examples |
The objective is to maximize the profit of the company, which consists ofthe profit for each product minus the cost for storing the unsold products. This can be stated as: | #0. Objective Function
obj = gp.quicksum(profit[product] * sell[month, product] - holding_cost * store[month, product]
for month in months for product in products)
factory.setObjective(obj, GRB.MAXIMIZE) | _____no_output_____ | Apache-2.0 | documents/Intermediate/FactoryPlanning1&2/factory_planning_1.ipynb | biancaitian/gurobi-official-examples |
Next, we start the optimization and Gurobi finds the optimal solution. | factory.optimize() | Gurobi Optimizer version 9.0.0 build v9.0.0rc2 (win64)
Optimize a model with 79 rows, 126 columns and 288 nonzeros
Model fingerprint: 0xead11e9d
Coefficient statistics:
Matrix range [1e-02, 1e+00]
Objective range [5e-01, 1e+01]
Bounds range [6e+01, 1e+03]
RHS range [5e+01, 2e+03]
Presolve remove... | Apache-2.0 | documents/Intermediate/FactoryPlanning1&2/factory_planning_1.ipynb | biancaitian/gurobi-official-examples |
--- AnalysisThe result of the optimization model shows that the maximum profit we can achieve is $\$93,715.18$.Let's see the solution that achieves that optimal result. Production PlanThis plan determines the amount of each product to make at each period of the planning horizon. For example, in February we make 700 uni... | rows = months.copy()
columns = products.copy()
make_plan = pd.DataFrame(columns=columns, index=rows, data=0.0)
for month, product in make.keys():
if (abs(make[month, product].x) > 1e-6):
make_plan.loc[month, product] = np.round(make[month, product].x, 1)
make_plan | _____no_output_____ | Apache-2.0 | documents/Intermediate/FactoryPlanning1&2/factory_planning_1.ipynb | biancaitian/gurobi-official-examples |
Sales PlanThis plan defines the amount of each product to sell at each period of the planning horizon. For example, in February we sell 600 units of product Prod1. | rows = months.copy()
columns = products.copy()
sell_plan = pd.DataFrame(columns=columns, index=rows, data=0.0)
for month, product in sell.keys():
if (abs(sell[month, product].x) > 1e-6):
sell_plan.loc[month, product] = np.round(sell[month, product].x, 1)
sell_plan | _____no_output_____ | Apache-2.0 | documents/Intermediate/FactoryPlanning1&2/factory_planning_1.ipynb | biancaitian/gurobi-official-examples |
Inventory PlanThis plan reflects the amount of product in inventory at the end of each period of the planning horizon. For example, at the end of February we have 100 units of Prod1 in inventory. | rows = months.copy()
columns = products.copy()
store_plan = pd.DataFrame(columns=columns, index=rows, data=0.0)
for month, product in store.keys():
if (abs(store[month, product].x) > 1e-6):
store_plan.loc[month, product] = np.round(store[month, product].x, 1)
store_plan | _____no_output_____ | Apache-2.0 | documents/Intermediate/FactoryPlanning1&2/factory_planning_1.ipynb | biancaitian/gurobi-official-examples |
Note* Instructions have been included for each segment. You do not have to follow them exactly, but they are included to help you think through the steps. | # Dependencies and Setup
import pandas as pd
# File to Load (Remember to Change These)
school_data_to_load = "Resources/schools_complete.csv"
student_data_to_load = "Resources/students_complete.csv"
# Read School and Student Data File and store into Pandas DataFrames
school_data = pd.read_csv(school_data_to_load)
stu... | _____no_output_____ | MIT | PyCitySchools_starter.ipynb | pratixashah/Pandas_City_School |
District Summary* Calculate the total number of schools* Calculate the total number of students* Calculate the total budget* Calculate the average math score * Calculate the average reading score* Calculate the percentage of students with a passing math score (70 or greater)* Calculate the percentage of students with ... | total_school = len(school_data_complete["school_name"].unique())
total_student = sum(school_data_complete["size"].unique())
student_pass_math = school_data_complete.loc[school_data_complete["math_score"] >= 70]
student_pass_reading = school_data_complete.loc[school_data_complete["reading_score"] >= 70]
student_pass_ma... | _____no_output_____ | MIT | PyCitySchools_starter.ipynb | pratixashah/Pandas_City_School |
School Summary * Create an overview table that summarizes key metrics about each school, including: * School Name * School Type * Total Students * Total School Budget * Per Student Budget * Average Math Score * Average Reading Score * % Passing Math * % Passing Reading * % Overall Passing (The percentage of ... | group_by_school_data = school_data_complete.groupby(["school_name","type"])
group_by_school_pass_math = student_pass_math.groupby(["school_name","type"])
group_by_school_pass_reading = student_pass_reading.groupby(["school_name","type"])
group_by_school_pass_math_and_reading = student_pass_math_and_reading.groupby(["s... | _____no_output_____ | MIT | PyCitySchools_starter.ipynb | pratixashah/Pandas_City_School |
Top Performing Schools (By % Overall Passing) * Sort and display the top five performing schools by % overall passing. | group_by_school_data_sorted = school_summary_df.sort_values("% Overall Passing", ascending=False)
group_by_school_data_sorted.head(5) | _____no_output_____ | MIT | PyCitySchools_starter.ipynb | pratixashah/Pandas_City_School |
Bottom Performing Schools (By % Overall Passing) * Sort and display the five worst-performing schools by % overall passing. | group_by_school_data_sorted = school_summary_df.sort_values("% Overall Passing")
group_by_school_data_sorted.head(5) | _____no_output_____ | MIT | PyCitySchools_starter.ipynb | pratixashah/Pandas_City_School |
Math Scores by Grade * Create a table that lists the average Reading Score for students of each grade level (9th, 10th, 11th, 12th) at each school. * Create a pandas series for each grade. Hint: use a conditional statement. * Group each series by school * Combine the series into a dataframe * Optional: give ... | # math_score_by_grade = school_data_complete.groupby(["school_name","grade"])
# math_score_by_grade["math_score"].mean()
math_score_by_grade_9 = school_data_complete.loc[school_data_complete["grade"] == "9th"]
math_score_by_grade_9_school = math_score_by_grade_9.groupby("school_name")
math_score_by_grade_10 = school_... | _____no_output_____ | MIT | PyCitySchools_starter.ipynb | pratixashah/Pandas_City_School |
Reading Score by Grade * Perform the same operations as above for reading scores | # reading_score_by_grade = school_data_complete.groupby(["school_name","grade"])
# reading_score_by_grade["reading_score"].mean()
reading_score_by_grade_9 = school_data_complete.loc[school_data_complete["grade"] == "9th"]
reading_score_by_grade_9_school = reading_score_by_grade_9.groupby("school_name")
reading_score_... | _____no_output_____ | MIT | PyCitySchools_starter.ipynb | pratixashah/Pandas_City_School |
Scores by School Spending * Create a table that breaks down school performances based on average Spending Ranges (Per Student). Use 4 reasonable bins to group school spending. Include in the table each of the following: * Average Math Score * Average Reading Score * % Passing Math * % Passing Reading * Overall Pa... | score_by_spending = school_summary.copy()
bins=[0,585,630,645,680]
labels=["<$585","$585-630","$630-645","$645-680"]
score_by_spending["Spending Ranges (Per Student)"] = pd.cut(score_by_spending["Per Student Budget"],bins,labels=labels, include_lowest=True)
score_by_spending
score_by_spending_group = score_by_spendin... | _____no_output_____ | MIT | PyCitySchools_starter.ipynb | pratixashah/Pandas_City_School |
Scores by School Size * Perform the same operations as above, based on school size. | score_by_school_size = school_summary.copy()
bins=[0,1000,2000,5000]
labels = ["Small (<1000)","Medium (1000-2000)","Large (2000-5000)"]
score_by_school_size["School Type"] = pd.cut(score_by_school_size["Total Students"],bins,labels=labels)
score_by_school_size_group = score_by_school_size.groupby(["School Type"])
s... | _____no_output_____ | MIT | PyCitySchools_starter.ipynb | pratixashah/Pandas_City_School |
Scores by School Type * Perform the same operations as above, based on school type | score_by_school_type = school_summary.copy()
score_by_school_type_group = score_by_school_type.groupby(["type"])
score_by_school_type_df = pd.DataFrame({
"Average Math Score":map("{:.2f}".format,score_by_school_type_group["Average Math Score"].mean()),
"Average Reading Score":map("{:.2f}".format,score_by_schoo... | _____no_output_____ | MIT | PyCitySchools_starter.ipynb | pratixashah/Pandas_City_School |
Lesson 2: Computer Vision Fundamentals Submission, Markus Schwickert, 2018-02-22 Photos | #importing some useful packages
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
import cv2
import os
%matplotlib inline
#reading in an image
k1=0 # select here which of the images in the directory you want to process (0-5)
test_images=os.listdir("test_images/")
print ('test_images/'+... | _____no_output_____ | MIT | L2_computer_vision.ipynb | schwickert/auto |
Estimating $\pi$ by Sampling PointsBy Evgenia "Jenny" Nitishinskaya and Delaney Granizo-MackenzieNotebook released under the Creative Commons Attribution 4.0 License.---A stochastic way to estimate the value of $\pi$ is to sample points from a square area. Some of the points will fall within the area of a circle as def... | # Import libraries
import math
import numpy as np
import matplotlib.pyplot as plt
in_circle = 0
outside_circle = 0
n = 10 ** 4
# Draw many random points
X = np.random.rand(n)
Y = np.random.rand(n)
for i in range(n):
if X[i]**2 + Y[i]**2 > 1:
outside_circle += 1
else:
in_circle += 1
area... | _____no_output_____ | CC-BY-4.0 | presentations/How To - Estimate Pi.ipynb | johnmathews/quant1 |
We can visualize the process to see how it works. | # Plot a circle for reference
circle1=plt.Circle((0,0),1,color='r', fill=False, lw=2)
fig = plt.gcf()
fig.gca().add_artist(circle1)
# Set the axis limits so the circle doesn't look skewed
plt.xlim((0, 1.8))
plt.ylim((0, 1.2))
plt.scatter(X, Y) | _____no_output_____ | CC-BY-4.0 | presentations/How To - Estimate Pi.ipynb | johnmathews/quant1 |
Finally, let's see how our estimate gets better as we increase $n$. We'll do this by computing the estimate for $\pi$ at each step and plotting that estimate to see how it converges. | in_circle = 0
outside_circle = 0
n = 10 ** 3
# Draw many random points
X = np.random.rand(n)
Y = np.random.rand(n)
# Make a new array
pi = np.ndarray(n)
for i in range(n):
if X[i]**2 + Y[i]**2 > 1:
outside_circle += 1
else:
in_circle += 1
area_of_quarter_circle = float(in_circle)/(... | _____no_output_____ | CC-BY-4.0 | presentations/How To - Estimate Pi.ipynb | johnmathews/quant1 |
Training a recommender system on a standalone datasetTrain a recommender system with fastai using a standalone dataset- This notebook ingests the Amazon reviews dataset (https://www.kaggle.com/saurav9786/amazon-product-reviews) | # imports for notebook boilerplate
!pip install -Uqq fastbook
import fastbook
from fastbook import *
from fastai.collab import *
# set up the notebook for fast.ai
fastbook.setup_book()
modifier = 'apr13' | _____no_output_____ | MIT | ch5/training_recommender_systems_on_standalone_dataset.ipynb | Vega95/Deep-Learning-with-fastai-Cookbook |
Ingest the dataset- define the path object- define a dataframe to contain the dataset | # ingest the standalone dataset
# this step assumes you have completed the steps in "Getting Ready"
# in section "Training a recommender system on a standalone dataset" of Chapter 5
path = URLs.path('amazon_reviews')
# examine the directory structure
path.ls()
# ingest the dataset into a Pandas dataframe
df = pd.read_c... | _____no_output_____ | MIT | ch5/training_recommender_systems_on_standalone_dataset.ipynb | Vega95/Deep-Learning-with-fastai-Cookbook |
Examine the dataset | # examine the first few records in the dataframe
df.head()
# get the number of records in the dataset
df.shape
# get the count of unique values in each column of the dataset
df.nunique()
# count the number of missing values in each column of the dataset
df.isnull().sum()
df['rating'].nunique()
%%time
# defined a Collab... | _____no_output_____ | MIT | ch5/training_recommender_systems_on_standalone_dataset.ipynb | Vega95/Deep-Learning-with-fastai-Cookbook |
Define and train the model | %%time
# define the model
learn=collab_learner(dls,y_range= [ 0 , 5.0 ] )
%%time
# train the model
learn.fit_one_cycle( 1 ) | _____no_output_____ | MIT | ch5/training_recommender_systems_on_standalone_dataset.ipynb | Vega95/Deep-Learning-with-fastai-Cookbook |
Exercise the trained model- define a dataframe containing test data- apply the trained model to the dataframe | # set values for test dataframe
scoring_columns = ['userID','productID']
test_df = pd.DataFrame(columns=scoring_columns)
test_df.at[0,'userID'] = 'A2NYK9KWFMJV4Y'
test_df.at[0,'productID'] = 'B008ABOJKS'
test_df.at[1,'userID'] = 'A29ZTEO6EKSRDV'
test_df.at[1,'productID'] = 'B006202R44'
test_df.head()
dl = learn.dls.tes... | _____no_output_____ | MIT | ch5/training_recommender_systems_on_standalone_dataset.ipynb | Vega95/Deep-Learning-with-fastai-Cookbook |
Good review of numpy https://www.youtube.com/watch?v=GB9ByFAIAH4 Numpy library - Remember to do pip install numpy Numpy provides support for math and logical operations on arrays https://www.tutorialspoint.com/numpy/index.htm It supports many more data types than python https://www.tutorialspoint.com/numpy/nu... | a = np.array([1,2,3,4])
print(id(a))
print(type(a))
b = np.array(a)
print(f'b = {id(b)}')
a = a + 1
a | 140321654298944
<class 'numpy.ndarray'>
b = 140321654357568
| MIT | 04-Linear_Regresion_Python/NumpyIntro-Answers.ipynb | Chilefase/MIT-1.001 |
# arange vs linspace - both generate a numpy array of numbers
import numpy as np
np.linspace(0,10,5) # specifies No. of values with 0 and 10 being first and last
np.arange(0, 10, 5) # specifies step size=5 starting at 0 up to but NOT including last
x = np.linspace(0,10,11) # generate 10 numbers
x = x + 1 ... | _____no_output_____ | MIT | 04-Linear_Regresion_Python/NumpyIntro-Answers.ipynb | Chilefase/MIT-1.001 | |
Normal Distribution $\text{the normal distribution is given by} \\$$$f(z)=\frac{1}{\sqrt{2 \pi}}e^{-\frac{(z)^2}{2}} $$$\text{This can be rewritten in term of the mean and variance} \\$$$f(x)=\frac{1}{\sigma \sqrt{2 \pi}}e^{-\frac{(x- \mu)^2}{2 \sigma^2}}$$The random variable $X$ described by the PDF is a normal vari... | # Normal Data
a = np.random.normal(10,2,10)
plt.hist(a,bins=np.arange(5,16,1),density=True)
plt.scatter(np.arange(5,15,1),a)
plt.plot(a)
plt.hist(a,bins=np.arange(5,16,0.1), density=True)
plt.hist(a,bins=np.arange(5,16,1))
import numpy as np
import matplotlib.pyplot as plt
a = np.random.normal(0,2,200)
plt.hist(a, ... | _____no_output_____ | MIT | 04-Linear_Regresion_Python/NumpyIntro-Answers.ipynb | Chilefase/MIT-1.001 |
Mean and Variance$$\mu = \frac{\sum(x)}{N}$$$$\sigma^{2} =\sum{\frac{(x - \mu)^{2}}{N} }$$ | # IN CLASS - Generate a Population and calculate its mean and variance
import matplotlib.pyplot as plt
Npoints = 10
p = np.random.normal(0,10,Npoints*100)
def myMean(sample):
N = len(sample)
total = 0
for x in sample:
total = total + x
return x/N
pmean = myMean(p)
print(f'mean= {pmean}')
def m... | _____no_output_____ | MIT | 04-Linear_Regresion_Python/NumpyIntro-Answers.ipynb | Chilefase/MIT-1.001 |
Calculate the mean and subtract the mean from each data value$$ | from matplotlib import collections as matcoll
Npoints = 20
x = np.arange(0,Npoints)
y = np.random.normal(loc=10, scale=2, size=Npoints )
lines = []
for i in range(Npoints):
pair=[(x[i],0), (x[i], y[i])]
lines.append(pair)
linecoll = matcoll.LineCollection(lines)
fig, ax = plt.subplots()
ax.add_collection(lineco... | _____no_output_____ | MIT | 04-Linear_Regresion_Python/NumpyIntro-Answers.ipynb | Chilefase/MIT-1.001 |
Numpy 2D Arrays | ## Multi-Dimensional Arrays
<img src='multiArray.png' width = 500>
import numpy as np
# Numpy 2_D Arrays
a = [0,1,2]
b = [3,4,5]
c = [6,7,8]
z = [a,
b,
c]
a = np.arange(0,9)
z = a.reshape(3,3)
z
z[2,2]
z[0:3:2,0:3:2]
## Exercise - Produce a 10x10 checkerboard of 1s and 0s
import numpy as np
import seabor... | _____no_output_____ | MIT | 04-Linear_Regresion_Python/NumpyIntro-Answers.ipynb | Chilefase/MIT-1.001 |
Practical Data Science in Python Unsupervised Learning: Classifying Spotify Tracks by Genre with $k$-Means ClusteringAuthors: Matthew Finney, Paulina Toro Isaza Run this First! (Function Definitions) | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_palette('Set1')
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler
from sklearn.cluster import KMeans
from IPython.display import Audio, Image, clear_output
rs = 123
np.random.seed(rs... | /usr/local/lib/python3.6/dist-packages/statsmodels/tools/_testing.py:19: FutureWarning: pandas.util.testing is deprecated. Use the functions in the public API at pandas.testing instead.
import pandas.util.testing as tm
| MIT | Session_2_Practical_Data_Science.ipynb | MattFinney/practical_data_science_in_python |
Recap from Session 1 In our earlier session, we started working with a dataset of Spotify tracks. We explored the variables in the dataset, and determined that audio features - like danceability, accousticness, and tempo - vary across the songs in our dataset and might help us to thoughtfully group the tracks into di... | # Plot the principal component analysis results
pca_plot(tracks_df[audio_feature_cols]) | _____no_output_____ | MIT | Session_2_Practical_Data_Science.ipynb | MattFinney/practical_data_science_in_python |
Today: Classification using $k$-Means Clustering Our Principal Component Analysis in the first session helped us to visualize the variation of track audio features in just two dimensions. Looking at the scatterplot of the first two principal components above, we can see that there are a few different groups of tracks.... | initial_k = ____
# Scale the data, so that the units of features don't impact feature importance
scaled_df = StandardScaler().fit_transform(tracks_df[audio_feature_cols])
# Cluster the data using the k means algorithm
initial_cluster_results = ______(n_clusters=initial_k, n_init=25, random_state=rs).fit(scaled_df) | _____no_output_____ | MIT | Session_2_Practical_Data_Science.ipynb | MattFinney/practical_data_science_in_python |
Now, let's print the cluster results. Notice that we're given a number (0 or 1) for each observation in our data set. This number is the id of the cluster assigned to each track. | # Print the cluster results
print(initial_cluster_results._______) | _____no_output_____ | MIT | Session_2_Practical_Data_Science.ipynb | MattFinney/practical_data_science_in_python |
And let's save the cluster results in our `tracks_df` dataframe as a column named `initial_cluster` so we can access them later. | # Save the cluster labels in our dataframe
tracks_df[______________] = ['Cluster ' + str(i) for i in __________.______] | _____no_output_____ | MIT | Session_2_Practical_Data_Science.ipynb | MattFinney/practical_data_science_in_python |
Let's plot the PCA plot and color each observation based on the assigned cluster to visualize our $k$-means results. | # Show a PCA plot of the clusters
pca_plot(tracks_df[audio_feature_cols], classes=tracks_df['initial_cluster']) | _____no_output_____ | MIT | Session_2_Practical_Data_Science.ipynb | MattFinney/practical_data_science_in_python |
Does it look like our $k$-means algorithm correctly separated the tracks into clusters? Does each color map to a distinct group of points? How do our clusters of songs differ? One way we can evaluate our clusters is by looking how the distribution of each data feature varies by cluster. In our case, let's check to see... | # Plot the distribution of audio features by cluster
g = sns.pairplot(tracks_df, hue="initial_cluster",
vars=['danceability', 'energy', 'loudness', 'speechiness', 'tempo'],
hue_order=sorted(tracks_df.initial_cluster.unique()), palette='Set1')
g.fig.suptitle('Distribution of Audio Featu... | _____no_output_____ | MIT | Session_2_Practical_Data_Science.ipynb | MattFinney/practical_data_science_in_python |
Experiment with different values of $k$ Use the slider to select different values of $k$, then run the cell below to see how the choice of the number of clusters affects our results. | trial_k = 10 #@param {type:"slider", min:1, max:10, step:1}
# Cluster the data using the k means algorithm
trial_cluster_results = KMeans(n_clusters=trial_k, n_init=25, random_state=rs).fit(scaled_df)
# Save the cluster labels in our dataframe
tracks_df['trial_cluster'] = ['Cluster ' + str(i) for i in trial_cluster_r... | _____no_output_____ | MIT | Session_2_Practical_Data_Science.ipynb | MattFinney/practical_data_science_in_python |
Which value of $k$ works best for our data? You may have noticed that the $k$-means algorithm requires you to choose $k$ and decide the number of clusters before you run the algorithm. But how do we know which value of $k$ is the best fit for our data? One approach is to track the total distance from points to their ... | # Calculate the Total Distance for each value of k between 1 and 10
scores = []
k_list = np.arange(____,____)
for i in k_list:
fit_k = _____(n_clusters=i, n_init=5, random_state=rs).fit(scaled_df)
scores.append(fit_k.inertia_)
# Plot this in an elbow plot
plt.figure(figsize=(11,8.5))
sns.lineplot(______, ____... | _____no_output_____ | MIT | Session_2_Practical_Data_Science.ipynb | MattFinney/practical_data_science_in_python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.