markdown
stringlengths
0
37k
code
stringlengths
1
33.3k
path
stringlengths
8
215
repo_name
stringlengths
6
77
license
stringclasses
15 values
Test the converted models To prove these models are still accurate after conversion and quantization, we'll use both of them to make predictions and compare these against our test results:
# Instantiate an interpreter for each model sine_model = tf.lite.Interpreter('sine_model.tflite') sine_model_quantized = tf.lite.Interpreter('sine_model_quantized.tflite') # Allocate memory for each model sine_model.allocate_tensors() sine_model_quantized.allocate_tensors() # Get the input and output tensors so we ca...
tensorflow/lite/micro/examples/hello_world/create_sine_model.ipynb
gunan/tensorflow
apache-2.0
We can see from the graph that the predictions for the original model, the converted model, and the quantized model are all close enough to be indistinguishable. This means that our quantized model is ready to use! We can print the difference in file size:
import os basic_model_size = os.path.getsize("sine_model.tflite") print("Basic model is %d bytes" % basic_model_size) quantized_model_size = os.path.getsize("sine_model_quantized.tflite") print("Quantized model is %d bytes" % quantized_model_size) difference = basic_model_size - quantized_model_size print("Difference i...
tensorflow/lite/micro/examples/hello_world/create_sine_model.ipynb
gunan/tensorflow
apache-2.0
Our quantized model is only 16 bytes smaller than the original version, which only a tiny reduction in size! At around 2.6 kilobytes, this model is already so small that the weights make up only a small fraction of the overall size, meaning quantization has little effect. More complex models have many more weights, mea...
# Install xxd if it is not available !apt-get -qq install xxd # Save the file as a C source file !xxd -i sine_model_quantized.tflite > sine_model_quantized.cc # Print the source file !cat sine_model_quantized.cc
tensorflow/lite/micro/examples/hello_world/create_sine_model.ipynb
gunan/tensorflow
apache-2.0
Reshaping DataFrame objects In the context of a single DataFrame, we are often interested in re-arranging the layout of our data. This dataset in from Table 6.9 of Statistical Methods for the Analysis of Repeated Measurements by Charles S. Davis, pp. 161-163 (Springer, 2002). These data are from a multicenter, randomi...
cdystonia = pd.read_csv("../data/cdystonia.csv", index_col=None) cdystonia.head()
notebooks/1.4 - Pandas Best Practices.ipynb
fonnesbeck/ngcm_pandas_2016
cc0-1.0
Have a peek at the structure of the index of the stacked data (and the data itself). To complement this, unstack pivots from rows back to columns.
stacked.unstack().head()
notebooks/1.4 - Pandas Best Practices.ipynb
fonnesbeck/ngcm_pandas_2016
cc0-1.0
Exercise Which columns uniquely define a row? Create a DataFrame called cdystonia2 with a hierarchical index based on these columns.
# Write your answer here
notebooks/1.4 - Pandas Best Practices.ipynb
fonnesbeck/ngcm_pandas_2016
cc0-1.0
If we want to transform this data so that repeated measurements are in columns, we can unstack the twstrs measurements according to obs.
twstrs_wide = cdystonia2['twstrs'].unstack('obs') twstrs_wide.head()
notebooks/1.4 - Pandas Best Practices.ipynb
fonnesbeck/ngcm_pandas_2016
cc0-1.0
We can now merge these reshaped outcomes data with the other variables to create a wide format DataFrame that consists of one row for each patient.
cdystonia_wide = (cdystonia[['patient','site','id','treat','age','sex']] .drop_duplicates() .merge(twstrs_wide, right_index=True, left_on='patient', how='inner')) cdystonia_wide.head()
notebooks/1.4 - Pandas Best Practices.ipynb
fonnesbeck/ngcm_pandas_2016
cc0-1.0
This illustrates the two formats for longitudinal data: long and wide formats. Its typically better to store data in long format because additional data can be included as additional rows in the database, while wide format requires that the entire database schema be altered by adding columns to every row as data are co...
(cdystonia[['patient','site','id','treat','age','sex']] .drop_duplicates() .merge(twstrs_wide, right_index=True, left_on='patient', how='inner') .head())
notebooks/1.4 - Pandas Best Practices.ipynb
fonnesbeck/ngcm_pandas_2016
cc0-1.0
This approach of seqentially calling methods is called method chaining, and despite the fact that it creates very long lines of code that must be properly justified, it allows for the writing of rather concise and readable code. Method chaining is possible because of the pandas convention of returning copies of the res...
cdystonia_subset = cdystonia[['patient','site','id','treat','age','sex']] cdystonia_complete = cdystonia_subset.drop_duplicates() cdystonia_merged = cdystonia_complete.merge(twstrs_wide, right_index=True, left_on='patient', how='inner') cdystonia_merged.head()
notebooks/1.4 - Pandas Best Practices.ipynb
fonnesbeck/ngcm_pandas_2016
cc0-1.0
This necessitates the creation of a slew of intermediate variables that we really don't need. Let's transform another dataset using method chaining. The measles.csv file contains de-identified cases of measles from an outbreak in Sao Paulo, Brazil in 1997. The file contains rows of individual records:
measles = pd.read_csv("../data/measles.csv", index_col=0, encoding='latin-1', parse_dates=['ONSET']) measles.head()
notebooks/1.4 - Pandas Best Practices.ipynb
fonnesbeck/ngcm_pandas_2016
cc0-1.0
The goal is to summarize this data by age groups and bi-weekly period, so that we can see how the outbreak affected different ages over the course of the outbreak. The best approach is to build up the chain incrementally. We can begin by generating the age groups (using cut) and grouping by age group and the date (ONSE...
(measles.assign(AGE_GROUP=pd.cut(measles.YEAR_AGE, [0,5,10,15,20,25,30,35,40,100], right=False)) .groupby(['ONSET', 'AGE_GROUP']))
notebooks/1.4 - Pandas Best Practices.ipynb
fonnesbeck/ngcm_pandas_2016
cc0-1.0
What we then want is the number of occurences in each combination, which we can obtain by checking the size of each grouping:
(measles.assign(AGE_GROUP=pd.cut(measles.YEAR_AGE, [0,5,10,15,20,25,30,35,40,100], right=False)) .groupby(['ONSET', 'AGE_GROUP']) .size()).head(10)
notebooks/1.4 - Pandas Best Practices.ipynb
fonnesbeck/ngcm_pandas_2016
cc0-1.0
This results in a hierarchically-indexed Series, which we can pivot into a DataFrame by simply unstacking:
(measles.assign(AGE_GROUP=pd.cut(measles.YEAR_AGE, [0,5,10,15,20,25,30,35,40,100], right=False)) .groupby(['ONSET', 'AGE_GROUP']) .size() .unstack()).head(5)
notebooks/1.4 - Pandas Best Practices.ipynb
fonnesbeck/ngcm_pandas_2016
cc0-1.0
Now, fill replace the missing values with zeros:
(measles.assign(AGE_GROUP=pd.cut(measles.YEAR_AGE, [0,5,10,15,20,25,30,35,40,100], right=False)) .groupby(['ONSET', 'AGE_GROUP']) .size() .unstack() .fillna(0)).head(5)
notebooks/1.4 - Pandas Best Practices.ipynb
fonnesbeck/ngcm_pandas_2016
cc0-1.0
Finally, we want the counts in 2-week intervals, rather than as irregularly-reported days, which yields our the table of interest:
case_counts_2w = (measles.assign(AGE_GROUP=pd.cut(measles.YEAR_AGE, [0,5,10,15,20,25,30,35,40,100], right=False)) .groupby(['ONSET', 'AGE_GROUP']) .size() .unstack() .fillna(0) .resample('2W') ...
notebooks/1.4 - Pandas Best Practices.ipynb
fonnesbeck/ngcm_pandas_2016
cc0-1.0
From this, it is easy to create meaningful plots and conduct analyses:
case_counts_2w.plot(cmap='hot')
notebooks/1.4 - Pandas Best Practices.ipynb
fonnesbeck/ngcm_pandas_2016
cc0-1.0
Pivoting The pivot method allows a DataFrame to be transformed easily between long and wide formats in the same way as a pivot table is created in a spreadsheet. It takes three arguments: index, columns and values, corresponding to the DataFrame index (the row headers), columns and cell values, respectively. For exampl...
cdystonia.pivot(index='patient', columns='obs', values='twstrs').head()
notebooks/1.4 - Pandas Best Practices.ipynb
fonnesbeck/ngcm_pandas_2016
cc0-1.0
Exercise Try pivoting the cdystonia DataFrame without specifying a variable for the cell values:
# Write your answer here
notebooks/1.4 - Pandas Best Practices.ipynb
fonnesbeck/ngcm_pandas_2016
cc0-1.0
Data transformation There are a slew of additional operations for DataFrames that we would collectively refer to as transformations which include tasks such as: removing duplicate values replacing values grouping values. Dealing with duplicates We can easily identify and remove duplicate values from DataFrame objects...
vessels = pd.read_csv('../data/AIS/vessel_information.csv') vessels.tail(10) vessels.duplicated(subset='names').tail(10)
notebooks/1.4 - Pandas Best Practices.ipynb
fonnesbeck/ngcm_pandas_2016
cc0-1.0
These rows can be removed using drop_duplicates
vessels.drop_duplicates(['names']).tail(10)
notebooks/1.4 - Pandas Best Practices.ipynb
fonnesbeck/ngcm_pandas_2016
cc0-1.0
Alternately, if we simply want to replace particular values in a Series or DataFrame, we can use the replace method. An example where replacement is useful is replacing sentinel values with an appropriate numeric value prior to analysis. A large negative number is sometimes used in otherwise positive-valued data to de...
scores = pd.Series([99, 76, 85, -999, 84, 95])
notebooks/1.4 - Pandas Best Practices.ipynb
fonnesbeck/ngcm_pandas_2016
cc0-1.0
In such situations, we can use replace to substitute nan where the sentinel values occur.
scores.replace(-999, np.nan)
notebooks/1.4 - Pandas Best Practices.ipynb
fonnesbeck/ngcm_pandas_2016
cc0-1.0
Inidcator variables For some statistical analyses (e.g. regression models or analyses of variance), categorical or group variables need to be converted into columns of indicators--zeros and ones--to create a so-called design matrix. The Pandas function get_dummies (indicator variables are also known as dummy variables)...
# Write your answer here
notebooks/1.4 - Pandas Best Practices.ipynb
fonnesbeck/ngcm_pandas_2016
cc0-1.0
We can now apply get_dummies to the vessel type to create 5 indicator variables.
pd.get_dummies(vessels5.type).head(10)
notebooks/1.4 - Pandas Best Practices.ipynb
fonnesbeck/ngcm_pandas_2016
cc0-1.0
Discretization Pandas' cut function can be used to group continuous or countable data in to bins. Discretization is generally a very bad idea for statistical analysis, so use this function responsibly! Lets say we want to bin the ages of the cervical dystonia patients into a smaller number of groups:
cdystonia.age.describe()
notebooks/1.4 - Pandas Best Practices.ipynb
fonnesbeck/ngcm_pandas_2016
cc0-1.0
Alternatively, one can specify custom quantiles to act as cut points:
quantiles = pd.qcut(vessels.max_loa, [0, 0.01, 0.05, 0.95, 0.99, 1]) quantiles[:30]
notebooks/1.4 - Pandas Best Practices.ipynb
fonnesbeck/ngcm_pandas_2016
cc0-1.0
Exercise Use the discretized segment lengths as the input for get_dummies to create 5 indicator variables for segment length:
# Write your answer here
notebooks/1.4 - Pandas Best Practices.ipynb
fonnesbeck/ngcm_pandas_2016
cc0-1.0
Categorical Variables One of the keys to maximizing performance in pandas is to use the appropriate types for your data wherever possible. In the case of categorical data--either the ordered categories as we have just created, or unordered categories like race, gender or country--the use of the categorical to encode st...
cdystonia_cat = cdystonia.assign(treatment=cdystonia.treat.astype('category')).drop('treat', axis=1) cdystonia_cat.dtypes cdystonia_cat.treatment.head() cdystonia_cat.treatment.cat.codes
notebooks/1.4 - Pandas Best Practices.ipynb
fonnesbeck/ngcm_pandas_2016
cc0-1.0
This creates an unordered categorical variable. To create an ordinal variable, we can specify order=True as an argument to astype:
cdystonia.treat.astype('category', ordered=True).head()
notebooks/1.4 - Pandas Best Practices.ipynb
fonnesbeck/ngcm_pandas_2016
cc0-1.0
However, this is not the correct order; by default, the categories will be sorted alphabetically, which here gives exactly the reverse order that we need. To specify an arbitrary order, we can used the set_categories method, as follows:
cdystonia.treat.astype('category').cat.set_categories(['Placebo', '5000U', '10000U'], ordered=True).head()
notebooks/1.4 - Pandas Best Practices.ipynb
fonnesbeck/ngcm_pandas_2016
cc0-1.0
Notice that we obtained set_categories from the cat attribute of the categorical variable. This is known as the category accessor, and is a device for gaining access to Categorical variables' categories, analogous to the string accessor that we have seen previously from text variables.
cdystonia_cat.treatment.cat
notebooks/1.4 - Pandas Best Practices.ipynb
fonnesbeck/ngcm_pandas_2016
cc0-1.0
Additional categoried can be added, even if they do not currently exist in the DataFrame, but are part of the set of possible categories:
cdystonia_cat['treatment'] = (cdystonia.treat.astype('category').cat .set_categories(['Placebo', '5000U', '10000U', '20000U'], ordered=True))
notebooks/1.4 - Pandas Best Practices.ipynb
fonnesbeck/ngcm_pandas_2016
cc0-1.0
To complement this, we can remove categories that we do not wish to retain:
cdystonia_cat.treatment.cat.remove_categories('20000U').head()
notebooks/1.4 - Pandas Best Practices.ipynb
fonnesbeck/ngcm_pandas_2016
cc0-1.0
Or, even more simply:
cdystonia_cat.treatment.cat.remove_unused_categories().head()
notebooks/1.4 - Pandas Best Practices.ipynb
fonnesbeck/ngcm_pandas_2016
cc0-1.0
For larger datasets, there is an appreciable gain in performance, both in terms of speed and memory usage.
vessels_merged = (pd.read_csv('../data/AIS/vessel_information.csv', index_col=0) .merge(pd.read_csv('../data/AIS/transit_segments.csv'), left_index=True, right_on='mmsi')) vessels_merged['registered'] = vessels_merged.flag.astype('category') %timeit vessels_merged.groupby('flag').avg_sog.mea...
notebooks/1.4 - Pandas Best Practices.ipynb
fonnesbeck/ngcm_pandas_2016
cc0-1.0
The add_prefix and add_suffix methods can be used to give the columns of the resulting table labels that reflect the transformation:
cdystonia_grouped.mean().add_suffix('_mean').head()
notebooks/1.4 - Pandas Best Practices.ipynb
fonnesbeck/ngcm_pandas_2016
cc0-1.0
Exercise Use the quantile method to generate the median values of the twstrs variable for each patient.
# Write your answer here
notebooks/1.4 - Pandas Best Practices.ipynb
fonnesbeck/ngcm_pandas_2016
cc0-1.0
It is easy to do column selection within groupby operations, if we are only interested split-apply-combine operations on a subset of columns:
%timeit cdystonia_grouped['twstrs'].mean().head()
notebooks/1.4 - Pandas Best Practices.ipynb
fonnesbeck/ngcm_pandas_2016
cc0-1.0
Or, as a DataFrame:
cdystonia_grouped[['twstrs']].mean().head()
notebooks/1.4 - Pandas Best Practices.ipynb
fonnesbeck/ngcm_pandas_2016
cc0-1.0
By default, groupby groups by row, but we can specify the axis argument to change this. For example, we can group our columns by dtype this way:
dict(list(cdystonia.groupby(cdystonia.dtypes, axis=1)))
notebooks/1.4 - Pandas Best Practices.ipynb
fonnesbeck/ngcm_pandas_2016
cc0-1.0
Its also possible to group by one or more levels of a hierarchical index. Recall cdystonia2, which we created with a hierarchical index:
cdystonia2.head(10)
notebooks/1.4 - Pandas Best Practices.ipynb
fonnesbeck/ngcm_pandas_2016
cc0-1.0
The level argument specifies which level of the index to use for grouping.
cdystonia2.groupby(level='obs', axis=0)['twstrs'].mean()
notebooks/1.4 - Pandas Best Practices.ipynb
fonnesbeck/ngcm_pandas_2016
cc0-1.0
Apply We can generalize the split-apply-combine methodology by using apply function. This allows us to invoke any function we wish on a grouped dataset and recombine them into a DataFrame. The function below takes a DataFrame and a column name, sorts by the column, and takes the n largest values of that column. We can ...
def top(df, column, n=5): return df.sort_index(by=column, ascending=False)[:n]
notebooks/1.4 - Pandas Best Practices.ipynb
fonnesbeck/ngcm_pandas_2016
cc0-1.0
To see this in action, consider the vessel transit segments dataset (which we merged with the vessel information to yield segments_merged). Say we wanted to return the 3 longest segments travelled by each ship:
goo = vessels_merged.groupby('mmsi') top3segments = vessels_merged.groupby('mmsi').apply(top, column='seg_length', n=3)[['names', 'seg_length']] top3segments.head(15)
notebooks/1.4 - Pandas Best Practices.ipynb
fonnesbeck/ngcm_pandas_2016
cc0-1.0
Notice that additional arguments for the applied function can be passed via apply after the function name. It assumes that the DataFrame is the first argument. Exercise Load the dataset in titanic.xls. It contains data on all the passengers that travelled on the Titanic.
from IPython.core.display import HTML HTML(filename='../data/titanic.html')
notebooks/1.4 - Pandas Best Practices.ipynb
fonnesbeck/ngcm_pandas_2016
cc0-1.0
Women and children first? Use the groupby method to calculate the proportion of passengers that survived by sex. Calculate the same proportion, but by class and sex. Create age categories: children (under 14 years), adolescents (14-20), adult (21-64), and senior(65+), and calculate survival proportions by age category...
# Write your answer here
notebooks/1.4 - Pandas Best Practices.ipynb
fonnesbeck/ngcm_pandas_2016
cc0-1.0
Help with commands If you ever need to look up a command, you can bring up the list of shortcuts by pressing H in command mode. The keyboard shortcuts are also available above in the Help menu. Go ahead and try it now. Creating new cells One of the most common commands is creating new cells. You can create a cell above...
## Practice here def fibo(n): # Recursive Fibonacci sequence! if n == 0: return 0 elif n == 1: return 1 return fibo(n-1) + fibo(n-2)
nd101 Deep Learning Nanodegree Foundation/notebooks/1 - playing with jupyter/keyboard-shortcuts.ipynb
anandha2017/udacity
mit
Line numbers A lot of times it is helpful to number the lines in your code for debugging purposes. You can turn on numbers by pressing L (in command mode of course) on a code cell. Exercise: Turn line numbers on and off in the above code cell. Deleting cells Deleting cells is done by pressing D twice in a row so D, ...
# below this cell # Move this cell down
nd101 Deep Learning Nanodegree Foundation/notebooks/1 - playing with jupyter/keyboard-shortcuts.ipynb
anandha2017/udacity
mit
Next, we will import the data we saved previously using the pickle library.
pickle_file = '-basic_data.pickle' with open(pickle_file, 'rb') as f: save = pickle.load(f) X = save['X'] y = save['y'] char_to_int = save['char_to_int'] int_to_char = save['int_to_char'] del save # hint to help gc free up memory print('Training set', X.shape, y.shape)
notebooks/week-6/02-using a pre-trained model with Keras.ipynb
kkkddder/dmc
apache-2.0
Now we need to define the Keras model. Since we will be loading parameters from a pre-trained model, this needs to match exactly the definition from the previous lab section. The only difference is that we will comment out the dropout layer so that the model uses all the hidden neurons when doing the predictions.
# define the LSTM model model = Sequential() model.add(LSTM(128, return_sequences=False, input_shape=(X.shape[1], X.shape[2]))) # model.add(Dropout(0.50)) model.add(Dense(y.shape[1], activation='softmax')) model.compile(loss='categorical_crossentropy', optimizer='adam')
notebooks/week-6/02-using a pre-trained model with Keras.ipynb
kkkddder/dmc
apache-2.0
Next we will load the parameters from the model we trained previously, and compile it with the same loss and optimizer function.
# load the parameters from the pretrained model filename = "-basic_LSTM.hdf5" model.load_weights(filename) model.compile(loss='categorical_crossentropy', optimizer='adam')
notebooks/week-6/02-using a pre-trained model with Keras.ipynb
kkkddder/dmc
apache-2.0
We also need to rewrite the sample() and generate() helper functions so that we can use them in our code:
def sample(preds, temperature=1.0): preds = np.asarray(preds).astype('float64') preds = np.log(preds) / temperature exp_preds = np.exp(preds) preds = exp_preds / np.sum(exp_preds) probas = np.random.multinomial(1, preds, 1) return np.argmax(probas) def generate(sentence, sample_length=50, diver...
notebooks/week-6/02-using a pre-trained model with Keras.ipynb
kkkddder/dmc
apache-2.0
Now we can use the generate() function to generate text of any length based on our imported pre-trained model and a seed text of our choice. For best result, the length of the seed text should be the same as the length of training sequences (100 in the previous lab section). In this case, we will test the overfitting ...
prediction_length = 500 seed_from_text = "america has shown that progress is possible. last year, income gains were larger for households at t" seed_original = "and as people around the world began to hear the tale of the lowly colonists who overthrew an empire" for seed in [seed_from_text, seed_original]: generat...
notebooks/week-6/02-using a pre-trained model with Keras.ipynb
kkkddder/dmc
apache-2.0
Data input We need some data to get started. Luckily, we have jQAssistant at our hand. It's integrated into the build process of Spring PetClinic repository above and scanned the Git repository information automatically with every executed build. So let's query our almighty Neo4j graph database that holds all the stru...
graph = py2neo.Graph() query = """ MATCH (author:Author)-[:COMMITED]-> (commit:Commit) RETURN author.name as name, author.email as email """ result = graph.data(query) # just how first three entries result[0:3]
notebooks/Committer Distribution.ipynb
feststelltaste/software-analytics
gpl-3.0
The query returns all commits with their authors and the author's email addresses. We get some nice, tabular data that we put into Pandas's DataFrame.
commits = pd.DataFrame(result) commits.head()
notebooks/Committer Distribution.ipynb
feststelltaste/software-analytics
gpl-3.0
Familiarization First, I like to check the raw data a little bit. I often do this by first having a look at the data types the data source is returning. It's a good starting point to check that Pandas recognizes the data types accordingly. You can also use this approach to check for skewed data columns very quickly (es...
commits.dtypes
notebooks/Committer Distribution.ipynb
feststelltaste/software-analytics
gpl-3.0
That's OK for our simple scenario. The two columns with texts are objects – nothing spectacular. In the next step, I always like to get a "feeling" of all the data. Primarily, I want to get a quick impression of the data quality again. It could always be that there is "dirty data" in the dataset or that there are...
commits['name'].value_counts()[0:10]
notebooks/Committer Distribution.ipynb
feststelltaste/software-analytics
gpl-3.0
OK, at first glance, something seems awkward. Let's have a look at the email addresses.
commits['email'].value_counts()[0:10]
notebooks/Committer Distribution.ipynb
feststelltaste/software-analytics
gpl-3.0
OK, the bad feeling is strengthening. We might have a problem with multiple authors having multiple email addresses. Let me show you the problem by better representing the problem. Interlude - begin In the interlude section, I take you to a short, mostly undocumented excursion with probably messy code (don't do this at...
grouped_by_authors = commits[['name', 'email']]\ .drop_duplicates().groupby('name').count()\ .sort_values('email', ascending=False).reset_index().reset_index() grouped_by_authors.head()
notebooks/Committer Distribution.ipynb
feststelltaste/software-analytics
gpl-3.0
Same procedure for the email addresses.
grouped_by_email = commits[['name', 'email']]\ .drop_duplicates().groupby('email').count()\ .sort_values('name', ascending=False).reset_index().reset_index() grouped_by_email.head()
notebooks/Committer Distribution.ipynb
feststelltaste/software-analytics
gpl-3.0
Then I merge the two DataFrames with a subset of the original data. I get each author and email index as well as the number of occurrences for author respectively emails. I only need the ones that are occurring multiple times, so I check for > 2.
plot_data = commits.drop_duplicates()\ .merge(grouped_by_authors, left_on='name', right_on="name", suffixes=["", "_from_authors"], how="outer")\ .merge(grouped_by_email, left_on='email', right_on="email", suffixes=["", "_from_emails"], how="outer") plot_data = plot_data[\ (plot_data['emai...
notebooks/Committer Distribution.ipynb
feststelltaste/software-analytics
gpl-3.0
I just add some nicely normalized indexes for plotting (note: there might be a method that's easier)
from sklearn import preprocessing le = preprocessing.LabelEncoder() le.fit(plot_data['index']) plot_data['normalized_index_name'] = le.transform(plot_data['index']) * 10 le.fit(plot_data['index_from_emails']) plot_data['normalized_index_email'] = le.transform(plot_data['index_from_emails']) * 10 plot_data.head()
notebooks/Committer Distribution.ipynb
feststelltaste/software-analytics
gpl-3.0
Plot an assignment table with the relationships between authors and email addresses.
fig1 = plt.figure(facecolor='white') ax1 = plt.axes(frameon=False) ax1.set_frame_on(False) ax1.get_xaxis().tick_bottom() ax1.axes.get_yaxis().set_visible(False) ax1.axes.get_xaxis().set_visible(False) # simply plot all the data (imperfection: duplicated will be displayed in bold font) for data in plot_data.iterrows():...
notebooks/Committer Distribution.ipynb
feststelltaste/software-analytics
gpl-3.0
Alright! Here we are! We see that multiple authors use multiple email addresses. And I see a pattern that could be used to get better data. Do you, too? Interlude - end If you skipped the interlude section: I just visualized / demonstrated that there are different email addresses per author (and vise versa). Some auth...
commits['nickname'] = commits['email'].apply(lambda x : x.split("@")[0]) commits.head()
notebooks/Committer Distribution.ipynb
feststelltaste/software-analytics
gpl-3.0
That looks pretty good. Now we want to get only the person's real name instead of the nickname. We use a little heuristic to determine the "best fitting" real name and replace all the others. For this, we need group by nicknames and determine the real names.
def determine_real_name(names): real_name = "" for name in names: # assumption: if there is a whitespace in the name, # someone thought about it to be first name and surname if " " in name: return name # else take the longest name elif len(name) > l...
notebooks/Committer Distribution.ipynb
feststelltaste/software-analytics
gpl-3.0
That looks great! Now we switch back to our previous DataFrame by joining in the new information.
commits = commits.merge(commits_grouped, left_on='nickname', right_index=True) # drop duplicated for better displaying commits.drop_duplicates().head()
notebooks/Committer Distribution.ipynb
feststelltaste/software-analytics
gpl-3.0
That should be enough data cleansing for today! Analysis Now that we have valid data, we can produce some new insights. Top 10 committers Easy tasks first: We simply produce a table with the Top 10 committers. We group by the real name and count every commit by using a subset (only the <tt>email</tt> column) of the Dat...
committers = commits.groupby('real_name')[['email']]\ .count().rename(columns={'email' : 'commits'})\ .sort_values('commits', ascending=False) committers.head(10) committers.head(10)
notebooks/Committer Distribution.ipynb
feststelltaste/software-analytics
gpl-3.0
Committer Distribution Next, we create a pie chart to get a good impression of the committers.
committers['commits'].plot(kind='pie')
notebooks/Committer Distribution.ipynb
feststelltaste/software-analytics
gpl-3.0
Uhh...that looks ugly and kind of weird. Let's first try to fix the mess on the right side that shows all authors with minor changes by summing up their number of commits. We will use a threshold value that makes sense with our data (e. g. the committers that contribute more than 3/4 to the code) to identify them. A ni...
committers_description = committers.describe() committers_description
notebooks/Committer Distribution.ipynb
feststelltaste/software-analytics
gpl-3.0
OK, we want the 3/4 main contributors...
threshold = committers_description.loc['75%'].values[0] threshold
notebooks/Committer Distribution.ipynb
feststelltaste/software-analytics
gpl-3.0
...that is > 75% of the commits of all contributors.
minor_committers = committers[committers['commits'] <= threshold] minor_committers.head()
notebooks/Committer Distribution.ipynb
feststelltaste/software-analytics
gpl-3.0
These are the entries we want to combine to our new "Others" section. But we don't want to loose the number of changes, so we store them for later usage.
others_number_of_changes = minor_committers.sum() others_number_of_changes
notebooks/Committer Distribution.ipynb
feststelltaste/software-analytics
gpl-3.0
Now we are deleting all authors that are in the <tt>author_minor_changes</tt>'s DataFrame. To not check on the threshold value from above again, we reuse the already calculated DataFrame.
main_committers = committers[~committers.isin(minor_committers)] main_committers.tail()
notebooks/Committer Distribution.ipynb
feststelltaste/software-analytics
gpl-3.0
This gives us for the contributors with just a few commits missing values for the <tt>changes</tt> column, because these values were in the <tt>author_minor_changes</tt> DataFrame. We drop all Nan values to get only the major contributors.
main_committers = main_committers.dropna() main_committers
notebooks/Committer Distribution.ipynb
feststelltaste/software-analytics
gpl-3.0
We add the "Others" row by appending to the DataFrame
main_committers.loc["Others"] = others_number_of_changes main_committers
notebooks/Committer Distribution.ipynb
feststelltaste/software-analytics
gpl-3.0
Almost there, you redraw with some styling and minor adjustments.
# some configuration for displaying nice diagrams plt.style.use('fivethirtyeight') plt.figure(facecolor='white') ax = main_committers['commits'].plot( kind='pie', figsize=(6,6), title="Main committers", autopct='%.2f', fontsize=12) # get rid of the distracting label for the y-axis ax.set_ylabel("")
notebooks/Committer Distribution.ipynb
feststelltaste/software-analytics
gpl-3.0
<hr> Signal Processing for Data Scientists Jed Ludlow UnitedHealth Group <hr> Get the code at https://github.com/jedludlow/sp-for-ds Overview Signal processing: Tools to separate the useful information from the nuisance information in a time series. Cover three areas today Fourier analysis in the frequency domain Di...
def fft_scaled(x, axis=-1, samp_freq=1.0, remove_mean=True): """ Fully scaled and folded FFT with physical amplitudes preserved. Arguments --------- x: numpy n-d array array of signal information. axis: int array axis along which to compute the FFT. samp_freq: float ...
sp_for_ds.ipynb
jedludlow/sp-for-ds
mit
1 Hz Square Wave
f_s = 1000.0 # Sampling frequency in Hz time = np.arange(0.0, 100.0 + 1.0/f_s, 1.0/f_s) square_wave = signal.square(2 * np.pi * time) plt.figure(figsize=(9, 5)) plt.plot(time, square_wave), plt.xlabel('time (s)'), plt.ylabel('x(t)'), plt.title('1 Hz Square Wave') plt.xlim((0, 3)), plt.ylim((-1.1, 1.1));
sp_for_ds.ipynb
jedludlow/sp-for-ds
mit
Fourier Analysis of Square Wave
fft_x, freq_sq = fft_scaled(square_wave, samp_freq=f_s) f_max = 24.0 plt.figure(figsize=(9, 5)), plt.plot(freq_sq, np.abs(fft_x)) plt.xticks(np.arange(0.0, f_max + 1.0, 1.0)) plt.xlim((0, f_max)), plt.xlabel('Frequency (Hz)'), plt.ylabel('Amplitude') plt.title('Frequency Spectrum of Square Wave');
sp_for_ds.ipynb
jedludlow/sp-for-ds
mit
Approximate 1 Hz Square Wave Let's sythesize an approximation to a square wave by summing a reduced number of sinusoidal components.
# Set frequency components and amplitudes. # Square waves contain all the odd harmonics # of the fundamental frequency. f_components = [1.0, 3.0, 5.0, 7.0, 9.0, 11.0] # f_components = [1.0, 3.0, 5.0, 7.0, 9.0, 11.0, # 13.0, 15.0, 17.0, 19.0, 21.0] amplitudes = [1.28 / f for f in f_components] # Generat...
sp_for_ds.ipynb
jedludlow/sp-for-ds
mit
Fourier Analysis of Approximate Square Wave
freq_spec, freq = fft_scaled(s_t, samp_freq=f_s) f_max = 12.0 plt.figure(figsize=(9, 5)), plt.plot(freq, np.abs(freq_spec)) plt.xticks(np.arange(0.0, f_max + 1.0, 1.0)) plt.xlim((0, f_max)), plt.xlabel('Frequency (Hz)'), plt.ylabel('Amplitude') plt.title('Frequency Spectrum of Approximate Square Wave');
sp_for_ds.ipynb
jedludlow/sp-for-ds
mit
Discrete-Time Sampling Nyquist-Shannon Sampling Theorem Consider a continuous signal $x(t)$ with Fourier transfom $X(f)$. Assume: A sampled version of the signal is constructed as $$x_k = x(kT), k \in \mathbb{I}$$ $x(t)$ is band-limited such that $$X(f) = 0 \ \forall \ |f| > B$$ <center><img src="images/Bandlimited...
def scale_and_fold(x): n = len(x) half_n = n // 2 # Scale by length of original signal x = (1.0 / n) * x[:half_n + 1] # Fold negative frequency x[1:] *= 2.0 return x def aliasing_demo(): f_c = 1000.0 # Hz f_s = 20.0 # Hz f_end = 25.0 # Hz f = 1.0 # Hz time_c = np.ar...
sp_for_ds.ipynb
jedludlow/sp-for-ds
mit
Avoiding Aliasing If you have control over the sampling process, specify a sampling frequency that is at least twice the highest frequency component of your signal. If you really want to preserve high fidelity, specify a sampling frequency that is ten times the highest frequency component in your signal. Digital Filter...
def butter_filt(x, sampling_freq_hz, corner_freq_hz=4.0, lowpass=True, filtfilt=False): """ Smooth data with a low-pass or high-pass filter. Apply a 2nd order Butterworth filter. Note that if filtfilt is True the applied filter is effectively a 4th order Butterworth. Parameters ---------- ...
sp_for_ds.ipynb
jedludlow/sp-for-ds
mit
Comparing surrogate models Tim Head, July 2016. Reformatted by Holger Nahrstaedt 2020 .. currentmodule:: skopt Bayesian optimization or sequential model-based optimization uses a surrogate model to model the expensive to evaluate function func. There are several choices for what kind of surrogate model to use. This not...
print(__doc__) import numpy as np np.random.seed(123) import matplotlib.pyplot as plt
0.7/notebooks/auto_examples/strategy-comparison.ipynb
scikit-optimize/scikit-optimize.github.io
bsd-3-clause
Toy model We will use the :class:benchmarks.branin function as toy model for the expensive function. In a real world application this function would be unknown and expensive to evaluate.
from skopt.benchmarks import branin as _branin def branin(x, noise_level=0.): return _branin(x) + noise_level * np.random.randn() from matplotlib.colors import LogNorm def plot_branin(): fig, ax = plt.subplots() x1_values = np.linspace(-5, 10, 100) x2_values = np.linspace(0, 15, 100) x_ax, y_ax...
0.7/notebooks/auto_examples/strategy-comparison.ipynb
scikit-optimize/scikit-optimize.github.io
bsd-3-clause
This shows the value of the two-dimensional branin function and the three minima. Objective The objective of this example is to find one of these minima in as few iterations as possible. One iteration is defined as one call to the :class:benchmarks.branin function. We will evaluate each model several times using a diff...
from functools import partial from skopt import gp_minimize, forest_minimize, dummy_minimize func = partial(branin, noise_level=2.0) bounds = [(-5.0, 10.0), (0.0, 15.0)] n_calls = 60 def run(minimizer, n_iter=5): return [minimizer(func, bounds, n_calls=n_calls, random_state=n) for n in range(n_iter)] ...
0.7/notebooks/auto_examples/strategy-comparison.ipynb
scikit-optimize/scikit-optimize.github.io
bsd-3-clause
Note that this can take a few minutes.
from skopt.plots import plot_convergence plot = plot_convergence(("dummy_minimize", dummy_res), ("gp_minimize", gp_res), ("forest_minimize('rf')", rf_res), ("forest_minimize('et)", et_res), true_minimum=0.397887, yscale="lo...
0.7/notebooks/auto_examples/strategy-comparison.ipynb
scikit-optimize/scikit-optimize.github.io
bsd-3-clause
Now, let’s import Marvin:
import marvin
docs/sphinx/jupyter/first-steps.ipynb
sdss/marvin
bsd-3-clause
Let's see what release we're using. Releases can be either MPLs (e.g. MPL-5) or DRs (e.g. DR13), however DRs are currently disabled in Marvin.
marvin.config.release
docs/sphinx/jupyter/first-steps.ipynb
sdss/marvin
bsd-3-clause
On intial import, Marvin will set the default data release to use the latest MPL available, currently MPL-6. You can change the version of MaNGA data using the Marvin Config.
from marvin import config config.setRelease('MPL-5') print('MPL:', config.release)
docs/sphinx/jupyter/first-steps.ipynb
sdss/marvin
bsd-3-clause
But let's work with MPL-6:
config.setRelease('MPL-6') # check designated version config.release
docs/sphinx/jupyter/first-steps.ipynb
sdss/marvin
bsd-3-clause
My First Cube Now let’s play with a Marvin Cube! Import the Marvin-Tools Cube class:
from marvin.tools.cube import Cube
docs/sphinx/jupyter/first-steps.ipynb
sdss/marvin
bsd-3-clause
Let's load a cube from a local file. Start by specifying the full path and name of the file, such as: /Users/Brian/Work/Manga/redux/v2_3_1/8485/stack/manga-8485-1901-LOGCUBE.fits.gz EDIT Next Cell
#----- EDIT THIS CELL -----# # filename = '/Users/Brian/Work/Manga/redux/v1_5_1/8485/stack/manga-8485-1901-LOGCUBE.fits.gz' filename = 'path/to/manga/cube/manga-8485-1901-LOGCUBE.fits.gz' filename = '/Users/andrews/manga/spectro/redux/v2_3_1/8485/stack/manga-8485-1901-LOGCUBE.fits.gz' filename = '/Users/Brian/Work/Ma...
docs/sphinx/jupyter/first-steps.ipynb
sdss/marvin
bsd-3-clause
Create a Cube object:
cc = Cube(filename=filename)
docs/sphinx/jupyter/first-steps.ipynb
sdss/marvin
bsd-3-clause
Now we have a Cube object:
print(cc)
docs/sphinx/jupyter/first-steps.ipynb
sdss/marvin
bsd-3-clause
How about we look at some meta-data
cc.ra, cc.dec, cc.header['SRVYMODE']
docs/sphinx/jupyter/first-steps.ipynb
sdss/marvin
bsd-3-clause
...and the quality and target bits
cc.target_flags cc.quality_flag
docs/sphinx/jupyter/first-steps.ipynb
sdss/marvin
bsd-3-clause
Get a Spaxel Cubes have several functions currently available: getSpaxel, getMaps, getAperture. Let's look at spaxels. We can retrieve spaxels from a cube easily via indexing. In this manner, spaxels are 0-indexed from the lower left corner. Let's get spaxel (x=10, y=10):
spax = cc[10,10] # print the spaxel to see the x,y coord from the lower left, and the coords relative to the cube center, x_cen/y_cen spax
docs/sphinx/jupyter/first-steps.ipynb
sdss/marvin
bsd-3-clause
Spaxels have a spectrum associated with it. It has the wavelengths and fluxes of each spectral channel: Alternatively grab a spaxel with getSpaxel. Use the xyorig keyword to set the coordinate origin point: 'lower' or 'center'. The default is "center"
# let's grab the central spaxel spax = cc.getSpaxel(x=0, y=0) spax spax.flux.wavelength spax.flux
docs/sphinx/jupyter/first-steps.ipynb
sdss/marvin
bsd-3-clause