markdown stringlengths 0 37k | code stringlengths 1 33.3k | path stringlengths 8 215 | repo_name stringlengths 6 77 | license stringclasses 15
values |
|---|---|---|---|---|
Convert numpy.datetime64 objects (which are the indices of our DataFrame) to matplotlib floating point numbers. These numbers represent the number of days (fraction part represents hours, minutes, seconds) since 0001-01-01 00:00:00 UTC (assuming Gregorian calendar). | # mdt = mdates.date2num(df.index.astype(pd.datetime)) | Day_2/17-Pandas-Intro.ipynb | ueapy/enveast_python_course_materials | mit |
Append the new data to the original DataFrame: | # df['mpl_date'] = mdt | Day_2/17-Pandas-Intro.ipynb | ueapy/enveast_python_course_materials | mit |
Create a scatter plot | # ax = df.plot(kind='scatter', x='OLR', y='SOI', c='mpl_date',
# colormap='viridis', colorbar=False, edgecolors='none')
# plt.colorbar(ax.collections[0], ticks=mdates.YearLocator(5),
# format=mdates.DateFormatter('%Y')) | Day_2/17-Pandas-Intro.ipynb | ueapy/enveast_python_course_materials | mit |
Exercise: rolling functions
1. Subset data
Start by subsetting the SOI DataFrame
Use either numerical indices, or, even better, datetime indices | # your code here | Day_2/17-Pandas-Intro.ipynb | ueapy/enveast_python_course_materials | mit |
2. Plot the subset data
You can create figure and axis using matplotlib.pyplot
Or just use the plot() method of pandas DataFrame | # your code here | Day_2/17-Pandas-Intro.ipynb | ueapy/enveast_python_course_materials | mit |
3. Explore what rolling() method is
What does this method return? | # df.rolling?
# your code here | Day_2/17-Pandas-Intro.ipynb | ueapy/enveast_python_course_materials | mit |
4. Plot the original series and the smoothed series | # your code here | Day_2/17-Pandas-Intro.ipynb | ueapy/enveast_python_course_materials | mit |
EXERCISE
Three Variables Exploration
Explore the relationship between age, income and defualt
5. Transform | # Let's again revisit the data types in the dataset
df.dtypes | credit-risk/notebooks/1-ML-Model.ipynb | amitkaps/full-stack-data-science | mit |
Two of the columns are categorical in nature - grade and ownership.
To build models, we need all of the features to be numeric. There exists a number of ways to convert categorical variables to numeric values.
We will use one of the popular options: LabelEncoding | from sklearn.preprocessing import LabelEncoder
# Let's not modify the original dataset.
# Let's transform it in another dataset
df_encoded = df.copy()
# instantiate label encoder
le_grade = LabelEncoder()
# fit label encoder
le_grade = le_grade.fit(df_encoded["grade"])
df_encoded.grade = le_grade.transform(df.grad... | credit-risk/notebooks/1-ML-Model.ipynb | amitkaps/full-stack-data-science | mit |
EXERCISE
Do label encoding on ownership
6. Model
Common approaches:
Linear models
Tree-based models
Neural Networks
...
Some choices to consider:
Interpretability
Run-time
Model complexity
Scalability
For the purpose of this workshop, we will use tree-based models.
We will do the following two:
Decision Tree
Rand... | X_2 = df_encoded.loc[:,('age', 'amount')]
y = df_encoded.loc[:,'default'] | credit-risk/notebooks/1-ML-Model.ipynb | amitkaps/full-stack-data-science | mit |
Step 3 - Visualize the decision tree | import pydotplus
from IPython.display import Image
dot_data = tree.export_graphviz(clf_dt_2, out_file='tree.dot', feature_names=X_2.columns,
class_names=['no', 'yes'], filled=True,
rounded=True, special_characters=True)
# Incase you don't have graphviz... | credit-risk/notebooks/1-ML-Model.ipynb | amitkaps/full-stack-data-science | mit |
EXERCISE
Change the depth of the Decision Tree classifier to 10 and plot the decision boundaries again.
Lets understand first just the difference between Class prediction and Class Probabilities | pred_class = clf_dt_10.predict(X_2)
pred_proba = clf_dt_10.predict_proba(X_2)
plt.hist(pred_class);
import seaborn as sns
sns.kdeplot(pred_proba[:,1], shade=True) | credit-risk/notebooks/1-ML-Model.ipynb | amitkaps/full-stack-data-science | mit |
EXERCISE
Build a decison tree classifier with max_depth = 10 and plot confusion_matrix & auc
Cross-validation
Now that we have chosen the error metric, how do we find the generalization error?
We do this using cross-validation. ([source]
(https://en.wikipedia.org/wiki/Cross-validation_(statistics))
From wiki:
One rou... | from sklearn.model_selection import StratifiedKFold
def cross_val(clf, k):
# Instantiate stratified k fold.
kf = StratifiedKFold(n_splits=k)
# Let's use an array to store the results of cross-validation
kfold_auc_score = []
# Run kfold CV
for train_index, test_index in kf.split(X,y):... | credit-risk/notebooks/1-ML-Model.ipynb | amitkaps/full-stack-data-science | mit |
EXERCISE
Build a classifier with max_depth = 10 and run a 5-fold CV to get the auc score.
Build a classifier with max_depth = 20 and run a 5-fold CV to get the auc score.
Bagging
Decision trees in general have low bias and high variance. We can think about it like this: given a training set, we can keep asking question... | from sklearn.ensemble import RandomForestClassifier
clf_rf = RandomForestClassifier(n_estimators=10)
cross_val(clf_rf, 5) | credit-risk/notebooks/1-ML-Model.ipynb | amitkaps/full-stack-data-science | mit |
EXERCISE
Change the number of trees from 10 to 100 and make it 5-fold. And report the cross-validation error (Hint: You should get ~ 0.74. )
A more detailed version of bagging and random forest can be found in the speakers' introductory machine learning workshop material
bagging
random forest
Model Selection
We choose ... | final_model = RandomForestClassifier(n_estimators=100)
final_model = final_model.fit(X, y) | credit-risk/notebooks/1-ML-Model.ipynb | amitkaps/full-stack-data-science | mit |
BigQuery query magic
Jupyter magics are notebook-specific shortcuts that allow you to run commands with minimal syntax. Jupyter notebooks come with many built-in commands. The BigQuery client library, google-cloud-bigquery, provides a cell magic, %%bigquery. The %%bigquery magic runs a SQL query and returns the results... | %%bigquery
SELECT name, SUM(number) as count
FROM `bigquery-public-data.usa_names.usa_1910_current`
GROUP BY name
ORDER BY count DESC
LIMIT 10 | notebooks/official/template_notebooks/bigquery_magic.ipynb | GoogleCloudPlatform/bigquery-notebooks | apache-2.0 |
Explicitly specify a project
By default, the %%bigquery magic command uses your default project to run the query. You may also explicitly provide a project ID using the --project flag. Note that your credentials must have permissions to create query jobs in the project you specify. | project_id = "your-project-id"
%%bigquery --project $project_id
SELECT name, SUM(number) as count
FROM `bigquery-public-data.usa_names.usa_1910_current`
GROUP BY name
ORDER BY count DESC
LIMIT 10 | notebooks/official/template_notebooks/bigquery_magic.ipynb | GoogleCloudPlatform/bigquery-notebooks | apache-2.0 |
The class below implements all the logic you need to run the momentum backtester. Go through it and make sure you understand each part. You can run it first and make changes later to see if you made any improvements over the naive strategy.
There are 6 functions within the class:
__init__
getSymbolsToTrade
getInstrume... | class MyTradingFunctions():
def __init__(self):
self.count = 0
# When to start trading
self.start_date = '2015/01/02'
# When to end trading
self.end_date = '2017/08/31'
self.params = {}
def getSymbolsToTrade(self):
'''
Specify the stock names tha... | courses/ai-for-finance/solution/momentum_using_hurst_solution.ipynb | GoogleCloudPlatform/training-data-analyst | apache-2.0 |
Create an example sales report
TODO(you): Write a query that shows key sales stats for each item sold from the Catalog and execute it here:
- total orders
- total unit quantity
- total revenue
- total profit
- sorted by total orders highest to lowest, limit 10 | %%bigquery --verbose
--TODO:
SELECT
FROM
`qwiklabs-resources.tpcds_2t_baseline.catalog_sales`
LIMIT
10 | quests/bq-teradata/01_teradata_bq_essentials/labs/bigquery_essentials_for_teradata_users.ipynb | GoogleCloudPlatform/training-data-analyst | apache-2.0 |
Figure 1. Behavior of the median filter with given window length and different S/N ratio. | # Calculate and save all values.
# Because the for loop doesn't count from 1 to 10 for example,
# we need a counter to iterate through the array.
# The counter is assigne to -1, so we can iterate from 0 to len(values)
count = -1
count2 = -1
values = np.zeros((len(sn), len(wl)))
for w in wl[:11]:
count = count + 1
... | MedianFilter/Python/06. Behavior of the median filter with white noise/.ipynb_checkpoints/Behavior of the median filter with a noised sine wave-checkpoint.ipynb | ktakagaki/kt-2015-DSPHandsOn | gpl-2.0 |
Figure 2.1: Behavior of the median filter with given window length and different S/N ratio | # Alternative
values = np.zeros((len(wl), len(sn)))
count = -1
count2 = -1
for x in sn:
count = count + 1
for w in wl:
count2 = count2 + 1
for i in range (len(diff_noise)):
diff_noise[i, :] = np.random.normal(0, 0.706341266/np.sqrt(x), len(data))
noised_sines[i, :] = data... | MedianFilter/Python/06. Behavior of the median filter with white noise/.ipynb_checkpoints/Behavior of the median filter with a noised sine wave-checkpoint.ipynb | ktakagaki/kt-2015-DSPHandsOn | gpl-2.0 |
Uniform random variables are super important because they are the basis from which we generate other random variables, such as binomial, normal, exponential etc.
Discussion
We could generate real random numbers by accessing, for example, noise on the ethernet network device but that noise might not be uniformly distrib... | a = 16807
m = pow(2,31)-1
DFLT_SEED = 666
x_i = DFLT_SEED # this is our x_i that changes each runif01() call
def runif01():
"Return a random value in U(0,1)"
global x_i
x_i = a * x_i % m
# display(callsviz(varnames=['a','m','x_i']))
return x_i / float(m) | notes/random-uniform.ipynb | parrt/msan501 | mit |
Notice that x_i is in the global space not the runif() space. | from lolviz import callsviz
runif01() | notes/random-uniform.ipynb | parrt/msan501 | mit |
Let's try it out: | [runif01() for i in range(4)] | notes/random-uniform.ipynb | parrt/msan501 | mit |
Exercise
Define a new function, runif(a,b) that generates a random number in [a,b) instead of [0,1). Hint: We need to scale and shift a random uniform value in [0,1). Note: You can't use random.random() or any other built-in random number generators for this lab.
python
def runif(a,b):
"Return a random value in U(a... | def runif(a,b):
"Return a random value in U(a,b)"
if b<a: # swap
t = a
a = b
b = t
return runif01()*(b-a) + a
print([runif(0,10) for i in range(3)])
print([runif(5,6) for i in range(3)]) | notes/random-uniform.ipynb | parrt/msan501 | mit |
Exercise
Define a new function, setseed(x), that updates the seed global variable.
python
def setseed(s):
"Update the seed global variable but ensure seed > 0"
...
This test sequence:
python
setseed(501)
print runif01()
print runif01()
print runif01()
should generate:
0.00392101099897
0.900431859726
0.558266... | def setseed(s):
"Update the seed global variable but ensure seed > 0"
global x_i
if s <= 0: s = 666
x_i = s
setseed(501)
print([runif01() for i in range(3)])
print([runif(5,6) for i in range(3)]) | notes/random-uniform.ipynb | parrt/msan501 | mit |
Random variable density function estimate
Jumping ahead a bit, we can use the histogram plotting example from Manipulating and Visualizing Data as a crude form of density estimation to verify that the distribution of random values is approximately uniform: | import matplotlib.pyplot as plt
# jupyter notebook command (ignore)
%matplotlib inline
sample = [runif01() for i in range(5000)] # Get 5000 random variables
plt.figure(figsize=(4, 1.5))
plt.hist(sample, bins=10, density=True, alpha=0.3)
plt.xlabel('Random value from U(0,1)')
plt.ylabel('Probability')
plt.show() | notes/random-uniform.ipynb | parrt/msan501 | mit |
透视表
~ pivot_table | df = pd.read_csv('data/_all_atlogger2.csv')
df.head()
#df.columns
df.plot(kind='area', stacked=False)
df.plot(kind='kde', stacked=False)
import pandas as pd
import matplotlib.pyplot as plt
ls data/pom_*
df = pd.read_csv('data/pom_1302.txt')
df.head() | R2Py/chaos.ipynb | OpenBookProjects/ipynb | mit |
Step 2. Reading the time series
The next step is to import the time series data. Three series are used in this example; the observed groundwater head, the rainfall and the evaporation. The data can be read using different methods, in this case the Pandas read_csv method is used to read the csv files. Each file consists... | obs = pd.read_csv('obs.csv', index_col='Date', parse_dates=True) * 0.3048
rain = pd.read_csv('rain.csv', index_col='Date', parse_dates=True) * 0.3048
rain = rain.asfreq("D", fill_value=0.0) # There are some nan-values present
evap = pd.read_csv('evap.csv', index_col='Date', parse_dates=True) * 0.3048 | examples/groundwater_paper/Ex1_simple_model/Example1.ipynb | gwtsa/gwtsa | mit |
7. Diagnosing the noise series
The diagnostics plot can be used to interpret how well the noise follows a normal distribution and suffers from autocorrelation (or not). | ml.plots.diagnostics() | examples/groundwater_paper/Ex1_simple_model/Example1.ipynb | gwtsa/gwtsa | mit |
Make plots for publication
In the next codeblocks the Figures used in the Pastas paper are created. The first codeblock sets the matplotlib parameters to obtain publication-quality figures. The following figures are created:
Figure of the impulse and step respons for the scaled Gamma response function
Figure of the st... | # Set matplotlib params to create publication figures
params = {
'axes.labelsize': 18,
'axes.grid': True,
'font.size': 16,
'font.family': 'serif',
'legend.fontsize': 16,
'xtick.labelsize': 16,
'ytick.labelsize': 16,
'text.usetex': False,
'figure.figsize': [8.2, 5],
'lines.linewidth' : 2
... | examples/groundwater_paper/Ex1_simple_model/Example1.ipynb | gwtsa/gwtsa | mit |
Make a plot of the impulse and step response for the Gamma and Hantush functions | rfunc = ps.Gamma(cutoff=0.999)
p = [100, 1.5, 15]
b = np.append(0, rfunc.block(p))
s = rfunc.step(p)
rfunc2 = ps.Hantush(cutoff=0.999)
p2 = [-100, 4, 15]
b2 = np.append(0, rfunc2.block(p2))
s2 = rfunc2.step(p2)
# Make a figure of the step and block response
fig, [ax1, ax2] = plt.subplots(1, 2, sharex=True, figsize=(8... | examples/groundwater_paper/Ex1_simple_model/Example1.ipynb | gwtsa/gwtsa | mit |
Make a plot of the stresses used in the model | fig, [ax1, ax2, ax3] = plt.subplots(3,1, sharex=True, figsize=(8, 7))
ax1.plot(obs, 'k.',label='obs', markersize=2)
ax1.set_ylabel('head (m)', labelpad=0)
ax1.set_yticks([-4, -3, -2])
plot_rain = ax2.plot(rain * 1000, color='k', label='prec', linewidth=1)
ax2.set_ylabel('rain (mm/d)', labelpad=-5)
ax2.set_xlabel('Dat... | examples/groundwater_paper/Ex1_simple_model/Example1.ipynb | gwtsa/gwtsa | mit |
Make a custom figure of the model fit and the estimated step response | # Create the main plot
fig, ax = plt.subplots(figsize=(16,5))
ax.plot(obs, marker=".", c="grey", linestyle=" ")
ax.plot(obs.loc[:"2013":14], marker="x", markersize=7, c="C3", linestyle=" ", mew=2)
ax.plot(ml.simulate(tmax="2019"), c="k")
plt.ylabel('head (m)')
plt.xlabel('year')
plt.title("")
plt.xticks([str(x) for x i... | examples/groundwater_paper/Ex1_simple_model/Example1.ipynb | gwtsa/gwtsa | mit |
Make a figure of the fit report | from matplotlib.font_manager import FontProperties
font = FontProperties()
#font.set_size(10)
font.set_weight('normal')
font.set_family('monospace')
font.set_name("courier new")
plt.text(-1, -1, str(ml.fit_report()), fontproperties=font)
plt.axis('off')
plt.tight_layout()
if savefig:
path = os.path.join(figpath, ... | examples/groundwater_paper/Ex1_simple_model/Example1.ipynb | gwtsa/gwtsa | mit |
Make a Figure of the noise, residuals and autocorrelation | fig, ax1 = plt.subplots(1,1, figsize=(8, 3))
ml.residuals(tmax="2019").plot(ax=ax1, c="k")
ml.noise(tmax="2019").plot(ax=ax1, c="C0")
plt.xticks([str(x) for x in np.arange(2004, 2019, 2)], rotation=0, horizontalalignment='center')
ax1.set_ylabel('(m)')
ax1.set_xlabel('year')
ax1.legend(["residuals", "noise"], ncol=2)
... | examples/groundwater_paper/Ex1_simple_model/Example1.ipynb | gwtsa/gwtsa | mit |
Get Field and Sample Blocks AOIs | def load_geojson(filename):
with open(filename, 'r') as f:
return json.load(f)
# this feature comes from within the sacramento_crops aoi
# it is the first feature in 'ground-truth-test.geojson', which
# was prepared in crop-classification/datasets-prepare.ipynb
field_filename = os.path.join('pre-data', 'fi... | jupyter-notebooks/pixels-to-tabular-data/field_statistical_analysis.ipynb | planetlabs/notebooks | apache-2.0 |
Part 2: Get Field NDVI
In this section, we use the Data and Orders APIs to find images that overlap the field AOI in the specified time period and then to download the NDVI values of pixels within the field for all of the images. Once the images are downloaded, we use the UDM2 asset to filter to images that have no unu... | # if your Planet API Key is not set as an environment variable, you can paste it below
API_KEY = os.environ.get('PL_API_KEY', 'PASTE_YOUR_KEY_HERE')
client = api.ClientV1(api_key=API_KEY)
# create an api request from the search specifications
# relax the cloud cover requirement as filtering will be done within the ao... | jupyter-notebooks/pixels-to-tabular-data/field_statistical_analysis.ipynb | planetlabs/notebooks | apache-2.0 |
Now that we have found the images that match the search criteria, let's make sure all of the images fully contain the field AOI (we don't want to just get half of the field) and then let's see what the image footprint and the AOI look like together. | footprints = [shape(i['geometry']) for i in items]
# make sure all footprints contain the field aoi (that is, no partial overlaps)
for f in footprints:
assert f.contains(shape(field_aoi))
# visualize aoi and footprint
MultiPolygon([shape(field_aoi), footprints[0]]) | jupyter-notebooks/pixels-to-tabular-data/field_statistical_analysis.ipynb | planetlabs/notebooks | apache-2.0 |
Whoa look! That AOI is tiny relative to the image footprint. We don't want to wrangle all those pixels outside of the AOI. We definately want to clip the imagery footprints to the AOI.
Step 2: Submit Order
Now that we have the scene ids, we can create the order. The output of this step is a single zip file that contain... | def get_tools(aoi_geom):
# clip to AOI
clip_tool = {'clip': {'aoi': aoi_geom}}
# convert to NDVI
ndvi_tool = {'bandmath': {
"pixel_type": "32R",
"b1": "(b4 - b3) / (b4+b3)"
}}
tools = [clip_tool, ndvi_tool]
return tools | jupyter-notebooks/pixels-to-tabular-data/field_statistical_analysis.ipynb | planetlabs/notebooks | apache-2.0 |
Step 2.2: Build Order Requests | def build_order(ids, name, aoi_geom):
# specify the PSScene 4-Band surface reflectance product
# make sure to get the *_udm2 bundle so you get the udm2 product
# note: capitalization really matters in item_type when using planet client orders api
item_type = 'PSScene'
bundle = 'analytic_sr_udm2'
... | jupyter-notebooks/pixels-to-tabular-data/field_statistical_analysis.ipynb | planetlabs/notebooks | apache-2.0 |
Step 2.3: Submit Order | def create_order(order_request, client):
orders_info = client.create_order(order_request).get()
return orders_info['id']
order_id = create_order(order_request, client)
order_id | jupyter-notebooks/pixels-to-tabular-data/field_statistical_analysis.ipynb | planetlabs/notebooks | apache-2.0 |
Step 3: Download Orders
Step 3.1: Wait Until Orders are Successful
Before we can download the orders, they have to be prepared on the server. | def poll_for_success(order_id, client, num_loops=50):
count = 0
while(count < num_loops):
count += 1
order_info = client.get_individual_order(order_id).get()
state = order_info['state']
print(state)
success_states = ['success', 'partial']
if state == 'failed':
... | jupyter-notebooks/pixels-to-tabular-data/field_statistical_analysis.ipynb | planetlabs/notebooks | apache-2.0 |
Step 3.2: Run Download
For this step we will use the planet python orders API because the CLI doesn't do a complete download with large orders. | data_dir = os.path.join('data', 'field_statistical_analysis')
# make the download directory if it doesn't exist
Path(data_dir).mkdir(parents=True, exist_ok=True)
def poll_for_download(dest, endswith, num_loops=50):
count = 0
while(count < num_loops):
count += 1
matched_files = (f for f... | jupyter-notebooks/pixels-to-tabular-data/field_statistical_analysis.ipynb | planetlabs/notebooks | apache-2.0 |
Step 4: Unzip Order
In this section, we will unzip the order into a directory named after the downloaded zip file. | def unzip(filename, overwrite=False):
location = Path(filename)
zipdir = location.parent / location.stem
if os.path.isdir(zipdir):
if overwrite:
print('{} exists. overwriting.'.format(zipdir))
shutil.rmtree(zipdir)
else:
raise Exception('{} already exists... | jupyter-notebooks/pixels-to-tabular-data/field_statistical_analysis.ipynb | planetlabs/notebooks | apache-2.0 |
Step 5: Filter by Cloudiness
In this section, we will filter images that have any clouds within the AOI. We use the Unusable Data Mask (UDM2) to determine cloud pixels. | udm2_files = [f for f in file_paths if 'udm2' in str(f)]
# we want to find pixels that are inside the footprint but cloudy
# the easiest way to do this is is the udm values (band 8)
# https://developers.planet.com/docs/data/udm-2/
# the UDM values are given in
# https://assets.planet.com/docs/Combined-Imagery-Product... | jupyter-notebooks/pixels-to-tabular-data/field_statistical_analysis.ipynb | planetlabs/notebooks | apache-2.0 |
Step 6: Get Clear Images | def get_img_path(img_id, file_paths):
filename = '{}_3B_AnalyticMS_SR_clip_bandmath.tif'.format(img_id)
return next(f for f in file_paths if f.name == filename)
def read_ndvi(img_filename):
with rasterio.open(img_filename) as img:
# ndvi is a single-band image
band = img.read(1)
return ... | jupyter-notebooks/pixels-to-tabular-data/field_statistical_analysis.ipynb | planetlabs/notebooks | apache-2.0 |
The field AOI isn't an exact square so there are some blank pixels. Let's mask those out. We can use the UDM for that. | def get_udm2_path(img_id, file_paths):
filename = '{}_3B_udm2_clip.tif'.format(img_id)
return next(f for f in file_paths if f.name == filename)
def read_blackfill(udm2_filename):
with rasterio.open(udm2_filename) as img:
# the last band is the udm band
udm_band = img.read(8)
blackfi... | jupyter-notebooks/pixels-to-tabular-data/field_statistical_analysis.ipynb | planetlabs/notebooks | apache-2.0 |
That looks better! We now have the NDVI values for the pixels within the field AOI.
Now, lets make that a little easier to generate. | def read_masked_ndvi_by_id(iid, file_paths):
return read_masked_ndvi(get_img_path(iid, file_paths), get_udm2_path(iid, file_paths))
plot.show(read_masked_ndvi_by_id(clear_ids[0], file_paths)) | jupyter-notebooks/pixels-to-tabular-data/field_statistical_analysis.ipynb | planetlabs/notebooks | apache-2.0 |
In the images above, we are just using the default visualization for the imagery.
But this is NDVI imagery. Values are given between -1 and 1. Let's see how this looks if we use visualization specivic to NDVI. | # we demonstrated visualization in the best practices tutorial
# here, we save space by just importing the functionality
from visual import show_ndvi
# and here's what it looks like when we visualize as ndvi
# (data range -1 to 1). it actually looks worse becaue the
# pixel value range is so small
show_ndvi(read_maske... | jupyter-notebooks/pixels-to-tabular-data/field_statistical_analysis.ipynb | planetlabs/notebooks | apache-2.0 |
Well, the contrast has certainly gone down. This is because the NDVI values within the field are pretty uniform. That's what we would expect for a uniform field! So it is actually good news. The NDVI values are pretty low, ranging from 0.16 to just above 0.22. The time range used for this search is basically the month ... | def block_aoi_masks(block_aois, ref_img_path):
# find the coordinate reference system of the image
with rasterio.open(ref_img_path) as src:
dst_crs = src.crs
# geojson features (the field block geometries)
# are always given in WGS84
# project these to the image coo... | jupyter-notebooks/pixels-to-tabular-data/field_statistical_analysis.ipynb | planetlabs/notebooks | apache-2.0 |
Step 2: Random Sampling
Summary statistics such as mean, mode, and variance will be easy to calculate with the numpy python package. We need to do a little work to get random sampling, however. | np.random.seed(0) # 0 - make random sampling repeatable, no arg - nonrepeatable
def random_mask_sample(mask, count):
# get shape of unmasked pixels
unmasked = mask == False
unmasked_shape = mask[unmasked].shape
# uniformly sample pixel indices
num_unmasked = unmasked_shape[0]
idx = np.rand... | jupyter-notebooks/pixels-to-tabular-data/field_statistical_analysis.ipynb | planetlabs/notebooks | apache-2.0 |
Ok, great! The first image shows what would result from sampling 13 pixels. The second image is for nearly all the pixels and demonstrates that the mask is taken into account with sampling.
Now lets get down to calculating the summary statistics and placing them in a table entry.
Step 3: Prepare Table of Summary Statis... | def get_stats(ndvi, masks):
def _get_stats(mask, block_number):
block = np.ma.array(ndvi, mask=mask)
mean = np.ma.mean(block)
median = np.ma.median(block)
var = np.ma.var(block)
random_mask = random_mask_sample(block.mask, 1)
random_val = np.ma.mean(np.ma.ar... | jupyter-notebooks/pixels-to-tabular-data/field_statistical_analysis.ipynb | planetlabs/notebooks | apache-2.0 |
Okay! We have statistics for each block in a table. Yay! Okay, now lets move on to running this across a time series.
Step 4: Perform Time Series Analysis | def get_stats_by_id(iid, block_masks, file_paths):
ndvi = read_masked_ndvi_by_id(iid, file_paths)
ndvi_stats = get_stats(ndvi, block_masks)
acquired = get_acquired(iid)
ndvi_stats['acquired'] = [acquired]*len(block_masks)
return ndvi_stats
def get_acquired(iid):
metadata_path = get_metadata(iid... | jupyter-notebooks/pixels-to-tabular-data/field_statistical_analysis.ipynb | planetlabs/notebooks | apache-2.0 |
Okay! We have 165 rows, which is (number of blocks)x(number of images). It all checks out.
Lets check out these stats in some plots!
In these plots, color indicates the blocks. The blocks are colored red, blue, green, black, and purple. The x axis is acquisition time. So each 'column' of colored dots is the block stati... | colors = {0:'red', 1:'blue', 2:'green', 3:'black', 4:'purple'}
df = all_stats
stats = ['mean', 'median', 'random', 'variance']
fig, axes = plt.subplots(2, 2, sharex=True, figsize=(15,15))
# print(dir(axes[0][0]))
for stat, ax in zip(stats, axes.flatten()):
ax.scatter(df['acquired'], df[stat], c=df['block'].apply(... | jupyter-notebooks/pixels-to-tabular-data/field_statistical_analysis.ipynb | planetlabs/notebooks | apache-2.0 |
Fetch the data and load it in pandas | local_filename = 'data/train.csv'
# Open file and print the first 3 lines
with open(local_filename) as fid:
for line in fid.readlines()[:3]:
print(line)
data = pd.read_csv(local_filename)
data.head()
data.shape
data.describe()
data.hist(figsize=(10, 10), bins=50, layout=(3, 2));
sns.pairplot(data); | rampwf/tests/kits/iris_old/iris_old_starting_kit.ipynb | paris-saclay-cds/ramp-workflow | bsd-3-clause |
Local testing (before submission)
It is <b><span style="color:red">important that you test your submission files before submitting them</span></b>. For this we provide a unit test. Note that the test runs on your files in submissions/starting_kit.
First pip install ramp-workflow or install it from the github repo. Make... | !ramp_test_submission | rampwf/tests/kits/iris_old/iris_old_starting_kit.ipynb | paris-saclay-cds/ramp-workflow | bsd-3-clause |
Alternatively, load and execute rampwf.utils.testing.py, and call assert_submission. This may be useful if you would like to understand how we instantiate the workflow, the scores, the data connectors, and the cross validation scheme defined in problem.py, and how we insert and train/test your submission. | # %load https://raw.githubusercontent.com/paris-saclay-cds/ramp-workflow/master/rampwf/utils/testing.py
# assert_submission() | rampwf/tests/kits/iris_old/iris_old_starting_kit.ipynb | paris-saclay-cds/ramp-workflow | bsd-3-clause |
All the above commands are using Pandas module for python....still dont know how to plot against time yet. Another option to look at is Yahoo's finance package | goog?
goog.T
goog.High
goog
goog.columns
goog.plot.im_self
plt.plot(goog.index,goog['High']);
%matplotlib qt
plt.plot(goog.index,goog['High']);
plt.plot(goog.index,goog['Low']);
%matplotlib inline
plt.plot(goog.index,goog['High'],goog.index,goog['Low'])
plt.grid()
goog.High[0]
a=[];
for i in range(1,len(goo... | analysis/notebooks/darvasBoxExperiments.ipynb | vakilp/darvasBox | gpl-2.0 |
So both the outputs wheter I have <= or < are the same for this set of data
Experiment with Drawing Darvas Box on Google Data | c=[];
for i in range(1,len(goog)):
if((goog.High[i]<=goog.High[i-1]) and (goog.Low[i]>=goog.Low[i-1])):
c.append(i)
len(c)
a_diff = np.diff(a)
%matplotlib qt
plt.plot(a_diff)
idx = 0;
d = []
for i in range(1,len(goog)):
if(goog.High[i]<=goog.High[i-1]):
idx = idx + 1;
else:
idx ... | analysis/notebooks/darvasBoxExperiments.ipynb | vakilp/darvasBox | gpl-2.0 |
So, the good thing here is that number of elements in box1.high is same as we expect | len(box1.low)
np.argmin(goog.Low[4:7])
goog.Low[4:7]
class box(object):
high = []
low = []
date_high = []
date_low = []
box1 = box()
idx = 0;
d = []
index = 0;
for i in range(1,len(goog)):
if(goog.High[i]<=goog.High[i-1]):
idx = idx + 1;
else:
idx = 0;
if idx==3:
... | analysis/notebooks/darvasBoxExperiments.ipynb | vakilp/darvasBox | gpl-2.0 |
So, clearly the rectangle is not working yet. Need to work that out | from matplotlib.patches import FancyBboxPatch
def draw_bbox(ax, bb):
# boxstyle=square with pad=0, i.e. bbox itself.
p_bbox = FancyBboxPatch((bb.xmin, bb.ymin),
abs(bb.width), abs(bb.height),
boxstyle="square,pad=0.",
ec="k", f... | analysis/notebooks/darvasBoxExperiments.ipynb | vakilp/darvasBox | gpl-2.0 |
Things to figure out about plotting:
How to close/clf a plot successfully so that I can draw a new plot?
How to get current axes for a given plot?
How to do hold on and hold off? | %matplotlib inline
bb = mtransforms.Bbox([[0.3, 0.4], [0.7, 0.6]])
ax = plt.subplot(111)
draw_bbox(ax,bb)
bb.corners
ax = plt.subplot(111)
plt.plot(date_high,high,'o',goog.index,goog.High,date_low,low,'ro',goog.index,goog.Low);
draw_bbox(ax,bb)
%matplotlib qt
ax = plt.subplot(111)
plt.plot(date_high,high,'o',goog.... | analysis/notebooks/darvasBoxExperiments.ipynb | vakilp/darvasBox | gpl-2.0 |
Time Stamps and Drawing Rectangles
The output of the read from finance.yahoo.com is timestamp class. To work with rectangles, I need x values that indicate time. The rectangles and bboxes work only with numbers. So, I need to convert the timestamp I have into a number. The way to do is as follows:
Pick out a timestamp... | x_high = box1.date_high[1]
x_high = x_high.to_datetime()
x_high
mdates.date2num(x_high)
x_low = box1.date_low[1]
x_low = x_low.to_datetime()
mdates.date2num(x_low)
box1.low[1]
box1.high[1]
bb = mtransforms.Bbox([[np.float(x_high), np.float(box1.low[1])], [np.float(x_low), np.float(box1.high[1])]])
ax = plt.subp... | analysis/notebooks/darvasBoxExperiments.ipynb | vakilp/darvasBox | gpl-2.0 |
So now that we know overfitting is a problem, but how do we fix it? One way is to throw more data at the problem. A simple rule of thumb as presented by Yaser Abu-Mostaf is his excellent machine learning course available from Caltech, is that you should have at least 10 times as many examples as the degrees for freedom... | #Regularization Parameter:
Lambda = 0.0001
#Need to make changes to costFunction and costFunctionPrim:
def costFunction(self, X, y):
#Compute cost for given X,y, use weights already stored in class.
self.yHat = self.forward(X)
J = 0.5*sum((y-self.yHat)**2)/X.shape[0] + (self.lambd/2)*(sum(self.W1**2)+sum(... | Python/ML_DL/DL/Neural-Networks-Demystified-master/.ipynb_checkpoints/Part 7 Overfitting, Testing, and Regularization-checkpoint.ipynb | vbsteja/code | apache-2.0 |
The Events and Annotations data structures
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Generally speaking, both the Events and :class:~mne.Annotations data
structures serve the same purpose: they provide a mapping between times
during an EEG/MEG recording and a description of what happened at those
times. In other words... | raw.copy().pick_types(meg=False, stim=True).plot(start=3, duration=6) | 0.19/_downloads/6684371ec2bc8e72513b3bdbec0d3a9f/plot_20_events_from_raw.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
You can see that STI 014 (the summation channel) contains pulses of
different magnitudes whereas pulses on other channels have consistent
magnitudes. You can also see that every time there is a pulse on one of the
other STIM channels, there is a corresponding pulse on STI 014.
.. TODO: somewhere in prev. section, link ... | events = mne.find_events(raw, stim_channel='STI 014')
print(events[:5]) # show the first 5 | 0.19/_downloads/6684371ec2bc8e72513b3bdbec0d3a9f/plot_20_events_from_raw.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
.. sidebar:: The middle column of the Events array
MNE-Python events are actually *three* values: in between the sample
number and the integer event code is a value indicating what the event
code was on the immediately preceding sample. In practice, that value is
almost always `0`, but it can be used to detect the *end... | testing_data_folder = mne.datasets.testing.data_path()
eeglab_raw_file = os.path.join(testing_data_folder, 'EEGLAB', 'test_raw.set')
eeglab_raw = mne.io.read_raw_eeglab(eeglab_raw_file)
print(eeglab_raw.annotations) | 0.19/_downloads/6684371ec2bc8e72513b3bdbec0d3a9f/plot_20_events_from_raw.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
More information on working with :class:~mne.Annotations objects, including
how to add annotations to :class:~mne.io.Raw objects interactively, and how
to plot, concatenate, load, save, and export :class:~mne.Annotations
objects can be found in the tutorial tut-annotate-raw.
Converting between Events arrays and Annotat... | events_from_annot, event_dict = mne.events_from_annotations(eeglab_raw)
print(event_dict)
print(events_from_annot[:5]) | 0.19/_downloads/6684371ec2bc8e72513b3bdbec0d3a9f/plot_20_events_from_raw.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
Making multiple events per annotation
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
As mentioned above, you can generate equally-spaced events from an
:class:~mne.Annotations object using the chunk_duration parameter of
:func:~mne.events_from_annotations. For example, suppose we have an
annotation in our :class:~mne.io.Raw obj... | # create the REM annotations
rem_annot = mne.Annotations(onset=[5, 41],
duration=[16, 11],
description=['REM'] * 2)
raw.set_annotations(rem_annot)
(rem_events,
rem_event_dict) = mne.events_from_annotations(raw, chunk_duration=1.5) | 0.19/_downloads/6684371ec2bc8e72513b3bdbec0d3a9f/plot_20_events_from_raw.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
🎯 Nomenclature
First off, let's clarify a bit the nomenclature we are going to use, introducing the following terms: Datasets, Scenarios, Benchmarks and Generators.
By Dataset we mean a collection of examples that can be used for training or testing purposes but not already organized to be processed as a stream of ba... | import torch
import torchvision
from avalanche.benchmarks.datasets import MNIST, FashionMNIST, KMNIST, EMNIST, \
QMNIST, FakeData, CocoCaptions, CocoDetection, LSUN, ImageNet, CIFAR10, \
CIFAR100, STL10, SVHN, PhotoTour, SBU, Flickr8k, Flickr30k, VOCDetection, \
VOCSegmentation, Cityscapes, SBDataset, USPS, Kinetics400... | notebooks/from-zero-to-hero-tutorial/03_benchmarks.ipynb | ContinualAI/avalanche | mit |
Of course also the basic utilities ImageFolder and DatasetFolder can be used. These are two classes that you can use to create a Pytorch Dataset directly from your files (following a particular structure). You can read more about these in the Pytorch official documentation here.
We also provide an additional FilelistDa... | from avalanche.benchmarks.utils import ImageFolder, DatasetFolder, FilelistDataset, AvalancheDataset | notebooks/from-zero-to-hero-tutorial/03_benchmarks.ipynb | ContinualAI/avalanche | mit |
🛠️ Benchmarks Basics
The Avalanche benchmarks (instances of the Scenario class), contains several attributes that characterize the benchmark. However, the most important ones are the train and test streams.
In Avalanche we often suppose to have access to these two parallel stream of data (even though some benchmarks m... | from avalanche.benchmarks.classic import SplitMNIST
split_mnist = SplitMNIST(n_experiences=5, seed=1)
# Original train/test sets
print('--- Original datasets:')
print(split_mnist.original_train_dataset)
print(split_mnist.original_test_dataset)
# A list describing which training patterns are assigned to each experienc... | notebooks/from-zero-to-hero-tutorial/03_benchmarks.ipynb | ContinualAI/avalanche | mit |
Train and Test Streams
The train and test streams can be used for training and testing purposes, respectively. This is what you can do with these streams: | # each stream has a name: "train" or "test"
train_stream = split_mnist.train_stream
print(train_stream.name)
# we have access to the scenario from which the stream was taken
train_stream.benchmark
# we can slice and reorder the stream as we like!
substream = train_stream[0]
substream = train_stream[0:2]
substream = t... | notebooks/from-zero-to-hero-tutorial/03_benchmarks.ipynb | ContinualAI/avalanche | mit |
Experiences
Each stream can in turn be treated as an iterator that produces a unique experience, containing all the useful data regarding a batch or task in the continual stream our algorithms will face. Check out how can you use these experiences below: | # we get the first experience
experience = train_stream[0]
# task label and dataset are the main attributes
t_label = experience.task_label
dataset = experience.dataset
# but you can recover additional info
experience.current_experience
experience.classes_in_this_experience
experience.classes_seen_so_far
experience.p... | notebooks/from-zero-to-hero-tutorial/03_benchmarks.ipynb | ContinualAI/avalanche | mit |
🏛️ Classic Benchmarks
Now that we know how our benchmarks work in general through scenarios, streams and experiences objects, in this section we are going to explore common benchmarks already available for you with one line of code yet flexible enough to allow proper tuning based on your needs: | from avalanche.benchmarks.classic import CORe50, SplitTinyImageNet, \
SplitCIFAR10, SplitCIFAR100, SplitCIFAR110, SplitMNIST, RotatedMNIST, \
PermutedMNIST, SplitCUB200, SplitImageNet
# creating PermutedMNIST (Task-Incremental)
perm_mnist = PermutedMNIST(
n_experiences=2,
seed=1234,
) | notebooks/from-zero-to-hero-tutorial/03_benchmarks.ipynb | ContinualAI/avalanche | mit |
Many of the classic benchmarks will download the original datasets they are based on automatically and put it under the "~/.avalanche/data" directory.
How to Use the Benchmarks
Let's see now how we can use the classic benchmark or the ones that you can create through the generators (see next section). For example, let'... | # creating the benchmark instance (scenario object)
perm_mnist = PermutedMNIST(
n_experiences=3,
seed=1234,
)
# recovering the train and test streams
train_stream = perm_mnist.train_stream
test_stream = perm_mnist.test_stream
# iterating over the train stream
for experience in train_stream:
print("Start of task... | notebooks/from-zero-to-hero-tutorial/03_benchmarks.ipynb | ContinualAI/avalanche | mit |
🐣 Benchmarks Generators
What if we want to create a new benchmark that is not present in the "Classic" ones? Well, in that case Avalanche offer a number of utilites that you can use to create your own benchmark with maximum flexibility: the benchmarks generators!
Specific Generators
The specific scenario generators ar... | from avalanche.benchmarks.generators import nc_benchmark, ni_benchmark | notebooks/from-zero-to-hero-tutorial/03_benchmarks.ipynb | ContinualAI/avalanche | mit |
Let's start by creating the MNIST dataset object as we would normally do in Pytorch: | from torchvision.transforms import Compose, ToTensor, Normalize, RandomCrop
train_transform = Compose([
RandomCrop(28, padding=4),
ToTensor(),
Normalize((0.1307,), (0.3081,))
])
test_transform = Compose([
ToTensor(),
Normalize((0.1307,), (0.3081,))
])
mnist_train = MNIST(
'./data/mnist', train... | notebooks/from-zero-to-hero-tutorial/03_benchmarks.ipynb | ContinualAI/avalanche | mit |
Then we can, for example, create a new benchmark based on MNIST and the classic Domain-Incremental scenario: | scenario = ni_benchmark(
mnist_train, mnist_test, n_experiences=10, shuffle=True, seed=1234,
balance_experiences=True
)
train_stream = scenario.train_stream
for experience in train_stream:
t = experience.task_label
exp_id = experience.current_experience
training_dataset = experience.dataset
pr... | notebooks/from-zero-to-hero-tutorial/03_benchmarks.ipynb | ContinualAI/avalanche | mit |
Or, we can create a benchmark based on MNIST and the Class-Incremental (what's commonly referred to as "Split-MNIST" benchmark): | scenario = nc_benchmark(
mnist_train, mnist_test, n_experiences=10, shuffle=True, seed=1234,
task_labels=False
)
train_stream = scenario.train_stream
for experience in train_stream:
t = experience.task_label
exp_id = experience.current_experience
training_dataset = experience.dataset
print('Ta... | notebooks/from-zero-to-hero-tutorial/03_benchmarks.ipynb | ContinualAI/avalanche | mit |
Generic Generators
Finally, if you cannot create your ideal benchmark since it does not fit well in the aforementioned new classes or new instances scenarios, you can always use our generic generators:
filelist_benchmark
paths_benchmark
dataset_benchmark
tensors_benchmark | from avalanche.benchmarks.generators import filelist_benchmark, dataset_benchmark, \
tensors_benchmark, paths_benchmark | notebooks/from-zero-to-hero-tutorial/03_benchmarks.ipynb | ContinualAI/avalanche | mit |
Let's start with the filelist_benchmark utility. This function is particularly useful when it is important to preserve a particular order of the patterns to be processed (for example if they are frames of a video), or in general if we have data scattered around our drive and we want to create a sequence of batches/task... | !wget -N --no-check-certificate \
https://storage.googleapis.com/mledu-datasets/cats_and_dogs_filtered.zip
!unzip -q -o cats_and_dogs_filtered.zip | notebooks/from-zero-to-hero-tutorial/03_benchmarks.ipynb | ContinualAI/avalanche | mit |
You can now see in the content directory on colab the image we downloaded. We are now going to create the filelists and then use the filelist_benchmark function to create our benchmark: | import os
# let's create the filelists since we don't have it
dirpath = "cats_and_dogs_filtered/train"
for filelist, rel_dir, t_label in zip(
["train_filelist_00.txt", "train_filelist_01.txt"],
["cats", "dogs"],
[0, 1]):
# First, obtain the list of files
filenames_list = os.listdir(os.p... | notebooks/from-zero-to-hero-tutorial/03_benchmarks.ipynb | ContinualAI/avalanche | mit |
In the previous cell we created a benchmark instance starting from file lists. However, paths_benchmark is a better choice if you already have the list of paths directly loaded in memory: | train_experiences = []
for rel_dir, label in zip(
["cats", "dogs"],
[0, 1]):
# First, obtain the list of files
filenames_list = os.listdir(os.path.join(dirpath, rel_dir))
# Don't create a file list: instead, we create a list of
# paths + class labels
experience_paths = []
for n... | notebooks/from-zero-to-hero-tutorial/03_benchmarks.ipynb | ContinualAI/avalanche | mit |
Let us see how we can use the dataset_benchmark utility, where we can use several PyTorch datasets as different batches or tasks. This utility expectes a list of datasets for the train, test (and other custom) streams. Each dataset will be used to create an experience: | train_cifar10 = CIFAR10(
'./data/cifar10', train=True, download=True
)
test_cifar10 = CIFAR10(
'./data/cifar10', train=False, download=True
)
generic_scenario = dataset_benchmark(
[train_MNIST, train_cifar10],
[test_MNIST, test_cifar10]
) | notebooks/from-zero-to-hero-tutorial/03_benchmarks.ipynb | ContinualAI/avalanche | mit |
Adding task labels can be achieved by wrapping each datasets using AvalancheDataset. Apart from task labels, AvalancheDataset allows for more control over transformations and offers an ever growing set of utilities (check the documentation for more details). | # Alternatively, task labels can also be a list (or tensor)
# containing the task label of each pattern
train_MNIST_task0 = AvalancheDataset(train_cifar10, task_labels=0)
test_MNIST_task0 = AvalancheDataset(test_cifar10, task_labels=0)
train_cifar10_task1 = AvalancheDataset(train_cifar10, task_labels=1)
test_cifar10_... | notebooks/from-zero-to-hero-tutorial/03_benchmarks.ipynb | ContinualAI/avalanche | mit |
And finally, the tensors_benchmark generator: | pattern_shape = (3, 32, 32)
# Definition of training experiences
# Experience 1
experience_1_x = torch.zeros(100, *pattern_shape)
experience_1_y = torch.zeros(100, dtype=torch.long)
# Experience 2
experience_2_x = torch.zeros(80, *pattern_shape)
experience_2_y = torch.ones(80, dtype=torch.long)
# Test experience
# F... | notebooks/from-zero-to-hero-tutorial/03_benchmarks.ipynb | ContinualAI/avalanche | mit |
As you can see, it doesn't generate the complete list like the listcomp above. Genexps don't produce entire lists in memory. You need to iterate over them, and then you will get the item one by one. No one is keeping the entire list! | for article in couleurs_et_tailles:
print(article) | Chapter 2 - Iterables Consistency.ipynb | rayxi2dot71828/FluentPython | mit |
Next, it's about tuple (in short, not just an immutable list), and slicing. More examples: | jours = ["lundi", "mardi", "mercredi", "jeudi", "vendredi", "samedi", "dimanche"]
all_slice = slice(None, None, None)
print(jours[all_slice])
every_other_slice = slice(0, None, 2)
print(jours[every_other_slice])
reverse_slice = slice(None, None, -1)
print(jours[reverse_slice]) | Chapter 2 - Iterables Consistency.ipynb | rayxi2dot71828/FluentPython | mit |
Next, the chapter moves on to list.sort() vs. sorted(). I kinda like sorted because it works with everything including generators, and it returns a new list. Whereas list.sort() is more limited because it is an in-place sort which returns None.
Next is about bisect, which is interesting but one can read the documentati... | jours = ["lundi", "mardi", "mercredi", "jeudi", "vendredi", "samedi", "dimanche"] # already ordered
print(sorted(jours))
print(sorted(jours, reverse=True))
print(sorted(jours, key=len, reverse=True)) # by length of string, descend
print(sorted(jours, reverse=True, key=lambda x: jours.index(x))) # by actual order of we... | Chapter 2 - Iterables Consistency.ipynb | rayxi2dot71828/FluentPython | mit |
Performance Test One: | timeit(get_subStrs_of_uniqueChars(longString, 6623))
# hackerrank, most voted solution from discussion board (for Python)
# S, N = input(), int(input())
def hackrRank_getSubsOfUniqueChars_v1(S, N):
# modified slightly to integrate for this timeit test:
rtnVal = [] # changed print() to rtnVal
... | PY_Basics/TMWP_PerfTesting_in_JupyterNBs.ipynb | TheMitchWorksPro/DataTech_Playground | mit |
Performance Test Two:
This one runs faster by a noticeable factor (6x faster). But the next one is even more extreme. | timeit(hackrRank_getSubsOfUniqueChars_v1(longString, 6623))
# a solution from the discussion board of hackerrank
def without_repetition(t):
s = set()
o = []
for c in t:
if c not in s:
s.add(c)
o.append(c)
return ''.join(o)
def hackrRank_getSubsOfUniqueChars_v2(s, ... | PY_Basics/TMWP_PerfTesting_in_JupyterNBs.ipynb | TheMitchWorksPro/DataTech_Playground | mit |
Performance Test Three:
This one runs faster by a much more extreme multiplier. Note that we have switched from ms to us in the output metric. If this function were called on big data, the performance boost would be significant (3 decimal places faster). | timeit(hackrRank_getSubsOfUniqueChars_v2(longString, 6623))
from collections import OrderedDict
def hackrRank_getSubsOfUniqueChars_v3(string, k):
rtnVal = []
for x in range(0,len(string),k):
rtnVal.append(''.join(list(OrderedDict.fromkeys(string[x:x+k]))))
return rtnVal
# tests to show it wo... | PY_Basics/TMWP_PerfTesting_in_JupyterNBs.ipynb | TheMitchWorksPro/DataTech_Playground | mit |
Performance Test Four:
Ironically, though this one also tests in microseconds, this ordered dictionary solution that also looks "more Pythonic" then the previous example, is not able to beat the performance of the previous example. It only comes in second place. | timeit(hackrRank_getSubsOfUniqueChars_v3(longString, 6623)) | PY_Basics/TMWP_PerfTesting_in_JupyterNBs.ipynb | TheMitchWorksPro/DataTech_Playground | mit |
Another Simple Test
This test shows how two lines performs better than one since it avoids doing a list conversion twice | def averageUniqueElements(array):
return sum(set(array)) / len(set(array))
def averageUniqueElements_v2(array):
arrSet = set(array)
return sum(arrSet) / len(arrSet)
timeit(averageUniqueElements([456789, 456789, 11111111, 111111111, 12111111111111, 78787878, 7878, 99999999, 99999999, 6]))
timeit(averageUn... | PY_Basics/TMWP_PerfTesting_in_JupyterNBs.ipynb | TheMitchWorksPro/DataTech_Playground | mit |
In this example, we will get the page for Berkeley, California and count the most commonly used words in the article. I'm using nltk, which is a nice library for natural language processing (although it is probably overkill for this). | bky = wikipedia.page("Berkeley, California")
bky
bk_split = bky.content.split()
bk_split[:10]
!pip install nltk
import nltk
fdist1 = nltk.FreqDist(bk_split)
fdist1.most_common(10) | scraping_wikipedia/wikipedia-api-query.ipynb | katyhuff/berkeley | bsd-3-clause |
There are many functions in a Wikipedia page object. We can also get all the Wikipedia articles that are linked from a page, all the URL links in the page, or all the geographical coordinates in the page.
There was a study about which domains were most popular in Wikipedia articles. | print(bky.references[:10])
print(bky.links[:10]) | scraping_wikipedia/wikipedia-api-query.ipynb | katyhuff/berkeley | bsd-3-clause |
Querying using pywikibot
pywikibot is one of the most well-developed and widely used libraries for querying the Wikipedia API. It does need a configuration script (user-config.py) in the directory where you are running the python script. It is often used by bots that edit, so there are many features that are not avail... | user_config="""
family = 'wikipedia'
mylang = 'en'
usernames['wikipedia']['en'] = u'REPLACE THIS WITH YOUR USERNAME'
"""
f = open('user-config.py', 'w')
f.write(user_config)
f.close()
!pip install pywikibot
import pywikibot
site = pywikibot.Site()
bky_page = pywikibot.Page(site, "Berkeley, California")
bky_page
# ... | scraping_wikipedia/wikipedia-api-query.ipynb | katyhuff/berkeley | bsd-3-clause |
Generators
Generators are a way of querying for a kind of page, and then iterating through those pages. Generators are frequently used with categories, but you can also use a generator for things like a search, or all pages linking to a page. | from pywikibot import pagegenerators
cat = pywikibot.Category(site,'Category:Cities in Alameda County, California')
gen = cat.members()
gen
# create an empty list
coord_d = []
for page in gen:
print(page.title(), page.coordinates())
pc = page.coordinates()
for coord in pc:
# If the page is not a... | scraping_wikipedia/wikipedia-api-query.ipynb | katyhuff/berkeley | bsd-3-clause |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.