markdown
stringlengths
0
37k
code
stringlengths
1
33.3k
path
stringlengths
8
215
repo_name
stringlengths
6
77
license
stringclasses
15 values
We can use head() to get a quick look at the contents of each table: * train: Contains store information on a daily basis, tracks things like sales, customers, whether that day was a holdiay, etc. * store: general info about the store including competition, etc. * store_states: maps store to state it is in * state_name...
for t in tables: display(t.head())
data_science/courses/temp/courses/dl1/lesson3-rossman.ipynb
jmhsi/justin_tinker
apache-2.0
This is very representative of a typical industry dataset. The following returns summarized aggregate information to each table accross each field.
for t in tables: display(DataFrameSummary(t).summary())
data_science/courses/temp/courses/dl1/lesson3-rossman.ipynb
jmhsi/justin_tinker
apache-2.0
Data Cleaning / Feature Engineering As a structured data problem, we necessarily have to go through all the cleaning and feature engineering, even though we're using a neural network.
train, store, store_states, state_names, googletrend, weather, test = tables len(train),len(test)
data_science/courses/temp/courses/dl1/lesson3-rossman.ipynb
jmhsi/justin_tinker
apache-2.0
We turn state Holidays to booleans, to make them more convenient for modeling. We can do calculations on pandas fields using notation very similar (often identical) to numpy.
train.StateHoliday = train.StateHoliday!='0' test.StateHoliday = test.StateHoliday!='0'
data_science/courses/temp/courses/dl1/lesson3-rossman.ipynb
jmhsi/justin_tinker
apache-2.0
join_df is a function for joining tables on specific fields. By default, we'll be doing a left outer join of right on the left argument using the given fields for each table. Pandas does joins using the merge method. The suffixes argument describes the naming convention for duplicate fields. We've elected to leave the ...
def join_df(left, right, left_on, right_on=None, suffix='_y'): if right_on is None: right_on = left_on return left.merge(right, how='left', left_on=left_on, right_on=right_on, suffixes=("", suffix))
data_science/courses/temp/courses/dl1/lesson3-rossman.ipynb
jmhsi/justin_tinker
apache-2.0
Join weather/state names.
weather = join_df(weather, state_names, "file", "StateName")
data_science/courses/temp/courses/dl1/lesson3-rossman.ipynb
jmhsi/justin_tinker
apache-2.0
In pandas you can add new columns to a dataframe by simply defining it. We'll do this for googletrends by extracting dates and state names from the given data and adding those columns. We're also going to replace all instances of state name 'NI' to match the usage in the rest of the data: 'HB,NI'. This is a good opport...
googletrend['Date'] = googletrend.week.str.split(' - ', expand=True)[0] googletrend['State'] = googletrend.file.str.split('_', expand=True)[2] googletrend.loc[googletrend.State=='NI', "State"] = 'HB,NI'
data_science/courses/temp/courses/dl1/lesson3-rossman.ipynb
jmhsi/justin_tinker
apache-2.0
The following extracts particular date fields from a complete datetime for the purpose of constructing categoricals. You should always consider this feature extraction step when working with date-time. Without expanding your date-time into these additional fields, you can't capture any trend/cyclical behavior as a func...
add_datepart(weather, "Date", drop=False) add_datepart(googletrend, "Date", drop=False) add_datepart(train, "Date", drop=False) add_datepart(test, "Date", drop=False)
data_science/courses/temp/courses/dl1/lesson3-rossman.ipynb
jmhsi/justin_tinker
apache-2.0
The Google trends data has a special category for the whole of the US - we'll pull that out so we can use it explicitly.
trend_de = googletrend[googletrend.file == 'Rossmann_DE']
data_science/courses/temp/courses/dl1/lesson3-rossman.ipynb
jmhsi/justin_tinker
apache-2.0
Now we can outer join all of our data into a single dataframe. Recall that in outer joins everytime a value in the joining field on the left table does not have a corresponding value on the right table, the corresponding row in the new table has Null values for all right table fields. One way to check that all records ...
store = join_df(store, store_states, "Store") len(store[store.State.isnull()]) joined = join_df(train, store, "Store") joined_test = join_df(test, store, "Store") len(joined[joined.StoreType.isnull()]),len(joined_test[joined_test.StoreType.isnull()]) joined = join_df(joined, googletrend, ["State","Year", "Week"]) joi...
data_science/courses/temp/courses/dl1/lesson3-rossman.ipynb
jmhsi/justin_tinker
apache-2.0
Next we'll fill in missing values to avoid complications with NA's. NA (not available) is how Pandas indicates missing values; many models have problems when missing values are present, so it's always important to think about how to deal with them. In these cases, we are picking an arbitrary signal value that doesn't o...
for df in (joined,joined_test): df['CompetitionOpenSinceYear'] = df.CompetitionOpenSinceYear.fillna(1900).astype(np.int32) df['CompetitionOpenSinceMonth'] = df.CompetitionOpenSinceMonth.fillna(1).astype(np.int32) df['Promo2SinceYear'] = df.Promo2SinceYear.fillna(1900).astype(np.int32) df['Promo2SinceWee...
data_science/courses/temp/courses/dl1/lesson3-rossman.ipynb
jmhsi/justin_tinker
apache-2.0
Next we'll extract features "CompetitionOpenSince" and "CompetitionDaysOpen". Note the use of apply() in mapping a function across dataframe values.
for df in (joined,joined_test): df["CompetitionOpenSince"] = pd.to_datetime(dict(year=df.CompetitionOpenSinceYear, month=df.CompetitionOpenSinceMonth, day=15)) df["CompetitionDaysOpen"] = df.Date.subtract(df.CompetitionOpenSince).dt.days
data_science/courses/temp/courses/dl1/lesson3-rossman.ipynb
jmhsi/justin_tinker
apache-2.0
We'll replace some erroneous / outlying data.
for df in (joined,joined_test): df.loc[df.CompetitionDaysOpen<0, "CompetitionDaysOpen"] = 0 df.loc[df.CompetitionOpenSinceYear<1990, "CompetitionDaysOpen"] = 0
data_science/courses/temp/courses/dl1/lesson3-rossman.ipynb
jmhsi/justin_tinker
apache-2.0
We add "CompetitionMonthsOpen" field, limiting the maximum to 2 years to limit number of unique categories.
for df in (joined,joined_test): df["CompetitionMonthsOpen"] = df["CompetitionDaysOpen"]//30 df.loc[df.CompetitionMonthsOpen>24, "CompetitionMonthsOpen"] = 24 joined.CompetitionMonthsOpen.unique()
data_science/courses/temp/courses/dl1/lesson3-rossman.ipynb
jmhsi/justin_tinker
apache-2.0
Same process for Promo dates.
for df in (joined,joined_test): df["Promo2Since"] = pd.to_datetime(df.apply(lambda x: Week( x.Promo2SinceYear, x.Promo2SinceWeek).monday(), axis=1).astype(pd.datetime)) df["Promo2Days"] = df.Date.subtract(df["Promo2Since"]).dt.days for df in (joined,joined_test): df.loc[df.Promo2Days<0, "Promo2Days...
data_science/courses/temp/courses/dl1/lesson3-rossman.ipynb
jmhsi/justin_tinker
apache-2.0
Durations It is common when working with time series data to extract data that explains relationships across rows as opposed to columns, e.g.: * Running averages * Time until next event * Time since last event This is often difficult to do with most table manipulation frameworks, since they are designed to work with re...
def get_elapsed(fld, pre): day1 = np.timedelta64(1, 'D') last_date = np.datetime64() last_store = 0 res = [] for s,v,d in zip(df.Store.values,df[fld].values, df.Date.values): if s != last_store: last_date = np.datetime64() last_store = s if v: last_date = d ...
data_science/courses/temp/courses/dl1/lesson3-rossman.ipynb
jmhsi/justin_tinker
apache-2.0
We'll be applying this to a subset of columns:
columns = ["Date", "Store", "Promo", "StateHoliday", "SchoolHoliday"] df = train[columns] df = test[columns]
data_science/courses/temp/courses/dl1/lesson3-rossman.ipynb
jmhsi/justin_tinker
apache-2.0
Let's walk through an example. Say we're looking at School Holiday. We'll first sort by Store, then Date, and then call add_elapsed('SchoolHoliday', 'After'): This will apply to each row with School Holiday: * A applied to every row of the dataframe in order of store and date * Will add to the dataframe the days since ...
fld = 'SchoolHoliday' df = df.sort_values(['Store', 'Date']) get_elapsed(fld, 'After') df = df.sort_values(['Store', 'Date'], ascending=[True, False]) get_elapsed(fld, 'Before')
data_science/courses/temp/courses/dl1/lesson3-rossman.ipynb
jmhsi/justin_tinker
apache-2.0
We'll do this for two more fields.
fld = 'StateHoliday' df = df.sort_values(['Store', 'Date']) get_elapsed(fld, 'After') df = df.sort_values(['Store', 'Date'], ascending=[True, False]) get_elapsed(fld, 'Before') fld = 'Promo' df = df.sort_values(['Store', 'Date']) get_elapsed(fld, 'After') df = df.sort_values(['Store', 'Date'], ascending=[True, False])...
data_science/courses/temp/courses/dl1/lesson3-rossman.ipynb
jmhsi/justin_tinker
apache-2.0
We're going to set the active index to Date.
df = df.set_index("Date")
data_science/courses/temp/courses/dl1/lesson3-rossman.ipynb
jmhsi/justin_tinker
apache-2.0
Then set null values from elapsed field calculations to 0.
columns = ['SchoolHoliday', 'StateHoliday', 'Promo'] for o in ['Before', 'After']: for p in columns: a = o+p df[a] = df[a].fillna(0)
data_science/courses/temp/courses/dl1/lesson3-rossman.ipynb
jmhsi/justin_tinker
apache-2.0
Next we'll demonstrate window functions in pandas to calculate rolling quantities. Here we're sorting by date (sort_index()) and counting the number of events of interest (sum()) defined in columns in the following week (rolling()), grouped by Store (groupby()). We do the same in the opposite direction.
bwd = df[['Store']+columns].sort_index().groupby("Store").rolling(7, min_periods=1).sum() fwd = df[['Store']+columns].sort_index(ascending=False ).groupby("Store").rolling(7, min_periods=1).sum()
data_science/courses/temp/courses/dl1/lesson3-rossman.ipynb
jmhsi/justin_tinker
apache-2.0
Next we want to drop the Store indices grouped together in the window function. Often in pandas, there is an option to do this in place. This is time and memory efficient when working with large datasets.
bwd.drop('Store',1,inplace=True) bwd.reset_index(inplace=True) fwd.drop('Store',1,inplace=True) fwd.reset_index(inplace=True) df.reset_index(inplace=True)
data_science/courses/temp/courses/dl1/lesson3-rossman.ipynb
jmhsi/justin_tinker
apache-2.0
Now we'll merge these values onto the df.
df = df.merge(bwd, 'left', ['Date', 'Store'], suffixes=['', '_bw']) df = df.merge(fwd, 'left', ['Date', 'Store'], suffixes=['', '_fw']) df.drop(columns,1,inplace=True) df.head()
data_science/courses/temp/courses/dl1/lesson3-rossman.ipynb
jmhsi/justin_tinker
apache-2.0
It's usually a good idea to back up large tables of extracted / wrangled features before you join them onto another one, that way you can go back to it easily if you need to make changes to it.
df.to_feather(f'{PATH}df') df = pd.read_feather(f'{PATH}df') df["Date"] = pd.to_datetime(df.Date) df.columns joined = join_df(joined, df, ['Store', 'Date']) joined_test = join_df(joined_test, df, ['Store', 'Date'])
data_science/courses/temp/courses/dl1/lesson3-rossman.ipynb
jmhsi/justin_tinker
apache-2.0
The authors also removed all instances where the store had zero sale / was closed. We speculate that this may have cost them a higher standing in the competition. One reason this may be the case is that a little exploratory data analysis reveals that there are often periods where stores are closed, typically for refurb...
joined = joined[joined.Sales!=0]
data_science/courses/temp/courses/dl1/lesson3-rossman.ipynb
jmhsi/justin_tinker
apache-2.0
We'll back this up as well.
joined.reset_index(inplace=True) joined_test.reset_index(inplace=True) joined.to_feather(f'{PATH}joined') joined_test.to_feather(f'{PATH}joined_test')
data_science/courses/temp/courses/dl1/lesson3-rossman.ipynb
jmhsi/justin_tinker
apache-2.0
We now have our final set of engineered features. While these steps were explicitly outlined in the paper, these are all fairly typical feature engineering steps for dealing with time series data and are practical in any similar setting. Create features
joined = pd.read_feather(f'{PATH}joined') joined_test = pd.read_feather(f'{PATH}joined_test') joined.head().T.head(40)
data_science/courses/temp/courses/dl1/lesson3-rossman.ipynb
jmhsi/justin_tinker
apache-2.0
Now that we've engineered all our features, we need to convert to input compatible with a neural network. This includes converting categorical variables into contiguous integers or one-hot encodings, normalizing continuous features to standard normal, etc...
cat_vars = ['Store', 'DayOfWeek', 'Year', 'Month', 'Day', 'StateHoliday', 'CompetitionMonthsOpen', 'Promo2Weeks', 'StoreType', 'Assortment', 'PromoInterval', 'CompetitionOpenSinceYear', 'Promo2SinceYear', 'State', 'Week', 'Events', 'Promo_fw', 'Promo_bw', 'StateHoliday_fw', 'StateHoliday_bw', 'SchoolHoliday...
data_science/courses/temp/courses/dl1/lesson3-rossman.ipynb
jmhsi/justin_tinker
apache-2.0
We're going to run on a sample.
idxs = get_cv_idxs(n, val_pct=150000/n) joined_samp = joined.iloc[idxs].set_index("Date") samp_size = len(joined_samp); samp_size
data_science/courses/temp/courses/dl1/lesson3-rossman.ipynb
jmhsi/justin_tinker
apache-2.0
To run on the full dataset, use this instead:
samp_size = n joined_samp = joined.set_index("Date")
data_science/courses/temp/courses/dl1/lesson3-rossman.ipynb
jmhsi/justin_tinker
apache-2.0
We can now process our data...
joined_samp.head(2) df, y, nas, mapper = proc_df(joined_samp, 'Sales', do_scale=True) yl = np.log(y) joined_test = joined_test.set_index("Date") df_test, _, nas, mapper = proc_df(joined_test, 'Sales', do_scale=True, skip_flds=['Id'], mapper=mapper, na_dict=nas) df.head(2)
data_science/courses/temp/courses/dl1/lesson3-rossman.ipynb
jmhsi/justin_tinker
apache-2.0
In time series data, cross-validation is not random. Instead, our holdout data is generally the most recent data, as it would be in real application. This issue is discussed in detail in this post on our web site. One approach is to take the last 25% of rows (sorted by date) as our validation set.
train_ratio = 0.75 # train_ratio = 0.9 train_size = int(samp_size * train_ratio); train_size val_idx = list(range(train_size, len(df)))
data_science/courses/temp/courses/dl1/lesson3-rossman.ipynb
jmhsi/justin_tinker
apache-2.0
An even better option for picking a validation set is using the exact same length of time period as the test set uses - this is implemented here:
val_idx = np.flatnonzero( (df.index<=datetime.datetime(2014,9,17)) & (df.index>=datetime.datetime(2014,8,1))) val_idx=[0]
data_science/courses/temp/courses/dl1/lesson3-rossman.ipynb
jmhsi/justin_tinker
apache-2.0
DL We're ready to put together our models. Root-mean-squared percent error is the metric Kaggle used for this competition.
def inv_y(a): return np.exp(a) def exp_rmspe(y_pred, targ): targ = inv_y(targ) pct_var = (targ - inv_y(y_pred))/targ return math.sqrt((pct_var**2).mean()) max_log_y = np.max(yl) y_range = (0, max_log_y*1.2)
data_science/courses/temp/courses/dl1/lesson3-rossman.ipynb
jmhsi/justin_tinker
apache-2.0
We can create a ModelData object directly from out data frame.
md = ColumnarModelData.from_data_frame(PATH, val_idx, df, yl.astype(np.float32), cat_flds=cat_vars, bs=128, test_df=df_test)
data_science/courses/temp/courses/dl1/lesson3-rossman.ipynb
jmhsi/justin_tinker
apache-2.0
Some categorical variables have a lot more levels than others. Store, in particular, has over a thousand!
cat_sz = [(c, len(joined_samp[c].cat.categories)+1) for c in cat_vars] cat_sz
data_science/courses/temp/courses/dl1/lesson3-rossman.ipynb
jmhsi/justin_tinker
apache-2.0
We use the cardinality of each variable (that is, its number of unique values) to decide how large to make its embeddings. Each level will be associated with a vector with length defined as below.
emb_szs = [(c, min(50, (c+1)//2)) for _,c in cat_sz] emb_szs m = md.get_learner(emb_szs, len(df.columns)-len(cat_vars), 0.04, 1, [1000,500], [0.001,0.01], y_range=y_range) lr = 1e-3 m.lr_find() m.sched.plot(100)
data_science/courses/temp/courses/dl1/lesson3-rossman.ipynb
jmhsi/justin_tinker
apache-2.0
Sample
m = md.get_learner(emb_szs, len(df.columns)-len(cat_vars), 0.04, 1, [1000,500], [0.001,0.01], y_range=y_range) lr = 1e-3 m.fit(lr, 3, metrics=[exp_rmspe]) m.fit(lr, 5, metrics=[exp_rmspe], cycle_len=1) m.fit(lr, 2, metrics=[exp_rmspe], cycle_len=4)
data_science/courses/temp/courses/dl1/lesson3-rossman.ipynb
jmhsi/justin_tinker
apache-2.0
All
m = md.get_learner(emb_szs, len(df.columns)-len(cat_vars), 0.04, 1, [1000,500], [0.001,0.01], y_range=y_range) lr = 1e-3 m.fit(lr, 1, metrics=[exp_rmspe]) m.fit(lr, 3, metrics=[exp_rmspe]) m.fit(lr, 3, metrics=[exp_rmspe], cycle_len=1)
data_science/courses/temp/courses/dl1/lesson3-rossman.ipynb
jmhsi/justin_tinker
apache-2.0
Test
m = md.get_learner(emb_szs, len(df.columns)-len(cat_vars), 0.04, 1, [1000,500], [0.001,0.01], y_range=y_range) lr = 1e-3 m.fit(lr, 3, metrics=[exp_rmspe]) m.fit(lr, 3, metrics=[exp_rmspe], cycle_len=1) m.save('val0') m.load('val0') x,y=m.predict_with_targs() exp_rmspe(x,y) pred_test=m.predict(...
data_science/courses/temp/courses/dl1/lesson3-rossman.ipynb
jmhsi/justin_tinker
apache-2.0
RF
from sklearn.ensemble import RandomForestRegressor ((val,trn), (y_val,y_trn)) = split_by_idx(val_idx, df.values, yl) m = RandomForestRegressor(n_estimators=40, max_features=0.99, min_samples_leaf=2, n_jobs=-1, oob_score=True) m.fit(trn, y_trn); preds = m.predict(val) m.score(trn, y_trn), m....
data_science/courses/temp/courses/dl1/lesson3-rossman.ipynb
jmhsi/justin_tinker
apache-2.0
Reading input-output data:
# creating the path to the data data_path = os.path.join(os.getcwd(),'..','data') # reading stimulus Stim = np.array(pd.read_csv(os.path.join(data_path,'Stim2.csv'),header = None)) # reading location of spikes # (lengths of tsp sequences are not equal so reading them line by line) tsp_list = [] with open(os.path.join...
notebooks/MLE_multipleNeuronsWeights.ipynb
valentina-s/GLM_PythonModules
bsd-2-clause
Extracting a spike train from spike positions:
dt = 0.01 y_list = [] for tsp in tsp_list: tsp = np.array(tsp).astype(np.float) tsp_int = np.ceil((tsp - dt*0.001)/dt) tsp_int = np.reshape(tsp_int,(tsp_int.shape[0],1)) tsp_int = tsp_int.astype(int) y_list.append(np.array([item in tsp_int for item in np.arange(Stim.shape[0]/dt)+1]).astype(int))
notebooks/MLE_multipleNeuronsWeights.ipynb
valentina-s/GLM_PythonModules
bsd-2-clause
Creating filters:
# create a stimulus filter kpeaks = np.array([0,round(20/3)]) pars_k = {'neye':5,'n':5,'kpeaks':kpeaks,'b':3} K,K_orth,kt_domain = filters.createStimulusBasis(pars_k, nkt = 20) # create a post-spike filter hpeaks = np.array([0.1,2]) pars_h = {'n':5,'hpeaks':hpeaks,'b':.4} H,H_orth,ht_domain = filters.createPostSpikeB...
notebooks/MLE_multipleNeuronsWeights.ipynb
valentina-s/GLM_PythonModules
bsd-2-clause
Conditional Intensity (spike rate): $$\lambda_{\beta}(i) = \exp(K(\beta_k)Stim + H(\beta_h)y + \sum_{j\ne i}w_j I(\beta_{I})*y_j) + \mu$$ $$\lambda_{\beta}(i) = \exp(M_k\beta_k + M_h \beta_h + Y w + \mu)$$ Creating a matrix of covariates:
M_k = lk.construct_M_k(Stim,K,dt) M_h_list = [] for tsp in tsp_list: tsp = np.array(tsp).astype(np.float) M_h_list.append(lk.construct_M_h(tsp,H_orth,dt,Stim)) # creating a matrix of output covariates Y = np.array(y_list).T
notebooks/MLE_multipleNeuronsWeights.ipynb
valentina-s/GLM_PythonModules
bsd-2-clause
<!---Simulating a neuron spike trains:-->
# tsp_list = [] # for i in range(nofCells): # tsp_list.append(auxfun.simSpikes(np.hstack((coeff_k,coeff_h)),M,dt)) M_list = [] for i in range(len(M_h_list)): # exclude the i'th spike-train M_list.append(np.hstack((M_k,M_h_list[i],np.delete(Y,i,1),np.ones((M_k.shape[0],1))))) #M_list.append(np.hstack((M_...
notebooks/MLE_multipleNeuronsWeights.ipynb
valentina-s/GLM_PythonModules
bsd-2-clause
Conditional intensity as a function of the covariates: $$ \lambda_{\beta} = \exp(M\beta) $$ Create a Poisson process model with this intensity: Setting initial parameters:
coeff_k0 = np.array([ 0.061453,0.284916,0.860335,1.256983,0.910615,0.488660,-0.887091,0.097441,0.026607,-0.090147]) coeff_h0 = np.zeros((5,)) coeff_w0 = np.zeros((nofCells,)) mu_0 = 0 pars0 = np.hstack((coeff_k0,coeff_h0,coeff_w0,mu_0)) pars0 = np.hstack((coeff_k0,coeff_h0,mu_0)) pars0 = np.zeros((17,))
notebooks/MLE_multipleNeuronsWeights.ipynb
valentina-s/GLM_PythonModules
bsd-2-clause
Fitting the likelihood:
res_list = [] for i in range(len(y_list)): model = PP.PPModel(M_list[i].T,dt = dt/100) res_list.append(model.fit(y_list[i],start_coef = pars0,maxiter = 500, method = 'L-BFGS-B'))
notebooks/MLE_multipleNeuronsWeights.ipynb
valentina-s/GLM_PythonModules
bsd-2-clause
Specifying the true parameters:
k_coeff = np.array([0.061453, 0.284916, 0.860335, 1.256983, 0.910615, 0.488660, -0.887091, 0.097441, 0.026607, -0.090147]) h_coeff = np.array([-15.18,38.24,-67.58,-14.06,-3.36]) for i in range(len(res_list)): k_coeff_predicted = res_list[i].x[:10] h_coeff_predicted = res_list[i].x[10:15] print('Estimated d...
notebooks/MLE_multipleNeuronsWeights.ipynb
valentina-s/GLM_PythonModules
bsd-2-clause
Extracting the weight matrix:
W = np.array([np.hstack((res_list[i].x[-(nofCells):-nofCells+i],0,res_list[i].x[-nofCells+i:-1])) for i in range(len(res_list))]) print(W)
notebooks/MLE_multipleNeuronsWeights.ipynb
valentina-s/GLM_PythonModules
bsd-2-clause
Load data
# Load TSG tsg = pd.read_csv('TSG.csv', names=['Time', 'SST']) # Load GO and make UNIX time colum go = pd.read_csv('GO.tsv', sep='\t') go['UNIXTime'] = go.apply( lambda row: int(datetime.timestamp( datetime.strptime(f'{getattr(row, "PC Date")} {getattr(row, "PC Time")}', '%d/%m/%Y %H:%M:%S')))...
Documentation/Algorithms/SensorOffsets/Offset Experiments.ipynb
BjerknesClimateDataCentre/QuinCe
gpl-3.0
Set Time Range
#time_start = 1547000000 #time_end = 1552000000 time_start = 1543618976 time_end = 1558552742 tsg_filtered = tsg.loc[(tsg['Time'] >= time_start) & (tsg['Time'] <= time_end)] go_filtered = go.loc[(go['UNIXTime'] >= time_start) & (go['UNIXTime'] <= time_end)] print(f'Select {len(tsg_filtered)}/{len(go_filtered)} value...
Documentation/Algorithms/SensorOffsets/Offset Experiments.ipynb
BjerknesClimateDataCentre/QuinCe
gpl-3.0
SST from TSG and EqT from GO
plt.figure(figsize=(16, 9)) plt.scatter(tsg_filtered['Time'], tsg_filtered['SST'], label='SST', s=2) plt.scatter(go_filtered['UNIXTime'], go_filtered['equ temp'], label='EqT', s=2) plt.legend()
Documentation/Algorithms/SensorOffsets/Offset Experiments.ipynb
BjerknesClimateDataCentre/QuinCe
gpl-3.0
Set up peak detector Set the parameters for the peak detection algorithm |Parameter |Meaning | |----------|-------------------------------------------------------------------------------| |lag |The number of values to use in the moving average...
# Peak detector settings DEFAULT_LAG_WINDOW = 86400 THRESHOLD=2.5 INFLUENCE=0.5 def calc_lag(times): value_count = len(times) time_range = times[len(times) - 1] - times[0] seconds_per_measurement = time_range / value_count lag_window = DEFAULT_LAG_WINDOW lag_size = floor(lag_window / seconds_p...
Documentation/Algorithms/SensorOffsets/Offset Experiments.ipynb
BjerknesClimateDataCentre/QuinCe
gpl-3.0
Run peak detector for SST and EqT
sst_lag_size = calc_lag(list(tsg_filtered['Time'])) print(sst_lag_size) sst = list(tsg_filtered['SST']) sst_peaks = thresholding_algo(sst, sst_lag_size, THRESHOLD, INFLUENCE) eqt_lag_size = calc_lag(list(go_filtered['UNIXTime'])) print(eqt_lag_size) eqt = list(go_filtered['equ temp']) eqt_peaks = thresholding_algo(eqt...
Documentation/Algorithms/SensorOffsets/Offset Experiments.ipynb
BjerknesClimateDataCentre/QuinCe
gpl-3.0
Extract peak positions Find the places in each time series where the peaks series goes from zero to one (or -1). We exclude periods where the source time series contains NaNs (not yet implemented).
def get_peak_positions(times, peaks): peak_positions = list() last_value = peaks[0] for i in range(1, len(peaks)): if peaks[i] != 0: if last_value == 0: peak_positions.append((times[i], int(peaks[i]))) last_value = peaks[i] return peak_...
Documentation/Algorithms/SensorOffsets/Offset Experiments.ipynb
BjerknesClimateDataCentre/QuinCe
gpl-3.0
Calculate offsets Offsets are calculated using two lists of peak positions: the base_list and the adjust_list. For SST and EqT we adjust the EqT to match the SST. Since SST is physically before EqT in the instrument, all adjustments must be backwards in time. We apply a maximum distance threshold to adjustments to prev...
def make_offsets(base_list, adjust_list, max_difference=600): adjustments = list() # Keep track of where we are in the base list base_index = -1 base_index_used = False # Loop through each peak in the adjust list for (pos, direction) in adjust_list: # Find the last base entry ...
Documentation/Algorithms/SensorOffsets/Offset Experiments.ipynb
BjerknesClimateDataCentre/QuinCe
gpl-3.0
From the figures above, it is difficult to determine an optimal number of clusters. The silhouette score clearly shows that we need more than 5 clusters. 6 looks like a good number, but one of the clusters shows odd behavior when plotting generation change vs net demand change (looks like 2 solid regression lines in th...
cluster_labels = cluster.export_cluster_id(k=16) cluster_labels[:5] labeled_plants = cluster.label_and_export(k=16) labeled_plants.to_clipboard() export_df = fossil_with_ramp.loc[:,['year', 'plant_id', 'cluster_id_6']] export_df.to_csv('Cluster labels.csv', index = False)
Group classification/Group classification.ipynb
gschivley/ERCOT_power
mit
PREVIOUS WORK BELOW Code above now does everything needed, below is kept for reference Variable definitions These variables will be used to cluster the power plants. - year: year that the data is for - fuel type: primary fuel type used at the facility (SUB, LIG, NG, etc) - 1-hr ramp rate: maximum or 95 percentile rate ...
# cols = ['year', 'fuel type', '1-hr ramp rate', '3-hr ramp rate', # 'efficiency', 'efficiency std', 'CF', 'CF std'] # #Add index of power plant IDs # df = pd.DataFrame(columns=cols) filename = 'Cluster_Data.csv' path = '../Clean Data' fullpath = os.path.join(path, filename) cluster_df = pd.read_csv(fullpath...
Group classification/Group classification.ipynb
gschivley/ERCOT_power
mit
missing '1-hr ramp rate'
cluster_df[cluster_df.plant_id==127] cluster_df[cluster_df.plant_id==3466] cluster_df[cluster_df.plant_id==3584] cluster_df['fuel_type'].unique()
Group classification/Group classification.ipynb
gschivley/ERCOT_power
mit
Filter out non-fossil plants
fossil_codes = ['SUB', 'LIG', 'NG', 'DFO', 'PC'] fossil_df = cluster_df.loc[cluster_df['fuel_type'].isin(fossil_codes)] fossil_df.describe() # Unique plants len(fossil_df.dropna().loc[:,'plant_id'].unique()) sns.distplot(fossil_df['capacity'].dropna()) fossil_with_ramp = fossil_df.dropna() sns.distplot(fossil_with_...
Group classification/Group classification.ipynb
gschivley/ERCOT_power
mit
Start classifying only with all nan values dropped
from sklearn.cluster import KMeans from sklearn.metrics import silhouette_samples, silhouette_score, calinski_harabaz_score from sklearn import preprocessing fossil_with_ramp.columns sns.pairplot(fossil_with_ramp, hue='fuel_type', vars=[u'capacity', u'capacity_factor', u'efficiency', u'ramp_rate'])
Group classification/Group classification.ipynb
gschivley/ERCOT_power
mit
The code below begins by scaling the X-vector data to mean 0 and a standard variance. It then loops through a wide range of k values for the number of clusters (3 to 14), calculating the labels for each plant, the Calinski Harabaz score, and the Silhouette score for each value of k.
cluster_data = pd.DataFrame(index=range(3,15), columns=['n_clusters', 'score', 'silhouette']) cluster_labels = {} X = fossil_with_ramp[['capacity', 'capacity_factor', 'efficiency', 'ramp_rate']] X_scaled = preprocessing.StandardScaler().fit_transform(X) for idx, n_clusters in enumerate(range(3,15)): cluster_data....
Group classification/Group classification.ipynb
gschivley/ERCOT_power
mit
The two score values are plotted below. They don't agree exactly on the optimal number of centers, but it looks like 6 or 8 is probably best.
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(8,3)) cluster_data.plot(y='score', ax=ax1) # ax1.plot(range(3,15), cluster_data['score']) ax1.set_title('Calinski Harabaz score\nHigher is better') cluster_data.plot(y='silhouette', ax=ax2) # ax2.plot(range(3,15), silhouette) ax2.set_title('Silhouette score\nLower is better...
Group classification/Group classification.ipynb
gschivley/ERCOT_power
mit
The integer appended to each of the cluster_id column labels is equal to the number of clusters.
for n_clusters in cluster_labels.keys(): fossil_with_ramp.loc[:,'cluster_id_{}'.format(n_clusters)] = cluster_labels[n_clusters] fossil_with_ramp.head() sns.pairplot(fossil_with_ramp, hue='cluster_id_6', vars=[u'capacity', u'capacity_factor', u'efficiency', u'ramp_rate'])
Group classification/Group classification.ipynb
gschivley/ERCOT_power
mit
Some basic information about each of the clusters I've created a bunch of tables and figures to better understand each of the clusters (k=6). The tables show mean, count, and variance. The first figure shows the number of power plants in each group (remember that each power plant is included for every year it operates ...
drop_columns = ['cluster_id_{}'.format(i) for i in [3,4,5,7,8,9,10,11,12,13,14]] grouped = fossil_with_ramp.drop(drop_columns, axis=1).groupby(['cluster_id_6', 'fuel_type']) grouped.mean() grouped.count() grouped.std() sns.countplot('cluster_id_6', hue='fuel_type', data=fossil_with_ramp) plt.title('Count of plants ...
Group classification/Group classification.ipynb
gschivley/ERCOT_power
mit
3. Report some descriptive statistics regarding this dataset. Include at least one measure of central tendency and at least one measure of variability. Congruent Incongruent Mean 14.051125 22.01591667 Standard Error 0.726550901 0.979195185 Median 14.3565 21.0175 Mode #N/A #N/A Standard Deviation 3.5593...
summary = df.describe() summary.transpose()
P1-Analyze the Stroop effect/Perceptual Phenomenon.ipynb
slimn/Data-Analyst
gpl-2.0
4. Provide one or two visualizations that show the distribution of the sample data. Write one or two sentences noting what you observe about the plot or plots.
#%matplotlib inline #plt.figure() ax = df.boxplot() plt.title('Measure time takes to name the ink colors') #plt.figure() #plt.legend()
P1-Analyze the Stroop effect/Perceptual Phenomenon.ipynb
slimn/Data-Analyst
gpl-2.0
From the plot, mean time for congruent word ~14. mean time for congruent word ~22. the incongruent word have two sample outlier, this data set need to verify. participance taken short time to say for congruent word condition. 5. Now, perform the statistical test and report your results. What is your confidence level a...
# Use scipy.stats.ttest_ind. #t_stat, p_val = ttest_ind(df['Congruent'], df['Incongruent'], equal_var=False) t_stat, p_val = ttest_ind(df['Congruent'], df['Incongruent']) print "t_stat ", t_stat print "P-value ", p_val
P1-Analyze the Stroop effect/Perceptual Phenomenon.ipynb
slimn/Data-Analyst
gpl-2.0
Starting with $t_1=0$ and $t_2=0$, when $x=1$, the time we wait turns out to be $\lambda$.
right = 0 left = 0 x = 1 lam = 50 k = 1.5 right = wait_time(x, left, lam, k) right
examples/shower.ipynb
AllenDowney/ThinkBayes2
mit
Now suppose we've waited 50 seconds on the left and we switch to the right. How long should we stay?
left = wait_time(x, right, lam, k) left
examples/shower.ipynb
AllenDowney/ThinkBayes2
mit
And now if we've spent left second on the left and switch to the right, how long should we stay.
right = wait_time(x, left, lam, k) right
examples/shower.ipynb
AllenDowney/ThinkBayes2
mit
But all of that is based on the assumption that x=1. Let's see what happens to the average total time as we vary x. Simulation The following function simulates the strategy I just outlined. It takes as parameters: correct: A Boolean indicating if we're on the right side. tau: The actual time to get hot water. this: Th...
def simulate(correct, tau, this, that, lam, k, x, trace): if len(trace) > 20: return 'Too many recursions' # print(correct, tau, this, that, lam, k, x, trace) # figure out the maximum time we should try before flipping wait = wait_time(x, that, lam, k) # if we're on the correc...
examples/shower.ipynb
AllenDowney/ThinkBayes2
mit
Here are a few test runs with x=0.5 and various values of correct and tau.
x = 0.5 simulate(True, 20, 0, 0, lam, k, x, []) simulate(False, 20, 0, 0, lam, k, x, []) simulate(True, 40, 0, 0, lam, k, x, []) simulate(False, 40, 0, 0, lam, k, x, []) simulate(True, 60, 0, 0, lam, k, x, []) simulate(False, 60, 0, 0, lam, k, x, []) simulate(True, 120, 0, 0, lam, k, x, []) simulate(False, 120, ...
examples/shower.ipynb
AllenDowney/ThinkBayes2
mit
Let's get the test data from Chris.
import os if not os.path.exists('shower_problem_tau_samples.csv'): !wget https://gist.github.com/csaid/a57c4ebaa1c7b0671cdc9692638ea4c4/raw/ad1709938834d7bc88b62ff0763733502eb6a329/shower_problem_tau_samples.csv import pandas as pd test_set = pd.read_csv('shower_problem_tau_samples.csv') test_set.head() test_se...
examples/shower.ipynb
AllenDowney/ThinkBayes2
mit
The following function uses the samples to run simulations and returns the average total time.
import numpy as np def run_simulations(samples, lam, k, x): res = [] for i, (direction, tau) in samples.iterrows(): # print(direction, tau) trace = simulate(direction, tau, 0, 0, lam, k, x, []) res.append((len(trace), sum(trace))) return np.transpose(res)
examples/shower.ipynb
AllenDowney/ThinkBayes2
mit
I'll train the algorithm with a different sample from the same distribution.
from scipy.stats import weibull_min train_set = test_set.copy() train_set['tau'] = weibull_min.rvs(k, scale=lam, size=20000) train_set.describe()
examples/shower.ipynb
AllenDowney/ThinkBayes2
mit
Here's a test run with x=1.
x = 1 lengths, totals = run_simulations(train_set, lam, k, x)
examples/shower.ipynb
AllenDowney/ThinkBayes2
mit
On average it takes about two tries and 116 seconds.
lengths.mean() totals.mean()
examples/shower.ipynb
AllenDowney/ThinkBayes2
mit
Optimization Now let's see how the average duration varies as we sweep through a range of values for the threshold probability, r:
xs = np.linspace(1, 3, 20) xs res = [] for x in xs: lengths, totals = run_simulations(train_set, lam, k, x) res.append((x, totals.mean())) from statsmodels.nonparametric.smoothers_lowess import lowess def make_lowess(series): """Use LOWESS to compute a smooth line. series: pd.Series returns: pd...
examples/shower.ipynb
AllenDowney/ThinkBayes2
mit
Here's what the results look like.
import matplotlib.pyplot as plt rs, ts = np.transpose(res) series = pd.Series(ts, rs) plot_series_lowess(series, 'C1') plt.xlabel("Threshold log odds where you flip (x)") plt.ylabel("Average total duration (seconds)");
examples/shower.ipynb
AllenDowney/ThinkBayes2
mit
It looks like the optimal value of x is about 2. Testing Now let's run the simulations with the optimal value of x and see what the average total time is for the test data.
lengths, totals = run_simulations(test_set, lam, k, 2)
examples/shower.ipynb
AllenDowney/ThinkBayes2
mit
The average total time is about 102 seconds, so it looks like this strategy is better than the current leader (assuming I haven't made a mistake in the simulation).
totals.mean()
examples/shower.ipynb
AllenDowney/ThinkBayes2
mit
Here's the distribution of total time, represented as a CDF.
try: import empiricaldist except ImportError: !pip install empiricaldist from empiricaldist import Cdf Cdf.from_seq(totals).plot(lw=2) plt.xlabel('Total time to connect (seconds)') plt.ylabel('CDF') plt.title('Distribution of total time to connect'); np.percentile(totals, 90)
examples/shower.ipynb
AllenDowney/ThinkBayes2
mit
And here's the distribution of flips.
from empiricaldist import Pmf pmf1 = Pmf.from_seq(lengths-1) pmf1.bar(alpha=0.7) plt.xlabel('How many times you have to flip') plt.ylabel('PMF') plt.title('Distribution of number of flips');
examples/shower.ipynb
AllenDowney/ThinkBayes2
mit
These are the polarization states:
H = Qobj([[1],[0]]) V = Qobj([[0],[1]]) P45 = Qobj([[1/sqrt(2)],[1/sqrt(2)]]) M45 = Qobj([[1/sqrt(2)],[-1/sqrt(2)]]) R = Qobj([[1/sqrt(2)],[-1j/sqrt(2)]]) L = Qobj([[1/sqrt(2)],[1j/sqrt(2)]])
Lab 2 - Quantum States - Blank.ipynb
amcdawes/QMlabs
mit
Devices: HWP - Half-wave plate axis at $\theta$ to the horizontal LP - Linear polarizer, axis at $\theta$ QWP - Quarter-wave plate, axis at $\theta$ Note, these are functions so you need to call them with a specific value of theta.
def HWP(theta): return Qobj([[cos(2*theta),sin(2*theta)],[sin(2*theta),-cos(2*theta)]]).tidyup() def LP(theta): return Qobj([[cos(theta)**2,cos(theta)*sin(theta)],[sin(theta)*cos(theta),sin(theta)**2]]).tidyup() def QWP(theta): return Qobj([[cos(theta)**2 + 1j*sin(theta)**2, (1-1j)*sin(th...
Lab 2 - Quantum States - Blank.ipynb
amcdawes/QMlabs
mit
Example 1) Check that the $|H\rangle$ state is normalized
H.dag()*H psi = Qobj([[1+1j], [2-1j]]) psi psi.dag() psi.dag().dag()
Lab 2 - Quantum States - Blank.ipynb
amcdawes/QMlabs
mit
Perform basic feature extraction Create a sample data set
scratch_df = pd.DataFrame({'x1': [1, 2.5, 3, 4.5], 'x2': [1.5, 2, 3.5, 4]}) scratch_df
02_analytical_data_prep/src/py_part_2_feature_extraction.ipynb
jphall663/GWU_data_mining
apache-2.0
Compress x1 and x2 into a single principal component
pca = PCA(n_components=1) pca.fit(scratch_df)
02_analytical_data_prep/src/py_part_2_feature_extraction.ipynb
jphall663/GWU_data_mining
apache-2.0
Principal components analysis finds vectors that represent that direction(s) of most variance in a data set. These are called eigenvectors.
print('First eigenvector = ', pca.components_)
02_analytical_data_prep/src/py_part_2_feature_extraction.ipynb
jphall663/GWU_data_mining
apache-2.0
Principal components are the projection of the data onto these eigenvectors. Principal components are usually centered around zero and each principal component is uncorrelated with all the others, i.e. principal components are orthogonal to one-another. Becuase prinicipal components represent the highest variance dimen...
scratch_df['Centered_PC1'] = pca.transform(scratch_df[['x1', 'x2']]) scratch_df['Non_centered_PC1'] = pca.transform(scratch_df[['x1', 'x2']] + pca.mean_) scratch_df['PC1_x1_back_projection'] = pd.Series(np.arange(1,8,2)) * pca.components_[0][0] scratch_df['PC1_x2_back_projection'] = pd.Series(np.arange(1,8,2)) * pca.co...
02_analytical_data_prep/src/py_part_2_feature_extraction.ipynb
jphall663/GWU_data_mining
apache-2.0
Initial hex layout Arrange land hexes in random order. Arrange port hexes in random order, interleaved with sea hexes (one sea hex between each pair of port hexes).
# ## Create hex grid ## hex_grid = HexGrid(8, 17, .165, 1.75) np.random.seed(2) # ## Set up board on grid ## # - Assign region (land, port, sea) and terrain type (clay, sheep, ore, wheat, wood, # desert, clay port, sheep port, ore port, wheat port, wood port, 3:1 port, sea) # to each hex. df_hexes = get_hexes(...
colonists/notebooks/Colonists map data structures.ipynb
cfobel/colonists
gpl-3.0
Place a camp [done] Place a camp at a selected node, subject to the following conditions: Selected node cannot already be occupied by a camp or village. Any immediate neighbour (i.e., only a single edge away) of the selected node cannot already be occupied by a camp or village.
selected = 60 df_node_contents = get_empty_node_contents(hex_grid.df_nodes) df_result = place_camp(hex_grid.df_nodes, hex_grid.df_edges, df_hexes, hex_grid.df_hex_links, selected, df_node_contents) df_node_contents.loc[selected] df_result.loc[selected]
colonists/notebooks/Colonists map data structures.ipynb
cfobel/colonists
gpl-3.0
The census documentation has example URLs but needs your API key to work. In this notebook, we'll use the IPython notebook HTML display mechanism to help out.
# http://api.census.gov/data/2010/sf1/geo.html from IPython.core.display import HTML HTML("<iframe src='http://api.census.gov/data/2010/sf1/geo.html' width='800px'/>") %%HTML <b>hi there</b> try: from urllib.parse import urlparse, urlencode, parse_qs, urlunparse except ImportError: from urlparse import url...
03_02_Displaying_Census_URLs.ipynb
rdhyee/diversity-census-calc
apache-2.0
Scraping the examples
import requests from lxml.html import parse, fromstring url = "http://api.census.gov/data/2010/sf1/geo.html" r = requests.get(url).content doc = fromstring(r) rows = doc.xpath("//table/tr") # first row is the header headers = [col.text for col in rows[0].findall('th')] headers # next rows are the census URL exampl...
03_02_Displaying_Census_URLs.ipynb
rdhyee/diversity-census-calc
apache-2.0
The square is just a number multiplied by itself. In python the code that as:
6**2
Week_05/Week05 - 02 - Functions.ipynb
biof-309-python/BIOF309-2016-Fall
mit
We can also assign this calculation to a varaible:
a = 6**2
Week_05/Week05 - 02 - Functions.ipynb
biof-309-python/BIOF309-2016-Fall
mit
What happens if we need to square different numbers in our hypothetical program? Cut and paste and change each time?
a = 6**2 b = 7**2 print(a) print(b)
Week_05/Week05 - 02 - Functions.ipynb
biof-309-python/BIOF309-2016-Fall
mit