markdown stringlengths 0 37k | code stringlengths 1 33.3k | path stringlengths 8 215 | repo_name stringlengths 6 77 | license stringclasses 15
values |
|---|---|---|---|---|
Strings can be written in different ways using escape characters and other symbols. | print("That is Alice's cat.")
print('Say hi to Bob\'s mother.') | AutomateTheBoringStuffWithPython/lesson19.ipynb | Vvkmnn/books | gpl-3.0 |
Many escape characters are available: | print('\'') # Single quote
print('\"') # Double quote
print('\t') # Tab
print('\n') # New line
print('\\') # Back slash | AutomateTheBoringStuffWithPython/lesson19.ipynb | Vvkmnn/books | gpl-3.0 |
Use r'' to print raw strings, where all characters are treated as strings. | print(r'That is Carol\'s cat.') | AutomateTheBoringStuffWithPython/lesson19.ipynb | Vvkmnn/books | gpl-3.0 |
Multi line strings (with '''' or """ are often easier.) | print("""Dear Alice,
Eve's cat has been arrested for catnapping, cat burglarly, and extortion.
Sincerly, Bob.""") | AutomateTheBoringStuffWithPython/lesson19.ipynb | Vvkmnn/books | gpl-3.0 |
Large strings are treated in this way. | import requests # get the Requests library
link = "https://automatetheboringstuff.com/files/rj.txt" # store the link where the file is at
rj = requests.get(link) # use Requests to get the link
print(rj.text) # Print out the text from Requests, and check that its stored | AutomateTheBoringStuffWithPython/lesson19.ipynb | Vvkmnn/books | gpl-3.0 |
Functions can now be run on it: | print(len(rj.text)) | AutomateTheBoringStuffWithPython/lesson19.ipynb | Vvkmnn/books | gpl-3.0 |
Strings can be treated like lists where each character is an elemant in that list. | hello = 'Hello World!'
print(hello[0])
print(hello[1:5])
print(hello[-1])
print('Hello' in hello)
print('x' in hello)
print('HELLO' in hello) | AutomateTheBoringStuffWithPython/lesson19.ipynb | Vvkmnn/books | gpl-3.0 |
confirm results from grouped rating approach (sample) | df_top_hops = df_ta_bar_reviews[df_ta_bar_reviews.bar=="Top_Hops"]
df_top_hops.head(15)
df_top_hops_grouped = pd.concat([df_top_hops[['first_of_month', 'rating']].groupby(['first_of_month']).mean(), \
df_top_hops[['first_of_month', 'rating']].groupby(['first_of_month']).count()], \
... | code/reseen/ta_reviews.ipynb | endlesspint8/endlesspint8.github.io | mit |
confirmed | m_weight = pd.Series( ( df_top_hops_grouped.index.max() - df_top_hops_grouped.index ) / ( np.timedelta64(1, 'M') ) ).apply(month_weight)
m_rating = df_top_hops_grouped.rating_mean.values * df_top_hops_grouped.rating_count.values
m_denom = np.sum( m_weight * df_top_hops_grouped.rating_count.values )
w_rating = np.sum(... | code/reseen/ta_reviews.ipynb | endlesspint8/endlesspint8.github.io | mit |
cycle through dates/index for moving weighted rating
(ignore missing months for time being) | moving_weighted_ratings = []
for row in range(df_top_hops_grouped.shape[0]):
m_weight = pd.Series((df_top_hops_grouped.iloc[row:].index.max() - df_top_hops_grouped.iloc[row:].index) / ( np.timedelta64(1, 'M') )).apply(month_weight)
m_rating = df_top_hops_grouped.iloc[row:]['rating_mean'].values * df_top_... | code/reseen/ta_reviews.ipynb | endlesspint8/endlesspint8.github.io | mit |
fill in missing months | df_top_hops_grouped = pd.concat([df_top_hops[['first_of_month', 'rating']].groupby(['first_of_month']).mean(), \
df_top_hops[['first_of_month', 'rating']].groupby(['first_of_month']).count()], \
axis=1)
df_top_hops_grouped.columns = ['rating_mean', 'rati... | code/reseen/ta_reviews.ipynb | endlesspint8/endlesspint8.github.io | mit |
let's run for all, merge and... | all_date_series = expand_dates(df_ta_bar_reviews, False, 'first_of_month')
df_all_dates = pd.DataFrame({'p_holder': np.zeros(len(all_date_series))}, index=all_date_series)
df_all_dates.sort_index(ascending=False, inplace=True)
df_all_dates.head()
df_bar_grouped = group_ratings_by_date(df_ta_bar_reviews[df_ta_bar_revi... | code/reseen/ta_reviews.ipynb | endlesspint8/endlesspint8.github.io | mit |
need to concat each bar on entire date range first and then work backwards in ratings, this will remove sudden zeroes in June | def bar_moving_weighted_ratings_macro_date_range(df, bar_field, bar_name, date_field, rating_field):
df_bar_grouped = group_ratings_by_date(df[df[bar_field] == bar_name], date_field, rating_field)
# change 1
df_macro_dates_grouped = group_ratings_by_date(df, date_field, rating_field)
# change 2
... | code/reseen/ta_reviews.ipynb | endlesspint8/endlesspint8.github.io | mit |
Loading data from a CSV
The Table is the basic class in agate. To create a table from a CSV we use the Table.from_csv class method: | exonerations = agate.Table.from_csv('examples/realdata/exonerations-20150828.csv') | tutorial.ipynb | onyxfish/journalism | mit |
With no other arguments specified, agate will automatically create an instance of TypeTester and use it to figure out the type of each column. TypeTester is a "best guess" approach to determining the kinds of data in your table. It can guess wrong. In that case you can create a TypeTester manually and use the force arg... | tester = agate.TypeTester(force={
'false_evidence': agate.Boolean()
})
exonerations = agate.Table.from_csv('examples/realdata/exonerations-20150828.csv', column_types=tester) | tutorial.ipynb | onyxfish/journalism | mit |
If you already know the types of your data you may wish to skip the TypeTester entirely. You may pass sequences of column names and column types to Table.from_csv as the column_names and column_types arguments, respectively.
For larger datasets the TypeTester can be slow to evaluate the data. In that case you can speci... | tester = agate.TypeTester(limit=100)
exonerations = agate.Table.from_csv('examples/realdata/exonerations-20150828.csv', column_types=tester) | tutorial.ipynb | onyxfish/journalism | mit |
The dataset we are using in this tutorial is simple enough that we can rely on the built-in TypeTester to guess quickly and accurately.
Note: agate's CSV reader and writer support unicode and other encodings for both Python 2 and Python 3. Try using them as a drop-in replacement for Python's builtin module: from agate ... | print(exonerations) | tutorial.ipynb | onyxfish/journalism | mit |
Navigating table data
agate goes to great pains to make accessing the data in your tables work seamlessly for a wide variety of use-cases. Access by both Column and Row is supported, via the Table.columns and Table.rows attributes respectively.
All four of these objects are examples of .MappedSequence, the foundational... | exonerations.columns['last_name']
exonerations.columns[0] | tutorial.ipynb | onyxfish/journalism | mit |
In the same way, rows can be accessed either by numeric index or by an optional, unique "row name" specified when the table is created. In this tutorial we won't use row names, but here is an example of how they work: | exonerations = agate.Table.from_csv('examples/realdata/exonerations-20150828.csv', row_names=lambda r: '%(last_name)s, %(first_name)s' % (r))
exonerations.rows[0]
exonerations.rows['Abbitt, Joseph Lamont'] | tutorial.ipynb | onyxfish/journalism | mit |
In this case we create our row names using a lambda function that takes a row and returns an unique identifer. If your data has a unique column, you can also just pass the column name. (For example, a column of USPS abbrevations or FIPS codes.) Note, however, that your row names can never be int, because that is reserv... | row = exonerations.rows[0]
row[0]
row['last_name'] | tutorial.ipynb | onyxfish/journalism | mit |
And the same goes for columns, which can be indexed numerically or by row name (if one has been setup): | column = exonerations.columns['crime']
column[0]
column['Abbitt, Joseph Lamont'] | tutorial.ipynb | onyxfish/journalism | mit |
For any instance of .MappedSequence, iteration returns values, in order. Here we print only the first ten: | for row in exonerations.rows[:10]:
print(row['last_name']) | tutorial.ipynb | onyxfish/journalism | mit |
To summarize, the four most common data structures in agate (Column, Row, Table.columns and Table.rows) are all instances of MappedSequence and therefore all behave in a uniform way. This is also true of TableSet, which will discuss later on.
Aggregating column data
With the basics out of the way, let's do some actual ... | exonerations.aggregate(agate.Count('false_confession', True)) | tutorial.ipynb | onyxfish/journalism | mit |
Let's look at another example, this time using a numerical aggregation.
Question: What was the median age of exonerated indviduals at time of arrest? | exonerations.aggregate(agate.Median('age')) | tutorial.ipynb | onyxfish/journalism | mit |
The answer to our question is "26 years old", however, as the warnings indicate, not every exonerated individual in the data has a value for the age column. The Median statistical operation has no standard way of accounting for null values, so it leaves them out of the calculation.
Question: How many individuals do not... | exonerations.aggregate(agate.Count('age', None)) | tutorial.ipynb | onyxfish/journalism | mit |
Only nine rows in this dataset don't have age, so it's certainly still useful to compute a median. However, we might still want to filter those rows out so we could have a consistent sample for all of our calculations. In the next section you'll learn how to do just that.
Different aggregations can be applied depending... | with_age = exonerations.where(lambda row: row['age'] is not None) | tutorial.ipynb | onyxfish/journalism | mit |
You'll notice we provide a lambda function to the Table.where. This function is applied to each row and if it returns True, then the row is included in the output table.
A crucial thing to understand about these table methods is that they return new tables. In our example above exonerations was a Table instance and we ... | len(exonerations.rows) - len(with_age.rows) | tutorial.ipynb | onyxfish/journalism | mit |
Nine rows were removed, which is the number of nulls we had already identified were in the column.
Now if we calculate the median age of these individuals, we don't see the warning anymore. | with_age.aggregate(agate.Median('age')) | tutorial.ipynb | onyxfish/journalism | mit |
Computing new columns
In addition to "column-wise" aggregations there are also "row-wise" computations. Computations go through a Table row-by-row and derive a new column using the existing data. To perform row computations in agate we use subclasses of Computation.
When one or more instances of Computation are applied... | with_years_in_prison = exonerations.compute([
('years_in_prison', agate.Change('convicted', 'exonerated'))
])
with_years_in_prison.aggregate(agate.Median('years_in_prison')) | tutorial.ipynb | onyxfish/journalism | mit |
The median number of years an exonerated individual spent in prison was 8 years.
Sometimes, the built-in computations, such as Change won't suffice. I mentioned before that you could perform arbitrary column-wise aggregations using Summary. You can do the same thing for row-wise computations using Formula. This is some... | full_names = exonerations.compute([
('full_name', agate.Formula(agate.Text(), lambda row: '%(first_name)s %(last_name)s' % row))
]) | tutorial.ipynb | onyxfish/journalism | mit |
For efficiency's sake, agate allows you to perform several computations at once (though their results can't depend on one another): | with_computations = exonerations.compute([
('full_name', agate.Formula(agate.Text(), lambda row: '%(first_name)s %(last_name)s' % row)),
('years_in_prison', agate.Change('convicted', 'exonerated'))
]) | tutorial.ipynb | onyxfish/journalism | mit |
You can also compute new columns to clean up your raw data. In the initial data, the state column has some values with a 'F-' prefix on the state abbreviation. Cases with that prefix are federal cases as opposed to state prosecutions. To make the data easier to use, we can create a new federal column to tag federal cas... | clean_state_data = exonerations.compute([
('federal', agate.Formula(agate.Boolean(), lambda row: row['state'].startswith('F-'))),
('state', agate.Formula(agate.Text(), lambda row: row['state'][2:] if row['state'].startswith('F-') else row['state']))
], replace=True) | tutorial.ipynb | onyxfish/journalism | mit |
We add the replace argument to our compute method to replace the state column in place.
If Formula is not flexible enough (for instance, if you needed to compute a new value based on the distribution of data in a column) you can always implement your own subclass of Computation. See the API documentation for [computati... | sorted_by_age = exonerations.order_by('age') | tutorial.ipynb | onyxfish/journalism | mit |
We can then use Table.limit get only the first ten rows of the data. | youngest_ten = sorted_by_age.limit(10) | tutorial.ipynb | onyxfish/journalism | mit |
Now let's use Table.print_table to help us pretty the results in a way we can easily review: | youngest_ten.print_table(max_columns=7) | tutorial.ipynb | onyxfish/journalism | mit |
If you find it impossible to believe that an eleven year-old was convicted of murder, I encourage you to read the Registry's description of the case.
Note: In the previous example we could have omitted the Table.limit and passed a max_rows=10 to Table.print_table instead. In this case they accomplish exactly the same ... | binned_ages = exonerations.bins('age', 10, 0, 100)
binned_ages.print_bars('age', 'Count', width=80) | tutorial.ipynb | onyxfish/journalism | mit |
Notice that we specify we want :code:10 bins spanning the range :code:0 to :code:100. If these values are omitted agate will attempt to infer good defaults. We also specify that we want our bar chart to span a width of :code:80 characters. This can be adjusted to a suitable width for your terminal or document.
Note: If... | by_state = clean_state_data.group_by('state') | tutorial.ipynb | onyxfish/journalism | mit |
This takes our original Table and groups it into a TableSet, which contains one table per state. As mentioned much earlier in this tutorial, TableSets are instances of MappedSequence. That means they work very much like Column and Row.
Now we need to aggregate the total for each state. This works in a very similar way ... | state_totals = by_state.aggregate([
('count', agate.Count())
])
sorted_totals = state_totals.order_by('count', reverse=True)
sorted_totals.print_table(max_rows=5) | tutorial.ipynb | onyxfish/journalism | mit |
You'll notice we pass a sequence of tuples to TableSet.aggregate. Each one includes two elements. The first is the new column name being created. The second is an instance of some Aggregation. Unsurpringly, in this case the results appear to be roughly proportional to population.
Question: What state has the longest me... | with_years_in_prison = exonerations.compute([
('years_in_prison', agate.Change('convicted', 'exonerated'))
])
state_totals = with_years_in_prison.group_by('state')
medians = state_totals.aggregate([
('count', agate.Count()),
('median_years_in_prison', agate.Median('years_in_prison'))
])
sorted_medians = ... | tutorial.ipynb | onyxfish/journalism | mit |
DC? Nebraska? What accounts for these states having the longest times in prison before exoneration? I have no idea! Given that the group sizes are small, it would probably be wise to look for outliers.
As with Table.aggregatehttps://agate.readthedocs.io/en/latest/api/table.html#agate.Table.aggregate and Table.compute, ... | # Filters rows without age data
only_with_age = with_years_in_prison.where(
lambda r: r['age'] is not None
)
# Group by race
race_groups = only_with_age.group_by('race')
# Sub-group by age cohorts (20s, 30s, etc.)
race_and_age_groups = race_groups.group_by(
lambda r: '%i0s' % (r['age'] // 10),
key_name='a... | tutorial.ipynb | onyxfish/journalism | mit |
Exploratory charting
Beginning with version 1.5.0, agate includes the pure-Python SVG charting library leather. Leather allows you to generate "good enough" charts with as little as one line of code. It's especially useful if you're working in a Jupyter Notebook, as the results will render inline.
There are currently f... | sorted_totals.bar_chart('state', 'count', height=1000) | tutorial.ipynb | onyxfish/journalism | mit |
Leather will try to maintain a reasonable aspect ratio for chart. In this case the chart is too short to display correctly. We've used the height argument to make the chart a little taller.
Exonerations by age bracket
When creating a chart you may omit the column name arguments. If you do so the first and second column... | binned_ages.bar_chart() | tutorial.ipynb | onyxfish/journalism | mit |
Exonerations by year | by_year_exonerated = exonerations.group_by('exonerated')
counts = by_year_exonerated.aggregate([
('count', agate.Count())
])
counts.order_by('exonerated').line_chart('exonerated', 'count') | tutorial.ipynb | onyxfish/journalism | mit |
Exonerations over time, for most commonly exonerated crimes
The real power of agate's exploratory charting comes when we want to compare different facets of data. With leather, agate can automatically render a of chart for each group in a TableSet. | # Filter to crimes with at least 100 exonerations
top_crimes = exonerations.group_by('crime').having([
('count', agate.Count())
], lambda t: t['count'] > 100)
# Group by year of exoneration
by_year = top_crimes.group_by('exonerated')
# Count number of exonerations in each year
counts = by_year.aggregate([
('c... | tutorial.ipynb | onyxfish/journalism | mit |
Styling charts
As mentioned above, leather is designed for making "good enough" charts. You are never going to create a polished chart. However, sometimes you may want more control than agate offers through it's own methods. You can take more control over how your charts are presented by using leather directly. | import leather
chart = leather.Chart('Total exonerations by state')
chart.add_y_axis(name='State')
chart.add_x_axis(name='Number of exonerations')
chart.add_bars(sorted_totals, x='count', y='state')
chart.to_svg(height=1000) | tutorial.ipynb | onyxfish/journalism | mit |
Language Model Downloading
Download BERT | bert_model = languagemodels.BERTModel() | videoretrieval/Demo notebook BERT.ipynb | googleinterns/via-content-understanding | apache-2.0 |
Encoding Generation
Generate Encodings for MSR-VTT | train.language_model.generate_and_cache_encodings(
bert_model, datasets.msrvtt_dataset) | videoretrieval/Demo notebook BERT.ipynb | googleinterns/via-content-understanding | apache-2.0 |
Training
Build Train Datasets
Initialize Models
Compile Encoders
Fit Model
Test Model
Datasets Generation | experts_used = [
experts.i3d,
experts.r2p1d,
experts.resnext,
experts.senet,
experts.speech_expert,
experts.ocr_expert,
experts.audio_expert,
experts.densenet,
experts.face_expert]
train_ds, valid_ds, test_ds = (
train.encoder_datasets.generate_language_model_fine_tuning_datasets(
bert_mo... | videoretrieval/Demo notebook BERT.ipynb | googleinterns/via-content-understanding | apache-2.0 |
Model Initialization | class MishLayer(tf.keras.layers.Layer):
def call(self, inputs):
return mish(inputs)
mish(tf.Variable([1.0]))
text_encoder = models.components.TextEncoder(
len(experts_used),
num_netvlad_clusters=28,
ghost_clusters=1,
language_model_dimensionality=768,
encoded_expert_dimensionality=512,... | videoretrieval/Demo notebook BERT.ipynb | googleinterns/via-content-understanding | apache-2.0 |
Encoder Compliation | def build_optimizer(lr=0.001):
learning_rate_scheduler = tf.keras.optimizers.schedules.ExponentialDecay(
initial_learning_rate=lr,
decay_steps=1000,
decay_rate=0.95,
staircase=True)
return tf.keras.optimizers.Adam(learning_rate_scheduler)
encoder.compile(build_optimizer(5e-5), ... | videoretrieval/Demo notebook BERT.ipynb | googleinterns/via-content-understanding | apache-2.0 |
Model fitting | encoder.fit(
train_ds_prepared,
#validation_data=valid_ds_prepared,
epochs=250,
) | videoretrieval/Demo notebook BERT.ipynb | googleinterns/via-content-understanding | apache-2.0 |
2. Load each array of Ps and Ts | import numpy as np
Ps = np.zeros(Nfiles, dtype=np.ndarray)
Ts = np.zeros(Nfiles, dtype=np.ndarray)
for n in range(Nfiles):
Ps[n] = np.load('C:/gh/data/example/lfp_set_PsTs/' + str(n) + '/out/Ps_data.npy')
Ts[n] = np.load('C:/gh/data/example/lfp_set_PsTs/' + str(n) + '/out/Ts_data.npy') | demo_OSG_python/demo_osg_python - plot output from OSG.ipynb | srcole/qwm | mit |
3. Load signals | lfps = np.zeros(Nfiles, dtype=np.ndarray)
for n in range(Nfiles):
if n == 0:
lfps[n] = np.load('C:/gh/data/example/lfp_set/' + str(10) + '.npy')
else:
lfps[n] = np.load('C:/gh/data/example/lfp_set/' + str(n) + '.npy') | demo_OSG_python/demo_osg_python - plot output from OSG.ipynb | srcole/qwm | mit |
4. Plot peaks and troughs on top of signals | import matplotlib.pyplot as plt
%matplotlib inline
plt.figure(figsize=(10,10))
for n in range(Nfiles):
plt.subplot(Nfiles, 1, n+1)
plt.plot(lfps[n], 'k')
plt.plot(Ps[n], lfps[n][Ps[n]], 'bo')
plt.plot(Ts[n], lfps[n][Ts[n]], 'ro')
if n == Nfiles-1:
plt.xlabel('Time (ms)')
else:
p... | demo_OSG_python/demo_osg_python - plot output from OSG.ipynb | srcole/qwm | mit |
Use a set of standard plots
A graphical representation can always be on hand | trace = Trace(platform, boost15_trace,
["sched_switch",
"sched_overutilized",
"sched_load_avg_cpu",
"sched_load_avg_task",
"sched_boost_cpu",
"sched_boost_task",
"cpu_frequency",
"cpu_capacity",
... | ipynb/tutorial/UseCaseExamples_SchedTuneAnalysis.ipynb | arnoldlu/lisa | apache-2.0 |
set the stage for data visualization | plt.interactive(False)
sns.set(style="whitegrid",color_codes=True) | scripts/general/Taarifa_Regression.ipynb | duttashi/Data-Analysis-Visualization | mit |
Load the dataset and make a copy of it | # Reading the data where low_memory=False increases the program efficiency
data= pd.read_csv("data-taarifa.csv", low_memory=False)
sub1=data.copy() | scripts/general/Taarifa_Regression.ipynb | duttashi/Data-Analysis-Visualization | mit |
List all the variables in the dataset | list(sub1.columns.values) | scripts/general/Taarifa_Regression.ipynb | duttashi/Data-Analysis-Visualization | mit |
Data standardisation- Lowercase all the variable names | #lowercase all variables
sub1.columns = [x.lower() for x in sub1.columns] | scripts/general/Taarifa_Regression.ipynb | duttashi/Data-Analysis-Visualization | mit |
A quick peek at the dataset | sub1.head(5) | scripts/general/Taarifa_Regression.ipynb | duttashi/Data-Analysis-Visualization | mit |
Problem challenge # 1
Missing value treatment
A majority of the variables in this dataset are categorical. Therefore, I treat the missing values to the mode (replacement of missing values by most frequently occuring values) | ## To fill every column with its own most frequent value you can use
sub1 = sub1.apply(lambda x:x.fillna(x.value_counts().index[0])) | scripts/general/Taarifa_Regression.ipynb | duttashi/Data-Analysis-Visualization | mit |
Problem challenge # 2
Using one hot encoding to convert categorical variables of interest to dummy continuous numbers
For reference see this Kaggle post by Mark, https://www.kaggle.com/c/titanic/forums/t/5379/handling-categorical-data-with-sklearn | from sklearn import preprocessing
le_enc = preprocessing.LabelEncoder()
#to convert into numbers
sub1.permit = le_enc.fit_transform(sub1.permit)
sub1.extraction_type_class=le_enc.fit_transform(sub1.extraction_type_class)
sub1.payment_type=le_enc.fit_transform(sub1.payment_type)
sub1.quality_group=le_enc.fit_transform(s... | scripts/general/Taarifa_Regression.ipynb | duttashi/Data-Analysis-Visualization | mit |
Another quick peek at the dataset. Notice, variables of interest like 'permit', 'extraction_type', 'payment_type', 'quality_group' have now been assigned dummy codes as required | sub1.head(5) | scripts/general/Taarifa_Regression.ipynb | duttashi/Data-Analysis-Visualization | mit |
explanatory variable is also known as the 'Independent variable' and response variable is also known as the 'dependent variable'
Variables of interest for this study are;
status_group,extraction_type_class,payment_type,quality_group,quantity_group,waterpoint_type_group,source_class,permit,water_quality
Correlational An... | print ("OLS regresssion model for the association between water pump condition status and quality of water in it")
reg1=smf.ols('status_group~permit',data=sub1).fit()
print (reg1.summary()) | scripts/general/Taarifa_Regression.ipynb | duttashi/Data-Analysis-Visualization | mit |
Status group is the response or dependent variable and permit is the independent variable.
The number of observations show the no. of observations that had valid data and thus were included in the analysis.
The F-statistic is 66.57 and the p value is very small (Prob (F-statistic))= 3.44e-16 considerably less than our... | # Now, I continue to add the variables to this model to check for any loss of significance
print ("OLS regresssion model for the association between status_group and other variables of interest")
reg1=smf.ols('status_group~quantity_group+extraction_type_class+waterpoint_type_group',data=sub1).fit()
print (reg1.summary(... | scripts/general/Taarifa_Regression.ipynb | duttashi/Data-Analysis-Visualization | mit |
Learn a projection using SEF
First, we have to create a linear SEF object. Note that we have to supply the number of input dimensions, as well as the target dimensionality. We can also specify the learning rate and the regularizer weight in the class constructor (usually the default values work just fine). | import sef_dr
linear_sef = sef_dr.LinearSEF(input_dimensionality=x_train.shape[1], output_dimensionality=9)
# Move the model to GPU (comment this out, if a cuda-enabled GPU is not availabe)
linear_sef.cuda() | tutorials/Supervised DR.ipynb | passalis/sef | mit |
Then, we fit the projection. We have to supply the type of the target similarity matrix (or a function that creates the target similarity matrix on-the-fly). | loss = linear_sef.fit(data=x_train[:5000], target_labels=y_train[:5000], target='supervised', epochs=100, regularizer_weight=0.001, learning_rate=0.0001, batch_size=128,) | tutorials/Supervised DR.ipynb | passalis/sef | mit |
Let's examine the loss function: | import matplotlib
import matplotlib.pyplot as plt
%matplotlib inline
plt.plot(np.arange(loss.shape[0]), loss)
plt.title('Loss during optimization')
plt.show() | tutorials/Supervised DR.ipynb | passalis/sef | mit |
The loss is practically the same after the 20th iteration, so a solution has been found. Let's evaluate it!
First, transform the data: | # Tranform the data
train_data = linear_sef.transform(x_train)
test_data = linear_sef.transform(x_test) | tutorials/Supervised DR.ipynb | passalis/sef | mit |
Then, use an SVM to evaluate the solution: | from sklearn import svm
from sklearn.grid_search import GridSearchCV
from sklearn.neighbors import NearestCentroid
from sklearn.preprocessing import MinMaxScaler
# Scale the data
scaler = MinMaxScaler()
train_data = scaler.fit_transform(train_data)
test_data = scaler.transform(test_data)
parameters = {'kernel': [... | tutorials/Supervised DR.ipynb | passalis/sef | mit |
Compare to LDA
The solution seems good enough, but let's compare it to the regular LDA method! | from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
# Fit the LDA projection
lda = LinearDiscriminantAnalysis(n_components=9)
lda.fit(x_train[:5000, :], y_train[:5000])
# Tranform the data
train_data = lda.transform(x_train)
test_data = lda.transform(x_test)
# Scale the data
scaler = MinMaxScaler()
... | tutorials/Supervised DR.ipynb | passalis/sef | mit |
You should see about a 27% increase in speed.
In the interest of transperency, if you change the target to parallel instead of cuda, the compiler will target the multi-core CPU availalbe on this instance and you will get similar performance to what you just got on the GPU. The reason for this is we're only porting a... | from mymandel import *
numIters = 20
# Run the GPU Version first
gimage = np.zeros((1024, 1536), dtype = np.uint8)
blockdim = (32, 8)
griddim = (32, 16)
with mytimer('Mandelbrot created on GPU'):
create_fractal_gpu[griddim, blockdim](-2.0, 1.0, -1.0, 1.0, gimage, numIters)
cuda.synchronize
imshow(gimage)
sho... | notes/nvidia_quicklabs/gpu_computing/Accelerated Computing.ipynb | rahul1990gupta/awesome-self-driving-car-resources | mit |
You should see around a 9x speed increase when moving from the GPU to the CPU when using the original parameters.
If you are interested in seeing the rest of the code used in the above example, please execute the next cell. This is not a requirement for the lab, but you may find it insightful after you perform the nex... | %load mymandel.py | notes/nvidia_quicklabs/gpu_computing/Accelerated Computing.ipynb | rahul1990gupta/awesome-self-driving-car-resources | mit |
Task 5 - Hello World
For this task, you get to try your hand and writing some CUDA Python code. We are going to be using the following concepts:
<code style="color:green">@cuda.autojit</code> - this decorator is used to tell the CUDA compiler that the function is to be compiled for the GPU. With autojit, the compile... | from numba import *
import numpy as np
@cuda.jit
def hello(data):
data[ , ] =
numBlocks = 1
threadsPerBlock = 5
data = np.ones((numBlocks, threadsPerBlock), dtype=np.uint8)
hello[numBlocks,threadsPerBlock](data)
print data | notes/nvidia_quicklabs/gpu_computing/Accelerated Computing.ipynb | rahul1990gupta/awesome-self-driving-car-resources | mit |
Vertex client library: AutoML tabular classification model for online prediction
<table align="left">
<td>
<a href="https://colab.research.google.com/github/GoogleCloudPlatform/vertex-ai-samples/blob/master/notebooks/community/gapic/automl/showcase_automl_tabular_classification_online.ipynb">
<img src="http... | import os
import sys
# Google Cloud Notebook
if os.path.exists("/opt/deeplearning/metadata/env_version"):
USER_FLAG = "--user"
else:
USER_FLAG = ""
! pip3 install -U google-cloud-aiplatform $USER_FLAG | notebooks/community/gapic/automl/showcase_automl_tabular_classification_online.ipynb | GoogleCloudPlatform/vertex-ai-samples | apache-2.0 |
Make a online prediction request
Now do a online prediction to your deployed model.
Make test item
You will use synthetic data as a test data item. Don't be concerned that we are using synthetic data -- we just want to demonstrate how to make a prediction. | INSTANCE = {
"petal_length": "1.4",
"petal_width": "1.3",
"sepal_length": "5.1",
"sepal_width": "2.8",
} | notebooks/community/gapic/automl/showcase_automl_tabular_classification_online.ipynb | GoogleCloudPlatform/vertex-ai-samples | apache-2.0 |
Section 1
In this section we'll cover:
Using Jax
Computing derivatives with Jax
Gradient Descent (single variable)
Newton's Method (single variable)
Jax
Autodiff cookbook
Jax is a python library that provides the ability to differentiate many python
functions. | import jax
import jax.numpy as jnp
from jax import jit, grad, vmap, api, random, jacfwd, jacrev
from jax.experimental import optimizers, stax | colabs/Multivariate Calculus for ML, 1 of 2.ipynb | google/physics-math-tutorials | apache-2.0 |
Basic autodiff example
Let's take the derivative of $y = f(x) = x^2$, which we know to be $f'(x) = 2x$. | def square(x):
return x * x
# Compute the derivative with grad from Jax
dsquare = grad(square)
# Plot the function and the derivative
domain = np.arange(0, 2.5, 0.1)
plt.plot(domain, square(domain), label="$y=x^2$")
plt.plot(domain, list(map(dsquare, domain)), label="$y'=\\frac{dy}{dx} = 2x$")
# Note can also use J... | colabs/Multivariate Calculus for ML, 1 of 2.ipynb | google/physics-math-tutorials | apache-2.0 |
Exercise
Write a function to compute the sigmoid
$$f(x) = \frac{1}{1 + e^{-x}}$$
using jnp.exp to compute $e^x$ -- need to use the Jax version of
numpy for autodiff to work.
Then verify that
$$ f'(x) = f(x) (1 - f(x))$$
For example, compare some explicit values and plot the differences between the derivative and $f(x) ... | ## Your code here
# Compute the sigmoid
def sigmoid(x):
pass
# Compute the derivative (using grad)
# Compare derivative values to f(x) * (1 - f(x))
# @title Solution (double-click to show)
# Compute the sigmoid
def sigmoid(x):
return 1. / (1. + jnp.exp(-x))
# Compute the derivative (using grad)
deriv = grad(... | colabs/Multivariate Calculus for ML, 1 of 2.ipynb | google/physics-math-tutorials | apache-2.0 |
Single variable gradient descent examples
In this example we solve $x^2=x$, which we know has two solutions. Different
initial starting points yield convergence to different solutions, or
non-convergence to either solution at $x_0 = 1/2$.
We need to turn the problem into one of finding local extrema. So we consider
the... | def f(x):
return (x**2 - x)**2
xs = np.arange(-1, 2.05, 0.05)
ys = f(xs)
plt.plot(xs, ys)
plt.show() | colabs/Multivariate Calculus for ML, 1 of 2.ipynb | google/physics-math-tutorials | apache-2.0 |
Let's define a function to compute iterations of gradient descent.
$$\begin{eqnarray}
x_{n+1} &=& x_n - \alpha f'(x_n) \
\end{eqnarray}$$ | def gradient_descent(dfunc, x0, iterations=100, alpha=0.1):
"""dfunc is the derivative of the function on which we
perform descent."""
xs = [x0]
for i in range(iterations):
x = xs[-1]
x = x - alpha * dfunc(float(x))
xs.append(x)
return xs
# Let's try it on our function f now.
# Compute the deriv... | colabs/Multivariate Calculus for ML, 1 of 2.ipynb | google/physics-math-tutorials | apache-2.0 |
Check your understanding: Explain what happened with each of the four curves in the plot.
Exercise: What happens if we decrease the learning rate $\alpha$?
Recreate the plot above using $\alpha=0.1$ instead. | ## Your code here
| colabs/Multivariate Calculus for ML, 1 of 2.ipynb | google/physics-math-tutorials | apache-2.0 |
Example 2
In this example we use gradient descent to approximate $\sqrt{3}$. We use
the function $f(x) = \left(x^2 - 3\right)^2$ and construct a sequence converging
to the positive solution. In this case notice the impact of the learning rate
both on the time to convergence and whether the convergence is monotonic or
o... | def f2(x):
return (x*x - 3)**2
df = grad(f2)
x0 = 2
for alpha in [0.08, 0.01]:
xs = gradient_descent(df, x0, iterations=40, alpha=alpha)
plt.plot(range(len(xs)), xs, label="$\\alpha = {}$".format(alpha))
plt.xlabel("iterations")
# Plot the correct value
sqrt3 = math.pow(3, 0.5)
n = len(xs)
plt.plot(range(n), [... | colabs/Multivariate Calculus for ML, 1 of 2.ipynb | google/physics-math-tutorials | apache-2.0 |
Exercise
Solve the equation $x = e^{-x}$, which does not have an easily obtainable solution algebraically.
The solution is approximately $x = 0.567$. Again note the impact of
the learning rate.
Use jnp.exp for the exponential function. | def f3(x):
"""Define the function f(x) = (x - e^(-x))^2."""
## Your code here
pass
# Compute the gradient
# Initial guess
x0 = 0.4
## Add code here for gradient descent using the functions above
## Plot the gradient descent values
#@title Solution (double click to expand)
def f3(x):
"""Define the functio... | colabs/Multivariate Calculus for ML, 1 of 2.ipynb | google/physics-math-tutorials | apache-2.0 |
Newton's method, single variable
We can use Newton's
method to find zeros of functions. Since local extrema occur at zeros of
the derivative, we can apply Newton's method to the first derivative to obtain
a second-order alternative to gradient descent.
$$\begin{eqnarray}
x_{n+1} &=& x_n - \alpha \frac{f'(x_n)}{f''(x_n)... | def newtons_method(func, x0, iterations=100, alpha=1.):
dfunc = grad(func)
xs = [x0]
for i in range(iterations):
x = xs[-1]
x = x - alpha * func(x) / dfunc(float(x))
xs.append(x)
return xs | colabs/Multivariate Calculus for ML, 1 of 2.ipynb | google/physics-math-tutorials | apache-2.0 |
Let's repeat the example of finding the value of $\sqrt{3}$ with Newton's method and compare to gradient descent.
For small $\alpha$, gradient descent seems to perform better: | def f(x):
return (x**2 - 3)**2
# Let's make a function we can reuse
def compare_gradient_newton(func, x0, alpha=0.01, iterations=50):
# Compute the first and second derivatives
df = grad(func)
# Compute Newton's method iterations
xs = newtons_method(df, x0, alpha=alpha, iterations=iterations)
# Compute g... | colabs/Multivariate Calculus for ML, 1 of 2.ipynb | google/physics-math-tutorials | apache-2.0 |
But for larger $\alpha$, Newton's method is better behaved and gradient descent fails to converge. | compare_gradient_newton(f, 2., alpha=0.1, iterations=50) | colabs/Multivariate Calculus for ML, 1 of 2.ipynb | google/physics-math-tutorials | apache-2.0 |
In this case we can also apply Newton's method with just the first derivative to find a zero of $x^2 - 3$, i.e. we don't have to look for a minimum of
$(x^2 - 3)^2$ since Newton's method can also find zeros of functions. | def f(x):
return x**2 - 3
xs = newtons_method(f, 2., alpha=0.5, iterations=10)
plt.plot(range(len(xs)), xs, label="$\\alpha = {}$".format(alpha))
plt.xlabel("iterations")
# Plot the solution
sqrt3 = math.pow(3, 0.5)
n = len(xs)
plt.plot(range(n), [sqrt3]*n, label="$\\sqrt{3}$", linestyle="--")
print(xs[-1]) | colabs/Multivariate Calculus for ML, 1 of 2.ipynb | google/physics-math-tutorials | apache-2.0 |
Section 2
Now we'll look at multivariate derivatives and gradient descent,
again using Jax.
Multivariate derivatives
$$f(x, y) = x y^2$$
$$ \nabla f = [y^2, 2 x y]$$ | def f(x, y):
return x * y * y
# Compute the partial derivatives with grad from Jax
# Use float as arguments, else Jax will complain
print("f(3, 1)=", f(3., 1.))
# argnums allows us to specify which variable to take the derivative of, positionally
print("Partial x derivative at (3, 1):", grad(f, argnums=0)(3., 1.))
... | colabs/Multivariate Calculus for ML, 1 of 2.ipynb | google/physics-math-tutorials | apache-2.0 |
We can plot some of the vectors of a gradient. Let's consider
$$f(x, y) = x^2 + y^2$$
The partial derivatives are
$$\frac{\partial f}{\partial x} = 2x$$
$$\frac{\partial f}{\partial y} = 2y$$
So the gradient is $$\nabla f = [2x, 2y]^T$$ | def f(x, y):
return x * x + y * y
partial_x = grad(f, argnums=0)
partial_y = grad(f, argnums=1)
xs = np.arange(-1, 1.25, 0.25)
ys = np.arange(-1, 1.25, 0.25)
plt.clf()
# Compute and plot the gradient vectors
for x in xs:
for y in ys:
u = partial_x(x, y)
v = partial_y(x, y)
plt.arrow(x, y, u, v, leng... | colabs/Multivariate Calculus for ML, 1 of 2.ipynb | google/physics-math-tutorials | apache-2.0 |
Jacobians and Hessians with Jax
Let's verify some of the example from the slides.
Let $f(x) = \sum_i{x_i} = x_1 + \cdots + x_n$. Then the gradient is $\nabla f (x) = [1, \ldots, 1]^T.$ | n = 4
def f(x):
return sum(x)
test_point = [1., 2., 3., 4.]
print("x = ", test_point)
print("Gradient(x):", [float(x) for x in grad(f)(test_point)])
## Try other test points, even random ones:
test_point = np.random.rand(4)
print()
print("x = ", test_point)
print("Gradient(x):", [float(x) for x in grad(f)(test_poi... | colabs/Multivariate Calculus for ML, 1 of 2.ipynb | google/physics-math-tutorials | apache-2.0 |
Exercise
Compute the gradient of the function that sums the squares of the elements of a vector. | # @title Solution (double click to show)
def sum_squares(x):
return jnp.dot(x, x)
test_point = np.array([1., 2., 3., 4.])
print("x = ", test_point)
print("Gradient(x):", [float(x) for x in grad(sum_squares)(test_point)]) | colabs/Multivariate Calculus for ML, 1 of 2.ipynb | google/physics-math-tutorials | apache-2.0 |
Let's try a Jacobian now. In the slides we saw that Jacobian of $f(\mathbf{x}) = Ax$ is $A$. Let's verify with Jax. | A = np.array([[1., 2.], [3., 4.]])
def f(x):
return jnp.dot(A, x)
x = np.array([1., 1.])
jacfwd(f)(x)
# Try some other matrices A and a 3x3 matrix
# Note that Jax handles larger matrices with the same code
# But you'll need a length 3 vector for x
| colabs/Multivariate Calculus for ML, 1 of 2.ipynb | google/physics-math-tutorials | apache-2.0 |
We can compute the Hessian by taking the Jacobian twice. In this case, $f(\mathbf{x}) = Ax$ is a linear function, so the second derivatives should all be zero. | A = np.array([[1., 2.], [3., 4.]])
def f(x):
return jnp.dot(A, x)
def hessian(f):
return jacfwd(jacrev(f))
x = np.array([1., 1.])
hessian(f)(x)
# Try some other matrices A and a 3x3 matrix
| colabs/Multivariate Calculus for ML, 1 of 2.ipynb | google/physics-math-tutorials | apache-2.0 |
Exercise
Now try to take derivatives of the function $f(\mathbf{x}) = x \cdot A x$. Hints:
* Is it scalar or vector-valued?
* Does it matter if $A$ is symmetric $(A = A^T)$ or anti-symmetric $(A = -A^T)$? | # Your code here
def f(x):
"""Compute x . A x"""
pass
# Compute the first and second derivatives at a test point x
#@title Solution (double-click to show)
A = np.array([[1., 0.], [0., 3.]])
def f(x):
return jnp.dot(x, jnp.dot(A, x))
x = np.array([2., -1.])
print(grad(f)(x))
print(hessian(f)(x)) | colabs/Multivariate Calculus for ML, 1 of 2.ipynb | google/physics-math-tutorials | apache-2.0 |
Exercise: Entropy
Compute the Gradient and Hessian of the Shannon entropy:
$$S = -\sum_{i}{x_i \log x_i}$$
Note that for a test point you'll need to have all the elements positive and summing to 1, so a good choice is $$[1 / n, \ldots, 1 / n]$$ | ## Your code here
def entropy(x):
pass
#@title Solution (double-click to show)
def entropy(x):
return - sum(a * jnp.log(a) for a in x)
x = np.array([1./2, 1./2])
print(entropy(x))
print(grad(entropy)(x))
print(hessian(entropy)(x)) | colabs/Multivariate Calculus for ML, 1 of 2.ipynb | google/physics-math-tutorials | apache-2.0 |
Example: Linear Regression with Jax
Given some data of the form $(x_i, y_i)$, let's find a best fit line $$ y = m x + b $$ by minimizing the sum of squared errors.
$$ S = \sum_{i}{\left(y_i - (m x_i + b) \right)^2}$$ | ## Adapted from JAX docs: https://coax.readthedocs.io/en/latest/examples/linear_regression/jax.html
# Generate some data using sklearn
X, y = make_regression(n_features=1, noise=10)
X, X_test, y, y_test = train_test_split(X, y)
# Plot the data
plt.scatter([x[0] for x in X], y)
plt.title("Randomly generated dataset")
... | colabs/Multivariate Calculus for ML, 1 of 2.ipynb | google/physics-math-tutorials | apache-2.0 |
Read through the following code, which minimizes the sum of squared errors for a linear model. | # In JAX, we can specify our parameters as various kinds of Python objects,
# including dictionaries.
# Initial model parameters
params = {
'w': jnp.zeros(X.shape[1:]),
'b': 0.
}
# The model function itself, a linear function.
def forward(params, X):
"""y = w x + b"""
return jnp.dot(X, params['w']) + para... | colabs/Multivariate Calculus for ML, 1 of 2.ipynb | google/physics-math-tutorials | apache-2.0 |
We can easily use another loss function, like the mean absolute error, where use the absolute value of residuals instead of the square, which reduces the
impact of outliers.
$$ S = \sum_{i}{\left|y_i - (m x_i + b) \right|}$$
This will give us a different best fit line for some data sets. | ## Minimize MAE instead of SSE
# MAE is the p=1 case of this function.
def lp_norm(p=2):
def norm(params, X, y):
err = forward(params, X) - y
return jnp.linalg.norm(err, ord=p)
return norm
# Generate some noisier data
X, y = make_regression(n_features=1, noise=100, bias=5)
X, X_test, y, y_test = train_tes... | colabs/Multivariate Calculus for ML, 1 of 2.ipynb | google/physics-math-tutorials | apache-2.0 |
Vi bruker her oversikten over lusetellinger fra fiskehelse.no/ Mattilsynet igjen | df = pd.read_excel('data/fiskehelse_2017-10-27-lakselus_per_fisk.xlsx') | notebooks/02 Vasking av data.ipynb | BergensTidende/dataskup-2017-notebooks | mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.