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 |
|---|---|---|---|---|---|
As expected, this plot shows that all of the agreement metrics as well as PRMSE ranks the systems correctly since all of them are being computed against the same rater pair. Note that systems known to have better performance rank "higher". Step 3: Evaluate each systems against a different pair of ratersNow, we change... | # first let's get rater pairs within each category
rater_pairs_per_category = df_rater_metadata.groupby('rater_category')['rater_id'].apply(lambda values: itertools.combinations(values, 2))
# next let's combine all possible rater pairs across the categories
combined_rater_pairs = [f"{rater_id1}+{rater_id2}" for rater_... | _____no_output_____ | MIT | notebooks/ranking_multiple_systems.ipynb | EducationalTestingService/prmse-simulations |
Before we proceed, let's see how the different system categories are distributed across different rater pairs. | # create a dataframe from our rater pairs with h1 and h2 as the two columns
df_rater_pairs_with_categories = pd.DataFrame(data=rater_pairs_for_systems, columns=['h1', 'h2'])
# add in the system metadata
df_rater_pairs_with_categories['system_id'] = df_system_metadata['system_id']
df_rater_pairs_with_categories['syste... | _____no_output_____ | MIT | notebooks/ranking_multiple_systems.ipynb | EducationalTestingService/prmse-simulations |
As the table shows, we see that systems in different categories were evaluated against rater pairs with different level of agreement. For example, 3 out of 5 systems in "low" category were evaluated against raters with "high" agreement. At the same time for systems in "medium" category, 3 out of 5 systems were evaluate... | # initialize an empty list to hold the metric values for each system ID
metric_values_list = []
# iterate over each system ID
for system_id, rater_id1, rater_id2 in zip(df_rater_pairs_with_categories['system_id'],
df_rater_pairs_with_categories['h1'],
... | _____no_output_____ | MIT | notebooks/ranking_multiple_systems.ipynb | EducationalTestingService/prmse-simulations |
Now that we have computed the metrics, we can plot each simulated system's measured performance via each of the metrics against its known performance, as indicated by its system category. | # now create a longer version of this data frame that's more amenable to plotting
df_metrics_different_rater_pairs_with_categories_long = df_metrics_different_rater_pairs_with_categories.melt(id_vars=['system_id', 'system_category'],
... | _____no_output_____ | MIT | notebooks/ranking_multiple_systems.ipynb | EducationalTestingService/prmse-simulations |
From this plot, we can see that only PRMSE values accurately separate the systems from each other whereas the other metrics are not able to do. Next, let's plot how the different systems are ranked by each of the metrics and also compare these ranks to the ranks from the same-rater scenario. | # get the ranks for the metrics
df_ranks_different_rater_pairs = compute_ranks_from_metrics(df_metrics_different_rater_pairs_with_categories)
# and now get a longer version of this data frame that's more amenable to plotting
df_ranks_different_rater_pairs_long = df_ranks_different_rater_pairs.melt(id_vars=['system_cat... | _____no_output_____ | MIT | notebooks/ranking_multiple_systems.ipynb | EducationalTestingService/prmse-simulations |
As this plot shows, only the PRMSE metric is still able to rank the systems accurately whereas all the other metrics are not. We can also make another plot that shows a more direct comparison between $R^2$ and PRMSE. | # plot PRMSE and R2 ranks only
df_r2_prmse_ranks_long = df_all_ranks_long[df_all_ranks_long['metric'].isin(['R2', 'PRMSE'])]
ax = sns.boxplot(x='system_category',
y='rank_diff',
hue='metric',
hue_order=['R2', 'PRMSE'],
data=df_r2_prmse_ranks_long,)
ax.... | _____no_output_____ | MIT | notebooks/ranking_multiple_systems.ipynb | EducationalTestingService/prmse-simulations |
Hyperparameter tuning with Cloud ML Engine **Learning Objectives:** * Improve the accuracy of a model by hyperparameter tuning | import os
PROJECT = 'cloud-training-demos' # REPLACE WITH YOUR PROJECT ID
BUCKET = 'cloud-training-demos-ml' # REPLACE WITH YOUR BUCKET NAME
REGION = 'us-central1' # REPLACE WITH YOUR BUCKET REGION e.g. us-central1
os.environ['TFVERSION'] = '1.8' # Tensorflow version
# for bash
os.environ['PROJECT'] = PROJECT
os.envir... | _____no_output_____ | Apache-2.0 | courses/machine_learning/deepdive/05_artandscience/b_hyperparam.ipynb | cjqian/training-data-analyst |
Create command-line programIn order to submit to Cloud ML Engine, we need to create a distributed training program. Let's convert our housing example to fit that paradigm, using the Estimators API. | %%bash
rm -rf trainer
mkdir trainer
touch trainer/__init__.py
%%writefile trainer/house.py
import os
import math
import json
import shutil
import argparse
import numpy as np
import pandas as pd
import tensorflow as tf
def train(output_dir, batch_size, learning_rate):
tf.logging.set_verbosity(tf.logging.INFO)
# ... | _____no_output_____ | Apache-2.0 | courses/machine_learning/deepdive/05_artandscience/b_hyperparam.ipynb | cjqian/training-data-analyst |
Create hyperparam.yaml | %%writefile hyperparam.yaml
trainingInput:
hyperparameters:
goal: MINIMIZE
maxTrials: 5
maxParallelTrials: 1
hyperparameterMetricTag: average_loss
params:
- parameterName: batch_size
type: INTEGER
minValue: 8
maxValue: 64
scaleType: UNIT_LINEAR_SCALE
- parameterName... | _____no_output_____ | Apache-2.0 | courses/machine_learning/deepdive/05_artandscience/b_hyperparam.ipynb | cjqian/training-data-analyst |
Big Brother - Healthcare edition Building a classifier using the [fastai](https://www.fast.ai/) library | from fastai.tabular import *
#hide
path = Path('./covid19_ml_education')
df = pd.read_csv(path/'covid_ml.csv')
df.head(3) | _____no_output_____ | Unlicense | UnivAiBlog/.ipynb_checkpoints/CoVID-49-checkpoint.ipynb | hargun3045/covid19-app |
Independent variableThis is the value we want to predict | y_col = 'urgency_of_admission' | _____no_output_____ | Unlicense | UnivAiBlog/.ipynb_checkpoints/CoVID-49-checkpoint.ipynb | hargun3045/covid19-app |
Dependent variableThe values on which we can make a prediciton | cat_names = ['sex', 'cough', 'fever', 'chills', 'sore_throat', 'headache', 'fatigue']
cat_names = ['sex', 'cough', 'fever', 'headache', 'fatigue']
cont_names = ['age']
#hide
procs = [FillMissing, Categorify, Normalize]
#hide
test = TabularList.from_df(df.iloc[660:861].copy(), path = path, cat_names= cat_names, cont_nam... | _____no_output_____ | Unlicense | UnivAiBlog/.ipynb_checkpoints/CoVID-49-checkpoint.ipynb | hargun3045/covid19-app |
ModelHere we build our machine learning model that will learn from the dataset to classify between patients Using Focal Loss | import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
class FocalLoss(nn.Module):
def __init__(self, gamma=0, alpha=None, size_average=True):
super(FocalLoss, self).__init__()
self.gamma = gamma
self.alpha = alpha
if isinstance(alpha,... | /usr/local/lib/python3.7/site-packages/pandas/core/indexing.py:205: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame
See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
self._setitem_with_i... | Unlicense | UnivAiBlog/.ipynb_checkpoints/CoVID-49-checkpoint.ipynb | hargun3045/covid19-app |
Making predictionsWe've taken out a test set to see how well our model works, by making predictions on them.Interestingly, all those predicted with 'High' urgency have a common trait of absence of **chills** and **sore throat** | testdf.urgency.value_counts()
testdf.predictions.value_counts()
from sklearn.metrics import classification_report
print(classification_report(testdf.predictions, testdf.urgency, labels = ["High", "Low"]))
print(classification_report(testdf.predictions, testdf.urgency, labels = ["High", "Low"]))
testdf = pd.read_csv('pr... | _____no_output_____ | Unlicense | UnivAiBlog/.ipynb_checkpoints/CoVID-49-checkpoint.ipynb | hargun3045/covid19-app |
Profile after focal loss | import seaborn as sns
import pandas as pd
fig, ax = plt.subplots()
fig.set_size_inches(7,5)
df_cm = pd.DataFrame(cm_test, index = ['Actual Low','Actual High'],
columns = ['Predicted Low','Predicted High'])
sns.set(font_scale=1.2)
sns.heatmap(df_cm, annot=True, ax = ax)
ax.set_ylim([0,2]);
ax.set_titl... | _____no_output_____ | Unlicense | UnivAiBlog/.ipynb_checkpoints/CoVID-49-checkpoint.ipynb | hargun3045/covid19-app |
Experimental SectionTrying to figure out top | for i in range(len(testdf)):
row = testdf.iloc[i][1:]
testdf.probability.iloc[i] = round(float(learn.predict(row[1:-1])[2][0]),5)
testdf.head()
testdf.sort_values(by=['probability'],ascending = False, inplace = True)
#
cumulative lift gain
baseline model - test 20%
Cost based affection
Give kits only top 20%... | _____no_output_____ | Unlicense | UnivAiBlog/.ipynb_checkpoints/CoVID-49-checkpoint.ipynb | hargun3045/covid19-app |
Edgar Holdings The examples in this notebook demonstrate using the GremlinPython library to connect to and work with a Neptune instance. Using a Jupyter notebook in this way provides a nice way to interact with your Neptune graph database in a familiar and instantly productive environment. Connect to the Neptune Data... | !pip install --upgrade pip
!pip install futures
!pip install gremlinpython
!pip install SPARQLWrapper
!pip install tornado
!pip install tornado-httpclient-session
!pip install tornado-utils
!pip install matplotlib
!pip install numpy
!pip install pandas
!pip install networkx | Requirement already up-to-date: pip in /home/ec2-user/anaconda3/envs/python3/lib/python3.6/site-packages (19.0.3)
Requirement already satisfied: futures in /home/ec2-user/anaconda3/envs/python3/lib/python3.6/site-packages (3.1.1)
Requirement already satisfied: gremlinpython in /home/ec2-user/anaconda3/envs/python3/lib/... | MIT-0 | neptune-sagemaker/notebooks/edgar/.ipynb_checkpoints/01-edar-checkpoint.ipynb | JanuaryThomas/amazon-neptune-samples |
Establish access to our Neptune instanceBefore we can work with our graph we need to establish a connection to it. This is done using the `DriverRemoteConnection` capability as defined by Apache TinkerPop and supported by GremlinPython. The `neptune.py` helper module facilitates creating this connection.Once this cell... | from gremlin_python import statics
from gremlin_python.structure.graph import Graph
from gremlin_python.process.graph_traversal import __
from gremlin_python.process.strategies import *
from gremlin_python.driver.driver_remote_connection import DriverRemoteConnection
endpoint="wss://dbfindata.carpeooi4ov5.us-east-1.ne... | _____no_output_____ | MIT-0 | neptune-sagemaker/notebooks/edgar/.ipynb_checkpoints/01-edar-checkpoint.ipynb | JanuaryThomas/amazon-neptune-samples |
Let's find out a bit about the graphLet's start off with a simple query just to make sure our connection to Neptune is working. The queries below look at all of the vertices and edges in the graph and create two maps that show the demographic of the graph. As we are using the air routes data set, not surprisingly, the... | vertices = g.V().groupCount().by(T.label).toList()
edges = g.E().groupCount().by(T.label).toList()
print(vertices)
print(edges) | _____no_output_____ | MIT-0 | neptune-sagemaker/notebooks/edgar/.ipynb_checkpoints/01-edar-checkpoint.ipynb | JanuaryThomas/amazon-neptune-samples |
Find routes longer than 8,400 milesThe query below finds routes in the graph that are longer than 8,400 miles. This is done by examining the `dist` property of the `routes` edges in the graph. Having found some edges that meet our criteria we sort them in descending order by distance. The `where` step filters out the ... | paths = g.V().hasLabel('airport').as_('a') \
.outE('route').has('dist',gt(8400)) \
.order().by('dist',Order.decr) \
.inV() \
.where(P.lt('a')).by('code') \
.path().by('code').by('dist').by('code').toList()
for p in paths:
print(p) | _____no_output_____ | MIT-0 | neptune-sagemaker/notebooks/edgar/.ipynb_checkpoints/01-edar-checkpoint.ipynb | JanuaryThomas/amazon-neptune-samples |
Draw a Bar Chart that represents the routes we just found.One of the nice things about using Python to work with our graph is that we can take advantage of the larger Python ecosystem of libraries such as `matplotlib`, `numpy` and `pandas` to further analyze our data and represent it pictorially. So, now that we have ... | import matplotlib.pyplot as plt; plt.rcdefaults()
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
routes = list()
dist = list()
# Construct the x-axis labels by combining the airport pairs we found
# into strings with with a "-" between them. We also build a list containing
# the distance valu... | _____no_output_____ | MIT-0 | neptune-sagemaker/notebooks/edgar/.ipynb_checkpoints/01-edar-checkpoint.ipynb | JanuaryThomas/amazon-neptune-samples |
Explore the distribution of airports by continentThe next example queries the graph to find out how many airports are in each continent. The query starts by finding all vertices that are continents. Next, those vertices are grouped, which creates a map (or dict) whose keys are the continent descriptions and whose valu... | # Return a map where the keys are the continent names and the values are the
# number of airports in that continent.
m = g.V().hasLabel('continent') \
.group().by('desc').by(__.out('contains').count()) \
.order(Scope.local).by(Column.keys) \
.next()
for c,n in m.items():
print('%4d %s' %... | _____no_output_____ | MIT-0 | neptune-sagemaker/notebooks/edgar/.ipynb_checkpoints/01-edar-checkpoint.ipynb | JanuaryThomas/amazon-neptune-samples |
Draw a pie chart representing the distribution by continentRather than return the results as text like we did above, it might be nicer to display them as percentages on a pie chart. That is what the code in the next cell does. Rather than return the descriptions of the continents (their names) this time our Gremlin qu... | import matplotlib.pyplot as plt; plt.rcdefaults()
import numpy as np
# Return a map where the keys are the continent codes and the values are the
# number of airports in that continent.
m = g.V().hasLabel('continent').group().by('code').by(__.out().count()).next()
fig,pie1 = plt.subplots()
pie1.pie(m.values() \
... | _____no_output_____ | MIT-0 | neptune-sagemaker/notebooks/edgar/.ipynb_checkpoints/01-edar-checkpoint.ipynb | JanuaryThomas/amazon-neptune-samples |
Find some routes from London to San Jose and draw themOne of the nice things about connected graph data is that it lends itself nicely to visualization that people can get value from looking at. The Python `networkx` library makes it fairly easy to draw a graph. The next example takes advantage of this capability to d... | import matplotlib.pyplot as plt; plt.rcdefaults()
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import networkx as nx
# Find up to 15 routes from LHR to SJC that make one stop.
paths = g.V().has('airport','code','LHR') \
.out().out().has('code','SJC').limit(15) \
.pat... | _____no_output_____ | MIT-0 | neptune-sagemaker/notebooks/edgar/.ipynb_checkpoints/01-edar-checkpoint.ipynb | JanuaryThomas/amazon-neptune-samples |
PART 2 - Examples that use iPython GremlinThis part of the notebook contains examples that use the iPython Gremlin Jupyter extension to work with a Neptune instance using Gremlin. Configuring iPython Gremlin to work with NeptuneBefore we can start to use iPython Gremlin we need to load the Jupyter Kernel extension an... | # Create a string containing the full Web Socket path to the endpoint
# Replace <neptune-instance-name> with the name of your Neptune instance.
# which will be of the form myinstance.us-east-1.neptune.amazonaws.com
#neptune_endpoint = '<neptune-instance-name>'
neptune_endpoint = os.environ['NEPTUNE_CLUSTER_ENDPOINT']
... | _____no_output_____ | MIT-0 | neptune-sagemaker/notebooks/edgar/.ipynb_checkpoints/01-edar-checkpoint.ipynb | JanuaryThomas/amazon-neptune-samples |
Run this cell if you need to reload the Gremlin extension.Occaisionally it becomes necessary to reload the iPython Gremlin extension to make things work. Running this cell will do that for you. | # Re-load the iPython Gremlin Jupyter Kernel extension.
%reload_ext gremlin | _____no_output_____ | MIT-0 | neptune-sagemaker/notebooks/edgar/.ipynb_checkpoints/01-edar-checkpoint.ipynb | JanuaryThomas/amazon-neptune-samples |
A simple query to make sure we can connect to the graph. Find all the airports in England that are in London. Notice that when using iPython Gremlin you do not need to use a terminal step such as `next` or `toList` at the end of the query in order to get it to return results. As mentioned earlier in this post, the `%r... | %reset -f
%gremlin g.V().has('airport','region','GB-ENG') \
.has('city','London').values('desc') | _____no_output_____ | MIT-0 | neptune-sagemaker/notebooks/edgar/.ipynb_checkpoints/01-edar-checkpoint.ipynb | JanuaryThomas/amazon-neptune-samples |
You can store the results of a query in a variable just as when using Gremlin Python.The query below is the same as the previous one except that the results of running the query are stored in the variable 'places'. We can then work with that variable in our code. | %reset -f
places = %gremlin g.V().has('airport','region','GB-ENG') \
.has('city','London').values('desc')
for p in places:
print(p) | _____no_output_____ | MIT-0 | neptune-sagemaker/notebooks/edgar/.ipynb_checkpoints/01-edar-checkpoint.ipynb | JanuaryThomas/amazon-neptune-samples |
Treating entire cells as GremlinAny cell that begins with `%%gremlin` tells iPython Gremlin to treat the entire cell as Gremlin. You cannot mix Python code into these cells. | %%gremlin
g.V().has('city','London').has('region','GB-ENG').count()
| _____no_output_____ | MIT-0 | neptune-sagemaker/notebooks/edgar/.ipynb_checkpoints/01-edar-checkpoint.ipynb | JanuaryThomas/amazon-neptune-samples |
Creating a pandas data frame for experimental PF valuesWan et al. (JCTC 2020) trained a forward model on experimentally measured HDX protection factors:* 72 PF values for backbone amides of ubiquitin taken from Craig et al.* 30 (of 53) for amibackbone amides of BPTI taken from Persson et al.In this notebook we have co... | import os, sys
import numpy as np
import pandas as pd
### Ubiquitin
ubiquitin_text ="""#residue\tresnum\tln PF \\
GLN & 2 & 6.210072 \\
ILE & 3 & 13.7372227 \\
PHE & 4 & 13.4839383 \\
VAL & 5 & 13.1523661 \\
LYS & 6 & 10.6909026 \\
THR & 7 & 10.4629467 \\
LEU & 8 & 0.67005226 \\
THR & 9 & 0 \\
GLY & 10 & 3.93511792 \... | all_lnPF_values.shape (102,)
all_lnPF_values_HONGBIN.shape (102,)
6.210072 6.210071995804942
13.737222699999998 13.737222664802477
13.4839383 13.483938304573131
13.1523661 13.152366051181989
10.6909026 10.690902586771355
10.4629467 10.462946662564942
0.67005226 0.6700522620612673
0.0 0.0
3.93511792 3.9351179239268244
5... | MIT | experimental-data/create_pd.ipynb | vvoelz/HDX-forward-model |
Implementation of a Devito skew self adjoint variable density visco- acoustic isotropic modeling operator -- Correctness Testing -- This operator is contributed by Chevron Energy Technology Company (2020)This operator is based on simplfications of the systems presented in:**Self-adjoint, energy-conserving second-order... | from scipy.special import hankel2
import numpy as np
from examples.seismic import RickerSource, Receiver, TimeAxis, Model, AcquisitionGeometry
from devito import (Grid, Function, TimeFunction, SpaceDimension, Constant,
Eq, Operator, solve, configuration)
from devito.finite_differences import Deriva... | _____no_output_____ | MIT | examples/seismic/skew_self_adjoint/ssa_03_iso_correctness.ipynb | dabiged/devito |
1. Analytic response in the far fieldTest that data generated in a wholespace matches analogous analytic data away from the near field. We copy/modify the material shown in the [examples/seismic/acoustic/accuracy.ipynb](https://github.com/devitocodes/devito/blob/master/examples/seismic/acoustic/accuracy.ipynb) noteboo... | # Define the analytic response
def analytic_response(fpeak, time_axis, src_coords, rec_coords, v):
nt = time_axis.num
dt = time_axis.step
v0 = v.data[0,0]
sx, sz = src_coords[0, :]
rx, rz = rec_coords[0, :]
ntpad = 20 * (nt - 1) + 1
tmaxpad = dt * (ntpad - 1)
time_axis_pad = TimeAxis(sta... | _____no_output_____ | MIT | examples/seismic/skew_self_adjoint/ssa_03_iso_correctness.ipynb | dabiged/devito |
Reset default shapes for subsequent tests | npad = 10
fpeak = 0.010
qmin = 0.1
qmax = 500.0
tmax = 1000.0
shape = (101, 81) | _____no_output_____ | MIT | examples/seismic/skew_self_adjoint/ssa_03_iso_correctness.ipynb | dabiged/devito |
2. Modeling operator linearity test, with respect to sourceFor random vectors $s$ and $r$, prove:$$\begin{aligned}F[m]\ (\alpha\ s) &\approx \alpha\ F[m]\ s \\[5pt]F[m]^\top (\alpha\ r) &\approx \alpha\ F[m]^\top r \\[5pt]\end{aligned}$$We first test the forward operator, and in the cell below that the adjoint operato... | #NBVAL_INGNORE_OUTPUT
solver = acoustic_ssa_setup(shape=shape, dtype=dtype, space_order=8, tn=tmax)
src = solver.geometry.src
a = -1 + 2 * np.random.rand()
rec1, _, _ = solver.forward(src)
src.data[:] *= a
rec2, _, _ = solver.forward(src)
rec1.data[:] *= a
# Check receiver wavefeild linearity
# Normalize by rms of re... | Operator `IsoFwdOperator` run in 0.03 s
Operator `IsoAdjOperator` run in 0.02 s
Operator `IsoAdjOperator` run in 0.03 s
| MIT | examples/seismic/skew_self_adjoint/ssa_03_iso_correctness.ipynb | dabiged/devito |
3. Modeling operator adjoint test, with respect to sourceFor random vectors $s$ and $r$, prove:$$r \cdot F[m]\ s \approx s \cdot F[m]^\top r$$ | #NBVAL_INGNORE_OUTPUT
src1 = solver.geometry.src
rec1 = solver.geometry.rec
rec2, _, _ = solver.forward(src1)
# flip sign of receiver data for adjoint to make it interesting
rec1.data[:] = rec2.data[:]
src2, _, _ = solver.adjoint(rec1)
sum_s = np.dot(src1.data.reshape(-1), src2.data.reshape(-1))
sum_r = np.dot(rec1.d... | Operator `IsoFwdOperator` run in 0.56 s
Operator `IsoAdjOperator` run in 1.42 s
| MIT | examples/seismic/skew_self_adjoint/ssa_03_iso_correctness.ipynb | dabiged/devito |
4. Nonlinear operator linearization test, with respect to modelFor initial velocity model $m$ and random perturbation $\delta m$ prove that the $L_2$ norm error in the linearization $E(h)$ is second order (decreases quadratically) with the magnitude of the perturbation.$$E(h) = \biggl\|\ f(m+h\ \delta m) - f(m) - h\ \... | #NBVAL_INGNORE_OUTPUT
src = solver.geometry.src
# Create Functions for models and perturbation
m0 = Function(name='m0', grid=solver.model.grid, space_order=8)
mm = Function(name='mm', grid=solver.model.grid, space_order=8)
dm = Function(name='dm', grid=solver.model.grid, space_order=8)
# Background model
m0.data[:] ... | _____no_output_____ | MIT | examples/seismic/skew_self_adjoint/ssa_03_iso_correctness.ipynb | dabiged/devito |
5. Jacobian operator linearity test, with respect to modelFor initial velocity model $m$ and random vectors $\delta m$ and $\delta r$, prove:$$\begin{aligned}\nabla F[m; q]\ (\alpha\ \delta m) &\approx \alpha\ \nabla F[m; q]\ \delta m \\[5pt](\nabla F[m; q])^\top (\alpha\ \delta r) &\approx \alpha\ (\nabla F[m; q])^\t... | #NBVAL_INGNORE_OUTPUT
src0 = solver.geometry.src
m0 = Function(name='m0', grid=solver.model.grid, space_order=8)
m1 = Function(name='m1', grid=solver.model.grid, space_order=8)
m0.data[:] = 1.5
# Model perturbation, box of random values centered on middle of model
m1.data[:] = 0
size = 5
ns = 2 * size + 1
nx2, nz2 =... | Operator `IsoFwdOperator` run in 0.55 s
Operator `IsoJacobianAdjOperator` run in 0.13 s
Operator `IsoJacobianAdjOperator` run in 2.34 s
| MIT | examples/seismic/skew_self_adjoint/ssa_03_iso_correctness.ipynb | dabiged/devito |
6. Jacobian operator adjoint test, with respect to model perturbation and receiver wavefield perturbation For initial velocity model $m$ and random vectors $\delta m$ and $\delta r$, prove:$$\delta r \cdot \nabla F[m; q]\ \delta m \approx \delta m \cdot (\nabla F[m; q])^\top \delta r$$ | #NBVAL_INGNORE_OUTPUT
src0 = solver.geometry.src
m0 = Function(name='m0', grid=solver.model.grid, space_order=8)
dm1 = Function(name='dm1', grid=solver.model.grid, space_order=8)
m0.data[:] = 1.5
# Model perturbation, box of random values centered on middle of model
dm1.data[:] = 0
size = 5
ns = 2 * size + 1
nx2, nz... | Operator `IsoFwdOperator` run in 0.09 s
Operator `IsoJacobianFwdOperator` run in 4.05 s
| MIT | examples/seismic/skew_self_adjoint/ssa_03_iso_correctness.ipynb | dabiged/devito |
7. Skew symmetry for shifted derivativesEnsure for random $x_1, x_2$ that Devito shifted derivative operators $\overrightarrow{\partial_x}$ and $\overrightarrow{\partial_x}$ are skew symmetric by verifying the following dot product test.$$x_2 \cdot \left( \overrightarrow{\partial_x}\ x_1 \right) \approx -\ x_1 \cdot \... | #NBVAL_INGNORE_OUTPUT
# Make 1D grid to test derivatives
n = 101
d = 1.0
shape = (n, )
spacing = (1 / (n-1), )
origin = (0., )
extent = (d * (n-1), )
dtype = np.float64
# Initialize Devito grid and Functions for input(f1,g1) and output(f2,g2)
# Note that space_order=8 allows us to use an 8th order finite differen... | Operator `Kernel` run in 0.01 s
| MIT | examples/seismic/skew_self_adjoint/ssa_03_iso_correctness.ipynb | dabiged/devito |
Support Vector Regression (SVR) Importing the libraries | import numpy as np
import matplotlib.pyplot as plt
import pandas as pd | _____no_output_____ | MIT | Regression/Support_vector_regression.ipynb | AstitvaSharma/ML_Algorithms |
Importing the dataset | dataset = pd.read_csv('Position_Salaries.csv')
x = dataset.iloc[:, 1:-1].values
y = dataset.iloc[:, -1].values
print(x)
print(y)
y = y.reshape(len(y), 1)
print(y) | [[ 45000]
[ 50000]
[ 60000]
[ 80000]
[ 110000]
[ 150000]
[ 200000]
[ 300000]
[ 500000]
[1000000]]
| MIT | Regression/Support_vector_regression.ipynb | AstitvaSharma/ML_Algorithms |
Feature Scaling | from sklearn.preprocessing import StandardScaler
sc_x = StandardScaler()
sc_y = StandardScaler()
x = sc_x.fit_transform(x)
y = sc_y.fit_transform(y)
print(x)
print(y) | [[-0.72004253]
[-0.70243757]
[-0.66722767]
[-0.59680786]
[-0.49117815]
[-0.35033854]
[-0.17428902]
[ 0.17781001]
[ 0.88200808]
[ 2.64250325]]
| MIT | Regression/Support_vector_regression.ipynb | AstitvaSharma/ML_Algorithms |
Training the SVR model on the whole dataset | from sklearn.svm import SVR
regressor = SVR(kernel = 'rbf')
regressor.fit(x, y) | /usr/local/lib/python3.7/dist-packages/sklearn/utils/validation.py:993: DataConversionWarning: A column-vector y was passed when a 1d array was expected. Please change the shape of y to (n_samples, ), for example using ravel().
y = column_or_1d(y, warn=True)
| MIT | Regression/Support_vector_regression.ipynb | AstitvaSharma/ML_Algorithms |
Predicting a new result | sc_y.inverse_transform([regressor.predict(sc_x.transform([[6.5]]))]) #requires 2D array, therefore added square brackets before regressor.predict | _____no_output_____ | MIT | Regression/Support_vector_regression.ipynb | AstitvaSharma/ML_Algorithms |
Visualising the SVR results | m=regressor.predict(x)
plt.scatter(sc_x.inverse_transform(x), sc_y.inverse_transform(y), color = 'red')
plt.plot(sc_x.inverse_transform(x), sc_y.inverse_transform(m.reshape(len(m),1)), color='blue') # requires 2d array therefore used reshape()
plt.title('truth or bluff (Support Vector Regression)')
plt.xlabel('Level')
... | _____no_output_____ | MIT | Regression/Support_vector_regression.ipynb | AstitvaSharma/ML_Algorithms |
Visualising the SVR results (for higher resolution and smoother curve) | X_unscaled = sc_x.inverse_transform(x)
y_unscaled = sc_y.inverse_transform(y)
X_grid = np.arange(min(x), max(x), 0.1)
X_grid = X_grid.reshape((len(X_grid), 1))
X_grid_unscaled = sc_x.inverse_transform(X_grid)
y_pred_grid = regressor.predict(X_grid)
y_pred_grid = sc_y.inverse_transform([y_pred_grid])
y_pred_grid = y_p... | _____no_output_____ | MIT | Regression/Support_vector_regression.ipynb | AstitvaSharma/ML_Algorithms |
The fundamental data structures are Series and DataFrame | s = pd.Series(np.random.randn(4), index =['a','f','t','y'])
s
s['a'] | _____no_output_____ | MIT | Untitled.ipynb | arora-anmol/pandas-practice |
The data argument can be dict, ndarray, or even a scalar etc | data = {'a': 3, 'b':4, 'c': 5, 'f':'something_else'}
data
s_dict = pd.Series(data, index=data.keys())
s_dict | _____no_output_____ | MIT | Untitled.ipynb | arora-anmol/pandas-practice |
When the dict doesn't have a matching key, it's not added. And when the index key is missing a value attached, NaN is given | s_dict_with_nan = pd.Series(data, index = ['a','b', 'j'])
s_dict_with_nan | _____no_output_____ | MIT | Untitled.ipynb | arora-anmol/pandas-practice |
Works differently with scalars | s_scalar = pd.Series(3, index=range(5)) | _____no_output_____ | MIT | Untitled.ipynb | arora-anmol/pandas-practice |
Works the same way even if you pass a list with one element, like [3] but fails if you pass [3,4] because expects 5 and not 2 | s_scalar | _____no_output_____ | MIT | Untitled.ipynb | arora-anmol/pandas-practice |
Series works just like an ndarray, if you have worked with numpy before. I do not have a lot of experience with numpy so can't comment on the full capabilites but according to what I know, you can apply vectorized operations to get a better code performance, slice in the same way we do with numpy ndarrays. | s | _____no_output_____ | MIT | Untitled.ipynb | arora-anmol/pandas-practice |
MENTIONING PYTHON DATA TYPE IN VARIABLE NAME IS NOT GOOD PRACTICE, SO TRY NOT TO | s[s>s.median()]
s[[3, 0, 1]]
np.exp(s)
s.values
s.keys
s.keys()
s.index
try :
some_random_var = s['g'] # Raises key error
except KeyError :
print('Caught key Error')
s.f # Can also access elements this way
s.a
s | _____no_output_____ | MIT | Untitled.ipynb | arora-anmol/pandas-practice |
Vectorized operations - Start of the end of matlab RIP | s+s
s*2
s*3
s/2 | _____no_output_____ | MIT | Untitled.ipynb | arora-anmol/pandas-practice |
Moving to Pandas DataFrame According to definition from https://pandas.pydata.org/pandas-docs/stable/dsintro.htmldsintro __DataFrame is a 2-dimensional labeled data structure with columns of potentially different types. You can think of it like a spreadsheet or SQL table, or a dict of Series objects. It is generally ... | data = {'one': pd.Series([1,2,3,4], index=['a','b','c','d']),
'two': pd.Series([3,4,5,56,6], index=['a','b','f','e','y'])}
df = pd.DataFrame(data)
df
| _____no_output_____ | MIT | Untitled.ipynb | arora-anmol/pandas-practice |
As you can see that it merged the two index together and filled the rest of the values with NaN | df_1 = pd.DataFrame(data, index=['a','b','c','f'])
df_1
df_2 = pd.DataFrame(data, columns=['two'])
df_2
df
df.index
df.columns
data_for_dict = { 'one': [1,2,4,5],
'two': [2.,5.4,4.,5]}
df_from_dict = pd.DataFrame(data_for_dict)
df_from_dict['one']
data = np.ones((2,8))
data
data.keys()
s = pd.Series([... | _____no_output_____ | MIT | Untitled.ipynb | arora-anmol/pandas-practice |
__A difference to note here is that Series does have a values and keys attribute whereas an ndarray doesn't. Good to know__ | rows = [[1,2,3,43],[3,5,6,6],[66,6,6]]
df_rows = pd.DataFrame(rows)
df_rows
df_rows_with_index = pd.DataFrame(rows, index=['first', 'second','third'])
df_rows_with_index # Number of indices should always match the rows count else will raise a shape error
try:
df_test = pd.DataFrame({'one':[2,23,4,5,56],
... | _____no_output_____ | MIT | Untitled.ipynb | arora-anmol/pandas-practice |
As we can see from the above couple of test df, when we pass a dictionary as data to DataFrame, the arrays needs to be of the same length. But if we pass a row of rows, they are adjusted accordinglyStrange, but need to know the reasoning. | df_test_4 | _____no_output_____ | MIT | Untitled.ipynb | arora-anmol/pandas-practice |
Working with POSTGIS In this chapter we will cover the following topics: Executing a PostGIS ST_Buffer analysis query and exporting it to GeoJSON Finding out whether a point is inside a polygon Splitting LineStrings at intersections using ST_Node Checking the validity of LineStrings Executing a spatial ... | #!/usr/bin/env python
import psycopg2
import json
from geojson import loads, Feature, FeatureCollection
# Database connection information
db_host = "localhost"
db_user = "calvin"
db_passwd = "planets"
db_database = "py_test"
db_port = "5432"
# connect to database
conn = psycopg2.connect(host=db_host, user=db_user,
... | _____no_output_____ | MIT | spatial_GIS_RS/python_notebooks/4. Working_with_Postgis.ipynb | OpitiCalvin/Scripts_n_Tutorials |
How it worksThe database connection is using the pyscopg2 module, so we import the libraries at the start alongside geojson and the standard json modules to handle our GeoJSON export.Our connection is created and then followed immediately with our SQL Buffer query string. The query uses three PostGIS functions. Workin... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
import psycopg2
from geojson import loads, Feature, FeatureCollection
# Database Connection Info
db_host = "localhost"
db_user = "pluto"
db_passwd = "stars"
db_database = "py_geoan_cb"
db_port = "5432"
# connect to DB
conn = psycopg2.connect(host=db_host, us... | _____no_output_____ | MIT | spatial_GIS_RS/python_notebooks/4. Working_with_Postgis.ipynb | OpitiCalvin/Scripts_n_Tutorials |
You can now view your newly created GeoJSON file on a great little site created by Mapbox at http://www.geojson.io. Simply drag and drop your GeoJSON file from Windows Explorer in Windows or Nautilus in Ubuntu onto the http://www.geojson.io web page and, Bob's your uncle, you should see 50 or so schools that are locate... | #!/usr/bin/env python
import psycopg2
import json
from geojson import loads, Feature, FeatureCollection
# Database Connection Info
db_host = "localhost"
db_user = "pluto"
db_passwd = "stars"
db_database = "py_geoan_cb"
db_port = "5432"
# connect to DB
conn = psycopg2.connect(host=db_host, user=db_user,
port=db_... | _____no_output_____ | MIT | spatial_GIS_RS/python_notebooks/4. Working_with_Postgis.ipynb | OpitiCalvin/Scripts_n_Tutorials |
Well, this was quite simple and we can now see that McNicoll Avenue is split at the intersection with Cypress Street. HOw it worksLooking at the code, we can see that the database connection remains the same and the only new thing is the query itself that creates the intersection. Here three separate PostGIS functions... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import psycopg2
# Database Connection Info
db_host = "localhost"
db_user = "pluto"
db_passwd = "stars"
db_database = "py_geoan_cb"
db_port = "5432"
# connect to DB
conn = psycopg2.connect(host=db_host, user=db_user,
port=db_port, password=db_passwd, database=db_data... | _____no_output_____ | MIT | spatial_GIS_RS/python_notebooks/4. Working_with_Postgis.ipynb | OpitiCalvin/Scripts_n_Tutorials |
This query should return an empty Python list, which means that we have no invalid geometries. If there are objects in your list, then you'll know that you have some manual work to do to correct those geometries. Your best bet is to fire up QGIS and get started with digitizing tools to clean things up. Executing a spa... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import psycopg2
# Database Connection Info
db_host = "localhost"
db_user = "pluto"
db_passwd = "stars"
db_database = "py_geoan_cb"
db_port = "5432"
# connect to DB
conn = psycopg2.connect(host=db_host, user=db_user, port=db_port, password=db_passwd, database=db_database)... | _____no_output_____ | MIT | spatial_GIS_RS/python_notebooks/4. Working_with_Postgis.ipynb | OpitiCalvin/Scripts_n_Tutorials |
**Getting Started With Spark using Python** Estimated time needed: **15** minutes  The Python API Spark is written in Scala, which compiles to Java bytecode, but you can write python code to communicate to the java virtual machine through a library called py4j. P... | # Installing required packages
!pip install pyspark
!pip install findspark
import findspark
findspark.init()
# PySpark is the Spark API for Python. In this lab, we use PySpark to initialize the spark context.
from pyspark import SparkContext, SparkConf
from pyspark.sql import SparkSession | _____no_output_____ | MIT | Coursera/Apache_Spark_Fundamentals.ipynb | SokolovVadim/Big-Data |
Exercise 1 - Spark Context and Spark Session In this exercise, you will create the Spark Context and initialize the Spark session needed for SparkSQL and DataFrames.SparkContext is the entry point for Spark applications and contains functions to create RDDs such as `parallelize()`. SparkSession is needed for SparkSQL... | # Creating a spark context class
sc = SparkContext()
# Creating a spark session
spark = SparkSession \
.builder \
.appName("Python Spark DataFrames basic example") \
.config("spark.some.config.option", "some-value") \
.getOrCreate() | _____no_output_____ | MIT | Coursera/Apache_Spark_Fundamentals.ipynb | SokolovVadim/Big-Data |
Task 2: Initialize Spark sessionTo work with dataframes we just need to verify that the spark session instance has been created. | spark | _____no_output_____ | MIT | Coursera/Apache_Spark_Fundamentals.ipynb | SokolovVadim/Big-Data |
Exercise 2: RDDsIn this exercise we work with Resilient Distributed Datasets (RDDs). RDDs are Spark's primitive data abstraction and we use concepts from functional programming to create and manipulate RDDs. Task 1: Create an RDD.For demonstration purposes, we create an RDD here by calling `sc.parallelize()`\We creat... | data = range(1,30)
# print first element of iterator
print(data[0])
len(data)
xrangeRDD = sc.parallelize(data, 4)
# this will let us know that we created an RDD
xrangeRDD | 1
| MIT | Coursera/Apache_Spark_Fundamentals.ipynb | SokolovVadim/Big-Data |
Task 2: Transformations A transformation is an operation on an RDD that results in a new RDD. The transformed RDD is generated rapidly because the new RDD is lazily evaluated, which means that the calculation is not carried out when the new RDD is generated. The RDD will contain a series of transformations, or computa... | subRDD = xrangeRDD.map(lambda x: x-1)
filteredRDD = subRDD.filter(lambda x : x<10)
| _____no_output_____ | MIT | Coursera/Apache_Spark_Fundamentals.ipynb | SokolovVadim/Big-Data |
Task 3: Actions A transformation returns a result to the driver. We now apply the `collect()` action to get the output from the transformation. | print(filteredRDD.collect())
filteredRDD.count() | [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
| MIT | Coursera/Apache_Spark_Fundamentals.ipynb | SokolovVadim/Big-Data |
Task 4: Caching Data This simple example shows how to create an RDD and cache it. Notice the **10x speed improvement**! If you wish to see the actual computation time, browse to the Spark UI...it's at host:4040. You'll see that the second calculation took much less time! | import time
test = sc.parallelize(range(1,50000),4)
test.cache()
t1 = time.time()
# first count will trigger evaluation of count *and* cache
count1 = test.count()
dt1 = time.time() - t1
print("dt1: ", dt1)
t2 = time.time()
# second count operates on cached data only
count2 = test.count()
dt2 = time.time() - t2
pri... | dt1: 1.997375726699829
dt2: 0.41718220710754395
| MIT | Coursera/Apache_Spark_Fundamentals.ipynb | SokolovVadim/Big-Data |
Exercise 3: DataFrames and SparkSQL In order to work with the extremely powerful SQL engine in Apache Spark, you will need a Spark Session. We have created that in the first Exercise, let us verify that spark session is still active. | spark | _____no_output_____ | MIT | Coursera/Apache_Spark_Fundamentals.ipynb | SokolovVadim/Big-Data |
Task 1: Create Your First DataFrame! You can create a structured data set (much like a database table) in Spark. Once you have done that, you can then use powerful SQL tools to query and join your dataframes. | # Download the data first into a local `people.json` file
!curl https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBM-BD0225EN-SkillsNetwork/labs/data/people.json >> people.json
# Read the dataset into a spark dataframe using the `read.json()` function
df = spark.read.json("people.json").cache()
# Prin... | _____no_output_____ | MIT | Coursera/Apache_Spark_Fundamentals.ipynb | SokolovVadim/Big-Data |
Task 2: Explore the data using DataFrame functions and SparkSQLIn this section, we explore the datasets using functions both from dataframes as well as corresponding SQL queries using sparksql. Note the different ways to achieve the same task! | # Select and show basic data columns
df.select("name").show()
df.select(df["name"]).show()
spark.sql("SELECT name FROM people").show()
# Perform basic filtering
df.filter(df["age"] > 21).show()
spark.sql("SELECT age, name FROM people WHERE age > 21").show()
# Perfom basic aggregation of data
df.groupBy("age").count(... | +----+-----+
| age|count|
+----+-----+
| 19| 1|
|null| 1|
| 30| 1|
+----+-----+
+----+-----+
| age|count|
+----+-----+
| 19| 1|
|null| 0|
| 30| 1|
+----+-----+
| MIT | Coursera/Apache_Spark_Fundamentals.ipynb | SokolovVadim/Big-Data |
*** Question 1 - RDDs Create an RDD with integers from 1-50. Apply a transformation to multiply every number by 2, resulting in an RDD that contains the first 50 even numbers. | # starter code
# numbers = range(1, 50)
# numbers_RDD = ...
# even_numbers_RDD = numbers_RDD.map(lambda x: ..)
# Code block for learners to answer
numbers = range(1, 50)
numbers_RDD = sc.parallelize(data, 4)
even_numbers_RDD = numbers_RDD.map(lambda x: x * 2)
even_numbers_RDD.collect() | _____no_output_____ | MIT | Coursera/Apache_Spark_Fundamentals.ipynb | SokolovVadim/Big-Data |
Question 2 - DataFrames and SparkSQL Similar to the `people.json` file, now read the `people2.json` file into the notebook, load it into a dataframe and apply SQL operations to determine the average age in our people2 file. | # starter code
# !curl https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBM-BD0225EN-SkillsNetwork/labs/data/people2.json >> people2.json
# df = spark.read...
# df.createTempView..
# spark.sql("SELECT ...")
# Code block for learners to answer
!curl https://cf-courses-data.s3.us.cloud-object-storage.ap... | % Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 326 100 326 0 0 478 0 --:--:-- --:--:-- --:--:-- 478
| MIT | Coursera/Apache_Spark_Fundamentals.ipynb | SokolovVadim/Big-Data |
Double-click **here** for a hint.<!-- The hint is below:1. The SQL query "Select AVG(column_name) from.." can be used to find the average value of a column. 2. Another possible way is to use the dataframe operations select() and mean()--> Double-click **here** for the solution.<!-- The answer is below:df = spark.read('... | # Code block for learners to answer
spark.stop() | _____no_output_____ | MIT | Coursera/Apache_Spark_Fundamentals.ipynb | SokolovVadim/Big-Data |
There are two ways to load the pretrained model, the first way is to load from local model directory. A model directory should consist of two files: config.pkl that describes the configuration of the model and model.pt, which is the model weights. If you use model.save(MODEL_DIR) to save the model, then, it should be g... | path = utils.download_pretrained_model('Morgan_AAC_DAVIS')
net = models.model_pretrained(path_dir = path)
net.config | _____no_output_____ | BSD-3-Clause | DEMO/load_pretraining_models_tutorial.ipynb | markcheung/DeepPurpose |
For models that provided by us, you can directly use the pre-designated model names. The full list is in the Github README https://github.com/kexinhuang12345/DeepPurpose/blob/master/README.mdpretrained-models | net = models.model_pretrained(model = 'MPNN_CNN_DAVIS')
net.config | Beginning Downloading MPNN_CNN_DAVIS Model...
Downloading finished... Beginning to extract zip file...
pretrained model Successfully Downloaded...
| BSD-3-Clause | DEMO/load_pretraining_models_tutorial.ipynb | markcheung/DeepPurpose |
SIR example Deterministic model | def SIR(t, y, b, d, beta, u, v):
N = y[0]+y[1]+y[2]
return [b*N - d*y[0] - beta*y[1]/N*y[0] - v*y[0],
beta*y[1]/N*y[0] - u*y[1] - d*y[1],
u*y[1] - d*y[2] + v*y[0]]
# Time interval for the simulation
t0 = 0
t1 = 120
t_span = (t0, t1)
t_eval = np.linspace(t_span[0], t_span[1], 10000)
# Init... | _____no_output_____ | MIT | LectureNotes/MC/MC.ipynb | enigne/ScientificComputingBridging |
Stochastic model | import numpy as np
# Plotting modules
import matplotlib.pyplot as plt
def sample_discrete(probs):
"""
Randomly sample an index with probability given by probs.
"""
# Generate random number
q = np.random.rand()
# Find index
i = 0
p_sum = 0.0
while p_sum < q:
p_sum += pro... | _____no_output_____ | MIT | LectureNotes/MC/MC.ipynb | enigne/ScientificComputingBridging |
Solve SIR in stochastic method | # Column changes S, I, R
simple_update = np.array([[-1, 1, 0],
[0, -1, 1],
[-1, 0, 1],
[-1, 0, 0],
[0, -1, 0],
[0, 0, -1],
[1, 0, 0]], dtype=np.int)
# Specify para... | _____no_output_____ | MIT | LectureNotes/MC/MC.ipynb | enigne/ScientificComputingBridging |
Simulate interest rate path by the CIR model | import math
import numpy as np
import matplotlib.pyplot as plt
def cir(r0, K, theta, sigma, T=1., N=10,seed=777):
np.random.seed(seed)
dt = T/float(N)
rates = [r0]
for i in range(N):
dr = K*(theta-rates[-1])*dt + \
sigma*math.sqrt(abs(rates[-1]))*np.random.normal()
rates... | _____no_output_____ | MIT | LectureNotes/MC/MC.ipynb | enigne/ScientificComputingBridging |
Import data and drop redundant data (rates) | # import data
df = pd.read_csv('../../data/deepsolar_tract.csv', encoding = "utf-8") | _____no_output_____ | MIT | EDA_Notebooks/EDA_Allison.ipynb | BudBernhard/Mod4Project-DeepSolarAnalysis |
Clean Data | df = drop_redundant_columns(df)
# Create our target column 'has_tiles', and drop additional redundant columns
df = create_has_tiles_target_column(df)
df.shape
# # # Figure out which variables are highly correlated, remove the most correlated ones one by one
# corr = pd.DataFrame((df.corr() > 0.8).sum())
# corr.sort_v... | _____no_output_____ | MIT | EDA_Notebooks/EDA_Allison.ipynb | BudBernhard/Mod4Project-DeepSolarAnalysis |
Checking for missing values | nulls = pd.DataFrame(df.isna().sum())
nulls.columns = ["missing"]
nulls[nulls['missing']>0].head()
# drop all missing values
df = df.dropna(axis = 0)
# Check class imbalance
df.has_tiles.value_counts()
df.shape | _____no_output_____ | MIT | EDA_Notebooks/EDA_Allison.ipynb | BudBernhard/Mod4Project-DeepSolarAnalysis |
Train test split | X = df.drop('has_tiles', axis = 1)
y = df['has_tiles']
df.shape
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, stratify = y) | _____no_output_____ | MIT | EDA_Notebooks/EDA_Allison.ipynb | BudBernhard/Mod4Project-DeepSolarAnalysis |
Sampling Techniques | # smote, undersampling, or oversampling
X_train, y_train = pick_sampling_method(X_train, y_train, method = 'oversampling')
y_train.value_counts() | _____no_output_____ | MIT | EDA_Notebooks/EDA_Allison.ipynb | BudBernhard/Mod4Project-DeepSolarAnalysis |
Scale Data | scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)
X_train.shape | _____no_output_____ | MIT | EDA_Notebooks/EDA_Allison.ipynb | BudBernhard/Mod4Project-DeepSolarAnalysis |
Modeling | from sklearn.metrics import classification_report | _____no_output_____ | MIT | EDA_Notebooks/EDA_Allison.ipynb | BudBernhard/Mod4Project-DeepSolarAnalysis |
Vanilla Decision Tree 0.74 | ## DUMMY
dummy = DecisionTreeClassifier()
dummy.fit(X_train, y_train)
y_pred = dummy.predict(X_test)
print("Precision: {}".format(precision_score(y_test, y_pred)))
print("Recall: {}".format(recall_score(y_test, y_pred)))
print("Accuracy: {}".format(accuracy_score(y_test, y_pred)))
print("F1 Score: {}".format(f1_score(y... | precision recall f1-score support
0 0.24 0.82 0.37 2500
1 0.79 0.21 0.33 8320
accuracy 0.35 10820
macro avg 0.51 0.51 0.35 10820
weighted avg 0.66 0.35 0.34 ... | MIT | EDA_Notebooks/EDA_Allison.ipynb | BudBernhard/Mod4Project-DeepSolarAnalysis |
Decision Tree with Hyperparameter Tuning | dt = find_hyperparameters(pipe_dt, params_dt, X_train, y_train)
dt.best_params_
best_dt = dt.best_estimator_
# Decision Tree: {'dt__max_depth': 2, 'dt__min_samples_leaf': 1, 'dt__min_samples_split': 2}
best_dt.fit(X_train, y_train)
best_dt.score(X_test, y_test)
# Decision Tree: 0.755637707948244
y_pred_dt = best_dt.pre... | Precision: 0.9131785238869989
Recall: 0.7420673076923077
Accuracy: 0.7474121996303142
F1 Score: 0.8187785955838471
| MIT | EDA_Notebooks/EDA_Allison.ipynb | BudBernhard/Mod4Project-DeepSolarAnalysis |
Final Model | # with oversampling
rf = RandomForestClassifier(max_features = 'sqrt', max_depth = 5, min_samples_leaf = 5, n_estimators = 30)
rf.fit(X_train, y_train)
y_pred = rf.predict(X_test)
print("Precision: {}".format(precision_score(y_test, y_pred)))
print("Recall: {}".format(recall_score(y_test, y_pred)))
print("Accuracy: {}"... | C:\Users\allis\Anaconda3\lib\site-packages\sklearn\base.py:197: FutureWarning: From version 0.24, get_params will raise an AttributeError if a parameter cannot be retrieved as an instance attribute. Previously it would return None.
FutureWarning)
C:\Users\allis\Anaconda3\lib\site-packages\yellowbrick\classifier\base.... | MIT | EDA_Notebooks/EDA_Allison.ipynb | BudBernhard/Mod4Project-DeepSolarAnalysis |
Vanilla Random Forests | rf = RandomForestClassifier()
rf.fit(X_train, y_train)
y_pred = rf.predict(X_test)
print("Precision: {}".format(precision_score(y_test, y_pred)))
print("Recall: {}".format(recall_score(y_test, y_pred)))
print("Accuracy: {}".format(accuracy_score(y_test, y_pred)))
print("F1 Score: {}".format(f1_score(y_test, y_pred)))
p... | _____no_output_____ | MIT | EDA_Notebooks/EDA_Allison.ipynb | BudBernhard/Mod4Project-DeepSolarAnalysis |
Random Forests with Hyperparameter Tuning | ### Random Forests
rf = find_hyperparameters(pipe_rf, params_rf, X_train, y_train)
print(rf.best_params_)
best_rf = rf.best_estimator_
#first hyperparamter tuning: {'rf__max_features': 'sqrt', 'rf__min_samples_leaf': 20, 'rf__n_estimators': 30}
# Second tuning: {'rf__min_samples_leaf': 5, 'rf__n_estimators': 50}
best_... | Precision: 0.8924837003321442
Recall: 0.8719951923076923
Accuracy: 0.8207948243992607
F1 Score: 0.8821204936470303
Balanced Accuracy: 0.7611975961538462
| MIT | EDA_Notebooks/EDA_Allison.ipynb | BudBernhard/Mod4Project-DeepSolarAnalysis |
Vanilla SVC | svc = SVC()
svc.fit(X_train, y_train)
y_pred_svc = svc.predict(X_test)
print("Precision: {}".format(precision_score(y_test, y_pred_svc)))
print("Recall: {}".format(recall_score(y_test, y_pred_svc)))
print("Accuracy: {}".format(accuracy_score(y_test, y_pred_svc)))
print("F1 Score: {}".format(f1_score(y_test, y_pred_svc)... | Precision: 0.9094472225976483
Recall: 0.8087740384615385
Accuracy: 0.7910351201478744
F1 Score: 0.8561613334181563
| MIT | EDA_Notebooks/EDA_Allison.ipynb | BudBernhard/Mod4Project-DeepSolarAnalysis |
SVC with Hyperparameter Tuning | svc = find_hyperparameters(pipe_svc, params_svc, X_train, y_train)
print(svc.best_params_)
best_svc = svc.best_estimator_
best_svc.fit(X_train, y_train)
best_svc.score(X_test, y_test)
y_pred_svc = best_svc.predict(X_test)
print("Precision: {}".format(precision_score(y_test, y_pred_svc)))
print("Recall: {}".format(recal... | _____no_output_____ | MIT | EDA_Notebooks/EDA_Allison.ipynb | BudBernhard/Mod4Project-DeepSolarAnalysis |
Vanilla KNN | knn = KNeighborsClassifier()
knn.fit(X_train, y_train)
y_pred_knn = knn.predict(X_test)
print("Precision: {}".format(precision_score(y_test, y_pred_knn)))
print("Recall: {}".format(recall_score(y_test, y_pred_knn)))
print("Accuracy: {}".format(accuracy_score(y_test, y_pred_knn)))
print("F1 Score: {}".format(f1_score(y_... | Precision: 0.9354388413889374
Recall: 0.6443509615384615
Accuracy: 0.6923290203327171
F1 Score: 0.7630773610419187
| MIT | EDA_Notebooks/EDA_Allison.ipynb | BudBernhard/Mod4Project-DeepSolarAnalysis |
KNN with Hyperparameter Tuning | knn = find_hyperparameters(pipe_knn, params_knn, X_train, y_train)
print(knn.best_params_)
best_knn = knn.best_estimator_
best_knn.fit(X_train, y_train)
best_knn.score(X_test, y_test)
y_pred_knn = best_knn.predict(X_test)
print("Precision: {}".format(precision_score(y_test, y_pred_knn)))
print("Recall: {}".format(recal... | _____no_output_____ | MIT | EDA_Notebooks/EDA_Allison.ipynb | BudBernhard/Mod4Project-DeepSolarAnalysis |
Preliminary Conclusions: Model Performance Comparisons Based on comparisons of both accuracy and balanced accuracy scores, our Random Forest Classifier model performed the best with oversampling methods and hyperparameter tuning. | falsepositives = isFalsePositive(df, X_test, y_test, rf)
inversefalsepositives = scaler.inverse_transform(falsepositives)
inversefalsepositives = pd.DataFrame(inversefalsepositives)
inversefalsepositives = inversefalsepositives.set_axis(falsepositives.columns, axis=1, inplace=False)
len(inversefalsepositives)
ozdf = pd... | _____no_output_____ | MIT | EDA_Notebooks/EDA_Allison.ipynb | BudBernhard/Mod4Project-DeepSolarAnalysis |
Running Model on Entire Dataset | ozdf = ozdf['Census_Tract_Number']
merged = df.merge(ozdf, how = 'left', left_on='fips',right_on='Census_Tract_Number')
merged = merged.dropna()
merged.drop('fips', axis = 1, inplace = True)
merged['has_tiles'].value_counts()
X_ozdf = merged.drop('has_tiles', axis = 1)
y_ozdf = merged['has_tiles']
y_pred_ozdf = rf.pred... | _____no_output_____ | MIT | EDA_Notebooks/EDA_Allison.ipynb | BudBernhard/Mod4Project-DeepSolarAnalysis |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.