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
5. Run WEAP**Please wait, it will take ~1-3 minutes** to finish calcualting the two WEAP Areas with their many scenarios
# Run WEAP WEAP.Areas("Bear_River_WEAP_Model_2017_Conservation").Open print WEAP.ActiveArea.Name WEAP.ActiveArea = "Bear_River_WEAP_Model_2017_Conservation" print WEAP.ActiveArea.Name print 'Please wait 1-3 min for the calculation to finish' WEAP.Calculate(2006,10,True) WEAP.SaveArea print '\n \n The calculation ...
_____no_output_____
BSD-3-Clause
3_VisualizePublish/07_Step7_Serve_NewScenarios_WEAP.ipynb
WamdamProject/WaMDaM_JupyterNotebooks
5.1 Get the unmet demand or Cache County sites in both the reference and the conservation scenarios
Scenarios=['Reference','Cons25PercCacheUrbWaterUse','Incr25PercCacheUrbWaterUse'] DemandSites=['Logan Potable','North Cache Potable','South Cache Potable'] UnmetDemandEstimate_Ref = pd.DataFrame(columns = DemandSites) UnmetDemandEstimate_Cons25 = pd.DataFrame(columns = DemandSites) UnmetDemandEstimate_Incr25 = pd.Data...
_____no_output_____
BSD-3-Clause
3_VisualizePublish/07_Step7_Serve_NewScenarios_WEAP.ipynb
WamdamProject/WaMDaM_JupyterNotebooks
5.2 Get the unmet demand as a percentage for the scenarios
######################################################################## # estimate the total reference demand for Cahce county to calcualte the percentage result_df_UseCase= pd.read_sql_query(Query_UseCase_text, conn) subsets = result_df_UseCase.groupby(['ScenarioName']) for subset in subsets.groups.keys(): if ...
_____no_output_____
BSD-3-Clause
3_VisualizePublish/07_Step7_Serve_NewScenarios_WEAP.ipynb
WamdamProject/WaMDaM_JupyterNotebooks
5.3 Export the unmet demand percent into Excel to load them into WaMDaM
# display(UnmetDemandEstimate) import xlsxwriter from collections import OrderedDict UnmetDemandEstimate.to_csv('UnmetDemandEstimate.csv') ExcelFileName='Test.xlsx' years =UnmetDemandEstimate.index.values #print years Columns=['ObjectType','InstanceName','ScenarioName','AttributeName','DateTimeStamp','Value'] # t...
_____no_output_____
BSD-3-Clause
3_VisualizePublish/07_Step7_Serve_NewScenarios_WEAP.ipynb
WamdamProject/WaMDaM_JupyterNotebooks
6. Plot the unmet demad for all the scenarios and years
trace2 = go.Scatter( x=years, y=Reference_vals_perc[0], name = 'Reference demand', mode = 'lines+markers', marker = dict( color = '#264DFF', )) trace3 = go.Scatter( x=years, y=Cons25PercCacheUrbWaterUse_vals_perc[0], name = 'Conserve demand by 25%', mode = 'l...
_____no_output_____
BSD-3-Clause
3_VisualizePublish/07_Step7_Serve_NewScenarios_WEAP.ipynb
WamdamProject/WaMDaM_JupyterNotebooks
7. Upload the new result scenarios to OpenAgua to visulize them there You already uploaded the results form WaMDaM SQLite earlier at the begnining of these Jupyter Notebooks. So all you need is to select to display the result in OpenAgua. Finally, click, load data. It should replicate the same figure above and Figure ...
# 9. Close the SQLite and WEAP API connections conn.close() print 'connection disconnected' # Uncomment WEAP.SaveArea # this command will close WEAP WEAP.Quit print 'Connection with WEAP API is disconnected'
_____no_output_____
BSD-3-Clause
3_VisualizePublish/07_Step7_Serve_NewScenarios_WEAP.ipynb
WamdamProject/WaMDaM_JupyterNotebooks
[![Binder](https://mybinder.org/badge_logo.svg)](https://lab.mlpack.org/v2/gh/mlpack/examples/master?urlpath=lab%2Ftree%2Fforest_covertype_prediction_with_random_forests%2Fcovertype-rf-py.ipynb)
# @file covertype-rf-py.ipynb # # Classification using Random Forest on the Covertype dataset. import mlpack import pandas as pd import numpy as np # Load the dataset from an online URL. df = pd.read_csv('https://lab.mlpack.org/data/covertype-small.csv.gz') # Split the labels. labels = df['label'] dataset = df.drop('la...
24513 correct out of 30000 (81.71%).
BSD-3-Clause
forest_covertype_prediction_with_random_forests/covertype-rf-py.ipynb
Davidportlouis/examples
Optimizing building HVAC with Amazon SageMaker RL
import sagemaker import boto3 from sagemaker.rl import RLEstimator from source.common.docker_utils import build_and_push_docker_image
_____no_output_____
Apache-2.0
reinforcement_learning/rl_hvac_ray_energyplus/train-hvac.ipynb
P15241328/amazon-sagemaker-examples
Initialize Amazon SageMaker
role = sagemaker.get_execution_role() sm_session = sagemaker.session.Session() # SageMaker SDK creates a default bucket. Change this bucket to your own bucket, if needed. s3_bucket = sm_session.default_bucket() s3_output_path = f's3://{s3_bucket}' print(f'S3 bucket path: {s3_output_path}') print(f'Role: {role}')
_____no_output_____
Apache-2.0
reinforcement_learning/rl_hvac_ray_energyplus/train-hvac.ipynb
P15241328/amazon-sagemaker-examples
Set additional training parameters Set instance typeSet `cpu_or_gpu` to either `'cpu'` or `'gpu'` for using CPU or GPU instances. Configure the framework you want to useSet `framework` to `'tf'` or `'torch'` for TensorFlow or PyTorch, respectively.You will also have to edit your entry point i.e., `train-sagemaker-dist...
job_name_prefix = 'energyplus-hvac-ray' cpu_or_gpu = 'gpu' # has to be either cpu or gpu if cpu_or_gpu != 'cpu' and cpu_or_gpu != 'gpu': raise ValueError('cpu_or_gpu has to be either cpu or gpu') framework = 'tf' instance_type = 'ml.g4dn.16xlarge' # g4dn.16x large has 1 GPU and 64 cores
_____no_output_____
Apache-2.0
reinforcement_learning/rl_hvac_ray_energyplus/train-hvac.ipynb
P15241328/amazon-sagemaker-examples
Train your homogeneous scaling job here Edit the training codeThe training code is written in the file `train-sagemaker-distributed.py` which is uploaded in the /source directory.*Note that ray will automatically set `"ray_num_cpus"` and `"ray_num_gpus"` in `_get_ray_config`*
!pygmentize source/train-sagemaker-distributed.py
_____no_output_____
Apache-2.0
reinforcement_learning/rl_hvac_ray_energyplus/train-hvac.ipynb
P15241328/amazon-sagemaker-examples
Train the RL model using the Python SDK Script modeWhen using SageMaker for distributed training, you can select a GPU or CPU instance. The RLEstimator is used for training RL jobs.1. Specify the source directory where the environment, presets and training code is uploaded.2. Specify the entry point as the training co...
# Build image repository_short_name = f'sagemaker-hvac-ray-{cpu_or_gpu}' docker_build_args = { 'CPU_OR_GPU': cpu_or_gpu, 'AWS_REGION': boto3.Session().region_name, 'FRAMEWORK': framework } image_name = build_and_push_docker_image(repository_short_name, build_args=docker_build_args) print("Using ECR i...
_____no_output_____
Apache-2.0
reinforcement_learning/rl_hvac_ray_energyplus/train-hvac.ipynb
P15241328/amazon-sagemaker-examples
Ray homogeneous scaling - Specify `train_instance_count` > 1Homogeneous scaling allows us to use multiple instances of the same type.Spot instances are unused EC2 instances that could be used at 90% discount compared to On-Demand prices (more information about spot instances can be found [here](https://aws.amazon.com/...
hyperparameters = { # no. of days to simulate. Remember to adjust the dates in RunPeriod of # 'source/eplus/envs/buildings/MediumOffice/RefBldgMediumOfficeNew2004_Chicago.idf' to match simulation days. 'n_days': 365, 'n_iter': 50, # no. of training iterations 'algorithm': 'APEX_DDPG', # only APEX_D...
_____no_output_____
Apache-2.0
reinforcement_learning/rl_hvac_ray_energyplus/train-hvac.ipynb
P15241328/amazon-sagemaker-examples
Spleen 3D segmentation with MONAI This tutorial demonstrates how MONAI can be used in conjunction with the [PyTorch Lightning](https://github.com/PyTorchLightning/pytorch-lightning) framework.We demonstrate use of the following MONAI features:1. Transforms for dictionary format data.2. Loading Nifti images with metada...
! pip install pytorch-lightning # Copyright 2020 MONAI Consortium # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicabl...
MONAI version: 0.1.0rc2+11.gdb4531b.dirty Python version: 3.6.8 (default, Oct 7 2019, 12:59:55) [GCC 8.3.0] Numpy version: 1.18.2 Pytorch version: 1.4.0 Ignite version: 0.3.0
Apache-2.0
examples/notebooks/spleen_segmentation_3d_lightning.ipynb
loftwah/MONAI
Define the LightningModuleThe LightningModule contains a refactoring of your training code. The following module is a refactoring of the code in `spleen_segmentation_3d.ipynb`:
class Net(LightningModule): def __init__(self): super().__init__() self._model = monai.networks.nets.UNet(dimensions=3, in_channels=1, out_channels=2, channels=(16, 32, 64, 128, 256), strides=(2, 2, 2, 2), num_res_units=2, norm=Norm.BATCH) self.loss_function ...
_____no_output_____
Apache-2.0
examples/notebooks/spleen_segmentation_3d_lightning.ipynb
loftwah/MONAI
Run the training
# initialise the LightningModule net = Net() # set up loggers and checkpoints tb_logger = loggers.TensorBoardLogger(save_dir='logs') checkpoint_callback = ModelCheckpoint(filepath='logs/{epoch}-{val_loss:.2f}-{val_dice:.2f}') # initialise Lightning's trainer. trainer = Trainer(gpus=[0], max_epochs=...
train completed, best_metric: 0.9435 at epoch 186
Apache-2.0
examples/notebooks/spleen_segmentation_3d_lightning.ipynb
loftwah/MONAI
View training in tensorboard
%load_ext tensorboard %tensorboard --logdir='logs'
_____no_output_____
Apache-2.0
examples/notebooks/spleen_segmentation_3d_lightning.ipynb
loftwah/MONAI
Check best model output with the input image and label
net.eval() device = torch.device("cuda:0") with torch.no_grad(): for i, val_data in enumerate(net.val_dataloader()): roi_size = (160, 160, 160) sw_batch_size = 4 val_outputs = sliding_window_inference(val_data['image'].to(device), roi_size, sw_batch_size, net) # plot the slice [:, :,...
_____no_output_____
Apache-2.0
examples/notebooks/spleen_segmentation_3d_lightning.ipynb
loftwah/MONAI
Westeros Tutorial Part 1 - Welcome to the MESSAGEix framework & Creating a baseline scenario *Integrated Assessment Modeling for the 21st Century*For information on how to install *MESSAGEix*, please refer to [Installation page](https://message.iiasa.ac.at/en/stable/getting_started.html) and for getting *MESSAGEix* t...
import pandas as pd import ixmp import message_ix from message_ix.utils import make_df %matplotlib inline
_____no_output_____
Apache-2.0
westeros/westeros_baseline.ipynb
fschoeni/homework_no3
The *MESSAGEix* model is built using the *ixmp* `Platform`. The `Platform` is your connection to a database for storing model input data and scenario results.
mp = ixmp.Platform()
_____no_output_____
Apache-2.0
westeros/westeros_baseline.ipynb
fschoeni/homework_no3
Once connected, we create a new `Scenario` to build our model. A `Scenario` instance will contain all the model input data and results.
scenario = message_ix.Scenario(mp, model='Westeros Electrified', scenario='baseline', version='new')
_____no_output_____
Apache-2.0
westeros/westeros_baseline.ipynb
fschoeni/homework_no3
Model StructureWe start by defining basic characteristics of the model, including time, space, and the energy system structure. The model horizon will span 3 decades (690-720). Let's assume that we're far in the future after the events of A Song of Ice and Fire (which occur ~300 years after Aegon the conqueror).| Math...
history = [690] model_horizon = [700, 710, 720] scenario.add_horizon({'year': history + model_horizon, 'firstmodelyear': model_horizon[0]})
_____no_output_____
Apache-2.0
westeros/westeros_baseline.ipynb
fschoeni/homework_no3
Our model will have a single `node`, i.e., its spatial dimension.| Math Notation | Model Meaning||---------------|--------------|| $n \in N$ | node |
country = 'Westeros' scenario.add_spatial_sets({'country': country})
_____no_output_____
Apache-2.0
westeros/westeros_baseline.ipynb
fschoeni/homework_no3
And we fill in the energy system's `commodities`, `levels`, `technologies`, and `modes` (i.e., modes of operation of technologies). This information defines how certain technologies operate. | Math Notation | Model Meaning||---------------|--------------|| $c \in C$ | commodity || $l \in L$ | level ||...
scenario.add_set("commodity", ["electricity", "light"]) scenario.add_set("level", ["secondary", "final", "useful"]) scenario.add_set("technology", ['coal_ppl', 'wind_ppl', 'grid', 'bulb']) scenario.add_set("mode", "standard")
_____no_output_____
Apache-2.0
westeros/westeros_baseline.ipynb
fschoeni/homework_no3
Supply and Demand (or Balancing Commodities) The fundamental premise of the model is to satisfy demand for energy (services).To first order, demand for services like electricity track with economic productivity (GDP).We define a GDP profile similar to first-world GDP growth from [1900-1930](https://en.wikipedia.org/wi...
gdp_profile = pd.Series([1., 1.5, 1.9], index=pd.Index(model_horizon, name='Time')) gdp_profile.plot(title='Demand')
_____no_output_____
Apache-2.0
westeros/westeros_baseline.ipynb
fschoeni/homework_no3
The `COMMODITY_BALANCE_GT` and `COMMODITY_BALANCE_LT` equations ensure that `demand` for each `commodity` is met at each `level` in the energy system.The equation is copied below in this tutorial notebook, but every model equation is available for reference inthe [Mathematical formulation](https://message.iiasa.ac.at/e...
demand_per_year = 40 * 12 * 1000 / 8760 light_demand = pd.DataFrame({ 'node': country, 'commodity': 'light', 'level': 'useful', 'year': model_horizon, 'time': 'year', 'value': (100 * gdp_profile).round(), 'unit': 'GWa', })
_____no_output_____
Apache-2.0
westeros/westeros_baseline.ipynb
fschoeni/homework_no3
`light_demand` illustrates the data format for *MESSAGEix* parameters. It is a `pandas.DataFrame` containing three types of information in a specific format:- A "value" column containing the numerical values for this parameter.- A "unit" column.- Other columns ("node", "commodity", "level", "time") that indicate the ke...
light_demand # We use add_par for adding data to a MESSAGEix parameter scenario.add_par("demand", light_demand)
_____no_output_____
Apache-2.0
westeros/westeros_baseline.ipynb
fschoeni/homework_no3
In order to define the input and output commodites of each technology, we define some common keys.- **Input** quantities require `_origin` keys that specify where the inputs are *received from*.- **Output** quantities require `_dest` keys that specify where the outputs are *transferred to*.
year_df = scenario.vintage_and_active_years() vintage_years, act_years = year_df['year_vtg'], year_df['year_act'] base = { 'node_loc': country, 'year_vtg': vintage_years, 'year_act': act_years, 'mode': 'standard', 'time': 'year', 'unit': '-', } base_input = make_df(base, node_origin=country, t...
_____no_output_____
Apache-2.0
westeros/westeros_baseline.ipynb
fschoeni/homework_no3
Working backwards along the Reference Energy System, we can add connections for the `bulb`. A light bulb…- receives *input* in the form of the "electricity" *commodity* at the "final [energy]" *level*, and- *outputs* the commodity "light" at the "useful [energy]" level.The `value` in the input and output parameter is u...
bulb_out = make_df(base_output, technology='bulb', commodity='light', level='useful', value=1.0) scenario.add_par('output', bulb_out) bulb_in = make_df(base_input, technology='bulb', commodity='electricity', level='final', value=1.0) scenario.add_par('input', bulb_in)
_____no_output_____
Apache-2.0
westeros/westeros_baseline.ipynb
fschoeni/homework_no3
Next, we parameterize the electrical `grid`, which…- receives electricity at the "secondary" energy level.- also outputs electricity, but at the "final" energy level (to be used by the light bulb).Because the grid has transmission losses, only 90% of the input electricity is available as output.
grid_efficiency = 0.9 grid_out = make_df(base_output, technology='grid', commodity='electricity', level='final', value=grid_efficiency) scenario.add_par('output', grid_out) grid_in = make_df(base_input, technology='grid', commodity='electricity', level='secondary', value=1.0) scen...
_____no_output_____
Apache-2.0
westeros/westeros_baseline.ipynb
fschoeni/homework_no3
And finally, our power plants. The model does not include the fossil resources used as `input` for coal plants; however, costs of coal extraction are included in the parameter $variable\_cost$.
coal_out = make_df(base_output, technology='coal_ppl', commodity='electricity', level='secondary', value=1.) scenario.add_par('output', coal_out) wind_out = make_df(base_output, technology='wind_ppl', commodity='electricity', level='secondary', value=1.) scenario.add_par('output...
_____no_output_____
Apache-2.0
westeros/westeros_baseline.ipynb
fschoeni/homework_no3
Operational Constraints and Parameters The model has a number of "reality" constraints, which relate built *capacity* (`CAP`) to available power, or the *activity* (`ACT`) of that technology.The **capacity constraint** limits the activity of a technology to the installed capacity multiplied by a capacity factor. Capac...
base_capacity_factor = { 'node_loc': country, 'year_vtg': vintage_years, 'year_act': act_years, 'time': 'year', 'unit': '-', } capacity_factor = { 'coal_ppl': 1, 'wind_ppl': 0.36, 'bulb': 1, } for tec, val in capacity_factor.items(): df = make_df(base_capacity_factor, technology=te...
_____no_output_____
Apache-2.0
westeros/westeros_baseline.ipynb
fschoeni/homework_no3
The model can further be provided `technical_lifetime`s in order to properly manage deployed capacity and related costs via the **capacity maintenance** constraint:$\text{CAP}_{n,t,y^V,y} \leq \text{remaining_capacity}_{n,t,y^V,y} \cdot \text{value} \quad \forall \quad t \in T^{INV}$where `value` can take different for...
base_technical_lifetime = { 'node_loc': country, 'year_vtg': model_horizon, 'unit': 'y', } lifetime = { 'coal_ppl': 20, 'wind_ppl': 20, 'bulb': 1, } for tec, val in lifetime.items(): df = make_df(base_technical_lifetime, technology=tec, value=val) scenario.add_par('technical_lifetime', ...
_____no_output_____
Apache-2.0
westeros/westeros_baseline.ipynb
fschoeni/homework_no3
Technological Diffusion and ContractionWe know from historical precedent that energy systems can not be transformed instantaneously. Therefore, we use a family of dynamic constraints on activity and capacity. These constraints define the upper and lower limit of the domain of activity and capacity over time based on t...
base_growth = { 'node_loc': country, 'year_act': model_horizon, 'time': 'year', 'unit': '-', } growth_technologies = [ "coal_ppl", "wind_ppl", ] for tec in growth_technologies: df = make_df(base_growth, technology=tec, value=0.1) scenario.add_par('growth_activity_up', df)
_____no_output_____
Apache-2.0
westeros/westeros_baseline.ipynb
fschoeni/homework_no3
Defining an Energy Mix (Model Calibration)To model the transition of an energy system, one must start with the existing system which are defined by the parameters `historical_activity` and `historical_new_capacity`. These parameters define the energy mix before the model horizon. We begin by defining a few key values...
historic_demand = 0.85 * demand_per_year historic_generation = historic_demand / grid_efficiency coal_fraction = 0.6 base_capacity = { 'node_loc': country, 'year_vtg': history, 'unit': 'GWa', } base_activity = { 'node_loc': country, 'year_act': history, 'mode': 'standard', 'time': 'year', ...
_____no_output_____
Apache-2.0
westeros/westeros_baseline.ipynb
fschoeni/homework_no3
Then, we can define the **activity** and **capacity** in the historic period
old_activity = { 'coal_ppl': coal_fraction * historic_generation, 'wind_ppl': (1 - coal_fraction) * historic_generation, } for tec, val in old_activity.items(): df = make_df(base_activity, technology=tec, value=val) scenario.add_par('historical_activity', df) act_to_cap = { 'coal_ppl': 1 / 10 / cap...
_____no_output_____
Apache-2.0
westeros/westeros_baseline.ipynb
fschoeni/homework_no3
Objective FunctionThe objective function drives the purpose of the optimization. Do we wish to seek maximum utility of the social planner, minimize carbon emissions, or something else? Classical IAMs seek to minimize total discounted system cost over space and time. $$\min \sum_{n,y \in Y^{M}} \text{interestrate}_{y} ...
scenario.add_par("interestrate", model_horizon, value=0.05, unit='-')
_____no_output_____
Apache-2.0
westeros/westeros_baseline.ipynb
fschoeni/homework_no3
`COST_NODAL` is comprised of a variety of costs related to the use of different technologies. Investment CostsCapital, or investment, costs are invoked whenever a new plant or unit is built$$\text{inv_cost}_{n,t,y} \cdot \text{construction_time_factor}_{n,t,y} \cdot \text{CAP_NEW}_{n,t,y}$$
base_inv_cost = { 'node_loc': country, 'year_vtg': model_horizon, 'unit': 'USD/kW', } # Adding a new unit to the library mp.add_unit('USD/kW') # in $ / kW (specific investment cost) costs = { 'coal_ppl': 500, 'wind_ppl': 1500, 'bulb': 5, } for tec, val in costs.items(): df = make_df(b...
_____no_output_____
Apache-2.0
westeros/westeros_baseline.ipynb
fschoeni/homework_no3
Fixed O&M CostsFixed cost are only relevant as long as the capacity is active. This formulation allows to include the potential cost savings from early retirement of installed capacity.$$\sum_{y^V \leq y} \text{fix_cost}_{n,t,y^V,y} \cdot \text{CAP}_{n,t,y^V,y}$$
base_fix_cost = { 'node_loc': country, 'year_vtg': vintage_years, 'year_act': act_years, 'unit': 'USD/kWa', } # in $ / kW / year (every year a fixed quantity is destinated to cover part of the O&M costs # based on the size of the plant, e.g. lightning, labor, scheduled maintenance, etc.) costs = { ...
_____no_output_____
Apache-2.0
westeros/westeros_baseline.ipynb
fschoeni/homework_no3
Variable O&M CostsVariable Operation and Maintence costs are associated with the costs of actively running the plant. Thus, they are not applied if a plant is on standby (i.e., constructed, but not currently in use).$$\sum_{\substack{y^V \leq y \\ m,h}} \text{var_cost}_{n,t,y^V,y,m,h} \cdot \text{ACT}_{n,t,y^V,y,m,h} ...
base_var_cost = { 'node_loc': country, 'year_vtg': vintage_years, 'year_act': act_years, 'mode': 'standard', 'time': 'year', 'unit': 'USD/kWa', } # in $ / kWa (costs associatied to the degradation of equipment when the plant is functioning # per unit of energy produced kW·year = 8760 kWh. # Ther...
_____no_output_____
Apache-2.0
westeros/westeros_baseline.ipynb
fschoeni/homework_no3
A full model will also have costs associated with- costs associated with technologies (investment, fixed, variable costs)- resource extraction: $\sum_{c,g} \ resource\_cost_{n,c,g,y} \cdot EXT_{n,c,g,y} $- emissions- land use (emulator): $\sum_{s} land\_cost_{n,s,y} \cdot LAND_{n,s,y}$ Time to Solve the ModelFirst, we...
from message_ix import log log.info('version number prior to commit: {}'.format(scenario.version)) scenario.commit(comment='basic model of Westeros electrification') log.info('version number prior committing to the database: {}'.format(scenario.version))
INFO:message_ix:version number prior to commit: 0 INFO:message_ix:version number prior committing to the database: 45
Apache-2.0
westeros/westeros_baseline.ipynb
fschoeni/homework_no3
An `ixmp` database can contain many scenarios, and possibly multiple versions of the same model and scenario name.These are distinguished by unique version numbers.To make it easier to retrieve the "correct" version (e.g., the latest one), you can set a specific scenario as the default version to use if the "Westeros E...
scenario.set_as_default() scenario.solve() scenario.var('OBJ')['lvl']
_____no_output_____
Apache-2.0
westeros/westeros_baseline.ipynb
fschoeni/homework_no3
Plotting ResultsWe make use of some custom code for plotting the results; see `tools.py` in the tutorial directory.
from tools import Plots p = Plots(scenario, country, firstyear=model_horizon[0])
_____no_output_____
Apache-2.0
westeros/westeros_baseline.ipynb
fschoeni/homework_no3
ActivityHow much energy is generated in each time period from the different potential sources?
p.plot_activity(baseyear=True, subset=['coal_ppl', 'wind_ppl'])
_____no_output_____
Apache-2.0
westeros/westeros_baseline.ipynb
fschoeni/homework_no3
CapacityHow much capacity of each plant is installed in each period?
p.plot_capacity(baseyear=True, subset=['coal_ppl', 'wind_ppl'])
_____no_output_____
Apache-2.0
westeros/westeros_baseline.ipynb
fschoeni/homework_no3
Electricity PriceAnd how much does the electricity cost? These prices are in fact **shadow prices** taken from the **dual variables** of the model solution.They reflect the marginal cost of electricity generation (i.e., the additional cost of the system for supplying one more unit ofelectricity), which is in fact the ...
p.plot_prices(subset=['light'], baseyear=True)
_____no_output_____
Apache-2.0
westeros/westeros_baseline.ipynb
fschoeni/homework_no3
Close the connection to the databaseWhen working with local HSQLDB database instances, you cannot connect to one database from multipe Jupyter notebooks (or processes) at the same time.If you want to easily switch between notebooks with connections to the same `ixmp` database, you need to close the connection in one n...
mp.close_db()
_____no_output_____
Apache-2.0
westeros/westeros_baseline.ipynb
fschoeni/homework_no3
Set UpToday you will create partial dependence plots and practice building insights with data from the [Taxi Fare Prediction](https://www.kaggle.com/c/new-york-city-taxi-fare-prediction) competition.We have again provided code to do the basic loading, review and model-building. Run the cell below to set everything up:
import pandas as pd from sklearn.ensemble import RandomForestRegressor from sklearn.linear_model import LinearRegression from sklearn.model_selection import train_test_split # Environment Set-Up for feedback system. from learntools.core import binder binder.bind(globals()) from learntools.ml_explainability.ex3 import ...
_____no_output_____
Apache-2.0
notebooks/ml_explainability/raw/ex3_partial_plots.ipynb
Mattjez914/Blackjack_Microchallenge
Question 1Here is the code to plot the partial dependence plot for pickup_longitude. Run the following cell.
from matplotlib import pyplot as plt from pdpbox import pdp, get_dataset, info_plots feat_name = 'pickup_longitude' pdp_dist = pdp.pdp_isolate(model=first_model, dataset=val_X, model_features=base_features, feature=feat_name) pdp.pdp_plot(pdp_dist, feat_name) plt.show()
_____no_output_____
Apache-2.0
notebooks/ml_explainability/raw/ex3_partial_plots.ipynb
Mattjez914/Blackjack_Microchallenge
Why does the partial dependence plot have this U-shape?Does your explanation suggest what shape to expect in the partial dependence plots for the other features?Create all other partial plots in a for-loop below (copying the appropriate lines from the code above).
for feat_name in base_features: pdp_dist = _ _ plt.show()
_____no_output_____
Apache-2.0
notebooks/ml_explainability/raw/ex3_partial_plots.ipynb
Mattjez914/Blackjack_Microchallenge
Do the shapes match your expectations for what shapes they would have? Can you explain the shape now that you've seen them? Uncomment the following line to check your intuition.
# q_1.solution()
_____no_output_____
Apache-2.0
notebooks/ml_explainability/raw/ex3_partial_plots.ipynb
Mattjez914/Blackjack_Microchallenge
Q2Now you will run a 2D partial dependence plot. As a reminder, here is the code from the tutorial. ```inter1 = pdp.pdp_interact(model=my_model, dataset=val_X, model_features=feature_names, features=['Goal Scored', 'Distance Covered (Kms)'])pdp.pdp_interact_plot(pdp_interact_out=inter1, feature_names=['Goal Scored...
# Add your code here
_____no_output_____
Apache-2.0
notebooks/ml_explainability/raw/ex3_partial_plots.ipynb
Mattjez914/Blackjack_Microchallenge
Uncomment the line below to see the solution and explanation for how one might reason about the plot shape.
# q_2.solution()
_____no_output_____
Apache-2.0
notebooks/ml_explainability/raw/ex3_partial_plots.ipynb
Mattjez914/Blackjack_Microchallenge
Question 3Consider a ride starting at longitude -73.92 and ending at longitude -74. Using the graph from the last question, estimate how much money the rider would have saved if they'd started the ride at longitude -73.98 instead?
savings_from_shorter_trip = _ q_3.check()
_____no_output_____
Apache-2.0
notebooks/ml_explainability/raw/ex3_partial_plots.ipynb
Mattjez914/Blackjack_Microchallenge
For a solution or hint, uncomment the appropriate line below.
# q_3.hint() # q_3.solution()
_____no_output_____
Apache-2.0
notebooks/ml_explainability/raw/ex3_partial_plots.ipynb
Mattjez914/Blackjack_Microchallenge
Question 4In the PDP's you've seen so far, location features have primarily served as a proxy to capture distance traveled. In the permutation importance lessons, you added the features `abs_lon_change` and `abs_lat_change` as a more direct measure of distance.Create these features again here. You only need to fill in...
# This is the PDP for pickup_longitude without the absolute difference features. Included here to help compare it to the new PDP you create feat_name = 'pickup_longitude' pdp_dist_original = pdp.pdp_isolate(model=first_model, dataset=val_X, model_features=base_features, feature=feat_name) pdp.pdp_plot(pdp_dist_origina...
_____no_output_____
Apache-2.0
notebooks/ml_explainability/raw/ex3_partial_plots.ipynb
Mattjez914/Blackjack_Microchallenge
Uncomment the lines below to see a hint or the solution (including an explanation of the important differences between the plots).
# q_4.hint() # q_4.solution()
_____no_output_____
Apache-2.0
notebooks/ml_explainability/raw/ex3_partial_plots.ipynb
Mattjez914/Blackjack_Microchallenge
Question 5Consider a scenario where you have only 2 predictive features, which we will call `feat_A` and `feat_B`. Both features have minimum values of -1 and maximum values of 1. The partial dependence plot for `feat_A` increases steeply over its whole range, whereas the partial dependence plot for feature B increas...
# q_5.solution()
_____no_output_____
Apache-2.0
notebooks/ml_explainability/raw/ex3_partial_plots.ipynb
Mattjez914/Blackjack_Microchallenge
Q6The code cell below does the following:1. Creates two features, `X1` and `X2`, having random values in the range [-2, 2].2. Creates a target variable `y`, which is always 1.3. Trains a `RandomForestRegressor` model to predict `y` given `X1` and `X2`.4. Creates a PDP plot for `X1` and a scatter plot of `X1` vs. `y`.D...
import numpy as np from numpy.random import rand n_samples = 20000 # Create array holding predictive feature X1 = 4 * rand(n_samples) - 2 X2 = 4 * rand(n_samples) - 2 # Create y. you should have X1 and X2 in the expression for y y = np.ones(n_samples) # create dataframe because pdp_isolate expects a dataFrame as an ...
_____no_output_____
Apache-2.0
notebooks/ml_explainability/raw/ex3_partial_plots.ipynb
Mattjez914/Blackjack_Microchallenge
Uncomment the lines below for a hint or solution
# q_6.hint() # q_6.solution()
_____no_output_____
Apache-2.0
notebooks/ml_explainability/raw/ex3_partial_plots.ipynb
Mattjez914/Blackjack_Microchallenge
Question 7Create a dataset with 2 features and a target, such that the pdp of the first feature is flat, but its permutation importance is high. We will use a RandomForest for the model.*Note: You only need to supply the lines that create the variables X1, X2 and y. The code to build the model and calculate insights ...
import eli5 from eli5.sklearn import PermutationImportance n_samples = 20000 # Create array holding predictive feature X1 = _ X2 = _ # Create y. you should have X1 and X2 in the expression for y y = _ # create dataframe because pdp_isolate expects a dataFrame as an argument my_df = pd.DataFrame({'X1': X1, 'X2': X2,...
_____no_output_____
Apache-2.0
notebooks/ml_explainability/raw/ex3_partial_plots.ipynb
Mattjez914/Blackjack_Microchallenge
Simple Model 3 Inception Module|true training data | Corr Training Data | Test Accuracy | Test Accuracy 0-1 | | ------------------ | ------------------ | ------------- | ----------------- || 100 | 47335 | 15 | 75 || 500 | 47335 | 16 | 80 | | 1000 | 47335 | 17 | 83 | | 2000 | 47335 | 19 | 92 | | 4000 |...
_____no_output_____
MIT
CODS_COMAD/SIN/MNIST/cnn_2layers_1000.ipynb
lnpandey/DL_explore_synth_data
Statistical analysis on NEMSIS BMI 6106 - Final Project Project by: Anwar Alsanea Luz Gabriela Iorg Jorge Rojas Abstract The National Emergency Medical Services Information System (NEMSIS) is a national database that contains Emergency Medical Services (EMS) data collected for the United States. In this project, w...
install.packages(c("FactoMineR", "factoextra")) install.packages("corrplot") install.packages("PCAmixdata") library(dplyr) library(ggplot2) library(gridExtra) library("FactoMineR") library("corrplot") library("factoextra") library(modelr) library(broom) library("PCAmixdata") require(stats) #require(pls)
_____no_output_____
MIT
Final_Proj/.ipynb_checkpoints/Stats Final Project -checkpoint.ipynb
alsaneaan/BMI_stats_final
Data: The file to import is saved under the name: events_cleaned_v3.txtThe code below is to import the data to the notebook
events = read.table(file = "events_cleaned_v3.txt", sep="|", header = TRUE, stringsAsFactors = F) head(events, n=7) #dim(events)
_____no_output_____
MIT
Final_Proj/.ipynb_checkpoints/Stats Final Project -checkpoint.ipynb
alsaneaan/BMI_stats_final
Data cleaning:- Create vectors, handle variables, and perform other basic functions (remove NAs)
event1 = select(events, age.in.years, gender, primary.method.of.payment, incident.location.type, primary.symptom, cause.of.injury, incident.patient.disposition, complaint.reported.by.dispatch ) event1[event1 < 0] <- NA #head(event1, n=50) event2 = na.exclude(event1)...
_____no_output_____
MIT
Final_Proj/.ipynb_checkpoints/Stats Final Project -checkpoint.ipynb
alsaneaan/BMI_stats_final
- Tackle data structures manipulation such as matrices, lists, factors, and data frames.
str(event2) #Converting gender as factor: event2$gender <-as.factor(event2$gender) levels(event2$gender) <- c("male", "female") #Converting dataframe as factor: event2 <- data.frame(lapply(event2, as.factor)) #Converting age.in.years as numeric: event2$age.in.years <-as.numeric(event2$age.in.years) #Checking summari...
'data.frame': 292 obs. of 8 variables: $ age.in.years : num 12 65 69 45 36 41 21 53 15 73 ... $ gender : Factor w/ 2 levels "male","female": 1 1 2 2 2 1 2 2 2 2 ... $ primary.method.of.payment : Factor w/ 6 levels "720","725","730",..: 1 1 3 5 4 4 2 2 2 3 ... $ incident...
MIT
Final_Proj/.ipynb_checkpoints/Stats Final Project -checkpoint.ipynb
alsaneaan/BMI_stats_final
Data Analysis: Build statistical models with linear regressions and analysis of variance Regressions: For our analysis, we are using the standard cut off at alpha = 0.05 Linear regression to predict gender :The first test is a generalized linear model to predict gender based on the remanining factors.The Null hypothe...
model = glm(gender ~. -gender, data= event2, family= binomial) summary(model) #Gender (outcome variable, Y) and the rest of the variables (predictors, X) #Null hypothesis (H0): the coefficients are equal to zero (i.e., no relationship between x and y) #Alternative Hypothesis (Ha): the coefficients are not equal to ze...
Warning message: “glm.fit: fitted probabilities numerically 0 or 1 occurred”
MIT
Final_Proj/.ipynb_checkpoints/Stats Final Project -checkpoint.ipynb
alsaneaan/BMI_stats_final
Linear regression results show that most factors had a P > 0.05, in which we have to accept the null hypothesis that the factors do not have an effect on gender and cannot predict gender. Except for primary.method.of.payment745 (which is Self Pay) and primary.symptom(1500 and 1505) are significantly associated with the...
model2 = lm(age.in.years ~. -age.in.years, data= event2) summary(model2) #age.in.years (outcome variable, Y) and the rest of the variables (predictors, X) #Null hypothesis (H0): the coefficients are equal to zero (i.e., no relationship between x and y) #Alternative Hypothesis (Ha): the coefficients are not equal to z...
_____no_output_____
MIT
Final_Proj/.ipynb_checkpoints/Stats Final Project -checkpoint.ipynb
alsaneaan/BMI_stats_final
Our results show that there are more factors having an effect on age than gender did. Primary methods 725 and 730 (medicaid and medicare) had high significance at P 65. Primary symptom 1500 (weakness) was significant towards age at P < 0.05. Weakness is a symptom that can explain more than one condition, it is however...
par(mfrow = c(2, 2)) plot(model2) #### Linearity of the data (Residuals vs Fitted). #There is no pattern in the residual plot. This suggests that we can assume linear relationship #between the predictors and the outcome variables. #### Normality of residuals (Normal Q-Q plot). #All the points fall approximately alo...
Warning message: “not plotting observations with leverage one: 13, 39, 65, 67, 82, 84, 105, 153, 239, 243, 258, 290, 291”Warning message: “not plotting observations with leverage one: 13, 39, 65, 67, 82, 84, 105, 153, 239, 243, 258, 290, 291”
MIT
Final_Proj/.ipynb_checkpoints/Stats Final Project -checkpoint.ipynb
alsaneaan/BMI_stats_final
Linearity of the data (Residuals vs Fitted plot): There is no pattern in the residual plot. This suggests that we can assume linear relationship between the predictors and the outcome variables. Normality of residuals (Normal Q-Q plot):All the points fall approximately along the reference line, so we can assume normal...
#Transformed Regression and new plot: model3 = lm(log(age.in.years) ~. -age.in.years, data= event2) plot(model3, 3) #heteroscedasticity has been improved.
Warning message: “not plotting observations with leverage one: 13, 39, 65, 67, 82, 84, 105, 153, 239, 243, 258, 290, 291”
MIT
Final_Proj/.ipynb_checkpoints/Stats Final Project -checkpoint.ipynb
alsaneaan/BMI_stats_final
Linear regression for age after log transformation:After the noticeable reduced heteroscedasticity in the data after using the log transformation, we examine the linear model again:
summary(model3) #After the log transformation of age, the p-values for the intercept and the predictor variables has #become more significant, hence indicating a stronger association between age.in.years and the predictors. ###Interpretation: #From the P value numbers we can say that primary.method.of.payment(725 ...
_____no_output_____
MIT
Final_Proj/.ipynb_checkpoints/Stats Final Project -checkpoint.ipynb
alsaneaan/BMI_stats_final
After the log transformation of age, the p-values for the intercept and the predictor variables has become more significant, hence indicating a stronger association between age.in.years and the predictors. *Interpretation:*From the P value numbers we can say that primary method of payment(725 and 730), incident locatio...
res.famd <- FAMD(event2, ncp=5, graph = FALSE) summary(res.famd) #About 5% of the variation is explained by this first eigenvalue, which is the first dimension. #Based on the contribution plots, the variables plots, and the significant categories, #we selected the next varibles for our simpler model: relevant = sele...
_____no_output_____
MIT
Final_Proj/.ipynb_checkpoints/Stats Final Project -checkpoint.ipynb
alsaneaan/BMI_stats_final
Visual representations for variables:
#Plots for the frequency of the variables' categories for (i in 2:8) { plot(event2[,i], main=colnames(event2)[i], ylab = "Count", xlab = "Categories", col="#00AFBB", las = 2) } #Some of the variable categories have a very low frequency. These variables could distort the analysis. #scree plot a = fviz_sc...
_____no_output_____
MIT
Final_Proj/.ipynb_checkpoints/Stats Final Project -checkpoint.ipynb
alsaneaan/BMI_stats_final
From the plots we can see that 19% of the variances contained in the data were retained by the first five principal components. The percentage value of our variables explains low variance among the factors. Variables gender, age, and incident patient disposition are strongly correlated with dimension 1. Hierarchical K...
df= select(relevant, age.in.years) #head(df) #Hierarchical K-means clustering hk3 <-hkmeans(df, 3) hk3$centers relevant2 = relevant relevant2$k3cluster = hk3$cluster relevant2$k3cluster <-as.factor(relevant2$k3cluster) #levels(relevant2$k3cluster) levels(relevant2$k3cluster) <- c("Child", "Young-Adult", "Adult" ) #l...
_____no_output_____
MIT
Final_Proj/.ipynb_checkpoints/Stats Final Project -checkpoint.ipynb
alsaneaan/BMI_stats_final
Una introducción a NuSA**NuSA** es una librería Python para resolver problemas de análisis estructural bidimensional. La idea es tener una estructura de códigos escritos utilizando la programación orientada a objetos, de modo que sea posible crear instancias de un modelo de elemento finito y operar con éste a través d...
_____no_output_____
MIT
docs/nusa-info/es/intro-nusa.ipynb
Bartman00/nusa
Training Arguments
datadir = '../../data' data_name = 'cifar10' fraction = float(0.1) num_epochs = int(300) select_every = int(20) feature = 'dss'# 70 warm_method = 0 # whether to use warmstart-onestep (1) or online (0) num_runs = 1 # number of random runs learning_rate = 0.05
_____no_output_____
MIT
examples/trials/cifar10_grad_match/notebooks/cifar10_example.ipynb
savan77/nni
Results Folder
all_logs_dir = './results/' + data_name +'/' + feature +'/' + str(fraction) + '/' + str(select_every) print(all_logs_dir) subprocess.run(["mkdir", "-p", all_logs_dir]) path_logfile = os.path.join(all_logs_dir, data_name + '.txt') logfile = open(path_logfile, 'w') exp_name = data_name + '_fraction:' + str(fraction) + '_...
./results/cifar10/dss/0.1/20 cifar10_fraction:0.1_epochs:300_selEvery:20_variant0_runs1
MIT
examples/trials/cifar10_grad_match/notebooks/cifar10_example.ipynb
savan77/nni
Loading CIFAR10 Dataset
print("=======================================", file=logfile) fullset, valset, testset, num_cls = load_mnist_cifar(datadir, data_name, feature)
Downloading https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz to ../data/cifar-10-python.tar.gz
MIT
examples/trials/cifar10_grad_match/notebooks/cifar10_example.ipynb
savan77/nni
Splitting Training dataset to train and validation sets
validation_set_fraction = 0.1 num_fulltrn = len(fullset) num_val = int(num_fulltrn * validation_set_fraction) num_trn = num_fulltrn - num_val trainset, validset = random_split(fullset, [num_trn, num_val]) N = len(trainset) trn_batch_size = 20
_____no_output_____
MIT
examples/trials/cifar10_grad_match/notebooks/cifar10_example.ipynb
savan77/nni
Creating DataLoaders
trn_batch_size = 20 val_batch_size = 1000 tst_batch_size = 1000 trainloader = torch.utils.data.DataLoader(trainset, batch_size=trn_batch_size, shuffle=False, pin_memory=True) valloader = torch.utils.data.DataLoader(valset, batch_size=val_batch_size, shuffle=False, ...
_____no_output_____
MIT
examples/trials/cifar10_grad_match/notebooks/cifar10_example.ipynb
savan77/nni
Budget for Data Subset Selection
bud = int(fraction * N) print("Budget, fraction and N:", bud, fraction, N) # Transfer all the data to GPU print_every = 3
Budget, fraction and N: 4500 0.1 45000
MIT
examples/trials/cifar10_grad_match/notebooks/cifar10_example.ipynb
savan77/nni
Loading ResNet Model
model = ResNet18(num_cls) model = model.to(device) print(model)
ResNet( (conv1): Conv2d(3, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) (bn1): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (layer1): Sequential( (0): BasicBlock( (conv1): Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=Fals...
MIT
examples/trials/cifar10_grad_match/notebooks/cifar10_example.ipynb
savan77/nni
Initial Random Subset for Training
start_idxs = np.random.choice(N, size=bud, replace=False)
_____no_output_____
MIT
examples/trials/cifar10_grad_match/notebooks/cifar10_example.ipynb
savan77/nni
Loss Type, Optimizer and Learning Rate Scheduler
criterion = nn.CrossEntropyLoss() optimizer = optim.SGD(model.parameters(), lr=learning_rate, momentum=0.9, weight_decay=5e-4) scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=num_epochs)
_____no_output_____
MIT
examples/trials/cifar10_grad_match/notebooks/cifar10_example.ipynb
savan77/nni
Last Layer GLISTER Strategy with Stcohastic Selection
setf_model = Strategy(trainloader, valloader, model, criterion, learning_rate, device, num_cls, False, 'Stochastic') idxs = start_idxs print("Starting Greedy Selection Strategy!") substrn_losses = np.zeros(num_epochs) fulltrn_losses = np.zeros(num_epochs) val_losses = np.zeros(num_epochs) ...
Starting Greedy Selection Strategy!
MIT
examples/trials/cifar10_grad_match/notebooks/cifar10_example.ipynb
savan77/nni
Training Loop
for i in tqdm.trange(num_epochs): subtrn_loss = 0 subtrn_correct = 0 subtrn_total = 0 start_time = time.time() if (((i+1) % select_every) == 0): cached_state_dict = copy.deepcopy(model.state_dict()) clone_dict = copy.deepcopy(model.state_dict()) ...
0%| | 1/300 [00:35<2:58:55, 35.91s/it]
MIT
examples/trials/cifar10_grad_match/notebooks/cifar10_example.ipynb
savan77/nni
Results Logging
print("SelectionRun---------------------------------") print("Final SubsetTrn and FullTrn Loss:", subtrn_loss, full_trn_loss) print("Validation Loss and Accuracy:", val_loss, val_acc[-1]) print("Test Data Loss and Accuracy:", tst_loss, tst_acc[-1]) print('-----------------------------------') print("GLISTER", file=log...
_____no_output_____
MIT
examples/trials/cifar10_grad_match/notebooks/cifar10_example.ipynb
savan77/nni
Full Data Training
torch.manual_seed(42) np.random.seed(42) model = ResNet18(num_cls) model = model.to(device) idxs = start_idxs criterion = nn.CrossEntropyLoss() #optimizer = optim.SGD(model.parameters(), lr=learning_rate) optimizer = optim.SGD(model.parameters(), lr=learning_rate, momentum=0.9, weight_decay=5e-4) sc...
_____no_output_____
MIT
examples/trials/cifar10_grad_match/notebooks/cifar10_example.ipynb
savan77/nni
Full Training Loop
for i in tqdm.trange(num_epochs): start_time = time.time() model.train() for batch_idx, (inputs, targets) in enumerate(trainloader): inputs, targets = inputs.to(device), targets.to(device, non_blocking=True) # Variables in Pytorch are differentiable. inputs, target = Variable(inputs)...
0%| | 0/300 [00:00<?, ?it/s]
MIT
examples/trials/cifar10_grad_match/notebooks/cifar10_example.ipynb
savan77/nni
Results and Timing Logging
print("SelectionRun---------------------------------") print("Final SubsetTrn and FullTrn Loss:", subtrn_loss, full_trn_loss) print("Validation Loss and Accuracy:", val_loss, val_acc[-1]) print("Test Data Loss and Accuracy:", tst_loss, tst_acc[-1]) print('-----------------------------------') print("Full Training", fi...
_____no_output_____
MIT
examples/trials/cifar10_grad_match/notebooks/cifar10_example.ipynb
savan77/nni
"Visualizing Earnings Based On College Majors"> "Awesome project using numpy, pandas & matplotlib"- toc: true- comments: true- image: images/cosmos.jpg- categories: [project]- tags: [Numpy, Pandas]- badges: true- twitter_large_image: true- featured: true
import pandas as pd import numpy as np import matplotlib.pyplot as plt %matplotlib inline recent_grads = pd.read_csv('recent-grads.csv') recent_grads.iloc[0] recent_grads.head() recent_grads.tail() recent_grads.describe() recent_grads.info() print('Number of Rows Before :', len(recent_grads)) recent_grads = recent_gra...
_____no_output_____
Apache-2.0
_notebooks/2021-05-12-visualizing-earnings.ipynb
MoRaouf/MoSpace
Nuevo Modelo
important_values = values\ .merge(labels, on="building_id") important_values.drop(columns=["building_id"], inplace = True) important_values["geo_level_1_id"] = important_values["geo_level_1_id"].astype("category") important_values important_values.shape X_train, X_test, y_train, y_test = train_test_spl...
building_id,damage_grade 300051,3 99355,2 890251,2 745817,1 421793,3 871976,2 691228,1 896100,3 343471,2
MIT
src/RandomForest/jf-model-8.ipynb
joaquinfontela/Machine-Learning
Equilibrium constantsCalculating equilibrium constants from energy values is easy.It's known that the stability constant of $\require{mhchem}\ce{Cd(MeNH2)4^{2+}}$ is around $10^{6.55}$:
from overreact import core, _thermo, simulate import numpy as np from scipy import constants K = _thermo.equilibrium_constant(-37.4 * constants.kilo) np.log10(K)
_____no_output_____
MIT
notebooks/tutorials/2 equilibrium constants.ipynb
geem-lab/overreact-guide
So let's check it:
scheme = core.parse_reactions(""" Cd2p + 4 MeNH2 <=> [Cd(MeNH2)4]2p """) scheme.compounds, scheme.reactions dydt = simulate.get_dydt(scheme, np.array([K[0], 1.])) y, r = simulate.get_y(dydt, y0=[0., 0., 1.]) y(y.t_max) Kobs = y(y.t_max)[2] / (y(y.t_max)[0] * y(y.t_max)[1]**4) np.log10(Kobs)
_____no_output_____
MIT
notebooks/tutorials/2 equilibrium constants.ipynb
geem-lab/overreact-guide
Binary classification from 2 features using K Nearest Neighbors (KNN)Classification using "raw" python or libraries.The binary classification is on a single boundary defined by a continuous function and added white noise
import numpy as np from numpy import random import matplotlib.pyplot as plt import matplotlib.colors as pltcolors from sklearn import metrics from sklearn.neighbors import KNeighborsClassifier as SkKNeighborsClassifier import pandas as pd import seaborn as sns
_____no_output_____
MIT
classification/ClassificationContinuous2Features-KNN.ipynb
tonio73/data-science
ModelQuadratic function as boundary between positive and negative valuesAdding some unknown as a Gaussian noiseThe values of X are uniformly distributed and independent
# Two features, Gaussian noise def generateBatch(N): # xMin = 0 xMax = 1 b = 0.1 std = 0.1 # x = random.uniform(xMin, xMax, (N, 2)) # 4th degree relation to shape the boundary boundary = 2*(x[:,0]**4 + (x[:,0]-0.3)**3 + b) # Adding some gaussian noise labels = boundary + rand...
_____no_output_____
MIT
classification/ClassificationContinuous2Features-KNN.ipynb
tonio73/data-science
Training data
N = 2000 # x has 1 dim in R, label has 1 dim in B xTrain, labelTrain = generateBatch(N) colors = ['blue','red'] fig = plt.figure(figsize=(15,4)) plt.subplot(1,3,1) plt.scatter(xTrain[:,0], xTrain[:,1], c=labelTrain, cmap=pltcolors.ListedColormap(colors), marker=',', alpha=0.1) plt.xlabel('x0') plt.ylabel('x1') plt.ti...
Bernouilli parameter of the distribution: 0.506
MIT
classification/ClassificationContinuous2Features-KNN.ipynb
tonio73/data-science
Test data for verification of the model
xTest, labelTest = generateBatch(N) testColors = ['navy', 'orangered']
_____no_output_____
MIT
classification/ClassificationContinuous2Features-KNN.ipynb
tonio73/data-science
Helpers
def plotHeatMap(X, classes, title=None, fmt='.2g', ax=None, xlabel=None, ylabel=None): """ Fix heatmap plot from Seaborn with pyplot 3.1.0, 3.1.1 https://stackoverflow.com/questions/56942670/matplotlib-seaborn-first-and-last-row-cut-in-half-of-heatmap-plot """ ax = sns.heatmap(X, xticklabels=classes...
_____no_output_____
MIT
classification/ClassificationContinuous2Features-KNN.ipynb
tonio73/data-science
K Nearest Neighbors (KNN)References:- https://en.wikipedia.org/wiki/K-nearest_neighbors_algorithm- https://machinelearningmastery.com/tutorial-to-implement-k-nearest-neighbors-in-python-from-scratch/ HomemadeUsing a simple algorithm.Unweighted : each of the K neighbors has the same weight
# Select a K k = 10 # Create a Panda dataframe in order to link x and y df = pd.DataFrame(np.concatenate((xTrain, labelTrain.reshape(-1,1)), axis=1), columns = ('x0', 'x1', 'label')) # Insert columns to compute the difference of current test to the train and the L2 df.insert(df.shape[1], 'diff0', 0) df.insert(df.shape[...
_____no_output_____
MIT
classification/ClassificationContinuous2Features-KNN.ipynb
tonio73/data-science