markdown
stringlengths
0
1.02M
code
stringlengths
0
832k
output
stringlengths
0
1.02M
license
stringlengths
3
36
path
stringlengths
6
265
repo_name
stringlengths
6
127
**About Google's Colaboratory: **This is a free Jupyter environment that runs in Google's cloud, which means you can run codes in your computer without having to install anything. You can create a copy of this tutorial in your own Google's Drive and make your own changes. Colaboratory also allows you to easily share y...
import seaborn as sns import numpy as np import pandas as pd from sklearn.model_selection import train_test_split import matplotlib.pyplot as plt from sklearn.svm import SVC from sklearn.metrics import confusion_matrix import itertools from mlxtend.plotting import plot_decision_regions import matplotlib as mpl import ...
_____no_output_____
MIT
The_Basics_of_Supervised_Learning_For_Astronomers.ipynb
marixko/tutorial_classifiers
**2. Read Data**For statistical/machine learning purposes it is **always** better to read the data in a dataframe (data structured in labels for rows and columns) format.
#Reading dataset from github and saving as dataframe url = 'https://raw.githubusercontent.com/marixko/' file = 'tutorial_classifiers/master/tutorial_data.txt' df = pd.read_csv(url+file, delim_whitespace=True, low_memory=False) # Run this cell to quickly check your dataset df # Check header list(df)
_____no_output_____
MIT
The_Basics_of_Supervised_Learning_For_Astronomers.ipynb
marixko/tutorial_classifiers
**3. Pre-analysis** Before applying any kind of analysis, you need to be aware of any problem in your dataset that can affect your training (e.g. missing values and outliers). Sometimes it will require pre-processing your dataset beforehand (e.g. for missing values, interpolating values or removing them from data may b...
# You can check your dataset by using describe(). # It will return the total count, mean, standard deviation, # minimum, Q1, Q2 (median), Q3 and maximum df.describe() # If you want to check a specific feature use for instance: # df.FWHM_n.describe()
_____no_output_____
MIT
The_Basics_of_Supervised_Learning_For_Astronomers.ipynb
marixko/tutorial_classifiers
Another good practice is to check high correlations in your dataset, which can allow you to identify which features are redundant. Thus, you can also be able to reduce dimensionality of your dataset.>> *"The fact that many features depend on one another often unduly influences the accuracy of supervised ML classificati...
plt.close() f, ax = plt.subplots(figsize=(8, 8)) var = ['FWHM_n', 'A', 'B', 'KrRadDet', 'uJAVA_auto', 'F378_auto', 'F395_auto', 'F410_auto', 'g_auto', 'F515_auto', 'r_auto', 'F660_auto', 'i_auto', 'F861_auto', 'z_auto'] corr = df[var].corr() sns.heatmap(corr, mask=np.zeros_like(corr, dtype=np.bool), ...
_____no_output_____
MIT
The_Basics_of_Supervised_Learning_For_Astronomers.ipynb
marixko/tutorial_classifiers
Qualitative variables can also be included. In this case, however, there are no qualitative features that came from S-PLUS observations.But let's check the classification label counts:
# For qualitative variables, use value_counts() df['class'].value_counts()
_____no_output_____
MIT
The_Basics_of_Supervised_Learning_For_Astronomers.ipynb
marixko/tutorial_classifiers
Note that for this example the classes are balanced. It represents a best case scenario, which rarely happens in the real world. Be very careful with imbalanced datasets! Some methods and metrics are not good for imbalanced cases, some manipulation in your sampling method (e.g. over/under-sampling) or in your algorithm...
dim15 = ['FWHM_n', 'A', 'B', 'KrRadDet', 'uJAVA_auto', 'F378_auto', 'F395_auto', 'F410_auto', 'g_auto', 'F515_auto', 'r_auto', 'F660_auto', 'i_auto', 'F861_auto', 'z_auto'] dim2 = ['FWHM_n','A']
_____no_output_____
MIT
The_Basics_of_Supervised_Learning_For_Astronomers.ipynb
marixko/tutorial_classifiers
** 5. Sampling training and testing sets ** Regardless of the classification method you choose, you will want to estimate how accurately your predictive model will perform. This is called **cross-validation** and there are several ways to do it. Some examples are:* **Holdout method**: randomly separate your original da...
label = pd.DataFrame(df['class']) # Transform strings into numbered labels label.loc[label['class'] == 'STAR', 'class'] = 0 label.loc[label['class'] == 'GALAXY', 'class'] = 1 # Use train_test_split() to sample your training and testing sets # Let's fix a random_state=42 in order to have the same sets # on each run. ...
_____no_output_____
MIT
The_Basics_of_Supervised_Learning_For_Astronomers.ipynb
marixko/tutorial_classifiers
** 6. Classification method: Support Vector Machine (SVM)** We finally reached the point where we are going to run a classification algorithm. It is common to think, at first, that this would be the most complicated part, but a well-done job will require you to spend most of your time on the other steps. There are seve...
# Train your model: clf2 = SVC(kernel= 'linear') clf2.fit(X_train[dim2], y_train.values.ravel()) # Make the predictions: y_pred2 = clf2.predict(X_test[dim2]) # Plot confusion matrix: matrix = confusion_matrix(y_test['class'], y_pred2) fig = plot_confusion_matrix(matrix, classes=['STAR','GALAXY']) plt.show()
_____no_output_____
MIT
The_Basics_of_Supervised_Learning_For_Astronomers.ipynb
marixko/tutorial_classifiers
From the confusion matrix above we can already see how good the results are: most of our stars (galaxies) are being assigned as stars (galaxies) and just a few percent were misclassified.Now let's check the plot and how the separation looks like:
plt.style.use('seaborn-pastel') fig = plt.figure(figsize=(18,6)) gs = gridspec.GridSpec(1, 2) ax = plt.subplot(gs[0,0]) sns.scatterplot(x=X_train.FWHM_n, y=X_train.A, hue=y_train['class']) #Calculate margin (from https://scikit-learn.org/stable/auto_examples/svm/plot_svm_margin.html) w = clf2.coef...
_____no_output_____
MIT
The_Basics_of_Supervised_Learning_For_Astronomers.ipynb
marixko/tutorial_classifiers
The solid line corresponds to the optimal threshold found by SVM. The dashed lines in the plots above correspond to the maximized margin that I mentioned in Section 6.1. These are calculated using only a small part of the data: the objects around where the separation may occur, they are called the Support Vectors. Let'...
fig = plt.figure(figsize=(9,7)) sns.scatterplot(x=X_train[dim2].FWHM_n, y=X_train[dim2].A, hue=y_train['class']) plt.scatter(clf2.support_vectors_[:, 0], clf2.support_vectors_[:, 1], s=8, zorder=10,color='red', marker='+') plt.xlim(0.9,2) plt.ylim(0.8,5) plt.plot(xx, yy, 'k-') plt.plot(xx, yy_d...
_____no_output_____
MIT
The_Basics_of_Supervised_Learning_For_Astronomers.ipynb
marixko/tutorial_classifiers
6.3. Feature space: dim15 In the last section we saw how SVM works in a 2D space. In that case, it is possible to visually check the separation. However, we have much more information available. if we analyse them altogether, it can improve our results. Although, it is impossible to visually check the results, so we n...
# Train your model: clf15 = SVC(kernel= 'linear') clf15.fit(X_train, y_train.values.ravel()) # Make predictions: y_pred = clf15.predict(X_test) # Plot confusion matrix: matrix = confusion_matrix(y_test['class'], y_pred) fig = plot_confusion_matrix(matrix, classes=['STAR','GALAXY']) plt.show() # Yeah, as simple as th...
_____no_output_____
MIT
The_Basics_of_Supervised_Learning_For_Astronomers.ipynb
marixko/tutorial_classifiers
** 7. Validation and Model Selection** How can we choose between two (or more) different models? For that, we have several performance metrics that we can consider when selecting the best model and I will show a few of them.The way you are going to analyze the metrics depends on your science goals. For instance: * In a...
print("Accuracy") print(" First model (dim2):", np.round(100*metrics.accuracy_score(y_test, y_pred2),2), '%') print(" Second model (dim15):", np.round(100*metrics.accuracy_score(y_test, y_pred),2), '%')
_____no_output_____
MIT
The_Basics_of_Supervised_Learning_For_Astronomers.ipynb
marixko/tutorial_classifiers
7.2. Precision Defined as:> Precision $\equiv \frac{TP}{(TP+FP)}$TP - True Positive ; FP - False PositiveNote that you need to define which class will be your "positive". For example: | STAR (predicted) | GALAXY (predicted)--- | ---**STAR** (true label) | True Negative | False Positive**GALAXY** (true label)| False Ne...
P2 = metrics.precision_score(y_test, y_pred2, pos_label=1) P = metrics.precision_score(y_test, y_pred, pos_label=1) print("Galaxy Precision") print(" First model (dim2):", np.round(100*P2,2), '%') print(" Second model (dim15):", np.round(100*P,2), '%') # Exercise: Calculate star precision for each model
_____no_output_____
MIT
The_Basics_of_Supervised_Learning_For_Astronomers.ipynb
marixko/tutorial_classifiers
7.3. Recall Defined as:> Recall $\equiv \frac{TP}{(TP+FN)}$TP - True Positive ; FN - False NegativeIn Astronomy, it's called **completeness**.
R2 = metrics.recall_score(y_test, y_pred2, pos_label=1) R = metrics.recall_score(y_test, y_pred, pos_label=1) print("Galaxy Recall") print(" First model (dim2):", np.round(100*R2,2), '%') print(" Second model (dim15):", np.round(100*R,2), '%') # Exercise: Calculate star recall for each model
_____no_output_____
MIT
The_Basics_of_Supervised_Learning_For_Astronomers.ipynb
marixko/tutorial_classifiers
7.4. F-measure It's the harmonic mean of Precision and Recall:$F = \frac{1}{2}\Big(P_i^{-1}+R_i^{-1}\Big)^{-1} = 2 \times \frac{P_iR_i}{P_i+R_i}, F \in [0,1]$
print("F-measure") print(" First model (dim2):", np.round(metrics.f1_score(y_test, y_pred2),3)) print(" Second model (dim15):", np.round(metrics.f1_score(y_test, y_pred),3))
_____no_output_____
MIT
The_Basics_of_Supervised_Learning_For_Astronomers.ipynb
marixko/tutorial_classifiers
Create base grid using NO2 dataset
ds_s5p = xr.open_dataset('/Users/kasmith/Code/kaggle_ds4g/data/starter_pack/s5p_no2/no2_1year.nc') ds_no2_clouds = ds_s5p[['NO2_column_number_density', 'cloud_fraction']] no2_regridder = make_regridder(ds_no2_clouds, ds_no2_clouds, 'NO2_column_number_density') ds_base_regrid = no2_regridder(ds_no2_clouds) ds_base_regri...
_____no_output_____
MIT
notebooks/Regrid.ipynb
kallisons/kaggle_ds4g_emissions_factor
Create land mask for base grid
#Download Super High Resolution SST file (0.01 degree grid) #https://coastwatch.pfeg.noaa.gov/erddap/griddap/jplG1SST.nc?SST[(2017-09-13T00:00:00Z):1:(2017-09-13T00:00:00Z)][(17.005):1:(19.005)][(-69.995):1:(-64.005)],mask[(2017-09-13T00:00:00Z):1:(2017-09-13T00:00:00Z)][(17.005):1:(19.005)][(-69.995):1:(-64.005)],anal...
_____no_output_____
MIT
notebooks/Regrid.ipynb
kallisons/kaggle_ds4g_emissions_factor
Compute daily averages
ds_base = ds_base_regrid.resample(time='1D').mean() ax = plt.axes(projection=ccrs.LambertConformal(central_longitude=-65, central_latitude=18)) ds_base['NO2_column_number_density'].isel(time=26).where(ds_base.land_mask == 1).plot(ax=ax, transform=ccrs.PlateCarree()) ax.set_extent([-67.5, -65, 17.5, 19]) ax.set_aspect("...
_____no_output_____
MIT
notebooks/Regrid.ipynb
kallisons/kaggle_ds4g_emissions_factor
Add wind speed
ds_gfs = xr.open_dataset('/Users/kasmith/Code/kaggle_ds4g/data/starter_pack/gfs/gfs_1year.nc') ds_gfs = ds_gfs.drop('crs') gfs_regridder = make_regridder(ds_gfs, ds_base_regrid, 'temperature_2m_above_ground') ds_gfs_regrid = gfs_regridder(ds_gfs) ds_gfs_regrid = ds_gfs_regrid.where(ds_gfs_regrid['temperature_2m_above_g...
_____no_output_____
MIT
notebooks/Regrid.ipynb
kallisons/kaggle_ds4g_emissions_factor
Add in weather
ds_gldas = xr.open_dataset('/Users/kasmith/Code/kaggle_ds4g/data/starter_pack/gldas/gldas_1year.nc') ds_gldas = ds_gldas.drop('crs') gldas_regridder = make_regridder(ds_gldas, ds_base_regrid, 'Tair_f_inst', 'nearest_s2d') ds_gldas_regrid = gldas_regridder(ds_gldas) ds_gldas_regrid = ds_gldas_regrid.where(ds_gldas_regr...
_____no_output_____
MIT
notebooks/Regrid.ipynb
kallisons/kaggle_ds4g_emissions_factor
Add in night time lights
ds_nightlights = xr.open_dataset('/Users/kasmith/Code/kaggle_ds4g/data/supplementary_data/nc/VIIRS_nighttime_lights.nc') ds_nightlights2 = ds_nightlights.drop('crs') nl_regridder = make_regridder(ds_nightlights2, ds_base_regrid, 'avg_rad') ds_nl_regrid = nl_regridder(ds_nightlights2) ds_nl_regrid = ds_nl_regrid.where(...
_____no_output_____
MIT
notebooks/Regrid.ipynb
kallisons/kaggle_ds4g_emissions_factor
Add in population
ds_population = xr.open_dataset('/Users/kasmith/Code/kaggle_ds4g/data/supplementary_data/nc/GPWv411_populationdensity.nc') ds_population = ds_population.drop('crs') pop_regridder = make_regridder(ds_population, ds_base_regrid, 'population_density') ds_pop_regrid = pop_regridder(ds_population) ds_pop_regrid = ds_pop_reg...
_____no_output_____
MIT
notebooks/Regrid.ipynb
kallisons/kaggle_ds4g_emissions_factor
Add in landcover
ds_landcover = xr.open_dataset('/Users/kasmith/Code/kaggle_ds4g/data/supplementary_data/nc/GFSAD1000_landcover.nc') ds_landcover = ds_landcover.drop('crs') land_regridder = make_regridder(ds_landcover, ds_base_regrid, 'landcover_category', 'nearest_s2d') ds_land_regrid = land_regridder(ds_landcover) ds_land_regrid.coo...
_____no_output_____
MIT
notebooks/Regrid.ipynb
kallisons/kaggle_ds4g_emissions_factor
Add power plants layer
plants = pd.read_csv('../data/starter_pack/gppd/gppd_120_pr.csv') plants = plants[['capacity_mw', 'estimated_generation_gwh', 'primary_fuel', '.geo']] coordinates = pd.json_normalize(plants['.geo'].apply(json.loads))['coordinates'] plants[['longitude', 'latitude']] = pd.DataFrame(coordinates.values.tolist(), index= coo...
_____no_output_____
MIT
notebooks/Regrid.ipynb
kallisons/kaggle_ds4g_emissions_factor
Calculate Annual Average NO2
ds_base_annual = ds_base.where((ds_base.wind_speed_mean <= 2)).mean(dim=['time']) ds_base_annual_n = ds_base.where((ds_base.wind_speed_mean <= 2)).count(dim=['time']) ax = plt.axes(projection=ccrs.LambertConformal(central_longitude=-65, central_latitude=18)) ds_base_annual['NO2_column_number_density'].where((ds_base_an...
_____no_output_____
MIT
notebooks/Regrid.ipynb
kallisons/kaggle_ds4g_emissions_factor
Calculate monthly average NO2
ds_base_monthly = ds_base.where((ds_base.wind_speed_mean <= 5)).resample(time='1M').mean() ax = plt.axes(projection=ccrs.LambertConformal(central_longitude=-65, central_latitude=18)) ds_base_monthly['NO2_column_number_density'].isel(time=6).where(ds_base_monthly.land_mask == 1).plot(ax=ax, transform=ccrs.PlateCarree())...
_____no_output_____
MIT
notebooks/Regrid.ipynb
kallisons/kaggle_ds4g_emissions_factor
Peform statistical analyses of GNSS station locations and tropospheric zenith delays**Author**: Simran Sangha, David Bekaert - Jet Propulsion LaboratoryThis notebook provides an overview of the functionality included in the **`raiderStats.py`** program. Specifically, we outline examples on how to perform basic statist...
import os import numpy as np import matplotlib.pyplot as plt ## Defining the home and data directories tutorial_home_dir = os.path.abspath(os.getcwd()) work_dir = os.path.abspath(os.getcwd()) print("Tutorial directory: ", tutorial_home_dir) print("Work directory: ", work_dir) # Verifying if RAiDER is installed correc...
_____no_output_____
Apache-2.0
notebooks/raiderStats/raiderStats_tutorial.ipynb
jlmaurer/RAiDER-docs
Overview of the raiderStats.py program The **`raiderStats.py`** program provides a suite of convinient statistical analyses of GNSS station locations and tropospheric zenith delays.Running **`raiderStats.py`** with the **`-h`** option will show the parameter options and outline several basic, practical examples. Let u...
!raiderStats.py -h
_____no_output_____
Apache-2.0
notebooks/raiderStats/raiderStats_tutorial.ipynb
jlmaurer/RAiDER-docs
1. Basic user input options Input CSV file (**`--file FNAME`**) **REQUIRED** argument. Provide a valid CSV file as input through **`--file`** which lists the GNSS station IDs (ID), lat/lon coordinates (Lat,Lon), dates in YYYY-MM-DD format (Date), and the desired data field in units of meters.Note that the complementa...
!raiderDownloadGNSS.py --out products --date 20160101 20191231 --returntime '00:00:00' --bounding_box '36 40 -124 -119' --cpus all
_____no_output_____
Apache-2.0
notebooks/raiderStats/raiderStats_tutorial.ipynb
jlmaurer/RAiDER-docs
All of the extracted tropospheric zenith delay information stored under **`GPS_delays`** is concatenated with the GNSS station location information stored under **`gnssStationList_overbbox.csv`** into a primary comprehensive file **`UNRcombinedGPS_ztd.csv`****`UNRcombinedGPS_ztd.csv`** may in turn be directly used to p...
!raiderStats.py --file products/UNRcombinedGPS_ztd.csv --workdir maps_ex1 --bounding_box '36 40 -124 -119' --timeinterval '2016-01-01 2020-12-31' --station_distribution --station_delay_mean --station_delay_stdev
_____no_output_____
Apache-2.0
notebooks/raiderStats/raiderStats_tutorial.ipynb
jlmaurer/RAiDER-docs
Now we can take a look at the generated products:
!ls maps_ex1/figures
_____no_output_____
Apache-2.0
notebooks/raiderStats/raiderStats_tutorial.ipynb
jlmaurer/RAiDER-docs
Here we visualize the spatial distribution of stations (*ZTD_station_distribution.png*) as black markers.To generate this figure alone, run:```!raiderStats.py --file products/UNRcombinedGPS_ztd.csv --workdir maps_ex1 --bounding_box '36 40 -124 -119' --timeinterval '2016-01-01 2020-12-31' --station_distribution``` Here ...
!raiderStats.py --file products/UNRcombinedGPS_ztd.csv --workdir maps_ex2 --bounding_box '36 40 -124 -119' --timeinterval '2016-01-01 2020-12-31' --grid_heatmap --grid_delay_mean --grid_delay_stdev --grid_to_raster --cpus all
_____no_output_____
Apache-2.0
notebooks/raiderStats/raiderStats_tutorial.ipynb
jlmaurer/RAiDER-docs
Now we can take a look at the generated rasters (i.e. the TIF files in the specified output directory):
!ls maps_ex2
_____no_output_____
Apache-2.0
notebooks/raiderStats/raiderStats_tutorial.ipynb
jlmaurer/RAiDER-docs
Now we can take a look at the generated plots:
!ls maps_ex2/figures
_____no_output_____
Apache-2.0
notebooks/raiderStats/raiderStats_tutorial.ipynb
jlmaurer/RAiDER-docs
Here we visualize the heatmap of gridded station array (*ZTD_grid_heatmap.png*) with a **`hot`** colorbar.Note that the colorbar bounds are saturated, which demonstrates the utility of plotting options outlined under section 7 such as **`--color_bounds`** and **`--colorpercentile`**To generate this figure alone, run:``...
!raiderStats.py --file maps_ex2/ZTD_grid_heatmap.tif --workdir maps_ex2a --color_bounds '10 40'
_____no_output_____
Apache-2.0
notebooks/raiderStats/raiderStats_tutorial.ipynb
jlmaurer/RAiDER-docs
Here we visualize the replotted heatmap of gridded station array (*ZTD_grid_heatmap.png*) with a **`hot`** colorbar. Example 3. Generate gridded mean tropospheric zenith delay plot, with stations superimposed Produce plot illustrating gridded mean tropospheric zenith delay, superimposed with individual station locati...
!raiderStats.py --file products/UNRcombinedGPS_ztd.csv --workdir maps_ex3 --bounding_box '36 40 -124 -119' --timeinterval '2016-01-01 2020-12-31' --seasonalinterval '03-21 06-21' --grid_delay_mean --stationsongrids --cpus all
_____no_output_____
Apache-2.0
notebooks/raiderStats/raiderStats_tutorial.ipynb
jlmaurer/RAiDER-docs
Now we can take a look at the generated plot:
!ls maps_ex3/figures
_____no_output_____
Apache-2.0
notebooks/raiderStats/raiderStats_tutorial.ipynb
jlmaurer/RAiDER-docs
Here we visualize the gridded mean tropospheric zenith delay (*ZTD_grid_delay_mean.png*) with a **`hot`** colorbar, with superimposed station locations denoted by blue markers. Example 4. Generate variogram plots Produce plots illustrating empirical/experimental variogram fits per gridded station and time-slice (**`-...
!raiderStats.py --file products/UNRcombinedGPS_ztd.csv --workdir maps_ex4 --bounding_box '36 40 -124 -119' --timeinterval '2016-01-01 2020-12-31' --seasonalinterval '03-21 06-21' --variogramplot --variogram_per_timeslice --grid_to_raster --cpus all
_____no_output_____
Apache-2.0
notebooks/raiderStats/raiderStats_tutorial.ipynb
jlmaurer/RAiDER-docs
Now we can take a look at the generated variograms:
!ls maps_ex4/variograms
_____no_output_____
Apache-2.0
notebooks/raiderStats/raiderStats_tutorial.ipynb
jlmaurer/RAiDER-docs
There are several subdirectories corresponding to each grid-cell that each contain empirical and experimental variograms generated for each time-slice (e.g. **`grid6_timeslice20160321_justEMPvariogram.eps `** and **`grid6_timeslice20160321_justEXPvariogram.eps `**, respectively) and across the entire sampled time perio...
!head maps_ex4/variograms/gridlocation_lookup.txt
_____no_output_____
Apache-2.0
notebooks/raiderStats/raiderStats_tutorial.ipynb
jlmaurer/RAiDER-docs
Now we can take a look at the other generated figures:
!ls maps_ex4/figures
_____no_output_____
Apache-2.0
notebooks/raiderStats/raiderStats_tutorial.ipynb
jlmaurer/RAiDER-docs
Here we visualize the gridded experimental variogram range (*ZTD_grid_range.png*) with a **`hot`** colorbar. Here we visualize the gridded experimental variogram variance (*ZTD_grid_variance.png*) with a **`hot`** colorbar. Example 5. Generate seasonal phase/amplitude plots Produce plots illustrating seasonal phase/a...
!raiderStats.py --file products/UNRcombinedGPS_ztd.csv --workdir maps_ex5 --bounding_box '36 40 -124 -119' --grid_seasonal_phase --station_seasonal_phase --min_span 3 0.6 --phaseamp_per_station --grid_to_raster --cpus all
_____no_output_____
Apache-2.0
notebooks/raiderStats/raiderStats_tutorial.ipynb
jlmaurer/RAiDER-docs
Now we can take a look at the generated rasters (i.e. the TIF files in the specified output directory):
!ls maps_ex5
_____no_output_____
Apache-2.0
notebooks/raiderStats/raiderStats_tutorial.ipynb
jlmaurer/RAiDER-docs
Now we can take a look at the generated debug figures illustrating the curve-fits vs data (**`--phaseamp_per_station`**):
!ls maps_ex5/phaseamp_per_station
_____no_output_____
Apache-2.0
notebooks/raiderStats/raiderStats_tutorial.ipynb
jlmaurer/RAiDER-docs
Here we visualize the time-series and curve-fit corresponding for one of the stations.
!ls maps_ex5/figures
_____no_output_____
Apache-2.0
notebooks/raiderStats/raiderStats_tutorial.ipynb
jlmaurer/RAiDER-docs
Now we can take a look at the generated plots: Here we visualize the seasonal phase of tropospheric zenith delay by station (*ZTD_station_seasonal_phase.png*) with a **`hot`** colorbar. Here we visualize the gridded mean of the station-wise seasonal phase of tropospheric zenith delay (*ZTD_grid_seasonal_phase.png*) wit...
!raiderDownloadGNSS.py --out GNSS_2019 --date 20190101 20191231 12 --returntime '00:00:00' --bounding_box '36 40 -124 -119' --cpus 12
_____no_output_____
Apache-2.0
notebooks/raiderStats/raiderStats_tutorial.ipynb
jlmaurer/RAiDER-docs
Compute tropospheric zenith delay from the GMAO weather-model for the year '2019', for every 12 days, at a UTC time of day 'HH:MM:SS' of '00:00:00', at stations located across a geographic bounding box '36 40 -124 -119' spanning over Northern California and captured in the `GNSS_2019/gnssStationList_overbbox.csv` list ...
!mkdir GMAO_2019 !cd GMAO_2019 !raiderDelay.py --model GMAO --date 20190101 20191231 12 --time 00:00 --station_file ../GNSS_2019/gnssStationList_overbbox.csv --zref 30000 -v !cd ../
_____no_output_____
Apache-2.0
notebooks/raiderStats/raiderStats_tutorial.ipynb
jlmaurer/RAiDER-docs
Combine delay files derived above from the GMAO weather-model (`--raider 'GMAO_2019/GMAO_Delay_*.csv' --raiderDir GMAO_2019 --raider_column totalDelay`) and GNSS stations (`GNSS_2019/UNRcombinedGPS_ztd.csv --column ZTD`) respectively, passing only data which are collocated in space and time.
!raiderCombine.py --gnss GNSS_2019/UNRcombinedGPS_ztd.csv --column ZTD --raider 'GMAO_2019/GMAO_Delay_*.csv' --raiderDir GMAO_2019 --raider_column totalDelay --out Combined_delays_GNSSandGMAO_2019.csv
_____no_output_____
Apache-2.0
notebooks/raiderStats/raiderStats_tutorial.ipynb
jlmaurer/RAiDER-docs
Using the file **`Combined_delays_GNSSandGMAO_2019.csv`** generated by **`raiderCombine.py`** as input and passing the weather-model/GNSS residual values (`--column_name ZTD_minus_RAiDER`), produce plots illustrating mean tropospheric zenith delay by station + across each grid-cell, and standard deviation of tropospher...
!raiderStats.py --file Combined_delays_GNSSandGMAO_2019.csv --column_name ZTD_minus_RAiDER --workdir maps_ex6 --bounding_box '36 40 -124 -119' --station_delay_mean --station_delay_stdev --grid_delay_mean --grid_delay_stdev --grid_to_raster --cpus all
_____no_output_____
Apache-2.0
notebooks/raiderStats/raiderStats_tutorial.ipynb
jlmaurer/RAiDER-docs
SMC for logistic regressionWe compare data tempering (IBIS) with temperature tempering.Code is from https://github.com/nchopin/particles/blob/master/book/smc_samplers/logistic_reg.py
!git clone https://github.com/nchopin/particles.git %cd /content/particles !pip install --user . import particles import particles.state_space_models as ssm import particles.distributions as dists """ Numerical experiment of Chapter 17 (SMC samplers). Compare IBIS and SMC tempering for approximating: * the normalising ...
_____no_output_____
MIT
notebooks/smc_logreg_tempering.ipynb
susnato/probml-notebooks
* basic roberta ft: 0.6589791487657798 (thr 0.3)* basic roberta ft (head first): 0.6768011808573329 (thr 0.42)* fine tune roberta on weird clf, then only head on spans, then whole: 0.6853127403287083 (thr 0.32)*
from transformers import RobertaTokenizer, RobertaForTokenClassification from transformers import BertTokenizer, BertForTokenClassification from transformers import AutoTokenizer, AutoModelForTokenClassification import torch import numpy as np import pandas as pd import os os.environ['CUDA_VISIBLE_DEVICES'] = '4' devic...
_____no_output_____
Apache-2.0
semeval2021/bert-multitask-reproduce.ipynb
skoltech-nlp/toxic-span-detection
```inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")labels = torch.tensor([1] * inputs["input_ids"].size(1)).unsqueeze(0) Batch size 1outputs = model(**inputs, labels=labels)``` Create labels for tagging
import os import numpy as np import pandas as pd from ast import literal_eval import re import nltk import matplotlib.pyplot as plt from nltk.tokenize import word_tokenize path = 'data/' trial = pd.read_csv(path + 'tsd_trial.csv') train = pd.read_csv(path + 'tsd_train.csv') # final_test = pd.read_csv(path + 'tsd_test....
_____no_output_____
Apache-2.0
semeval2021/bert-multitask-reproduce.ipynb
skoltech-nlp/toxic-span-detection
Dataset for classification
import pandas as pd df1 = pd.read_csv('../data/train/train.1.tsv', sep='\t') df0 = pd.read_csv('../data/train/train_small.0.tsv', sep='\t') df01 = pd.concat([df1, df0], ignore_index=True) df01.label = df01.label.astype(int) print(df01.shape) df01.sample(3) from sklearn.model_selection import train_test_split df_train, ...
_____no_output_____
Apache-2.0
semeval2021/bert-multitask-reproduce.ipynb
skoltech-nlp/toxic-span-detection
Train a single-task model https://github.com/huggingface/notebooks/blob/master/examples/token_classification.ipynbhttps://huggingface.co/transformers/custom_datasets.html
from transformers import Trainer, TrainingArguments, EarlyStoppingCallback from transformers.file_utils import cached_property from typing import Tuple class TrAr(TrainingArguments): @cached_property def _setup_devices(self): return device torch.cuda.set_device(device) model = AutoModelForTokenClassifi...
_____no_output_____
Apache-2.0
semeval2021/bert-multitask-reproduce.ipynb
skoltech-nlp/toxic-span-detection
* The minimal loss of a single-task model (full) was about 28% on validation with 0.04 on train. * If we first train only head (batch 8, lr 1e-3 with 3K warmup and 1e-8 decline), we get minimal loss of 0.185 on validation with 0.23 on train* Training then the whole model (batch 8, lr 1e-5 with 3K warmup and 1e-8 declin...
trainer.train() model.save_pretrained('./models2/roberta_single') trainer.evaluate()
_____no_output_____
Apache-2.0
semeval2021/bert-multitask-reproduce.ipynb
skoltech-nlp/toxic-span-detection
evaluate
pred = trainer.predict(eval_dataset) for threshold in [0, 0.01, 0.03, 0.1, 0.3, 0.4, 0.5, 0.6, 0.7, 1]: preds = [] for text, pr in zip(trial.text, pred.predictions): proba = np.exp(pr[pr[:, 0]!=-100]) proba /= proba.sum(axis=1, keepdims=True) labels = (proba[:, 1] >= threshold).astype(in...
0.3 0.6691954194658056 0.32 0.6719575974133731 0.35 0.6718814105545576 0.38 0.6704494596966453 0.4 0.6734060063813712 0.42 0.6733924519991911 0.45 0.675073109186953 0.5 0.6728307956631072 0.55 0.6635405099600963 0.6 0.652604453261445
Apache-2.0
semeval2021/bert-multitask-reproduce.ipynb
skoltech-nlp/toxic-span-detection
Prepare a submission
pred = trainer.predict(final_test_dataset) threshold = 0.4 preds = [] for text, pr in zip(final_test.text, pred.predictions): proba = np.exp(pr[pr[:, 0]!=-100]) proba /= proba.sum(axis=1, keepdims=True) labels = (proba[:, 1] >= threshold).astype(int).tolist() preds.append(labels2spans(text, labels, toke...
_____no_output_____
Apache-2.0
semeval2021/bert-multitask-reproduce.ipynb
skoltech-nlp/toxic-span-detection
65.31%
print(np.mean([f1(p, y) for p, y in zip(preds, final_test.spans)]))
0.6631491659944739
Apache-2.0
semeval2021/bert-multitask-reproduce.ipynb
skoltech-nlp/toxic-span-detection
WM Classifier + tagging
from transformers import RobertaTokenizer, RobertaForTokenClassification, RobertaForSequenceClassification from transformers import BertTokenizer, BertForTokenClassification from transformers import AutoTokenizer, AutoModelForTokenClassification import torch from transformers.models.roberta.modeling_roberta import Robe...
_____no_output_____
Apache-2.0
semeval2021/bert-multitask-reproduce.ipynb
skoltech-nlp/toxic-span-detection
The strategy: first tune the head only with large batches and LR, then tune the whole model. Head-only stops at loss 0.4185, full model - at loss 0.302685
for param in model.roberta.parameters(): param.requires_grad = False NEW_MODEL_NAME = './models2/roberta_clf_wm' training_args = TrAr( output_dir=NEW_MODEL_NAME, # output directory overwrite_output_dir=True, num_train_epochs=10, # total # of training epochs per_device_train_batch_size=8...
_____no_output_____
Apache-2.0
semeval2021/bert-multitask-reproduce.ipynb
skoltech-nlp/toxic-span-detection
Fine tune the averager classifier
model = AutoModelForTokenClassification.from_pretrained('./models2/roberta_clf_wm') NEW_MODEL_NAME = './models2/roberta_clf_wm_ft' for param in model.roberta.parameters(): param.requires_grad = False training_args = TrAr( output_dir=NEW_MODEL_NAME, # output directory overwrite_output_dir=True, num_tra...
_____no_output_____
Apache-2.0
semeval2021/bert-multitask-reproduce.ipynb
skoltech-nlp/toxic-span-detection
* the raw quasi-classifier: no use in the model at all* fine tuned head: still no use, the best score is 0.2138* fine tune whole model: 0.3 0.6849391042415774
for param in model.parameters(): param.requires_grad = True training_args = TrAr( output_dir=NEW_MODEL_NAME, # output directory overwrite_output_dir=True, num_train_epochs=10, # total # of training epochs per_device_train_batch_size=8, # batch size per device during training per_de...
_____no_output_____
Apache-2.0
semeval2021/bert-multitask-reproduce.ipynb
skoltech-nlp/toxic-span-detection
* The minimal loss of a single-task model (full) was about 28% on validation with 0.04 on train. * If we first train only head (batch 8, lr 1e-3 with 3K warmup and 1e-8 decline), we get minimal loss of 0.185 on validation with 0.23 on train* Training then the whole model (batch 8, lr 1e-5 with 3K warmup and 1e-8 declin...
trainer.train() NEW_MODEL_NAME model.save_pretrained(NEW_MODEL_NAME) pred = trainer.predict(eval_dataset) for threshold in [0, 0.01, 0.03, 0.1, 0.25, 0.3, 0.35, 0.4, 0.5, 0.6, 0.7, 1]: preds = [] for text, pr in zip(trial.text, pred.predictions): proba = np.exp(pr[pr[:, 0]!=-100]) proba /= proba...
0.6503622193673821
Apache-2.0
semeval2021/bert-multitask-reproduce.ipynb
skoltech-nlp/toxic-span-detection
Try to reproduce the score of an ordinary classifier fine tuned as tagger ```* roberta_clf_proba - roberta classifier with wm head* roberta_clf_ft_plus_pseudolabels - roberta_clf_ft + pseudolabels fine-tuning on data/train/train.1.tsv* roberta_clf - preliminary form of roberta_clf_proba* roberta_clf_ft - ...
model = RobertaForTokenClassification.from_pretrained('models/roberta_ft_v2') model.to(device); training_args = TrAr( output_dir='tmp', per_device_eval_batch_size=8, ) trainer = Trainer( model=model, args=training_args, data_collator=data_collator, toke...
0.1 0.5545336665297276 0.15 0.5882344110328829 0.2 0.6077757811791716 0.25 0.622973609210159 0.3 0.633958561050074 0.35 0.6443207294927615 0.4 0.6519269346134431 0.45 0.6589416029476445 0.5 0.6639145447542181 0.55 0.6676402819948017 0.6 0.6695941122804318 0.65 0.6756992752387653 0.7 0.6785258499047722 0.75 0.6851208918...
Apache-2.0
semeval2021/bert-multitask-reproduce.ipynb
skoltech-nlp/toxic-span-detection
roberta_clf_ft
model = RobertaForTokenClassification.from_pretrained('models/roberta_clf_ft') model.to(device); training_args = TrAr( output_dir='tmp', per_device_eval_batch_size=8, ) trainer = Trainer( model=model, args=training_args, data_collator=data_collator, tok...
0.1 0.5752439183819529 0.15 0.6090082887908743 0.2 0.6286550876155881 0.25 0.6431153729750709 0.3 0.6569361916626016 0.35 0.6647910078957441 0.4 0.6682952103234534 0.45 0.6754628567024429 0.5 0.680619717437095 0.55 0.6809661485870909 0.6 0.6832488454134622 0.65 0.6797076042739688 0.7 0.6773883276721572 0.75 0.668369614...
Apache-2.0
semeval2021/bert-multitask-reproduce.ipynb
skoltech-nlp/toxic-span-detection
roberta_clf_ft_plus_pseudolabels
model = RobertaForTokenClassification.from_pretrained('models/roberta_clf_ft_plus_pseudolabels') model.to(device); training_args = TrAr( output_dir='tmp', per_device_eval_batch_size=8, ) trainer = Trainer( model=model, args=training_args, data_collator=data...
0.1 0.5602049029090154 0.15 0.5965378234529369 0.2 0.6161116736335367 0.25 0.6329899472598364 0.3 0.6458124347386611 0.35 0.6555907203988778 0.4 0.6620672594740299 0.45 0.6692636447522394 0.5 0.674174837442134 0.55 0.6786709542304435 0.6 0.6819797727432348 0.65 0.6816887377159155 0.7 0.6820785225830176 0.75 0.680704093...
Apache-2.0
semeval2021/bert-multitask-reproduce.ipynb
skoltech-nlp/toxic-span-detection
roberta_single_v2
model = RobertaForTokenClassification.from_pretrained('models/roberta_single_v2') model.to(device); training_args = TrAr( output_dir='tmp', per_device_eval_batch_size=8, ) trainer = Trainer( model=model, args=training_args, data_collator=data_collator, ...
0.682, 0.7, 0.668, 0.678 0.682, 0.7, 0.674, 0.682 0.686, 0.8, 0.664, 0.670 0.683, 0.6, 0.681, 0.683
Apache-2.0
semeval2021/bert-multitask-reproduce.ipynb
skoltech-nlp/toxic-span-detection
standard deviation of score
threshold = 0.5 preds = [] for text, pr in zip(final_test.text, pred.predictions): proba = np.exp(pr[pr[:, 0]!=-100]) proba /= proba.sum(axis=1, keepdims=True) labels = (proba[:, 1] >= threshold).astype(int).tolist() preds.append(labels2spans(text, labels, tokenizer)) ff = [f1(p, y) for p, y in zip(pred...
_____no_output_____
Apache-2.0
semeval2021/bert-multitask-reproduce.ipynb
skoltech-nlp/toxic-span-detection
Predicting Credit Card Default with Neural Networks
import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import os %matplotlib inline
_____no_output_____
MIT
Chapter6/ch6-2-classification-with-neural-networks.ipynb
PacktPublishing/-Hands-On-Predictive-Analytics-with-Python
Back with the credit card default dataset
# Loading the dataset DATA_DIR = '../data' FILE_NAME = 'credit_card_default.csv' data_path = os.path.join(DATA_DIR, FILE_NAME) ccd = pd.read_csv(data_path, index_col="ID") ccd.rename(columns=lambda x: x.lower(), inplace=True) ccd.rename(columns={'default payment next month':'default'}, inplace=True) # getting the grou...
_____no_output_____
MIT
Chapter6/ch6-2-classification-with-neural-networks.ipynb
PacktPublishing/-Hands-On-Predictive-Analytics-with-Python
Split and standarize the dataset
numerical_features = numerical_features + ['months_delayed'] binary_features = ['male','married','grad_school','university'] X = ccd[numerical_features + binary_features] y = ccd['default'].astype(int) ## Split from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, ...
C:\Users\direc\Anaconda3\envs\mybook\lib\site-packages\pandas\core\indexing.py:543: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/index...
MIT
Chapter6/ch6-2-classification-with-neural-networks.ipynb
PacktPublishing/-Hands-On-Predictive-Analytics-with-Python
Building the neural network for classification
from keras.models import Sequential nn_classifier = Sequential() from keras.layers import Dense n_input = X_train.shape[1] n_units_hidden = 64 nn_classifier.add(Dense(units=n_units_hidden, activation='relu', input_shape=(n_input,))) # add 2nd hidden layer nn_classifier.add(Dense(units=n_units_hidden, activation='relu')...
_____no_output_____
MIT
Chapter6/ch6-2-classification-with-neural-networks.ipynb
PacktPublishing/-Hands-On-Predictive-Analytics-with-Python
Training the network
## compiling step nn_classifier.compile(loss='binary_crossentropy', optimizer='adam') nn_classifier.summary() nn_classifier.save_weights('class_initial_w.h5') batch_size = 64 n_epochs = 150 nn_classifier.fit(X_train, y_train, epochs=n_epochs, batch_size=batch_size)
Epoch 1/150 25000/25000 [==============================] - 1s 30us/step - loss: 0.4635 Epoch 2/150 25000/25000 [==============================] - 0s 17us/step - loss: 0.4467 Epoch 3/150 25000/25000 [==============================] - 0s 15us/step - loss: 0.4432 Epoch 4/150 25000/25000 [==============================] - ...
MIT
Chapter6/ch6-2-classification-with-neural-networks.ipynb
PacktPublishing/-Hands-On-Predictive-Analytics-with-Python
Evaluating predictions
## Getting the probabilities y_pred_train_prob = nn_classifier.predict(X_train) y_pred_test_prob = nn_classifier.predict(X_test) ## Classifications from predictions y_pred_train = (y_pred_train_prob > 0.5).astype(int) y_pred_test = (y_pred_test_prob > 0.5).astype(int) from sklearn.metrics import accuracy_score train_a...
Train Accuracy: 0.923 Test Accuracy: 0.740
MIT
Chapter6/ch6-2-classification-with-neural-networks.ipynb
PacktPublishing/-Hands-On-Predictive-Analytics-with-Python
Re-training the network with less epochs
## load the initial weights nn_classifier.load_weights('class_initial_w.h5') batch_size = 64 n_epochs = 50 nn_classifier.compile(loss='binary_crossentropy', optimizer='adam') nn_classifier.fit(X_train, y_train, epochs=n_epochs, batch_size=batch_size) ## Getting the probabilities y_pred_train_prob = nn_classifier.predic...
Train Accuracy: 0.852 Test Accuracy: 0.786
MIT
Chapter6/ch6-2-classification-with-neural-networks.ipynb
PacktPublishing/-Hands-On-Predictive-Analytics-with-Python
Now we will load our stcakoverflow survery data
df = pd.read_csv('data/survey_results_public.csv', index_col = 'Respondent') schema_df = pd.read_csv('data/survey_results_schema.csv', index_col = 'Column') # Filtering data for people's salaries above/below a certain amount. # If you dont know which column in the data frame gives the salary, you can find that using sc...
_____no_output_____
MIT
Filtering.ipynb
tejasvi541/Pandas-Tutorial
WELL NOTEBOOK Well logs visualization &amp; petrophysics Install the the repository reservoirpy from github and import the required packages
import os path = os.path.join('/home/santiago/Documents/dev/reservoirpy') import sys sys.path.insert(0,path) import pandas as pd import geopandas as gpd import numpy as np import matplotlib.pyplot as plt import seaborn as sns from shapely.geometry import Point import folium from pyproj import Proj, transform, CRS, Tran...
_____no_output_____
MIT
examples/welllogs/1-basics/2-groups_wells.ipynb
scuervo91/reservoirpy
Well atributesWell atributes, name, rte, coordinates, survey
deviation = pd.read_csv('survey.csv', header=[0]) deviation.head() tops1 = ph.tops({'formation':['fm1','fm2'],'md_top':[5000,5100],'md_bottom':[5099,5145]}) tops1
_____no_output_____
MIT
examples/welllogs/1-basics/2-groups_wells.ipynb
scuervo91/reservoirpy
Create some wells
#Create the well object name1 = 'well-1' rte1 = 1515.78 # Rotary table Elevation surf_coord1 = [1000000,1000000]#Point(1000100,1000000,520) crs1 = 'EPSG:3117' tops1 = ph.tops({'formation':['fm1','fm2'],'md_top':[12000,12100],'md_bottom':[12099,12145]}) deviation1 = deviation.copy() deviation1['azi'] = deviation1['azi']...
_____no_output_____
MIT
examples/welllogs/1-basics/2-groups_wells.ipynb
scuervo91/reservoirpy
Create an empty wells groupYou can create a `wells_group` object either empty or not. It only receives `well` object.
g1 = ph.wells_group(w1)
_____no_output_____
MIT
examples/welllogs/1-basics/2-groups_wells.ipynb
scuervo91/reservoirpy
To see the list of wells call the method `wells_group.wells`. It contains a dictionary with the name of each well as the key and the `well` object as the item
g1.wells
_____no_output_____
MIT
examples/welllogs/1-basics/2-groups_wells.ipynb
scuervo91/reservoirpy
Add more wells to existing listby calling the method `wells_group.add_well()` you can add more wells to an existing group
g1.add_well(w2,w3) g1.wells
_____no_output_____
MIT
examples/welllogs/1-basics/2-groups_wells.ipynb
scuervo91/reservoirpy
Get attributes from a `wells_group`
g1.wells['well-3'].surf_coord.wkt
_____no_output_____
MIT
examples/welllogs/1-basics/2-groups_wells.ipynb
scuervo91/reservoirpy
Describe each well with its attributes
g1.describe()
_____no_output_____
MIT
examples/welllogs/1-basics/2-groups_wells.ipynb
scuervo91/reservoirpy
Wells topsGet the wells formations tops. If no parameters passed, it returns all wells and formations. You can pass `wells` and `formations` parameter to get the selected wells and formations
g1.wells_tops() g1.wells_tops(wells=['well-1','well-2'], formations=['fm1'])
_____no_output_____
MIT
examples/welllogs/1-basics/2-groups_wells.ipynb
scuervo91/reservoirpy
Wells survey
g1.wells_surveys().head() g1.wells_surveys(wells=['well-1','well-2']) g1.wells_distance(dims=['z']) dist = g1.wells_distance(wells=['well-1','well-2'],dims=['y','z','x']) dist m = g1.wells_map(zoom=13) m g1.wells_coordinates() g1.wells_tops().head() g1.formation_distance(formation='fm2') g1.formation_distance(wells=['w...
_____no_output_____
MIT
examples/welllogs/1-basics/2-groups_wells.ipynb
scuervo91/reservoirpy
Export wells survey to PyVista object vtk
w1_vtk = g1.wells['well-1'].get_vtk() w1_vtk w1_vtk.plot(notebook=False) ss=g1.wells_surveys_vtk() ss.plot(notebook=False) p=pv.Plotter(notebook=False) p.add_mesh(ss['well-1'], scalars='azi') p.add_mesh(ss['well-2'], scalars='tvdss') p.show() tops_vtk = g1.tops_vtk() tops_vtk.plot(notebook=False) str_vtk = g1.structu...
_____no_output_____
MIT
examples/welllogs/1-basics/2-groups_wells.ipynb
scuervo91/reservoirpy
** Dolby.io Developer Days Media APIs 101 - Getting Started ** ** Notebook 1: Getting Started** Starting with a Raw Audio FileWe can run code blocks like this in Binder by pressing "Control+Enter". Try it now after clicking the below code block!
import IPython # Helper library to play audio files in Python natively. # Set this link to any publically accessible media file you would like! original_audio_file = "https://dolbyio.s3-us-west-1.amazonaws.com/public/shelby/airplane.original.mp4" IPython.display.Audio(original_audio_file) # Display the audio embedded...
_____no_output_____
CC0-1.0
Workshop_Part_1.ipynb
dolbyio-samples/Workshop-Media-APIs-Getting-Started
This installed IPython to our workspace, to let us play media files natively within Python, and set a variable to this public media file we will use for the rest of this notebook. **Step 1:** Gathering Credentials- Go to http://dashboard.dolby.io/signup/ to sign up for a Dolby.io account.- At the bottom of the "Applic...
# Enter your Dolby.io Media API Key here. api_key = "<YOUR_API_KEY_HERE>" # Enter your name here to customize the output URL later. name = "<YOUR_NAME_HERE>" print("API Key and Name set!")
_____no_output_____
CC0-1.0
Workshop_Part_1.ipynb
dolbyio-samples/Workshop-Media-APIs-Getting-Started
Now we have two key variables set:1. The link to the original media file we want to process.2. Our API key so we can properly call the REST API endpoints.As well as your name, just so we can differentiate output later on. **Step 2:** Calling the Enhance Job> Note: all of the following code is adapted from the Enhance ...
import requests # Python library to make HTTP requests output_url = f"dlb://out/workshop-{name}.mp4" # Setting the output URL to have a different location based on your name! # Building the body of the request body = { "input" : original_audio_file, "output" : output_url, } # Building the headers and url of the ...
_____no_output_____
CC0-1.0
Workshop_Part_1.ipynb
dolbyio-samples/Workshop-Media-APIs-Getting-Started
**Step 3:** Checking Job Status- Now that we have created a job, we should check its status.- Run the cell below to check the status, this file is small so it should take only a couple of seconds.
url = "https://api.dolby.com/media/enhance" headers = { "x-api-key": api_key, "Content-Type": "application/json", "Accept": "application/json" } params = { "job_id": response.json()["job_id"] } response = requests.get(url, params=params, headers=headers) response.raise_for_status() print(response.json())
_____no_output_____
CC0-1.0
Workshop_Part_1.ipynb
dolbyio-samples/Workshop-Media-APIs-Getting-Started
This should look like the following when done:```json{'path': '/media/enhance', 'status': 'Success', 'progress': 100, 'api_version': 'v1.1.2', 'result': {}}``` **Step 4:** Download the Processed File- Now we want to download the file!- We can do this with another request.
import shutil # The name of the file that will be downloaded locally! output_path = f"workshop-{name}.mp4" url = "https://api.dolby.com/media/output" headers = { "x-api-key": api_key, "Content-Type": "application/json", "Accept": "application/json", } args = { "url": output_url } # Take the response...
_____no_output_____
CC0-1.0
Workshop_Part_1.ipynb
dolbyio-samples/Workshop-Media-APIs-Getting-Started
When it is done downloading, you'll see it pop up on the left side bar.Now that the file is downloaded lets give it a listen. Does it sound better?
IPython.display.Audio(output_path)
_____no_output_____
CC0-1.0
Workshop_Part_1.ipynb
dolbyio-samples/Workshop-Media-APIs-Getting-Started
Import
import matplotlib.pyplot as plt import numpy as np import pandas as pd import matplotlib matplotlib.__version__ np.__version__, pd.__version__
_____no_output_____
Apache-2.0
Notebooks/SWMat.ipynb
PuneetGrov3r/SWMat
Dataset:
from sklearn.datasets import california_housing data = california_housing.fetch_california_housing() X = data['data'] y = data['target'] columns = data['feature_names'] train_df = pd.DataFrame(X, index=np.arange(len(X)), columns=columns) train_df['target'] = y train_df.head()
_____no_output_____
Apache-2.0
Notebooks/SWMat.ipynb
PuneetGrov3r/SWMat
1) Initialize:
import sys sys.path.append('../SWMat/') from SWMat import SWMat from matplotlib.patches import Wedge, Polygon from matplotlib.collections import PatchCollection fig = plt.figure(figsize=(10, 7)) ax = plt.gca() for pos in ["right", "left", "top", "bottom"]: ax.spines[pos].set_visible(False) ax.xaxis.set_visible(Fa...
_____no_output_____
Apache-2.0
Notebooks/SWMat.ipynb
PuneetGrov3r/SWMat
CIFAR subset data First we want to view our data to check if everything is how we expect it to be. Setup
DATA_PATH = Path('data') PATH = DATA_PATH/'cifar10_dog_air' TRAIN_PATH = PATH/'train' dog_fn = list((TRAIN_PATH/'dog').iterdir())[0] dog_image = PIL.Image.open(dog_fn) dog_image.resize((256,256)) air_fn = list((TRAIN_PATH/'airplane').iterdir())[1] air_image = PIL.Image.open(air_fn) air_image.resize((256,256))
_____no_output_____
Apache-2.0
deep-learning/fastai-docs/fastai_docs-master/dev_nb/snapshot/002_images.ipynb
AadityaGupta/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
Simple Dataset/Dataloader We will build a Dataset class for our image files. A Dataset class needs to have two functions: `__len__` and `__getitem__`. Our `ImageDataset` class additionally gets image files from their respective directories and transforms them to tensors.
#export def image2np(image:Tensor)->np.ndarray: "convert from torch style `image` to numpy/matplot style" res = image.cpu().permute(1,2,0).numpy() return res[...,0] if res.shape[2]==1 else res def show_image(img:Tensor, ax:plt.Axes=None, figsize:tuple=(3,3), hide_axis:bool=True, title:Optio...
_____no_output_____
Apache-2.0
deep-learning/fastai-docs/fastai_docs-master/dev_nb/snapshot/002_images.ipynb
AadityaGupta/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
Data augmentation We are going to augment our data to increase the size of our training set with artificial images. These new images are basically "free" data that we can use in our training to help our model generalize better (reduce overfitting). Lighting We will start by changing the **brightness** and **contrast*...
#export def logit(x:Tensor)->Tensor: return -(1/x-1).log() def logit_(x:Tensor)->Tensor: return (x.reciprocal_().sub_(1)).log_().neg_() def contrast(x:Tensor, scale:float)->Tensor: return x.mul_(scale) #export FlowField = Tensor LogitTensorImage = TensorImage AffineMatrix = Tensor KWArgs = Dict[str,Any] ArgStar = Coll...
_____no_output_____
Apache-2.0
deep-learning/fastai-docs/fastai_docs-master/dev_nb/snapshot/002_images.ipynb
AadityaGupta/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
Transform class
class Transform(): _wrap=None def __init__(self, func): self.func=func def __call__(self, x, *args, **kwargs): if self._wrap: return getattr(x, self._wrap)(self.func, *args, **kwargs) else: return self.func(x, *args, **kwargs) class TfmLighting(Transform): _wrap='lighting' @Tfm...
_____no_output_____
Apache-2.0
deep-learning/fastai-docs/fastai_docs-master/dev_nb/snapshot/002_images.ipynb
AadityaGupta/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials