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 |
|---|---|---|---|---|---|
From the documentation we know this is the max return --- How can we get all the results? | # Let's mkae a function that updates our search to get the new pages
def ping_acled(api_url):
'''
Takes one parameter search term for API
'''
response = requests.get(api_url)
data = response.json()
return data
results = [] # empty data strcture to store results
num_results = 500 # c... | _____no_output_____ | MIT | Session 5/Acled - Niger.ipynb | Josedbarnes/applications |
Do the right thing, take some time to look at the codebook and see what these columns are | yemen_res.columns
| _____no_output_____ | MIT | Session 5/Acled - Niger.ipynb | Josedbarnes/applications |
Homework --- Make a map of some ACLED Data (absolutely use the code from the Global Terrorism Database exercise) | from bokeh.tile_providers import get_provider, Vendors
from pyproj import Transformer
tile_provider =get_provider('STAMEN_TERRAIN')
import math
from bokeh.plotting import figure, output_notebook, show
#Pike got help from my coworker Brandon Mohr on this
#Will be borrowing this technique for other mapping projects
#as... | _____no_output_____ | MIT | Session 5/Acled - Niger.ipynb | Josedbarnes/applications |
for idx, row in yemen_map.iterrows(): if row['data_id'] in map_dict.keys(): if math.isnan(row["latitude"]): if row['data_id'] in nan_count.keys(): nan_count[row['data_id']] += 1 else: nan_count[row['data_id']] = 1 else: point - transformer.... | pts = [(19.07, 41.68), (12.01, 54.87)]
bbox = []
for pt in transformer.itransform(pts):
bbox.append(pt)
#Pike included the Red Sea Bab al Mandab strait and island of Socotra for completeness sake
NPA_x = []
NPA_y = []
for k, v in map_dict.items():
for pt in v:
NPA_x.append(pt[0])
NPA_y.appe... | _____no_output_____ | MIT | Session 5/Acled - Niger.ipynb | Josedbarnes/applications |
Priors on the subhalo and field halo mass functionsA reasonable assumption to impose on the inference is that the number of subhalos varies proportionally with the number of field halos, since subhalos are accreted from the field. We can enforce this by choosing an expected amplitude for the subhalo mass function in $... | def couple_mass_functions(samples, sigma_sub_theory=0.025, coupling_strength=0.2):
delta_los_samples = samples[:, 0]
sigma_sub_samples = samples[:, -1]
delta_sigma_sub = sigma_sub_samples/sigma_sub_theory
chi2 = (delta_sigma_sub - delta_los_samples)**2/coupling_strength**2
return chi2
extrapo... | _____no_output_____ | MIT | notebooks_Pk/Pk_inference_shethTormen_pivot01.ipynb | dangilman/lenslikelihood |
Plot the likelihoodFirst we show the likelihood as inferred from the lenses with no additional modeling assumptions | from trikde.triangleplot import TrianglePlot
fig = plt.figure()
cmap = 'jet'
triangle_plot = TrianglePlot([likelihood_noprior])
triangle_plot.set_cmap(cmap, marginal_col='k')
triangle_plot.truth_color = 'k'
truths = {'sigma_sub': 1.05, 'LOS_normalization': 1., 'beta': 0.85, 'log10c0': np.log10(18.5), 'delta_power_law_i... | /Users/danielgilman/.local/lib/python3.6/site-packages/matplotlib/contour.py:1173: UserWarning: No contour levels were found within the data range.
warnings.warn("No contour levels were found"
| MIT | notebooks_Pk/Pk_inference_shethTormen_pivot01.ipynb | dangilman/lenslikelihood |
Likelihood with a priorNow we show the likelihood after adding the prior coupling $\Sigma_{\rm{sub}}$ to $\delta_{LOS}$, assuming $\Sigma_{\rm{sub}} = 0.05 \rm{kpc^{-1}}$ in $\Lambda$CDM, corresponding to doubly efficient tidal disruption of halos between in the Milky Way relative to massive ellipticals | fig = plt.figure()
triangle_plot = TrianglePlot([likelihood])
triangle_plot.set_cmap(cmap, marginal_col='k')
triangle_plot.truth_color = 'k'
truths= {'sigma_sub': 1.05, 'LOS_normalization': 1., 'beta': 0.85, 'log10c0': np.log10(18.5), 'delta_power_law_index': 0.}
axes = triangle_plot.make_triplot(filled_contours=False,... | _____no_output_____ | MIT | notebooks_Pk/Pk_inference_shethTormen_pivot01.ipynb | dangilman/lenslikelihood |
Systematic modeling errorsWe allow for systematic errors in the model by changing the internal mapping between the parameters describing the mass function and concentration-mass relation | error_type = 'INTERPOLATED_GRID'
if error_type == 'INTERPOLATED_GRID':
f = open('./systematic_error_interpolations/systematic_error_interpolation_lowfit_'+mass_function_model+'_pivot'+pivot_string+'_3D', 'rb')
systematic_interp_lowfit = pickle.load(f)
f.close()
f = open('./systematic_error_interp... | _____no_output_____ | MIT | notebooks_Pk/Pk_inference_shethTormen_pivot01.ipynb | dangilman/lenslikelihood |
Final setup | delta_los_range = [0., 2.5]
beta_range = [-0.2, 15.]
log10c0_range = [0., 4.]
delta_alpha_range = [-0.6, 0.9]
sigma_sub_range = [0., 0.125]
param_ranges_lensing = [delta_los_range, beta_range, log10c0_range, delta_alpha_range, sigma_sub_range]
n_draw = 50000
extrapolate_ranges = [[0., 2.5],
[-0.2,... | _____no_output_____ | MIT | notebooks_Pk/Pk_inference_shethTormen_pivot01.ipynb | dangilman/lenslikelihood |
Compute the likelihood of the power spectrum parametersWe can compute the likelihood the parameters describing $P\left(k\right)$, adding systematic models errors by hand | if error_type == 'INTERPOLATED_GRID':
samples_no_sys, like_no_sys = sample_power_spectra_with_systematic_interp(n_draw, param_ranges_pk, param_ranges_lensing, structure_formation_interp_As, interpolated_lens_likelihood,
systematic_interp_highfit, extrapolate=extrapolate_like... | _____no_output_____ | MIT | notebooks_Pk/Pk_inference_shethTormen_pivot01.ipynb | dangilman/lenslikelihood |
Plot the likelihood of the parameters describing the power spectrum | nbins = 20
param_names_pk = [r'$n_s$', r'$a_{\rm{run}}$', r'$b_{\rm{run}}$']
samples_marginalized = np.vstack((np.vstack((np.vstack((np.vstack((np.vstack((samples_no_sys, samples_sys1)), samples_sys2)), samples_sys_noamp_1)), samples_sys_noamp_2)), samples_sys_noslope))
likelihood_marginalized = np.append(np.append(n... | _____no_output_____ | MIT | notebooks_Pk/Pk_inference_shethTormen_pivot01.ipynb | dangilman/lenslikelihood |
Content:1. [Definitions](1.-Definitions)2. [The root finding problem](2.-The-root-finding-problem)3. [Fixed point iteration](3.-Fixed-point-iteration)>3.1 [The cobweb diagram](3.1-The-cobweb-diagram) >3.2 [Fixed point iteration theorem](3.2-Fixed-point-iteration-theorem) >3.3 [The code](3.3-The-code)4. [Bisection ... | import numpy as np
import matplotlib.pyplot as plt
def weierstrass(a,b,M,x):
val = 0.0
for n in range(0,M):
val = val + a**n * np.cos(b**n*np.pi*x)
return val
x = np.linspace(-2,2,1000) # 1000 points between -2 and +2
a=0.5
b=3.0
N=x.size
y=np.zeros(N)
M=1
for i in range(N):
y[i]=weierstrass... | _____no_output_____ | MIT | notebooks/.ipynb_checkpoints/nm_08_RootFinding-checkpoint.ipynb | raghurama123/NumericalMethods |
---Homework-16: Find examples for polynomial, rational, trigonometric, exponential and logarithmic functions that are in $C^\infty[{\bf R}],~{\rm where}~{\bf R}$ is the real number line. --- 2. The root-finding problem  3. Fixed point iteration  | def g_fn(x):
val=np.sqrt(10.0/x)
return val
N=15
x=np.zeros(N,float)
g=np.zeros(N,float)
x0=1.0 # initial guess
Ni=10
for i in range(0,Ni):
x[i]=x0
g[i]=g_fn(x0)
x0=g[i]
#print(x,g)
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure() # comment if... | <ipython-input-6-348e80d82643>:2: RuntimeWarning: divide by zero encountered in double_scalars
val=np.sqrt(10.0/x)
| MIT | notebooks/.ipynb_checkpoints/nm_08_RootFinding-checkpoint.ipynb | raghurama123/NumericalMethods |
Let's try another problem: $x - 1/x^2 = 0;~g(x)=1/x^2;~x_0 = 0.1$ | import numpy as np
def g_fn(x):
val=1.0/x**2
return val
def f_fn(x):
val=x-1.0/x**2
return val
x=0.1
for i in range(0,4):
gx=g_fn(x)
fx=f_fn(x)
fstring=(f'''Iteration={i:5d} x={x:10.4f} g(x)={gx:10.4f} f(x)={np.abs(fx):10.4f}''') # using f-string
print(fstring)
x=g_fn(x) | Iteration= 0 x= 0.1000 g(x)= 100.0000 f(x)= 99.9000
Iteration= 1 x= 100.0000 g(x)= 0.0001 f(x)= 99.9999
Iteration= 2 x= 0.0001 g(x)=100000000.0000 f(x)=99999999.9999
Iteration= 3 x=100000000.0000 g(x)= 0.0000 f(x)=100000000.0000
| MIT | notebooks/.ipynb_checkpoints/nm_08_RootFinding-checkpoint.ipynb | raghurama123/NumericalMethods |
Diverges! 3.2 Fixed point iteration theorem  in x = g(x) that we want to solve
# x is the initial guess, x0
# xthresh is convergence thershold
# maxeval - maximum number of evaluation of fn
# iprint control printing, iprint = 1 for extra output
def fixedpoint(fn, x, xthresh, maxeval, iprint):
if iprint == 1:
p... | #iter x g(x) dx
0 1.000000e+00 3.162278e+00 2.162278e+00
1 3.162278e+00 1.778279e+00 1.383998e+00
2 1.778279e+00 2.371374e+00 5.930943e-01
3 2.371374e+00 2.053525e+00 3.178487e-01
4 2.053525e+00 2.206734e+00 1.532090e-01
5 2.206734e+00 ... | MIT | notebooks/.ipynb_checkpoints/nm_08_RootFinding-checkpoint.ipynb | raghurama123/NumericalMethods |
Let's try another problem: $\exp(-x) + x/5 - 1 = 0$ Let's look at the graphical solution by plotting the function $f(x)$ and see where it takes the value zero. | import numpy as np
import matplotlib.pyplot as plt
def f(x):
val=np.exp(-x)+x/5.0-1
return val
xmin=-5.0
xmax=10.0
plt.xlim(xmin, xmax)
plt.ylim(-3, 10)
x = np.linspace(xmin,xmax,100)
N=x_grids.size
y=np.zeros(N)
for i in range(N):
y[i]=f(x[i])
plt.plot(x,x*0,'k-')
plt.plot(x,y,'b-')
plt.grid()
plt.s... | _____no_output_____ | MIT | notebooks/.ipynb_checkpoints/nm_08_RootFinding-checkpoint.ipynb | raghurama123/NumericalMethods |
There are two roots for this equation. One at 0.0 and another near 5.0. There are two ways of rearranging the equation to apply the fixed-point iteration $x_{n+1}=g(x_n)$.* Option-1: $g_1(x)=5\left[ 1- \exp(-x) \right]$ * Option-2: $g_2(x)=-\log\left[ 1 - x/5 \right]$ | def g1(x):
val=5 * ( 1 - np.exp(-x) )
return val
x0 = 2 # somewhere in between both the solutions
maxeval = 20
xthresh = 0.0001
iprint=1
x = fixedpoint(g1, x0, xthresh, maxeval,iprint)
print('The solution is: ',x)
def g2(x):
val=-np.log(1-x/5.0)
return val
x0 = 2.0 # somewhere in between both th... | #iter x g(x) dx
0 2.000000e+00 5.108256e-01 1.489174e+00
1 5.108256e-01 1.077691e-01 4.030565e-01
2 1.077691e-01 2.178950e-02 8.597961e-02
3 2.178950e-02 4.367423e-03 1.742207e-02
4 4.367423e-03 8.738663e-04 3.493557e-03
5 8.738663e-04 ... | MIT | notebooks/.ipynb_checkpoints/nm_08_RootFinding-checkpoint.ipynb | raghurama123/NumericalMethods |
---Homework-17: $For~the~above~example,~using~the~fixed~point~convergence~relation~explain~why~using~g_1(x)~results~in~the~solution~x^*=4.965~while~g_2(x)~results~in~x^*=0.0.~In~both~cases,~use~x_0=2.0~as~the~initial~guess.$ --- 4. Bisection method ![boa... | import numpy as np
def bisection(fn, a0, b0, xthresh, maxeval, iprint):
if iprint == 1:
print('#iter a b x dx')
ieval=0
iiter=1
a=a0
b=b0
dx = abs(a-b)
while dx > xthresh or iiter < 10:
x = (a+b)/2.0... | #iter a b x dx
The upper limit seems to be a root. Stopping program.
Exiting fixed-point iteration, convergence reached
The solution is: 1
| MIT | notebooks/.ipynb_checkpoints/nm_08_RootFinding-checkpoint.ipynb | raghurama123/NumericalMethods |
Project No.: 3Time Taken: 3 daysDifficulty: Intermediate.This is the toughest dataset I've worked with. Learnt a lot. Still a long way to go...Would love it if you left a comment with advice on where I could have improved, what you liked/disliked about my work, or any thing else. And if you like it, please give it an u... | # This Python 3 environment comes with many helpful analytics libraries installed
# It is defined by the kaggle/python docker image: https://github.com/kaggle/docker-python
# For example, here's several helpful packages to load in
import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O... | _____no_output_____ | Apache-2.0 | Predicting Costs Of Used Cars - MachineHack.ipynb | billumillu/Predicting-Costs-Of-Used-Cars |
1. The Problem**What is the problem?**Task(T): Predicting the cost of a used car in India.Experience(E): Data collected from various sources and distributed across various locations in India.Performance(P): Mean Absolute Error**My plan of action:*** Clean the data (missing values and categorical variables).'.* Build t... | df_full = pd.read_excel("../input/Data_Train.xlsx")
df_test = pd.read_excel("../input/Data_Test.xlsx")
df_full.head(10)
df_full.shape | _____no_output_____ | Apache-2.0 | Predicting Costs Of Used Cars - MachineHack.ipynb | billumillu/Predicting-Costs-Of-Used-Cars |
Mileage contains kmp/kg and kmpl, Engine contains CC, Power contains bhp and New_Price contains Lakh. By removing them I can convert them from 'object' to 'int'/'float'. | df_full.info()
df_full.isnull().sum() | _____no_output_____ | Apache-2.0 | Predicting Costs Of Used Cars - MachineHack.ipynb | billumillu/Predicting-Costs-Of-Used-Cars |
2. Data Preparation Let's first modify the 'Name' of the car and extract just the brand name. | df_full['Name'] = df_full.Name.str.split().str.get(0)
df_test['Name'] = df_test.Name.str.split().str.get(0)
df_full.head()
df_full['Name'].value_counts().sum() | _____no_output_____ | Apache-2.0 | Predicting Costs Of Used Cars - MachineHack.ipynb | billumillu/Predicting-Costs-Of-Used-Cars |
df_full.shape = (6019,13). So I guess all rows have been modified. Now I gotta modify 'Mileage', 'Power', 'Engine' and 'New_Price'. But first, I have to deal with missing values. 2.1 Missing Values | # Get names of columns with missing values
cols_with_missing = [col for col in df_full.columns
if df_full[col].isnull().any()]
print("Columns with missing values:")
print(cols_with_missing)
# Let's deal with them one by one.
df_full['Seats'].fillna(df_full['Seats'].mean(),inplace=True)
df_test['Se... | _____no_output_____ | Apache-2.0 | Predicting Costs Of Used Cars - MachineHack.ipynb | billumillu/Predicting-Costs-Of-Used-Cars |
NOTE: To get more accurate values, we need more data. So I'll combine df_train and df_test data. | data = pd.concat([df_full,df_test], sort=False)
import matplotlib.pyplot as plt
plt.figure(figsize=(20,5))
data['Mileage'].value_counts().head(100).plot.bar()
plt.show()
df_full['Mileage'] = df_full['Mileage'].fillna('17.0 kmpl')
df_test['Mileage'] = df_test['Mileage'].fillna('17.0 kmpl')
#I noticed the 14th entry (a... | _____no_output_____ | Apache-2.0 | Predicting Costs Of Used Cars - MachineHack.ipynb | billumillu/Predicting-Costs-Of-Used-Cars |
Now let's deal with 'New_Price'. **Appoach 1:** Fill the missing values with the value which occurs the most. | plt.figure(figsize=(20,5))
data['New_Price'].value_counts().head(100).plot.bar()
plt.show()
# # I'll select 4.78 cuz the others are way too high.
# df_full['New_Price'] = df_full['New_Price'].fillna('4.78 Lakh')
# df_test['New_Price'] = df_test['New_Price'].fillna('4.78 Lakh')
# # Run the method get_number() defined ... | _____no_output_____ | Apache-2.0 | Predicting Costs Of Used Cars - MachineHack.ipynb | billumillu/Predicting-Costs-Of-Used-Cars |
**Approach 2:** Group by Brand names and get the mean of the available values for 'New_Price'. Use these to fill the missing values for the respective brands.First of all I'll have to convert it into numeric data (or else mean() won't work). For that, I'll have to first deal with missing values. So! Here's what we're g... | # Method to extract 'float' from 'object'
import re
def get_number(name):
title_search = re.search('([\d+\.+\d]+\W)', name)
if title_search:
return title_search.group(1)
return "" | _____no_output_____ | Apache-2.0 | Predicting Costs Of Used Cars - MachineHack.ipynb | billumillu/Predicting-Costs-Of-Used-Cars |
I got the code for the above step from [here](https://www.kaggle.com/funxexcel/titanic-basic-solution-with-logistic-regression) and modified it. | data['New_Price'] = data['New_Price'].fillna('0.0 Lakh') # dealt with missing values.
data['New_Price'] = data['New_Price'].apply(get_number).astype('float') #converted to float
total = data['New_Price'].groupby(data['Name'])
print(total.mean().round(2)) | _____no_output_____ | Apache-2.0 | Predicting Costs Of Used Cars - MachineHack.ipynb | billumillu/Predicting-Costs-Of-Used-Cars |
We got avg 'New_Price' values for more than half the brands. There are still 6 Brands whose values are not given. For that, another plan!First of all, deal with the brands that we have values for. After that, use a bar chart to get the value of the most occurring 'New_Price' value. Use that to fill the rest of them. | df_full['New_Price'] = df_full['New_Price'].fillna('0.0 Lakh') # dealt with missing values.
df_full['New_Price'] = df_full['New_Price'].apply(get_number).astype('float') #converted to float
df_full.loc[df_full['Name']=="Audi", 'New_Price'] = df_full.loc[df_full['Name']=="Audi", 'New_Price'].replace(0.0,5.02)
df_full.lo... | _____no_output_____ | Apache-2.0 | Predicting Costs Of Used Cars - MachineHack.ipynb | billumillu/Predicting-Costs-Of-Used-Cars |
I must have filled most of the missing values. Now let's use a bar chart to get the most occurring values and fill the rest of them. | plt.figure(figsize=(20,5))
df_full['New_Price'].value_counts().head(100).plot.bar()
plt.show()
plt.figure(figsize=(20,5))
df_test['New_Price'].value_counts().head(100).plot.bar()
plt.show()
df_full.loc[df_full['Name']=="Ambassador", 'New_Price'] = df_full.loc[df_full['Name']=="Ambassador", 'New_Price'].replace(0.0,1.2... | _____no_output_____ | Apache-2.0 | Predicting Costs Of Used Cars - MachineHack.ipynb | billumillu/Predicting-Costs-Of-Used-Cars |
Now let's convert 'Mileage', 'Engine' and 'Power' into numbers. | #Using the above defined method get_number()
df_full['Mileage'] = df_full['Mileage'].apply(get_number).astype('float')
df_full['Engine'] = df_full['Engine'].apply(get_number).astype('int')
df_full['Power'] = df_full['Power'].apply(get_number).astype('float')
df_test['Mileage'] = df_test['Mileage'].apply(get_number).a... | _____no_output_____ | Apache-2.0 | Predicting Costs Of Used Cars - MachineHack.ipynb | billumillu/Predicting-Costs-Of-Used-Cars |
Looks good!! 2.2 Categorical Variables | from sklearn.model_selection import train_test_split
y = df_full.Price
X = df_full.drop(['Price'],axis=1)
# df_test = df_test.drop('New_Price',axis=1)
X_train, X_valid, y_train, y_valid = train_test_split(X,y,train_size=0.82,test_size=0.18,random_state=0)
from sklearn.preprocessing import LabelEncoder
label_encoder ... | _____no_output_____ | Apache-2.0 | Predicting Costs Of Used Cars - MachineHack.ipynb | billumillu/Predicting-Costs-Of-Used-Cars |
Ah finally!! After 3 days! Quickly tried scaling too. Not a cool move. | # # Let's try scaling too.
# from sklearn.preprocessing import StandardScaler
# scaler = StandardScaler().fit(X_train)
# rescaled_X_train = scaler.transform(X_train)
# scaler = StandardScaler().fit(X_valid)
# rescaled_X_valid = scaler.transform(X_valid)
# scaler = StandardScaler().fit(df_test)
# rescaled_df_test = s... | _____no_output_____ | Apache-2.0 | Predicting Costs Of Used Cars - MachineHack.ipynb | billumillu/Predicting-Costs-Of-Used-Cars |
3. ModelI will use XGBRegressor to build the model and MAE to check the performance. I will also check out mean_squared_error and mean_squared_log_error. | from xgboost import XGBRegressor
from sklearn.metrics import mean_absolute_error,mean_squared_error,mean_squared_log_error
my_model = XGBRegressor(n_estimators=1000, learning_rate=0.05)
my_model.fit(X_train, y_train,
early_stopping_rounds=5,
eval_set=[(X_valid, y_valid)],
verb... | _____no_output_____ | Apache-2.0 | Predicting Costs Of Used Cars - MachineHack.ipynb | billumillu/Predicting-Costs-Of-Used-Cars |
4. Predictions | preds_test = my_model.predict(df_test)
print(preds_test)
# The Price is in the format xx.xx So let's round off and submit.
preds_test = preds_test.round(2)
print(preds_test)
output = pd.DataFrame({'Price': preds_test})
output.to_excel('submission.xlsx', index=False) | _____no_output_____ | Apache-2.0 | Predicting Costs Of Used Cars - MachineHack.ipynb | billumillu/Predicting-Costs-Of-Used-Cars |
Artificial Intelligence Nanodegree Convolutional Neural Networks---In this notebook, we train a CNN on augmented images from the CIFAR-10 database. 1. Load CIFAR-10 Database | import keras
from keras.datasets import cifar10
# load the pre-shuffled train and test data
(x_train, y_train), (x_test, y_test) = cifar10.load_data() | Using TensorFlow backend.
| MIT | cifar10-augmentation/cifar10_augmentation_mine.ipynb | rhombhi/aind2-cnn |
2. Visualize the First 24 Training Images | import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
fig = plt.figure(figsize=(20,5))
for i in range(36):
ax = fig.add_subplot(3, 12, i + 1, xticks=[], yticks=[])
ax.imshow(np.squeeze(x_train[i])) | _____no_output_____ | MIT | cifar10-augmentation/cifar10_augmentation_mine.ipynb | rhombhi/aind2-cnn |
3. Rescale the Images by Dividing Every Pixel in Every Image by 255 | # rescale [0,255] --> [0,1]
x_train = x_train.astype('float32')/255
x_test = x_test.astype('float32')/255 | _____no_output_____ | MIT | cifar10-augmentation/cifar10_augmentation_mine.ipynb | rhombhi/aind2-cnn |
4. Break Dataset into Training, Testing, and Validation Sets | from keras.utils import np_utils
# break training set into training and validation sets
(x_train, x_valid) = x_train[5000:], x_train[:5000]
(y_train, y_valid) = y_train[5000:], y_train[:5000]
# one-hot encode the labels
num_classes = len(np.unique(y_train))
y_train = keras.utils.to_categorical(y_train, num_classes)
y... | x_train shape: (45000, 32, 32, 3)
45000 train samples
10000 test samples
5000 validation samples
| MIT | cifar10-augmentation/cifar10_augmentation_mine.ipynb | rhombhi/aind2-cnn |
5. Create and Configure Augmented Image Generator | from keras.preprocessing.image import ImageDataGenerator
datagen_train = ImageDataGenerator(width_shift_range=.1,
height_shift_range=.1, horizontal_flip=True)
datagen_train.fit(x_train) | _____no_output_____ | MIT | cifar10-augmentation/cifar10_augmentation_mine.ipynb | rhombhi/aind2-cnn |
6. Visualize Original and Augmented Images | fig = plt.figure(figsize=(20,2))
fig.suptitle('Actual images', fontsize=20)
for i in range(10):
ax = fig.add_subplot(1, 10, i+1, xticks=[], yticks=[])
ax.imshow(np.squeeze(x_train[i]))
fig = plt.figure(figsize=(20,2))
fig.suptitle('Augmented images')
for x_batch in datagen_train.flow(x_train[:10]):
for i... | _____no_output_____ | MIT | cifar10-augmentation/cifar10_augmentation_mine.ipynb | rhombhi/aind2-cnn |
7. Define the Model Architecture | from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout
model = Sequential()
model.add(Conv2D(filters=16, kernel_size=2, padding='same', activation='relu',
input_shape=(32, 32, 3)))
model.add(MaxPooling2D(pool_size=2))
model.add(Conv2D(filters... | _________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
conv2d_1 (Conv2D) (None, 32, 32, 16) 208
________________________________________________________... | MIT | cifar10-augmentation/cifar10_augmentation_mine.ipynb | rhombhi/aind2-cnn |
8. Compile the Model | # compile the model
model.compile(loss='categorical_crossentropy', optimizer='rmsprop',
metrics=['accuracy']) | _____no_output_____ | MIT | cifar10-augmentation/cifar10_augmentation_mine.ipynb | rhombhi/aind2-cnn |
9. Train the Model | from keras.callbacks import ModelCheckpoint
batch_size = 32
epochs = 100
# train the model
checkpointer = ModelCheckpoint(filepath='aug_model.weights.best.mine.hdf5', verbose=1,
save_best_only=True)
model.fit_generator(datagen_train.flow(x_train, y_train, batch_size=batch_size),
... | Epoch 1/100
- 64s - loss: 1.6690 - acc: 0.3944 - val_loss: 1.5590 - val_acc: 0.4352
Epoch 00001: val_loss improved from inf to 1.55902, saving model to aug_model.weights.best.hdf5
Epoch 2/100
- 54s - loss: 1.3915 - acc: 0.4976 - val_loss: 1.1726 - val_acc: 0.5744
Epoch 00002: val_loss improved from 1.55902 to 1.172... | MIT | cifar10-augmentation/cifar10_augmentation_mine.ipynb | rhombhi/aind2-cnn |
10. Load the Model with the Best Validation Accuracy | # load the weights that yielded the best validation accuracy
model.load_weights('aug_model.weights.best.mine.hdf5') | _____no_output_____ | MIT | cifar10-augmentation/cifar10_augmentation_mine.ipynb | rhombhi/aind2-cnn |
11. Calculate Classification Accuracy on Test Set | # evaluate and print test accuracy
score = model.evaluate(x_test, y_test, verbose=0)
print('\n', 'Test accuracy:', score[1]) |
Test accuracy: 0.6665
| MIT | cifar10-augmentation/cifar10_augmentation_mine.ipynb | rhombhi/aind2-cnn |
Introducing Scikit-Learn There are several Python libraries which provide solid implementations of a range of machine learning algorithms.One of the best known is [Scikit-Learn](http://scikit-learn.org), a package that provides efficient versions of a large number of common algorithms.Scikit-Learn is characterized by ... | import pandas as pd
import numpy as np
from IPython.display import Pretty as disp
hint = 'https://raw.githubusercontent.com/soltaniehha/Business-Analytics/master/docs/hints/' # path to hints on GitHub
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
sns.set(rc={'figure.figsize':(10,8)}) # Figu... | _____no_output_____ | MIT | 16-Introducing-Scikit-Learn.ipynb | Jeff0603/Deep-Learning-in-Computer-Vision |
iris.species.unique() | _____no_output_____ | MIT | 16-Introducing-Scikit-Learn.ipynb | Jeff0603/Deep-Learning-in-Computer-Vision | |
Here each row of the data refers to a single observed flower, and the number of rows is the total number of flowers in the dataset.In general, we will refer to the rows of the matrix as *samples*, and the number of rows as ``n_samples``.Likewise, each column of the data refers to a particular quantitative piece of info... | sns.pairplot(iris, hue='species', height=2.5); | _____no_output_____ | MIT | 16-Introducing-Scikit-Learn.ipynb | Jeff0603/Deep-Learning-in-Computer-Vision |
For use in Scikit-Learn, we will extract the features matrix and target array from the ``DataFrame``, which we can do using some of the Pandas ``DataFrame`` operations we've learned: | X_iris = iris.drop('species', axis=1)
X_iris.shape
y_iris = iris['species']
y_iris.shape | _____no_output_____ | MIT | 16-Introducing-Scikit-Learn.ipynb | Jeff0603/Deep-Learning-in-Computer-Vision |
To summarize, the expected layout of features and target values is visualized in the following diagram: With this data properly formatted, we can move on to consider the *estimator* API of Scikit-Learn: Scikit-Learn's Estimator API The Scikit-Learn API is designed with the following guiding principles in mind, as out... | X = iris[['petal_width']]
y = iris[['petal_length']]
plt.scatter(X, y); | _____no_output_____ | MIT | 16-Introducing-Scikit-Learn.ipynb | Jeff0603/Deep-Learning-in-Computer-Vision |
With this data in place, we can use the recipe outlined earlier. Let's walk through the process: 1. Choose a class of modelIn Scikit-Learn, every class of model is represented by a Python class.So, for example, if we would like to compute a simple linear regression model, we can import the linear regression class: | from sklearn.linear_model import LinearRegression | _____no_output_____ | MIT | 16-Introducing-Scikit-Learn.ipynb | Jeff0603/Deep-Learning-in-Computer-Vision |
Note that other more general linear regression models exist as well; you can read more about them in the [``sklearn.linear_model`` module documentation](http://Scikit-Learn.org/stable/modules/linear_model.html). 2. Choose model hyperparametersAn important point is that *a class of model is not the same as an instance ... | model = LinearRegression(fit_intercept=True)
model | _____no_output_____ | MIT | 16-Introducing-Scikit-Learn.ipynb | Jeff0603/Deep-Learning-in-Computer-Vision |
Keep in mind that when the model is instantiated, the only action is the storing of these hyperparameter values.In particular, we have not yet applied the model to any data: the Scikit-Learn API makes very clear the distinction between *choice of model* and *application of model to data*. 3. Arrange data into a featur... | print(X.shape)
print(y.shape) | (150, 1)
(150, 1)
| MIT | 16-Introducing-Scikit-Learn.ipynb | Jeff0603/Deep-Learning-in-Computer-Vision |
4. Fit the model to your dataNow it is time to apply our model to data.This can be done with the ``fit()`` method of the model: | model.fit(X, y) | _____no_output_____ | MIT | 16-Introducing-Scikit-Learn.ipynb | Jeff0603/Deep-Learning-in-Computer-Vision |
This ``fit()`` command causes a number of model-dependent internal computations to take place, and the results of these computations are stored in model-specific attributes that the user can explore.In Scikit-Learn, by convention all model parameters that were learned during the ``fit()`` process have trailing undersco... | model.coef_
model.intercept_ | _____no_output_____ | MIT | 16-Introducing-Scikit-Learn.ipynb | Jeff0603/Deep-Learning-in-Computer-Vision |
These two parameters represent the slope and intercept of the simple linear fit to the data.Comparing to the data definition, we see that they are very close to the input slope of 2.2 and intercept of 1.One question that frequently comes up regards the uncertainty in such internal model parameters.In general, Scikit-Le... | xfit = np.linspace(0, 2.5)
xfit = pd.DataFrame(xfit)
xfit.shape | _____no_output_____ | MIT | 16-Introducing-Scikit-Learn.ipynb | Jeff0603/Deep-Learning-in-Computer-Vision |
We have coerced these *x* values into a ``[n_samples, n_features]`` features matrix, after which we can feed it to the model: | yfit = model.predict(xfit) | _____no_output_____ | MIT | 16-Introducing-Scikit-Learn.ipynb | Jeff0603/Deep-Learning-in-Computer-Vision |
Finally, let's visualize the results by plotting first the raw data, and then this model fit: | plt.scatter(X, y)
plt.plot(xfit, yfit, c='gray')
plt.xlabel('petal_width')
plt.ylabel('petal_length'); | _____no_output_____ | MIT | 16-Introducing-Scikit-Learn.ipynb | Jeff0603/Deep-Learning-in-Computer-Vision |
Typically the efficacy of the model is evaluated by comparing its results to some known baseline, as we will see in the next example Supervised learning example: Iris classificationLet's take a look at another example of this process, using the Iris dataset we discussed earlier.Our question will be this: given a model... | from sklearn.model_selection import train_test_split
Xtrain, Xtest, ytrain, ytest = train_test_split(X_iris, y_iris, test_size=0.3, random_state=833) | _____no_output_____ | MIT | 16-Introducing-Scikit-Learn.ipynb | Jeff0603/Deep-Learning-in-Computer-Vision |
With the data arranged, we can follow our recipe to predict the labels: | from sklearn.naive_bayes import GaussianNB # 1. choose model class
model = GaussianNB() # 2. instantiate model
model.fit(Xtrain, ytrain) # 3. fit model to data
y_model = model.predict(Xtest) # 4. predict on new data | _____no_output_____ | MIT | 16-Introducing-Scikit-Learn.ipynb | Jeff0603/Deep-Learning-in-Computer-Vision |
Finally, we can use the ``accuracy_score`` utility to see the fraction of predicted labels that match their true value: | from sklearn.metrics import accuracy_score
accuracy_score(ytest, y_model) | _____no_output_____ | MIT | 16-Introducing-Scikit-Learn.ipynb | Jeff0603/Deep-Learning-in-Computer-Vision |
With an accuracy topping 93%, we see that even this very naive classification algorithm is effective for this particular dataset!To learn more about Gaussian naive Bayes check out [this YouTube video](https://www.youtube.com/watch?v=r1in0YNetG8). Your TurnFor this exercise we are going to make some predictions using T... | df = pd.read_csv('https://raw.githubusercontent.com/soltaniehha/Business-Analytics/master/data/Telco-Customer-Churn.csv')
df.head(3) | _____no_output_____ | MIT | 16-Introducing-Scikit-Learn.ipynb | Jeff0603/Deep-Learning-in-Computer-Vision |
Column `TotalCharges` has 11 rows with an empty string (" "). Replace these values by `0` as they represent new customers that haven't received a bill yet. Once you replaced the values, convert that column to a `float32` data type. | # Your answer goes here
# SOLUTION: Uncomment and execute the cell below to get help
#disp(hint + '09-02-TotalCharges') | _____no_output_____ | MIT | 16-Introducing-Scikit-Learn.ipynb | Jeff0603/Deep-Learning-in-Computer-Vision |
If we check the `df.info()` now we should see that `TotalCharges` is now a `float32`: | df.info() | <class 'pandas.core.frame.DataFrame'>
RangeIndex: 7043 entries, 0 to 7042
Data columns (total 21 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 customerID 7043 non-null object
1 gender 7043 non-null object
2 SeniorCitizen 70... | MIT | 16-Introducing-Scikit-Learn.ipynb | Jeff0603/Deep-Learning-in-Computer-Vision |
Before we get to splitting our dataset into train/test we would have to make sure all of our values are numerical as most of ML algorithms work with numerical values only. How to Convert Categorical Data to Numerical Data?In order to do this we have to convert all of the categorical variables to numerical values. This... | churn_df = df.drop('customerID', axis=1) # dropping customerID as it doesn't have any predictive power
df_dummified = pd.get_dummies(churn_df, drop_first=True) # One-hot encoding
df_dummified.rename(columns={'Churn_Yes': 'Churn'}, inplace=True) # renaming Churn_Yes to Churn
df_dummified.head() | _____no_output_____ | MIT | 16-Introducing-Scikit-Learn.ipynb | Jeff0603/Deep-Learning-in-Computer-Vision |
Using `df_dummified` dataframe, create two dataframes for features matrix and target vector and call them `X_df` and `y_df` respectively: | # Your answer goes here
# X_df
# Your answer goes here
# y_df
# SOLUTION: Uncomment and execute the cell below to get help
#disp(hint + '09-02-X_df-y_df') | _____no_output_____ | MIT | 16-Introducing-Scikit-Learn.ipynb | Jeff0603/Deep-Learning-in-Computer-Vision |
Check their shape: | # Your answer goes here
# SOLUTION: Uncomment and execute the cell below to get help
#disp(hint + '09-02-shape') | _____no_output_____ | MIT | 16-Introducing-Scikit-Learn.ipynb | Jeff0603/Deep-Learning-in-Computer-Vision |
From `X_df` and `y_df` create the train/test splits. * Set 30% of the data to test and the remainder to train. * Use `random_state=833`, so you get the same result as in the notebook. * Name the resulting objects: `Xtrain`, `Xtest`, `ytrain`, `ytest`. | # Your answer goes here
# SOLUTION: Uncomment and execute the cell below to get help
#disp(hint + '09-02-split') | _____no_output_____ | MIT | 16-Introducing-Scikit-Learn.ipynb | Jeff0603/Deep-Learning-in-Computer-Vision |
From `sklearn.naive_bayes` import `GaussianNB`: | # Your answer goes here
# SOLUTION: Uncomment and execute the cell below to get help
#disp(hint + '09-02-import') | _____no_output_____ | MIT | 16-Introducing-Scikit-Learn.ipynb | Jeff0603/Deep-Learning-in-Computer-Vision |
Instantiate a `GaussianNB` model and call it `model`: | # Your answer goes here
# SOLUTION: Uncomment and execute the cell below to get help
#disp(hint + '09-02-model') | _____no_output_____ | MIT | 16-Introducing-Scikit-Learn.ipynb | Jeff0603/Deep-Learning-in-Computer-Vision |
Fit model to data: | # Your answer goes here
# SOLUTION: Uncomment and execute the cell below to get help
#disp(hint + '09-02-fit') | _____no_output_____ | MIT | 16-Introducing-Scikit-Learn.ipynb | Jeff0603/Deep-Learning-in-Computer-Vision |
Now let's make some predictions. Use the `Xtest` feature dataframe to predict whether these customers are churning or not. Call the outcome (predictions) `y_model`: | # Your answer goes here
# SOLUTION: Uncomment and execute the cell below to get help
#disp(hint + '09-02-predict') | _____no_output_____ | MIT | 16-Introducing-Scikit-Learn.ipynb | Jeff0603/Deep-Learning-in-Computer-Vision |
Accuracy is not the most reliable metric when it comes to evaluating classification algorithms, but it's one of the most simple ones. Let's calculate it below: | # Your answer goes here
# SOLUTION: Uncomment and execute the cell below to get help
#disp(hint + '09-02-accuracy') | _____no_output_____ | MIT | 16-Introducing-Scikit-Learn.ipynb | Jeff0603/Deep-Learning-in-Computer-Vision |
Is this model any good? If we had said no one will churn, what the accuracy would have been?We would have identified all the ones who didn't churn correctly, but missed all the ones who did actually churn. Let's calculate the accuracy for this simplistic model below:hint: all you need to work with is `ytest` | # Your answer goes here
# SOLUTION: Uncomment and execute the cell below to get help
#disp(hint + '09-02-accuracy-base') | _____no_output_____ | MIT | 16-Introducing-Scikit-Learn.ipynb | Jeff0603/Deep-Learning-in-Computer-Vision |
So, after all our ML model is not that great. But the scope of this exercise is not to fine-tune this model, but understand the pipeline and how to read the outcome. Let's continue with some simple questions. How many people did we have in the test dataset? Save it to a variable called `n_test`: | # Your answer goes here
# SOLUTION: Uncomment and execute the cell below to get help
#disp(hint + '09-02-test-size') | _____no_output_____ | MIT | 16-Introducing-Scikit-Learn.ipynb | Jeff0603/Deep-Learning-in-Computer-Vision |
How many of these customers churned? Save it to a variable and call it `P`: | # Your answer goes here
# SOLUTION: Uncomment and execute the cell below to get help
#disp(hint + '09-02-churned') | _____no_output_____ | MIT | 16-Introducing-Scikit-Learn.ipynb | Jeff0603/Deep-Learning-in-Computer-Vision |
How many true positives did the model generate? (True positive = correctly identified in the "positive" class. Take "Yes" as the positive class).Save it to a variable and call it `TP`: | # Your answer goes here
# SOLUTION: Uncomment and execute the cell below to get help
#disp(hint + '09-02-TP') | _____no_output_____ | MIT | 16-Introducing-Scikit-Learn.ipynb | Jeff0603/Deep-Learning-in-Computer-Vision |
What is the true positive rate (or sensitivity)?**Sensitivity** (also called the **true positive rate (TPR)**, the recall, or probability of detection in some fields) measures the proportion of actual positives that are correctly identified as such (e.g., the percentage of sick people who are correctly identified as ha... | # Your answer goes here
# SOLUTION: Uncomment and execute the cell below to get help
#disp(hint + '09-02-sensitivity') | _____no_output_____ | MIT | 16-Introducing-Scikit-Learn.ipynb | Jeff0603/Deep-Learning-in-Computer-Vision |
How many of the customers in the test set didn't churn?Save it to `N`: | # Your answer goes here
# SOLUTION: Uncomment and execute the cell below to get help
#disp(hint + '09-02-N') | _____no_output_____ | MIT | 16-Introducing-Scikit-Learn.ipynb | Jeff0603/Deep-Learning-in-Computer-Vision |
How many true negatives did the model generate? (True negative = correctly rejected). Save a to a variable and call it `TN`: | # Your answer goes here
# SOLUTION: Uncomment and execute the cell below to get help
#disp(hint + '09-02-TN') | _____no_output_____ | MIT | 16-Introducing-Scikit-Learn.ipynb | Jeff0603/Deep-Learning-in-Computer-Vision |
What is the true negative rate (or specificity)?**Specificity** (also called the **true negative rate**) measures the proportion of actual negatives that are correctly identified as such (e.g., the percentage of healthy people who are correctly identified as not having the condition). ~Wikipedia$TNR=\frac{TN}{N}$, wher... | # Your answer goes here
# SOLUTION: Uncomment and execute the cell below to get help
#disp(hint + '09-02-specificity') | _____no_output_____ | MIT | 16-Introducing-Scikit-Learn.ipynb | Jeff0603/Deep-Learning-in-Computer-Vision |
PredictionsI believe the Logistic Regression model will perform better than the Random Forest Classifier as the data is not randomized.How about after scaling the data?I expect the Logistic Regression to perform better on the scaled data. In this particular case, the Logistic Regression is the appropriate regression a... | # Retrieving the datasets
train_df = pd.read_csv("Resources/2019loans.csv")
test_df = pd.read_csv("Resources/2020Q1loans.csv")
# Processing the Data
X_train_dummies = pd.get_dummies(train_df)
print(X_train_dummies.columns)
X_train_dummies
train_df
test_df
# Convert categorical data to numeric and separate target featur... | Train Score: 1.000
Test Score: 0.630
| ADSL | credit risk evaluator.ipynb | jorgeaserrano/Supervised-Machine-Learning |
Demonstration of integrating POI Points to OSM road network1. Use anyway you like to get the sample [POI data](https://assets.onemap.sg/shp/supermarkets.zip) consisting of supermarkets from [OneMap SG](https://www.onemap.sg/).2. Use [OSMnx](https://osmnx.readthedocs.io/en/stable/index.html) to download the pedestrian ... | import os
import wget
import osmnx as ox
import geopandas as gpd
from toolbox import connect_poi | _____no_output_____ | MIT | demo_connect_poi.ipynb | ywnch/toolbox |
1. Prepare POIs | # get POI data
url = "https://assets.onemap.sg/shp/supermarkets.zip"
PATH = 'data/supermarkets.zip'
if os.path.exists(PATH):
print('File existed.')
else:
PATH = wget.download(url, PATH)
print('File downloaded.')
# load and subset the POI based on a bounding box
bbox = (103.8427, 1.3308, 103.8601, 1.3416) ... | /Users/Yuwen/anaconda/lib/python3.6/site-packages/fiona/env.py:398: FionaDeprecationWarning: The vfs keyword argument is deprecated. Instead, pass a URL that uses a zip or tar (for example) scheme.
return f(*args, **kwargs)
| MIT | demo_connect_poi.ipynb | ywnch/toolbox |
[NOTE] For use in pandana, you may want to ensure the key column for the input is numeric-only to avoid processing errors. Preferably use unique integers (int or str) only, and be aware not to intersect with the node key, which is 'osmid' if you use OSM data, in the nodes gdf. 2. Prepare network | # get road network and save as .shp
G = ox.graph_from_bbox(bbox[3], bbox[1], bbox[2], bbox[0], network_type='walk')
ox.save_graph_shapefile(G, filepath='data/sample/', encoding='utf-8')
# load as GeoDataFrame
nodes = gpd.read_file('data/sample/nodes.shp')
edges = gpd.read_file('data/sample/edges.shp') | _____no_output_____ | MIT | demo_connect_poi.ipynb | ywnch/toolbox |
3. Integrate POIs and network | connect_poi?
# it's a one-liner, but is still at beta at the moment
new_nodes, new_edges = connect_poi(pois, nodes, edges, key_col='key', path=None) | Building rtree...
Updating external nodes...
Projecting POIs to the network...
Updating internal nodes...
Updating internal edges...
Updating external links...
Remove faulty projections: 0/7 (0.00%)
NOTE: duplication in node coordinates keys
Nodes count: 845
Node coordinates key count: 843
Missing 'from' nodes: 0
Missi... | MIT | demo_connect_poi.ipynb | ywnch/toolbox |
4. Check output1. First is an example of how edges will be broken into segments when there is a POI to be linked onto it. This process accommodates for multiple POIs. E.g., for 2 POIs projecting onto a same edge (but not overlapping nor on either vertices of the edge), the edge will be replaced with 3 segments.2. Then... | # original edge
edges[edges['from'] == 3370311549][['from', 'to', 'length']]
# new edges replacing the original (953, 954) and connecting the poi (964)
new_edges[(new_edges['from'] == 3370311549) |
(new_edges['from'] == 9990000005) |
(new_edges['to'] == 9990000005) ][['from', 'to', 'length']]
# outp... | _____no_output_____ | MIT | demo_connect_poi.ipynb | ywnch/toolbox |
Pincipal component analysis | import numpy as np
import matplotlib.pyplot as plt | _____no_output_____ | MIT | lectures/Lecture_19.ipynb | KiranArun/CSMM.102x-Machine_Learning |
this is reducing data to a lower dimensional space$q^tq = 1$$q^Tx_i =$ distance of datapoint after projecting it on line of vector q$(q^Tx_i)q =$ stretches vector to the datapoint- this is the prediction of the data- using the vector q which is constant for all data points- and the value which stretches the vector to a... | x = np.linspace(0, 5, 201)
def f(x):
return np.exp(-x)*
y = f(x)
fig, ax = plt.subplots(1, figsize=(8,4))
ax.plot(x,y)
ax.grid(True)
plt.show()
| /usr/local/lib/python2.7/dist-packages/ipykernel_launcher.py:4: RuntimeWarning: divide by zero encountered in log
after removing the cwd from sys.path.
| MIT | lectures/Lecture_19.ipynb | KiranArun/CSMM.102x-Machine_Learning |
Parameters | sample_number = 0 | _____no_output_____ | BSD-2-Clause | format_and_add_errors.ipynb | chummels/cgm_modeling_challenge |
Load Mock Data | # Load using my preferred wrapper for hdf5 files.
data = verdict.Dict.from_hdf5( './data/synthetic_data/sample{}/observers_file.h5'.format( sample_number ) ) | _____no_output_____ | BSD-2-Clause | format_and_add_errors.ipynb | chummels/cgm_modeling_challenge |
Assign ErrorsOur goal is to create semi-realistic errors.We won't put too much effort into this, so we'll roughly fit a gamma function to the distribution of errors from COS-Halos data, and sample from the distribution.We do provide a bound on 1.5 the maximum observed error, however, to prevent getting anything too cr... | df = pd.read_fwf(
'./data/cos_halos_data.txt',
skiprows = 31,
names = [ 'ID', 'z', 'Ion', 'Vel', 'e_Vel', 'b', 'e_b', 'logN', 'elogN', 'l_logNA', ',logNA', 'e_logNA' ],
)
# Find ions used
ions = list( set( df['Ion'] ) )
ions.remove( np.nan )
ions.append( 'H I' )
# Get out errors from data, mildly processed
... | _____no_output_____ | BSD-2-Clause | format_and_add_errors.ipynb | chummels/cgm_modeling_challenge |
Apply to Data | data_out = {}
for ion in data.keys():
dist = errs[ion]['dist']
ion_errs = []
modified_columns = []
for i, column in enumerate( data[ion] ):
ion_err = np.inf
while ( ion_err > elogNs[ion].max()*1.5 ) or ( ion_err < elogNs[ion].min() / 1.5 ):
ion_err = dist.r... | <ipython-input-21-1a3bbd98ad63>:19: RuntimeWarning: divide by zero encountered in log10
modified_columns.append( np.round( np.log10( modified_column ), decimals=3 ) )
| BSD-2-Clause | format_and_add_errors.ipynb | chummels/cgm_modeling_challenge |
Save Output | data_out.to_hdf5( './data/sample{}.h5'.format( sample_number ) ) | _____no_output_____ | BSD-2-Clause | format_and_add_errors.ipynb | chummels/cgm_modeling_challenge |
Reload for Checking | data_out = verdict.Dict.from_hdf5( './data/synthetic_data_samples/sample{}.h5'.format( sample_number ) ) | _____no_output_____ | BSD-2-Clause | format_and_add_errors.ipynb | chummels/cgm_modeling_challenge |
Fitting a diagonal covariance Gaussian mixture model to text dataIn a previous assignment, we explored k-means clustering for a high-dimensional Wikipedia dataset. We can also model this data with a mixture of Gaussians, though with increasing dimension we run into two important issues associated with using a full cov... | from __future__ import print_function # to conform python 2.x print to python 3.x
import turicreate | _____no_output_____ | MIT | 4-ml-clustering-and-retrieval/Week_4-assignment-2.ipynb | anilk991/Coursera-Machine-Learning-Specialization-UW |
We also have a Python file containing implementations for several functions that will be used during the course of this assignment. | from em_utilities import * | _____no_output_____ | MIT | 4-ml-clustering-and-retrieval/Week_4-assignment-2.ipynb | anilk991/Coursera-Machine-Learning-Specialization-UW |
Load Wikipedia data and extract TF-IDF features Load Wikipedia data and transform each of the first 5000 document into a TF-IDF representation. | wiki = turicreate.SFrame('people_wiki.sframe/').head(5000)
wiki['tf_idf'] = turicreate.text_analytics.tf_idf(wiki['text']) | _____no_output_____ | MIT | 4-ml-clustering-and-retrieval/Week_4-assignment-2.ipynb | anilk991/Coursera-Machine-Learning-Specialization-UW |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.