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 |
|---|---|---|---|---|---|
9. Export your model as a pickle file | def save_model(model, model_filepath):
"""
Save the model as a pickle file:
This procedure saves the model as a pickle file
Args: model, X set, y set
Returns:
nothing, it runs the model and it displays accuracy metrics
"""
try:
pickle.dump(model, open(model_filepat... | _____no_output_____ | CNRI-Python | notebooks/ML Pipeline Preparation.ipynb | inmaugarc/DataScience_Disaster_Response_Pipeline |
10. Use this notebook to complete `train.py`Use the template file attached in the Resources folder to write a script that runs the steps above to create a database and export a model based on a new dataset specified by the user. Refactoring | def load_data(db_file):
"""
Load data function
This method receives a database file on a path and it loads data
from that database file into a pandas datafile.
It also splits the data into X and y (X: features to work and y: labels to predict)
It returns two sets of data: X and y
... | _____no_output_____ | CNRI-Python | notebooks/ML Pipeline Preparation.ipynb | inmaugarc/DataScience_Disaster_Response_Pipeline |
And now let's try some queries to show interesting data on the html web | top_10_mes = df.iloc[:,5:].sum().sort_values(ascending=False)[0:10]
top_10_mes
top_10_mes_names = list(top_10_mes.index)
top_10_mes_names
mes_categories = df.columns[5:-1]
mes_categories
mes_categories_count = df[mes_categories].sum()
mes_categories_count
bottom_10_mes = df.iloc[:,5:].sum().sort_values()[0:10]
bottom_1... | _____no_output_____ | CNRI-Python | notebooks/ML Pipeline Preparation.ipynb | inmaugarc/DataScience_Disaster_Response_Pipeline |
AutoRec: Rating Prediction with AutoencodersAlthough the matrix factorization model achieves decent performance on the rating prediction task, it is essentially a linear model. Thus, such models are not capable of capturing complex nonlinear and intricate relationships that may be predictive of users' preferences. In ... | import mxnet as mx
from mxnet import autograd, gluon, np, npx
from mxnet.gluon import nn
from d2l import mxnet as d2l
npx.set_np() | _____no_output_____ | MIT | python/d2l-en/mxnet/chapter_recommender-systems/autorec.ipynb | rtp-aws/devpost_aws_disaster_recovery |
Implementing the ModelA typical autoencoder consists of an encoder and a decoder. The encoder projects the input to hidden representations and the decoder maps the hidden layer to the reconstruction layer. We follow this practice and create the encoder and decoder with dense layers. The activation of encoder is set to... | class AutoRec(nn.Block):
def __init__(self, num_hidden, num_users, dropout=0.05):
super(AutoRec, self).__init__()
self.encoder = nn.Dense(num_hidden, activation='sigmoid',
use_bias=True)
self.decoder = nn.Dense(num_users, use_bias=True)
self.dropout = ... | _____no_output_____ | MIT | python/d2l-en/mxnet/chapter_recommender-systems/autorec.ipynb | rtp-aws/devpost_aws_disaster_recovery |
Reimplementing the EvaluatorSince the input and output have been changed, we need to reimplement the evaluation function, while we still use RMSE as the accuracy measure. | def evaluator(network, inter_matrix, test_data, devices):
scores = []
for values in inter_matrix:
feat = gluon.utils.split_and_load(values, devices, even_split=False)
scores.extend([network(i).asnumpy() for i in feat])
recons = np.array([item for sublist in scores for item in sublist])
#... | _____no_output_____ | MIT | python/d2l-en/mxnet/chapter_recommender-systems/autorec.ipynb | rtp-aws/devpost_aws_disaster_recovery |
Training and Evaluating the ModelNow, let us train and evaluate AutoRec on the MovieLens dataset. We can clearly see that the test RMSE is lower than the matrix factorization model, confirming the effectiveness of neural networks in the rating prediction task. | devices = d2l.try_all_gpus()
# Load the MovieLens 100K dataset
df, num_users, num_items = d2l.read_data_ml100k()
train_data, test_data = d2l.split_data_ml100k(df, num_users, num_items)
_, _, _, train_inter_mat = d2l.load_data_ml100k(train_data, num_users,
num_items)
_, _,... | train loss 0.000, test RMSE 0.898
34453968.4 examples/sec on [gpu(0), gpu(1)]
| MIT | python/d2l-en/mxnet/chapter_recommender-systems/autorec.ipynb | rtp-aws/devpost_aws_disaster_recovery |
4 Trajectory Analysis *** ** Important Note **Before proceeding to the rest of the analysis, it is a good time to define a path that points to the location of the MD simulation data, which we will analyze here.If you successfully ran the MD simulation, the correct path should be: | path="OxCompBio-Datafiles/run" | _____no_output_____ | BSD-3-Clause | tutorials/MD/04_Trajectory_Analysis_Solutions.ipynb | AfroditiMariaZaki/OxCompBio |
If however, you need/want to use the data from the simulation that has been already performed, uncomment the command below to instead define the path that points to the prerun simulation. | #path="OxCompBio-Datafiles/prerun/run" | _____no_output_____ | BSD-3-Clause | tutorials/MD/04_Trajectory_Analysis_Solutions.ipynb | AfroditiMariaZaki/OxCompBio |
4.1 Visualize the simulation The simplest and easiest type of analysis you should always do is to look at it with your eyes! Your eyes will tell you if something strange is happening immediately. A numerical analysis may not. 4.1.1 VMD *Note: Again, this step is optional. If you don't have VMD, go to section 4.1.2 ... | # Import MDAnalysis and NGLView
import MDAnalysis
import nglview
# Load the protein structure and the trajectory as a universe named protein
protein=MDAnalysis.Universe(f"{path}/em.gro", f"{path}/md_fit.xtc")
protein_view = nglview.show_mdanalysis(protein)
protein_view.gui_style = 'ngl'
#Color the protein based on it... | _____no_output_____ | BSD-3-Clause | tutorials/MD/04_Trajectory_Analysis_Solutions.ipynb | AfroditiMariaZaki/OxCompBio |
**Questions** * How would you say the protein behaves? * Is it doing anything unexpected? What would you consider unexpected behaviour? Now that we are sure the simulation is not doing anything ridiculous, we can start to ask questions about the simulation. The first thing to establish is whether the simulation has ... | # We declare matplotlib inline to make sure it plots properly
%matplotlib inline
# We need to import numpy
import numpy as np
# We need pyplot from matplotlib to generate our plots
from matplotlib import pyplot | _____no_output_____ | BSD-3-Clause | tutorials/MD/04_Trajectory_Analysis_Solutions.ipynb | AfroditiMariaZaki/OxCompBio |
Now, using numpy, we can read the data from the `1hsg_temperature.xvg` file; the first column is the time (in ps) and the secong is the system temperature (in K). | # Read the file that contains the system temperature for each frame
time=np.loadtxt(f"{path}/1hsg_temperature.xvg", comments=['#','@'])[:, 0]
temperature=np.loadtxt(f"{path}/1hsg_temperature.xvg", comments=['#','@'])[:, 1] | _____no_output_____ | BSD-3-Clause | tutorials/MD/04_Trajectory_Analysis_Solutions.ipynb | AfroditiMariaZaki/OxCompBio |
You can use numpy again to compute the average temperature and its standard deviation. | # Calculate and print the mean temperature and the standard deviation
# Keep only two decimal points
mean_temperature=round(np.mean(temperature), 2)
std_temperature=round(np.std(temperature), 2)
print(f"The mean temperature is {mean_temperature} ± {std_temperature} K") | The mean temperature is 300.01 ± 1.79 K
| BSD-3-Clause | tutorials/MD/04_Trajectory_Analysis_Solutions.ipynb | AfroditiMariaZaki/OxCompBio |
Finally, you can plot the temperature *vs* simulation time. | # Plot the temperature
pyplot.plot(time, temperature, color='darkred')
pyplot.title("Temperature over time")
pyplot.xlabel("Time [ps]")
pyplot.ylabel("Temperature [K]")
pyplot.show() | _____no_output_____ | BSD-3-Clause | tutorials/MD/04_Trajectory_Analysis_Solutions.ipynb | AfroditiMariaZaki/OxCompBio |
4.2.2 Energy of the system Another set of properties that is quite useful to examine is the various energetic contributions to the energy. The totalenergy should be constant. but the various contributions can change and this can sometimes indicate somethinginteresting or strange happening in your simulation. Let us ... | # Read the file that contains the various energetic components for each frame
time=np.loadtxt(f"{path}/1hsg_energies.xvg", comments=['#','@'])[:, 0]
lennard_jones=np.loadtxt(f"{path}/1hsg_energies.xvg", comments=['#','@'])[:, 1]
coulomb=np.loadtxt(f"{path}/1hsg_energies.xvg", comments=['#','@'])[:, 2]
potential=np.load... | _____no_output_____ | BSD-3-Clause | tutorials/MD/04_Trajectory_Analysis_Solutions.ipynb | AfroditiMariaZaki/OxCompBio |
And now that we read the data file, we can plot the energetic components *vs* simulation time in separate plots using matplotlib. | # Plot the Lennard-Jones energy
pyplot.plot(time, lennard_jones, color='blue')
pyplot.title("Lennard Jones energy over time")
pyplot.xlabel("Time [ps]")
pyplot.ylabel("LJ energy [kJ/mol]")
pyplot.show()
# Plot the electrostatic energy
pyplot.plot(time, coulomb, color='purple')
pyplot.title("Electrostatic energy over t... | _____no_output_____ | BSD-3-Clause | tutorials/MD/04_Trajectory_Analysis_Solutions.ipynb | AfroditiMariaZaki/OxCompBio |
**Questions** * Can you plot the Coulomb energy and the potential energy, following the same steps as above? * Is the total energy stable in this simulation? * What is the dominant contribution to the potential energy? 4.3 Analysis of Protein 4.3.1 Root mean square deviation (RMSD) of 1HSG The RMSD gives us an i... | # Import built-in MDAnalysis tools for alignment and RMSD.
from MDAnalysis.analysis import align
from MDAnalysis.analysis.rms import RMSD as rmsd
# Define the simulation universe and the reference structure (protein structure at first frame)
protein = MDAnalysis.Universe(f"{path}/md.gro", f"{path}/md_fit.xtc")
protein... | _____no_output_____ | BSD-3-Clause | tutorials/MD/04_Trajectory_Analysis_Solutions.ipynb | AfroditiMariaZaki/OxCompBio |
**Questions** * What does this tell you about the stability of the protein? Is it in a state of equilibrium and if so why and at what time?* Can you think of a situation where this approach might not be a very good indication of stability? 4.3.2 Root mean square fluctuation (RMSF) of 1HSG A similar property that i... | from MDAnalysis.analysis.rms import RMSF as rmsf
# Define again the simulation universe, using however the renumbered .gro file that you had generated earlier
protein = MDAnalysis.Universe(f"{path}/em.gro", f"{path}/md_fit.xtc")
# Reset the trajectory to the first frame
protein.trajectory[0]
# We will need to select... | _____no_output_____ | BSD-3-Clause | tutorials/MD/04_Trajectory_Analysis_Solutions.ipynb | AfroditiMariaZaki/OxCompBio |
**Questions** * Can you identify structural regions alone from this plot and does that fit in with the structure?* Residues 43-58 form part of the flexible flap that covers the binding site. How does this region behave in the simulation? 4.3.3 Hydrogen Bond Formation We can also use the simulation to monitor the f... | # Import the MDAnalysis built-in tool for HB Analysis
from MDAnalysis.analysis.hydrogenbonds.hbond_analysis import HydrogenBondAnalysis as HBA
# Define the protein universe
# Note that when using this tool, it is recommended to include the .tpr file instead of the .gro file,
# because it contains bond information, req... | /home/mjkikaz2/anaconda3/envs/oxpy/lib/python3.6/site-packages/MDAnalysis/core/topologyattrs.py:2011: VisibleDeprecationWarning: Creating an ndarray from ragged nested sequences (which is a list-or-tuple of lists-or-tuples-or ndarrays with different lengths or shapes) is deprecated. If you meant to do this, you must sp... | BSD-3-Clause | tutorials/MD/04_Trajectory_Analysis_Solutions.ipynb | AfroditiMariaZaki/OxCompBio |
Automatic generation of Notebook using PyCropML This notebook implements a crop model. Model Cumulttfrom | model_cumulttfrom <- function (calendarMoments_t1 = c('Sowing'),
calendarCumuls_t1 = c(0.0),
cumulTT = 8.0){
#'- Name: CumulTTFrom -Version: 1.0, -Time step: 1
#'- Description:
#' * Title: CumulTTFrom Model
#' * Author: Pierre Martre
#' * Reference:... | _____no_output_____ | MIT | test/Models/pheno_pkg/test/r/Cumulttfrom.ipynb | cyrillemidingoyi/PyCropML |
Store Item Demand Forecasting Challenge Benchmark ModelsLink to competition on Kaggle.In this notebook, two simple benchmarking techniques are presented. | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
pd.options.display.max_columns = 99
plt.rcParams['figure.figsize'] = (16, 9) | _____no_output_____ | MIT | StoreItemDemand/BenchmarkModels.ipynb | AidanCooper/Kaggle |
Load Data | df_train = pd.read_csv('data/train.csv', parse_dates=['date'], index_col=['date'])
df_test = pd.read_csv('data/test.csv', parse_dates=['date'], index_col=['date'])
df_train.shape, df_test.shape
df_train.head()
num_stores = len(df_train['store'].unique())
fig, axes = plt.subplots(num_stores, figsize=(8, 16))
for s in d... | _____no_output_____ | MIT | StoreItemDemand/BenchmarkModels.ipynb | AidanCooper/Kaggle |
All stores appear to show identical trends and seasonality; they just differ in scale. Average MethodFor our first and simplest model, we make our predictions using the average value from the historical data. For our first and simplest model, we make our predictions using the average value from the historical data. | am_results = df_test.copy()
am_results['sales'] = 0
for s in am_results['store'].unique():
for i in am_results['item'].unique():
historical_average = df_train.loc[(df_train['store'] == s) & (df_train['item'] == i), 'sales'].mean()
am_results.loc[(am_results['store'] == s) & (am_results['item'] == i... | _____no_output_____ | MIT | StoreItemDemand/BenchmarkModels.ipynb | AidanCooper/Kaggle |
Scores 28.35111 on the leaderboard. Seasonal Naive MethodFor this model, we predict the value from the same time the previous year. | snm_results = df_test.copy()
snm_results['sales'] = 0
import datetime
prev_dates = snm_results.loc[(snm_results['store'] == 1) & (snm_results['item'] == 1)].index - datetime.timedelta(days=365)
for s in snm_results['store'].unique():
for i in snm_results['item'].unique():
snm_results.loc[(snm_results['stor... | _____no_output_____ | MIT | StoreItemDemand/BenchmarkModels.ipynb | AidanCooper/Kaggle |
Tutorial 2: Hidden Markov Model**Week 3, Day 2: Hidden Dynamics****By Neuromatch Academy**__Content creators:__ Yicheng Fei with help from Jesse Livezey and Xaq Pitkow__Content reviewers:__ John Butler, Matt Krause, Meenakshi Khosla, Spiros Chavlis, Michael Waskom__Production editor:__ Ella Batty Tutorial ob... | # @title Video 1: Introduction
from ipywidgets import widgets
out2 = widgets.Output()
with out2:
from IPython.display import IFrame
class BiliVideo(IFrame):
def __init__(self, id, page=1, width=400, height=300, **kwargs):
self.id=id
src = 'https://player.bilibili.com/player.html?bvid={0}&... | _____no_output_____ | CC-BY-4.0 | tutorials/W3D2_HiddenDynamics/student/W3D2_Tutorial2.ipynb | Beilinson/course-content |
Setup | # Imports
import numpy as np
import time
from scipy import stats
from scipy.optimize import linear_sum_assignment
from collections import namedtuple
import matplotlib.pyplot as plt
from matplotlib import patches
#@title Figure Settings
# import ipywidgets as widgets # interactive display
from IPython.html impor... | _____no_output_____ | CC-BY-4.0 | tutorials/W3D2_HiddenDynamics/student/W3D2_Tutorial2.ipynb | Beilinson/course-content |
--- Section 1: Binary HMM with Gaussian measurementsIn contrast to last tutorial, the latent state in an HMM is not fixed, but may switch to a different state at each time step. The time dependence is simple: the probability of the state at time $t$ is wholely determined by the state at time $t-1$. This is called calle... | # @title Video 2: Binary HMM with Gaussian measurements
from ipywidgets import widgets
out2 = widgets.Output()
with out2:
from IPython.display import IFrame
class BiliVideo(IFrame):
def __init__(self, id, page=1, width=400, height=300, **kwargs):
self.id=id
src = 'https://player.bilibili.... | _____no_output_____ | CC-BY-4.0 | tutorials/W3D2_HiddenDynamics/student/W3D2_Tutorial2.ipynb | Beilinson/course-content |
Coding Exercise 1.1: Simulate a binary HMM with Gaussian measurementsIn this exercise, you will implement a binary HMM with Gaussian measurements. Your HMM will start in State +1 and transition between states (both $-1 \rightarrow 1$ and $1 \rightarrow -1$) with probability `switch_prob`. Each state emits measurements... | GaussianHMM1D = namedtuple('GaussianHMM1D', ['startprob', 'transmat','means','vars','n_components'])
def create_HMM(switch_prob=0.1, noise_level=1e-1, startprob=[1.0, 0.0]):
"""Create an HMM with binary state variable and 1D Gaussian measurements
The probability to switch to the other state is `switch_prob`. Two
... | _____no_output_____ | CC-BY-4.0 | tutorials/W3D2_HiddenDynamics/student/W3D2_Tutorial2.ipynb | Beilinson/course-content |
[*Click for solution*](https://github.com/NeuromatchAcademy/course-content/tree/master//tutorials/W3D2_HiddenDynamics/solutions/W3D2_Tutorial2_Solution_76573dcd.py) You should see that the first five measurements are: `[-3.09355908 1.58552915 -3.93502804 -1.98819072 -1.32506947]` while the first five states are: `[0 ... | #@title
#@markdown Execute this cell to enable the widget!
nstep = 100
@widgets.interact
def plot_samples_widget(
switch_prob=widgets.FloatSlider(min=0.0, max=1.0, step=0.02, value=0.1),
log10_noise_level=widgets.FloatSlider(min=-1., max=1., step=.01, value=-0.3),
flag_m=widgets.Checkbox(value=False, des... | _____no_output_____ | CC-BY-4.0 | tutorials/W3D2_HiddenDynamics/student/W3D2_Tutorial2.ipynb | Beilinson/course-content |
[*Click for solution*](https://github.com/NeuromatchAcademy/course-content/tree/master//tutorials/W3D2_HiddenDynamics/solutions/W3D2_Tutorial2_Solution_507ce9e9.py) | # @title Video 3: Section 1 Exercises Discussion
from ipywidgets import widgets
out2 = widgets.Output()
with out2:
from IPython.display import IFrame
class BiliVideo(IFrame):
def __init__(self, id, page=1, width=400, height=300, **kwargs):
self.id=id
src = 'https://player.bilibili.com/pla... | _____no_output_____ | CC-BY-4.0 | tutorials/W3D2_HiddenDynamics/student/W3D2_Tutorial2.ipynb | Beilinson/course-content |
**Applications**. Measurements could be:* fish caught at different times as the school of fish moves from left to right* membrane voltage when an ion channel changes between open and closed* EEG frequency measurements as the brain moves between sleep statesWhat phenomena can you imagine modeling with these HMMs? ---- S... | # @title Video 4: Forgetting in a changing world
from ipywidgets import widgets
out2 = widgets.Output()
with out2:
from IPython.display import IFrame
class BiliVideo(IFrame):
def __init__(self, id, page=1, width=400, height=300, **kwargs):
self.id=id
src = 'https://player.bilibili.com/pla... | _____no_output_____ | CC-BY-4.0 | tutorials/W3D2_HiddenDynamics/student/W3D2_Tutorial2.ipynb | Beilinson/course-content |
Interactive Demo 2.1: Forgetting in a changing worldEven if we know the world state for sure, the world changes. We become less and less certain as time goes by since our last measurement. In this exercise, we'll see how a Hidden Markov Model gradually "forgets" the current state when predicting the future without mea... | # @markdown Execute this cell to enable helper function `simulate_prediction_only`
def simulate_prediction_only(model, nstep):
"""
Simulate the diffusion of HMM with no observations
Args:
model (GaussianHMM1D instance): the HMM instance
nstep (int): total number of time steps to simulate(include initial... | _____no_output_____ | CC-BY-4.0 | tutorials/W3D2_HiddenDynamics/student/W3D2_Tutorial2.ipynb | Beilinson/course-content |
[*Click for solution*](https://github.com/NeuromatchAcademy/course-content/tree/master//tutorials/W3D2_HiddenDynamics/solutions/W3D2_Tutorial2_Solution_8357dee2.py) | # @title Video 5: Section 2 Exercise Discussion
from ipywidgets import widgets
out2 = widgets.Output()
with out2:
from IPython.display import IFrame
class BiliVideo(IFrame):
def __init__(self, id, page=1, width=400, height=300, **kwargs):
self.id=id
src = 'https://player.bilibili.com/play... | _____no_output_____ | CC-BY-4.0 | tutorials/W3D2_HiddenDynamics/student/W3D2_Tutorial2.ipynb | Beilinson/course-content |
Section 3: Forward inference in an HMM*Estimated timing to here from start of tutorial: 35 min* | # @title Video 6: Inference in an HMM
from ipywidgets import widgets
out2 = widgets.Output()
with out2:
from IPython.display import IFrame
class BiliVideo(IFrame):
def __init__(self, id, page=1, width=400, height=300, **kwargs):
self.id=id
src = 'https://player.bilibili.com/player.html?bv... | _____no_output_____ | CC-BY-4.0 | tutorials/W3D2_HiddenDynamics/student/W3D2_Tutorial2.ipynb | Beilinson/course-content |
Coding Exercise 3.1: Forward inference of HMMAs a recursive algorithm, let's assume we already have yesterday's posterior from time $t-1$: $p(s_{t-1}|m_{1:t-1})$. When the new data $m_{t}$ comes in, the algorithm performs the following steps:* **Predict**: transform yesterday's posterior over $s_{t-1}$ into today's pr... | # @markdown Execute to enable helper functions `compute_likelihood` and `simulate_forward_inference`
def compute_likelihood(model, M):
"""
Calculate likelihood of seeing data `M` for all measurement models
Args:
model (GaussianHMM1D): HMM
M (float or numpy vector)
Returns:
L (numpy vector or matr... | _____no_output_____ | CC-BY-4.0 | tutorials/W3D2_HiddenDynamics/student/W3D2_Tutorial2.ipynb | Beilinson/course-content |
[*Click for solution*](https://github.com/NeuromatchAcademy/course-content/tree/master//tutorials/W3D2_HiddenDynamics/solutions/W3D2_Tutorial2_Solution_69ce2879.py)*Example output:* Interactive Demo 3.2: Forward inference in binary HMMNow visualize your inference algorithm. Play with the sliders and checkboxes to help... | # @markdown Execute this cell to enable the demo
nstep = 100
@widgets.interact
def plot_forward_inference_widget(
switch_prob=widgets.FloatSlider(min=0.0, max=1.0, step=0.01, value=0.05),
log10_noise_level=widgets.FloatSlider(min=-1., max=1., step=.01, value=0.1),
t=widgets.IntSlider(min=0, max=nstep-1, s... | _____no_output_____ | CC-BY-4.0 | tutorials/W3D2_HiddenDynamics/student/W3D2_Tutorial2.ipynb | Beilinson/course-content |
A tutorial for the whitebox Python packageThis notebook demonstrates the usage of the **whitebox** Python package for geospatial analysis, which is built on a stand-alone executable command-line program called [WhiteboxTools](https://github.com/jblindsay/whitebox-tools).* Authors: Dr. John Lindsay (https://jblindsay.g... | import whitebox
wbt = whitebox.WhiteboxTools() | _____no_output_____ | MIT | examples/whitebox.ipynb | MarceloClaro/whitebox-python |
**Prints the whitebox-tools help...a listing of available commands** | print(wbt.help()) | WhiteboxTools Help
The following commands are recognized:
--cd, --wd Changes the working directory; used in conjunction with --run flag.
-h, --help Prints help information.
-l, --license Prints the whitebox-tools license.
--listtools Lists all available tools. Keywords may also be used, --listtools... | MIT | examples/whitebox.ipynb | MarceloClaro/whitebox-python |
**Prints the whitebox-tools license** | print(wbt.license()) | WhiteboxTools License
Copyright 2017-2019 John Lindsay
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
associated documentation files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, pub... | MIT | examples/whitebox.ipynb | MarceloClaro/whitebox-python |
**Prints the whitebox-tools version** | print("Version information: {}".format(wbt.version())) | Version information: WhiteboxTools v1.0.0 by Dr. John B. Lindsay (c) 2017-2019
WhiteboxTools is an advanced geospatial data analysis platform developed at
the University of Guelph's Geomorphometry and Hydrogeomatics Research
Group (GHRG). See https://jblindsay.github.io/ghrg/WhiteboxTools/index.html
for more details.... | MIT | examples/whitebox.ipynb | MarceloClaro/whitebox-python |
**Print the help for a specific tool.** | print(wbt.tool_help("ElevPercentile")) | ElevPercentile
Description:
Calculates the elevation percentile raster from a DEM.
Toolbox: Geomorphometric Analysis
Parameters:
Flag Description
----------------- -----------
-i, --input, --dem Input raster DEM file.
-o, --output Output raster file.
--filterx Size of the filter kernel in... | MIT | examples/whitebox.ipynb | MarceloClaro/whitebox-python |
**Tool names in the whitebox Python package can be called either using the snake_case or CamelCase convention (e.g. lidar_info or LidarInfo). The example below uses snake_case.** | import os, pkg_resources
# identify the sample data directory of the package
data_dir = os.path.dirname(pkg_resources.resource_filename("whitebox", 'testdata/'))
# set whitebox working directory
wbt.set_working_dir(data_dir)
wbt.verbose = False
# call whiteboxtools
wbt.feature_preserving_smoothing("DEM.tif", "smooth... | _____no_output_____ | MIT | examples/whitebox.ipynb | MarceloClaro/whitebox-python |
**You can search tools using keywords. For example, the script below searches and lists tools with 'lidar' or 'LAS' in tool name or description.** | lidar_tools = wbt.list_tools(['lidar', 'LAS'])
for index, tool in enumerate(lidar_tools):
print("{} {}: {} ...".format(str(index+1).zfill(3), tool, lidar_tools[tool][:45])) | 001 classify_overlap_points: Classifies or filters LAS points in regions o ...
002 clip_lidar_to_polygon: Clips a LiDAR point cloud to a vector polygon ...
003 erase_polygon_from_lidar: Erases (cuts out) a vector polygon or polygon ...
004 filter_lidar_classes: Removes points in a LAS file with certain spe ...
005 filt... | MIT | examples/whitebox.ipynb | MarceloClaro/whitebox-python |
**List all available tools in whitebox-tools**. Currently, **whitebox** contains 372 tools. More tools will be added as they become available. | all_tools = wbt.list_tools()
for index, tool in enumerate(all_tools):
print("{} {}: {} ...".format(str(index+1).zfill(3), tool, all_tools[tool][:45])) | 001 absolute_value: Calculates the absolute value of every cell i ...
002 adaptive_filter: Performs an adaptive filter on an image. ...
003 add: Performs an addition operation on two rasters ...
004 add_point_coordinates_to_table: Modifies the attribute table of a point vecto ...
005 aggregate_raster: Aggregates a rast... | MIT | examples/whitebox.ipynb | MarceloClaro/whitebox-python |
Getting data This section demonstrates two ways to get data into Binder so that you can test **whitebox** on the cloud using your own data. * [Getting data from direct URLs](Getting-data-from-direct-URLs) * [Getting data from Google Drive](Getting-data-from-Google-Drive) Getting data from direct URLsIf you have data ... | import os
import zipfile
import tarfile
import shutil
import urllib.request | _____no_output_____ | MIT | examples/whitebox.ipynb | MarceloClaro/whitebox-python |
Create a folder named *whitebox* under the user home folder and set it as the working directory. | work_dir = os.path.join(os.path.expanduser("~"), 'whitebox')
if not os.path.exists(work_dir):
os.mkdir(work_dir)
os.chdir(work_dir)
print("Working directory: {}".format(work_dir)) | Working directory: /home/qiusheng/whitebox
| MIT | examples/whitebox.ipynb | MarceloClaro/whitebox-python |
Replace the following URL with your own direct URL hosting your data. | url = "https://github.com/giswqs/whitebox/raw/master/examples/testdata.zip" | _____no_output_____ | MIT | examples/whitebox.ipynb | MarceloClaro/whitebox-python |
Download data the from the above URL and unzip the file if needed. | # download the file
zip_name = os.path.basename(url)
zip_path = os.path.join(work_dir, zip_name)
print('Downloading {} ...'.format(zip_name))
urllib.request.urlretrieve(url, zip_path)
print('Downloading done.'.format(zip_name))
# if it is a zip file
if '.zip' in zip_name:
print("Decompressing {} ...... | Downloading testdata.zip ...
Downloading done.
Decompressing testdata.zip ...
Decompressing done.
Data directory: /home/qiusheng/whitebox/testdata
| MIT | examples/whitebox.ipynb | MarceloClaro/whitebox-python |
You have successfully downloaded data to Binder. Therefore, you can skip to [Using whitebox](Using-whitebox) and start testing whitebox with your own data. Getting data from Google DriveAlternatively, you can upload data to [Google Drive](https://www.google.com/drive/) and then [share files publicly from Google Drive... | gfile_url = 'https://drive.google.com/file/d/1xgxMLRh_jOLRNq-f3T_LXAaSuv9g_JnV' | _____no_output_____ | MIT | examples/whitebox.ipynb | MarceloClaro/whitebox-python |
**Extract the file id from the above URL.** | file_id = gfile_url.split('/')[5] #'1xgxMLRh_jOLRNq-f3T_LXAaSuv9g_JnV'
print('Google Drive file id: {}'.format(file_id)) | Google Drive file id: 1xgxMLRh_jOLRNq-f3T_LXAaSuv9g_JnV
| MIT | examples/whitebox.ipynb | MarceloClaro/whitebox-python |
**Download the shared file from Google Drive.** | from google_drive_downloader import GoogleDriveDownloader as gdd
dest_path = './testdata.zip' # choose a name for the downloaded file
gdd.download_file_from_google_drive(file_id, dest_path, unzip=True) | _____no_output_____ | MIT | examples/whitebox.ipynb | MarceloClaro/whitebox-python |
You have successfully downloaded data from Google Drive to Binder. You can now continue to [Using whitebox](Using-whitebox) and start testing whitebox with your own data. Using whitebox Here you can specify where your data are located. In this example, we will use [DEM.tif](https://github.com/giswqs/whitebox/blob/mas... | data_dir = './testdata/'
print(os.listdir(data_dir)) | ['breached_sink.tif', 'DEM.dep', 'smoothed.tif', 'DEM.tif.aux.xml', 'DEM.tif', 'breached_sink.tif.aux.xml']
| MIT | examples/whitebox.ipynb | MarceloClaro/whitebox-python |
In this simple example, we smooth [DEM.tif](https://github.com/giswqs/whitebox/blob/master/examples/testdata/DEM.tif) using a [feature preserving denoising](https://github.com/jblindsay/whitebox-tools/blob/master/src/tools/terrain_analysis/feature_preserving_denoise.rs) algorithm. Then, we fill depressions in the DEM u... | import whitebox
wbt = whitebox.WhiteboxTools()
# set whitebox working directory
wbt.set_working_dir(data_dir)
wbt.verbose = False
# call whiteboxtool
wbt.feature_preserving_smoothing("DEM.tif", "smoothed.tif", filter=9)
wbt.breach_depressions("smoothed.tif", "breached.tif")
wbt.d_inf_flow_accumulation("breached.tif", ... | _____no_output_____ | MIT | examples/whitebox.ipynb | MarceloClaro/whitebox-python |
Displaying resultsThis section demonstrates how to display images on Jupyter Notebook. Three Python packages are used here, including [matplotlib](https://matplotlib.org/), [imageio](https://imageio.readthedocs.io/en/stable/installation.html), and [tifffile](https://pypi.org/project/tifffile/). These three packages ca... | # comment out the third line (%matplotlib inline) if you run the tutorial in other IDEs other than Jupyter Notebook
import matplotlib.pyplot as plt
import imageio
%matplotlib inline | _____no_output_____ | MIT | examples/whitebox.ipynb | MarceloClaro/whitebox-python |
**Display one single image.** | raster = imageio.imread(os.path.join(data_dir, 'DEM.tif'))
plt.imshow(raster)
plt.show() | _____no_output_____ | MIT | examples/whitebox.ipynb | MarceloClaro/whitebox-python |
**Read images as numpy arrays.** | original = imageio.imread(os.path.join(data_dir, 'DEM.tif'))
smoothed = imageio.imread(os.path.join(data_dir, 'smoothed.tif'))
breached = imageio.imread(os.path.join(data_dir, 'breached.tif'))
flow_accum = imageio.imread(os.path.join(data_dir, 'flow_accum.tif')) | _____no_output_____ | MIT | examples/whitebox.ipynb | MarceloClaro/whitebox-python |
**Display multiple images in one plot.** | fig=plt.figure(figsize=(16,11))
ax1 = fig.add_subplot(2, 2, 1)
ax1.set_title('Original DEM')
plt.imshow(original)
ax2 = fig.add_subplot(2, 2, 2)
ax2.set_title('Smoothed DEM')
plt.imshow(smoothed)
ax3 = fig.add_subplot(2, 2, 3)
ax3.set_title('Breached DEM')
plt.imshow(breached)
ax4 = fig.add_subplot(2, 2, 4)
ax4.set... | _____no_output_____ | MIT | examples/whitebox.ipynb | MarceloClaro/whitebox-python |
Dictionaries in Python Welcome! This notebook will teach you about the dictionaries in the Python Programming Language. By the end of this lab, you'll know the basics dictionary operations in Python, including what it is, and the operations on it. Table of Contents Dictiona... | # Create the dictionary
Dict = {"key1": 1, "key2": "2", "key3": [3, 3, 3], "key4": (4, 4, 4), ('key5'): 5, (0, 1): 6}
Dict | _____no_output_____ | MIT | Dictionaries.ipynb | niksom406/IBM-Python-for-Data-Science |
The keys can be strings: | # Access to the value by the key
Dict["key1"] | _____no_output_____ | MIT | Dictionaries.ipynb | niksom406/IBM-Python-for-Data-Science |
Keys can also be any immutable object such as a tuple: | # Access to the value by the key
Dict[(0, 1)] | _____no_output_____ | MIT | Dictionaries.ipynb | niksom406/IBM-Python-for-Data-Science |
Each key is separated from its value by a colon ":". Commas separate the items, and the whole dictionary is enclosed in curly braces. An empty dictionary without any items is written with just two curly braces, like this "{}". | # Create a sample dictionary
release_year_dict = {"Thriller": "1982", "Back in Black": "1980", \
"The Dark Side of the Moon": "1973", "The Bodyguard": "1992", \
"Bat Out of Hell": "1977", "Their Greatest Hits (1971-1975)": "1976", \
"Saturday Night Fever": "1... | _____no_output_____ | MIT | Dictionaries.ipynb | niksom406/IBM-Python-for-Data-Science |
In summary, like a list, a dictionary holds a sequence of elements. Each element is represented by a key and its corresponding value. Dictionaries are created with two curly braces containing keys and values separated by a colon. For every key, there can only be one single value, however, multiple keys can hold the sa... | # Get value by keys
release_year_dict['Thriller'] | _____no_output_____ | MIT | Dictionaries.ipynb | niksom406/IBM-Python-for-Data-Science |
This corresponds to: Similarly for The Bodyguard | # Get value by key
release_year_dict['The Bodyguard'] | _____no_output_____ | MIT | Dictionaries.ipynb | niksom406/IBM-Python-for-Data-Science |
Now let you retrieve the keys of the dictionary using the method release_year_dict(): | # Get all the keys in dictionary
release_year_dict.keys() | _____no_output_____ | MIT | Dictionaries.ipynb | niksom406/IBM-Python-for-Data-Science |
You can retrieve the values using the method values(): | # Get all the values in dictionary
release_year_dict.values() | _____no_output_____ | MIT | Dictionaries.ipynb | niksom406/IBM-Python-for-Data-Science |
We can add an entry: | # Append value with key into dictionary
release_year_dict['Graduation'] = '2007'
release_year_dict | _____no_output_____ | MIT | Dictionaries.ipynb | niksom406/IBM-Python-for-Data-Science |
We can delete an entry: | # Delete entries by key
del(release_year_dict['Thriller'])
del(release_year_dict['Graduation'])
release_year_dict | _____no_output_____ | MIT | Dictionaries.ipynb | niksom406/IBM-Python-for-Data-Science |
We can verify if an element is in the dictionary: | # Verify the key is in the dictionary
'The Bodyguard' in release_year_dict | _____no_output_____ | MIT | Dictionaries.ipynb | niksom406/IBM-Python-for-Data-Science |
Quiz on Dictionaries You will need this dictionary for the next two questions: | # Question sample dictionary
soundtrack_dic = {"The Bodyguard":"1992", "Saturday Night Fever":"1977"}
soundtrack_dic | _____no_output_____ | MIT | Dictionaries.ipynb | niksom406/IBM-Python-for-Data-Science |
a) In the dictionary soundtrack_dict what are the keys ? | # Write your code below and press Shift+Enter to execute
soundtrack_dic = {"The Bodyguard":"1992", "Saturday Night Fever":"1977"}
soundtrack_dic.keys()
| _____no_output_____ | MIT | Dictionaries.ipynb | niksom406/IBM-Python-for-Data-Science |
Double-click __here__ for the solution.<!-- Your answer is below:soundtrack_dic.keys() The Keys "The Bodyguard" and "Saturday Night Fever" --> b) In the dictionary soundtrack_dict what are the values ? | # Write your code below and press Shift+Enter to execute
soundtrack_dic.values()
| _____no_output_____ | MIT | Dictionaries.ipynb | niksom406/IBM-Python-for-Data-Science |
Double-click __here__ for the solution.<!-- Your answer is below:soundtrack_dic.values() The values are "1992" and "1977"--> You will need this dictionary for the following questions: The Albums Back in Black, The Bodyguard and Thriller have the following music recording sales in millions 50, 50 and 65 respectively: ... | # Write your code below and press Shift+Enter to execute
album_sales_dict = {'Back in Black':50,'The Bodyguard':50,'Thriller' : 65}
album_sales_dict
| _____no_output_____ | MIT | Dictionaries.ipynb | niksom406/IBM-Python-for-Data-Science |
Double-click __here__ for the solution.<!-- Your answer is below:album_sales_dict = {"The Bodyguard":50, "Back in Black":50, "Thriller":65}--> b) Use the dictionary to find the total sales of Thriller: | # Write your code below and press Shift+Enter to execute
album_sales_dict['Thriller']
| _____no_output_____ | MIT | Dictionaries.ipynb | niksom406/IBM-Python-for-Data-Science |
Double-click __here__ for the solution.<!-- Your answer is below:album_sales_dict["Thriller"]--> c) Find the names of the albums from the dictionary using the method keys: | # Write your code below and press Shift+Enter to execute
album_sales_dict.keys()
A = [1,4,'John']
A[0]
A = (1,4,'John')
A[1]
A = {1:4,'John':'x'}
A['John']
A = [1,4,'John']
A[0:2]
A[::2]
A = (1,4,'John')
A[::2]
.a | _____no_output_____ | MIT | Dictionaries.ipynb | niksom406/IBM-Python-for-Data-Science |
Double-click __here__ for the solution.<!-- Your answer is below:album_sales_dict.keys()--> d) Find the names of the recording sales from the dictionary using the method values: | # Write your code below and press Shift+Enter to execute
album_sales_dict.values() | _____no_output_____ | MIT | Dictionaries.ipynb | niksom406/IBM-Python-for-Data-Science |
gQuant TutorialFirst import all the necessary modules. | import sys; sys.path.insert(0, '..')
import os
import warnings
import ipywidgets as widgets
from gquant.dataframe_flow import TaskGraph
warnings.simplefilter("ignore") | _____no_output_____ | Apache-2.0 | notebooks/02_single_stock_trade.ipynb | philtrade/gQuant |
In this tutorial, we are going to use gQuant to do a simple quant job. The task is fully described in a yaml file | !head -n 31 ../task_example/simple_trade.yaml | - id: load_csv_data
type: CsvStockLoader
conf:
path: ./data/stock_price_hist.csv.gz
inputs: []
- id: node_assetFilter
type: AssetFilterNode
conf:
asset: 22123
inputs:
- load_csv_data
- id: node_sort
type: SortNode
conf:
keys:
- asset
- datetime
inputs:
- node_assetFi... | Apache-2.0 | notebooks/02_single_stock_trade.ipynb | philtrade/gQuant |
The yaml file is describing the computation task by a graph, we can visualize it | task_graph = TaskGraph.load_taskgraph('../task_example/simple_trade.yaml')
task_graph.draw(show='ipynb') | _____no_output_____ | Apache-2.0 | notebooks/02_single_stock_trade.ipynb | philtrade/gQuant |
We define a method to organize the output images | def plot_figures(o, symbol):
# format the figures
figure_width = '1200px'
figure_height = '400px'
bar_figure = o[2]
sharpe_number = o[0]
cum_return = o[1]
signals = o[3]
bar_figure.layout.height = figure_height
bar_figure.layout.width = figure_width
cum_return.layout.height = fi... | _____no_output_____ | Apache-2.0 | notebooks/02_single_stock_trade.ipynb | philtrade/gQuant |
We load the symbol name to symbol id mapping file: | node_stockSymbol = {"id": "node_stockSymbol",
"type": "StockNameLoader",
"conf": {"path": "./data/security_master.csv.gz"},
"inputs": []}
name_graph = TaskGraph([node_stockSymbol])
list_stocks = name_graph.run(outputs=['node_stockSymbol'])[0].to_pandas().set_i... | _____no_output_____ | Apache-2.0 | notebooks/02_single_stock_trade.ipynb | philtrade/gQuant |
Evaluate the output nodes and plot the results: | symbol = 'REXX'
action = "load" if os.path.isfile('./.cache/load_csv_data.hdf5') else "save"
o = task_graph.run(
outputs=['node_sharpeRatio', 'node_cumlativeReturn',
'node_barplot', 'node_lineplot', 'load_csv_data'],
replace={'load_csv_data': {action: True},
... | _____no_output_____ | Apache-2.0 | notebooks/02_single_stock_trade.ipynb | philtrade/gQuant |
Change the strategy parameters | o = task_graph.run(
outputs=['node_sharpeRatio', 'node_cumlativeReturn',
'node_barplot', 'node_lineplot'],
replace={'load_csv_data': {"load": cached_input},
'node_barplot': {'conf': {"points": 200}},
'node_ma_strategy': {'conf': {'fa... | _____no_output_____ | Apache-2.0 | notebooks/02_single_stock_trade.ipynb | philtrade/gQuant |
Cuaderno para cargar metadatos Este cuaderno toma un directorio de MinIO con estructura de datos abiertos y crea la definición para Hive-Metastore para cada una de las tablas Librerias | from minio import Minio
import pandas as pd
from io import StringIO
from io import BytesIO
import json
from pyhive import hive
| _____no_output_____ | Apache-2.0 | services/python-jupyter/scripts/CargaMetastore.ipynb | irvcaza/datalake4os |
Definicion de coneccion a MinIO | client = Minio(
"minio:9000",
access_key="minio",
secret_key="minio123",
secure=False
) | _____no_output_____ | Apache-2.0 | services/python-jupyter/scripts/CargaMetastore.ipynb | irvcaza/datalake4os |
Ruta al diccionario de correpondencia | #corr_file = None
corr_file = 'correspondence.json'
#corr_file = 'correspondence.csv' | _____no_output_____ | Apache-2.0 | services/python-jupyter/scripts/CargaMetastore.ipynb | irvcaza/datalake4os |
Funciones de ayuda | # Obtine el diccionario de correspondencia de un archivo
def get_corrr_dic(corr_file = None):
corr_dic = {"tables":{},"columns":{}}
if corr_file is None:
# Si se pasa None a la funcion dara un diccionario en blanco
pass
elif corr_file.endswith(".json"):
with open(corr_file, 'r') as... | _____no_output_____ | Apache-2.0 | services/python-jupyter/scripts/CargaMetastore.ipynb | irvcaza/datalake4os |
Ejemplo de ejecucionEn este ejemplo se toman los datos cargados en el cuaderno CargaObjetos.ipynb para crear las definiciones de tablas.**Nota:** En los datos a descargar hay un problema con el archivo *conjunto_de_datos_enigh_2018_ns_csv\conjunto_de_datos_poblacion_enigh_2018_ns\diccionario_de_datos\diccionario_datos... | corr_dic = get_corrr_dic(corr_file)
sqls = create_dataset_tables(client,"hive","warehouse/conjunto_de_datos_enigh_2018_ns_csv/")
sqls += create_dataset_tables(client,"hive","warehouse/conjunto_de_datos_enigh2016_nueva_serie_csv/")
sqls += create_dataset_tables(client,"hive","warehouse/enigh_ncv_2014_csv/")
print(sqls... | _____no_output_____ | Apache-2.0 | services/python-jupyter/scripts/CargaMetastore.ipynb | irvcaza/datalake4os |
The first step in any data analysis is acquiring and munging the dataAn example data set can be found at: https://jakecoltman.gitlab.io/website/post/pydata/Download the file output.txt and transform it into a format like below where the event column should be 0 if there's only one entry for an id, and 1 if there are ... | running_id = 0
output = [[0]]
with open("E:/output.txt") as file_open:
for row in file_open.read().split("\n"):
cols = row.split(",")
if cols[0] == output[-1][0]:
output[-1].append(cols[1])
output[-1].append(True)
else:
output.append(cols)
output = out... | Plotting alpha
Plotting beta
| MIT | Full presentation.ipynb | Journeyman08/BayesianSurvivalAnalysis |
Problems: 2 - Try to fit your data from section 1 3 - Use the results to plot the distribution of the median -------- 4 - Try adjusting the number of samples, the burn parameter and the amount of thinning to correct get good answers 5 - Try adjusting the prior and see how it affects the estimate ---... | #Solution to question 4:
def weibull_median(alpha, beta):
return beta * ((log(2)) ** ( 1 / alpha))
plt.hist([weibull_median(x[0], x[1]) for x in zip(mcmc.trace("alpha"), mcmc.trace("beta"))])
#Solution to question 4:
### Increasing the burn parameter allows us to discard results before convergence
### Thinning the ... | _____no_output_____ | MIT | Full presentation.ipynb | Journeyman08/BayesianSurvivalAnalysis |
If we want to look at covariates, we need a new approach. We'll use Cox proprtional hazards. More information here. | #Fitting solution
cf = lifelines.CoxPHFitter()
cf.fit(df, 'lifetime', event_col = 'event')
cf.summary | C:\Users\j.coltman\AppData\Local\Continuum\Anaconda3\lib\site-packages\lifelines\fitters\coxph_fitter.py:285: FutureWarning: sort(columns=....) is deprecated, use sort_values(by=.....)
df.sort(duration_col, inplace=True)
| MIT | Full presentation.ipynb | Journeyman08/BayesianSurvivalAnalysis |
Once we've fit the data, we need to do something useful with it. Try to do the following things: 1 - Plot the baseline survival function 2 - Predict the functions for a particular set of features 3 - Plot the survival function for two different set of features 4 - For your results in part 3 caculate how mu... | #Solution to 1
fig, axis = plt.subplots(nrows=1, ncols=1)
cf.baseline_survival_.plot(ax = axis, title = "Baseline Survival")
# Solution to prediction
regressors = np.array([[1,45,0,0]])
survival = cf.predict_survival_function(regressors)
survival
#Solution to plotting multiple regressors
fig, axis = plt.subplots(nrows=... | _____no_output_____ | MIT | Full presentation.ipynb | Journeyman08/BayesianSurvivalAnalysis |
Model selectionDifficult to do with classic tools (here)Problem: 1 - Calculate the BMA coefficient values 2 - Compare these results to past the lifelines results 3 - Try running with different priors |
##Solution to 1
from pyBMA import CoxPHFitter
bmaCox = pyBMA.CoxPHFitter.CoxPHFitter()
bmaCox.fit(df, "lifetime", event_col= "event", priors= [0.5]*4)
print(bmaCox.summary)
#Low probability for everything favours parsimonious models
bmaCox = pyBMA.CoxPHFitter.CoxPHFitter()
bmaCox.fit(df, "lifetime", event_col= "event"... | coef exp(coef)
age -0.000967 0.999033
brand 0.000085 1.000085
male 0.917849 2.503900
search -1.050716 0.349687
| MIT | Full presentation.ipynb | Journeyman08/BayesianSurvivalAnalysis |
Swath profile with scatter plotIt is sometimes desired to plot the geological features with the swath profile. For example, plot the glacial points coupling with the mountain range profile [(Dortch et al. 2011)](https://www.sciencedirect.com/science/article/pii/S0169555X11004120). PyOSP provides simple workflow to plo... | import pyosp
baseline = pyosp.datasets.get_path("homo_baseline.shp") # the path to baseline shapefile
raster = pyosp.datasets.get_path("homo_mount.tif") # the path to raster file
elev = pyosp.Elev_curv(baseline, raster, width=100,
min_elev=0.01,
line_stepsize=3, cross_st... | Processing: [#########################] 71 of 71 lineSteps | Apache-2.0 | docs/notebooks/swath_scatter.ipynb | PyOSP-devs/PyOSP |
Step 3. Plot the scatter with the swath profileIf we pass the points path to the method *profile_plot*, these points' distance and elevation information will be processed and plot in the same figure of swath profile. | from pyosp import point_coords
pointsPath = pyosp.datasets.get_path("checking_points.shp")
elev.profile_plot(points=pointsPath) | _____no_output_____ | Apache-2.0 | docs/notebooks/swath_scatter.ipynb | PyOSP-devs/PyOSP |
We can make some changes to the figure to make it clear. | import matplotlib.pyplot as plt
fig, ax = plt.subplots()
# Note parameter "color" means color of swath profile, "c" and additional
# parameters are passed to the Matplolib scatter function.
elev.profile_plot(ax=ax, points=pointsPath, color="navy", c="red", marker="s")
| _____no_output_____ | Apache-2.0 | docs/notebooks/swath_scatter.ipynb | PyOSP-devs/PyOSP |
Note that method *profile_plot* has addotional parameters *start* and *end*. By defining those, user can limit the distance range to be plotted.**User can offer simple values to these parameters. Also, parameters can be defined by points on baseline to indicate the starting and ending locations, as shown below.** | from pyosp import point_coords
pointsPath = pyosp.datasets.get_path("homo_start_end.shp") # the path to the points
pointsCoords = point_coords(pointsPath)
# we drew the ending points first here
elev.profile_plot(start=pointsCoords[1], end=pointsCoords[0]) | _____no_output_____ | Apache-2.0 | docs/notebooks/swath_scatter.ipynb | PyOSP-devs/PyOSP |
pip install kaggle -q
import json
token = {'username':'aljeshishe','key':'32deca82aa1c29fbaeadcce2bf470af4'}
with open('kaggle.json', 'w') as file:
json.dump(token, file)
!mkdir ~/.kaggle
!mv kaggle.json ~/.kaggle/kaggle.json
!chmod 600 ~/.kaggle/kaggle.json
!kaggle competitions download -c dogs-vs-cats
!unzip test... | _____no_output_____ | BSD-3-Clause | How_much_samples_is_enough_for_transfer_learning_same_steps_per_epoch_InceptionResNetV2.ipynb | aljeshishe/FrameworkBenchmarks | |
Scraping the Data I used the BeautifulSoup package to transform the data in the table on the Wikipedia page into pandas dataframe | import requests
website_url = requests.get('https://en.wikipedia.org/wiki/List_of_postal_codes_of_Canada:_M').text
from bs4 import BeautifulSoup
soup = BeautifulSoup(website_url,'lxml') | _____no_output_____ | MIT | Exploring-the-neighborhoods-in-Toronto.ipynb | Gabriellavoura/Coursera_Capstone |
We can observe that the tabular data is availabe in table and belongs to class="wikitable sortable", So we need to extract only table | Minha_tabela = soup.find('table',{'class':'wikitable sortable'})
print(Minha_tabela.tr.text)
headers="Postcode,Borough,Neighbourhood" | _____no_output_____ | MIT | Exploring-the-neighborhoods-in-Toronto.ipynb | Gabriellavoura/Coursera_Capstone |
Geting the values in tr and separate each td within by "," | tabela1=""
for tr in Minha_tabela.find_all('tr'):
row1=""
for tds in tr.find_all('td'):
row1=row1+","+tds.text
tabela1=tabela1+row1[1:]
print(tabela1) | M1A,Not assigned,Not assigned
M2A,Not assigned,Not assigned
M3A,North York,Parkwoods
M4A,North York,Victoria Village
M5A,Downtown Toronto,Harbourfront
M6A,North York,Lawrence Heights
M6A,North York,Lawrence Manor
M7A,Downtown Toronto,Queen's Park
M8A,Not assigned,Not assigned
M9A,Etobicoke,Islington Avenue
M1B,Scarboro... | MIT | Exploring-the-neighborhoods-in-Toronto.ipynb | Gabriellavoura/Coursera_Capstone |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.