markdown
stringlengths
0
37k
code
stringlengths
1
33.3k
path
stringlengths
8
215
repo_name
stringlengths
6
77
license
stringclasses
15 values
summary With python batch_size = 128 num_hidden_nodes = 1024 beta = 1e-3 num_steps = 3001 Results * Test accuracy: 88.5% with beta=0.000000 (no L2 regulization) * Test accuracy: 86.7% with beta=0.000010 * Test accuracy: 88.8% with beta=0.000100 * Test accuracy: 92.6% with beta=0.001000 * Test accuracy: 89.7% with beta=...
offset = 0 #offset = (step * batch_size) % (train_labels.shape[0] - batch_size)
google_dl_udacity/lesson3/3_regularization.ipynb
jinzishuai/learn2deeplearn
gpl-3.0
With python batch_size = 128 num_hidden_nodes = 1024 beta = 1e-3 num_steps = 3001 Results * Original Test accuracy: 92.6% with beta=0.001000 * With offset = 0: Test accuracy: 67.5% with beta=0.001000 Problem 3 Introduce Dropout on the hidden layer of the neural network. Remember: Dropout should only be introduced duri...
keep_rate = 0.5 dropout = tf.nn.dropout(activated_hidden_layer, keep_rate) #dropout if applied after activation logits = tf.matmul(dropout, weights2) + biases2
google_dl_udacity/lesson3/3_regularization.ipynb
jinzishuai/learn2deeplearn
gpl-3.0
Change the above cell to refer to the file locations on your computer (The reason it is two files is that I encountered a previously unseen error halfway through, and had to put a new try/except into the code and restart the scraping).
len(scrape1) len(scrape2) df = pd.concat([scrape1,scrape2]) len(df) df.columns df['days_jailed'] = df.release_timestamp - df.booking_timestamp df['days_jailed_np'] = df.days_jailed.dt.days df.loc[df['days_jailed_np']>7,'days_jailed_np'] = 7 sns.distplot(df['days_jailed_np'].dropna())
src/visualization/Fulton County Data Viz.ipynb
lahoffm/aclu-bail-reform
mit
This gives us the overall distribution of time imprisoned for everyone in our dataset who has been released.
df.groupby('inmate_race').agg({'days_jailed_np' : np.mean}).plot(kind='bar')
src/visualization/Fulton County Data Viz.ipynb
lahoffm/aclu-bail-reform
mit
This gives us mean time in prison by race.
ax= sns.violinplot(data=df, x='inmate_race', y='days_jailed_np', cut=0, scale='width') for tick in ax.get_xticklabels(): tick.set_rotation(45)
src/visualization/Fulton County Data Viz.ipynb
lahoffm/aclu-bail-reform
mit
Get IRS data on businesses The IRS website has some aggregated statistics on business returns in Excel files. We will use the Selected Income and Tax Items for Selected Years. The original data is from the file linked here: https://www.irs.gov/pub/irs-soi/14intaba.xls, but I cleaned it up by hand to remove footnotes an...
raw = pd.read_excel('data/14intaba_cleaned.xls', skiprows=2)
notebooks/input_output.ipynb
tanyaschlusser/stats-via-python
mit
Look at the last 3 rows The function pd.read_excel returns an object called a 'Data Frame', that is defined inside of the Pandas library. It has associated functions that access and manipulate the data inside. For example:
# Look at the last 3 rows raw.tail(3)
notebooks/input_output.ipynb
tanyaschlusser/stats-via-python
mit
Split out the 'Current dollars' and 'Constant 1990 dollars' There are two sets of data — for the actual dollars for each variable, and also for constant dollars (accounting for inflation). We will split the raw dataset into two and then index the rows by the units (whether they're number of returns or amount paid/claim...
index_cols = ['Units', 'Variable'] current_dollars_cols = index_cols + [ c for c in raw.columns if c.startswith('Current') ] constant_dollars_cols = index_cols + [ c for c in raw.columns if c.startswith('Constant') ] current_dollars_data = raw[current_dollars_cols][9:] current_dollars_data.set_index(keys=index...
notebooks/input_output.ipynb
tanyaschlusser/stats-via-python
mit
Statistics Pandas provides methods for statistical summaries. The describe method gives an overall summary. dropna(axis=1) deletes columns containing null values. If it were axis=0 it would be deleting rows.
per_entry = ( constant_dollars_data.transpose()['Amount (thousand USD)'] * 1000 / constant_dollars_data.transpose()['Number of returns'] ) per_entry.dropna(axis=1).describe().round()
notebooks/input_output.ipynb
tanyaschlusser/stats-via-python
mit
Plot The library that provides plot functions is called Matplotlib. To show the plots in this notebook you need to use the "magic method" %matplotlib inline. It should be used at the beginning of the notebook for clarity.
# This should always be at the beginning of the notebook, # like all magic statements and import statements. # It's only here because I didn't want to describe it earlier. %matplotlib inline import matplotlib.pyplot as plt plt.rcParams['figure.figsize'] = (10, 12)
notebooks/input_output.ipynb
tanyaschlusser/stats-via-python
mit
The per-entry data The data are (I think) for every form filed, not really per capita, but since we're not interpreting it for anything important we can conflate the two. Per capita income (Blue line) rose a lot with the tech bubble, then sunk with its crash, and then followed the housing bubble and crash. It also look...
styles = ['b-', 'g-.', 'r--', 'c-', 'm:'] axes = per_entry[[ 'Total income', 'Total social security benefits (not in income)', 'Business or profession net income less loss', 'Total payments', 'Unemployment compensation']].plot(style=styles) plt.suptitle('Average USD per return (w...
notebooks/input_output.ipynb
tanyaschlusser/stats-via-python
mit
Also with log-y We can see the total social security benefits payout (Green dot dash) increase as the baby boomers come of age, and we see the unemployment compensation (Magenta dots) spike after the 2008 crisis and then fall off.
styles = ['b-', 'r--', 'g-.', 'c-', 'm:'] axes = constant_dollars_data.transpose()['Amount (thousand USD)'][[ 'Total income', 'Total payments', 'Total social security benefits (not in income)', 'Business or profession net income less loss', 'Unemployment compensation']].plot(logy...
notebooks/input_output.ipynb
tanyaschlusser/stats-via-python
mit
Step 2: Load Training Data
print("Running on system: %s" % socket.gethostname()) if True: # Using a local copy of data volume #inDir = '/Users/graywr1/code/bio-segmentation/data/ISBI2012/' inDir = '/home/pekalmj1/Data/EM_2012' X = ndp.nddl.load_cube(os.path.join(inDir, 'train-volume.tif')) Y = ndp.nddl.load_cube(os.path.joi...
examples/isbi2012_train.ipynb
neurodata/ndparse
apache-2.0
Step 3: Training
# Note that for demonstration purposes we use an artifically low # number of training slices and epochs. For actualy training, # you would use more data and train for longer. train_slices = np.arange(2) # e.g. change to np.arange(25) valid_slices = np.arange(25,30) n_epochs = 1 tic = time.time() model = ndp.nd...
examples/isbi2012_train.ipynb
neurodata/ndparse
apache-2.0
Next, we need to authenticate ourselves to Google Cloud Platform. If you are running the code cell below for the first time, a link will show up, which leads to a web page for authentication and authorization. Login with your crendentials and make sure the permissions it requests are proper, after clicking Allow button...
auth.authenticate_user()
datathon/nusdatathon18/tutorials/ddsm_ml_tutorial.ipynb
GoogleCloudPlatform/healthcare
apache-2.0
At the same time, let's set the project we are going to use throughout the tutorial.
project_id = 'nus-datathon-2018-team-00' os.environ["GOOGLE_CLOUD_PROJECT"] = project_id
datathon/nusdatathon18/tutorials/ddsm_ml_tutorial.ipynb
GoogleCloudPlatform/healthcare
apache-2.0
Optional: In this Colab we can opt to use GPU to train our model by clicking "Runtime" on the top menus, then clicking "Change runtime type", select "GPU" for hardware accelerator. You can verify that GPU is working with the following code cell.
# Should output something like '/device:GPU:0'. tf.test.gpu_device_name()
datathon/nusdatathon18/tutorials/ddsm_ml_tutorial.ipynb
GoogleCloudPlatform/healthcare
apache-2.0
Dataset We have already extracted the images from the DICOM files to separate folders on GCS, and some preprocessing were also done with the raw images (If you need custom preprocessing, please consult our tutorial on image preprocessing). The folders ending with _demo contain subsets of training and test images. Speci...
client = storage.Client() bucket_name = 'datathon-cbis-ddsm-colab' bucket = client.get_bucket(bucket_name) def load_images(folder): images = [] labels = [] # The image name is in format: <LABEL>_Calc_{Train,Test}_P_<Patient_ID>_{Left,Right}_CC. for label in [1, 2, 3, 4]: blobs = bucket.list_blobs(prefix=(...
datathon/nusdatathon18/tutorials/ddsm_ml_tutorial.ipynb
GoogleCloudPlatform/healthcare
apache-2.0
Let's create a model function, which will be passed to an estimator that we will create later. The model has an architecture of 6 layers: Convolutional Layer: Applies 32 5x5 filters, with ReLU activation function Pooling Layer: Performs max pooling with a 2x2 filter and stride of 2 Convolutional Layer: Applies 64 5x5 ...
KERNEL_SIZE = 5 #@param DROPOUT_RATE = 0.25 #@param def cnn_model_fn(features, labels, mode): """Model function for CNN.""" # Input Layer. # Reshape to 4-D tensor: [batch_size, height, width, channels] # DDSM images are grayscale, which have 1 channel. input_layer = tf.reshape(features["x"], [-1, 95, 128, 1...
datathon/nusdatathon18/tutorials/ddsm_ml_tutorial.ipynb
GoogleCloudPlatform/healthcare
apache-2.0
Now that we have a model function, next step is feeding it to an estimator for training. Here are are creating a main function as required by tensorflow.
BATCH_SIZE = 20 #@param STEPS = 1000 #@param artifacts_bucket_name = 'nus-datathon-2018-team-00-shared-files' # Append a random number to avoid collision. artifacts_path = "ddsm_model_%s" % random.randint(0, 1000) model_dir = "gs://%s/%s" % (artifacts_bucket_name, artifacts_path) def main(_): # Load training and te...
datathon/nusdatathon18/tutorials/ddsm_ml_tutorial.ipynb
GoogleCloudPlatform/healthcare
apache-2.0
Finally, here comes the exciting moment. We are going to train and evaluate the model we just built! Run the following code cell and pay attention to the accuracy printed at the end of logs. Note if this is not the first time you run the following cell, to avoid weird errors like "NaN loss during training", please run ...
# Remove temporary files. artifacts_bucket = client.get_bucket(artifacts_bucket_name) artifacts_bucket.delete_blobs(artifacts_bucket.list_blobs(prefix=artifacts_path)) # Set logging level. tf.logging.set_verbosity(tf.logging.INFO) # Start training, this will call the main method defined above behind the scene. # The ...
datathon/nusdatathon18/tutorials/ddsm_ml_tutorial.ipynb
GoogleCloudPlatform/healthcare
apache-2.0
UMAP vs T-SNE Uniform Manifold Approximation and Projection (UMAP) is a dimension reduction technique that can be used for visualisation similarly to t-SNE, but also for general non-linear dimension reduction. The algorithm is founded on three assumptions about the data The data is uniformly distributed on a Riemannia...
corpus = load_hobbies()
examples/Sangarshanan/comparing_corpus_visualizers.ipynb
pdamodaran/yellowbrick
apache-2.0
Writing a Function to quickly Visualize Corpus Which can then be used for rapid comparison
def visualize(dim_reduction,encoding,corpus,labels = True,alpha=0.7,metric=None): if 'tfidf' in encoding.lower(): encode = TfidfVectorizer() if 'count' in encoding.lower(): encode = CountVectorizer() docs = encode.fit_transform(corpus.data) if labels is True: labels = corpus.t...
examples/Sangarshanan/comparing_corpus_visualizers.ipynb
pdamodaran/yellowbrick
apache-2.0
Quickly Comparing Plots by Controlling The Dimensionality Reduction technique used The Encoding Technique used The dataset to be visualized Whether to differentiate Labels or not Set the alpha parameter Set the metric for UMAP
visualize('t-sne','tfidf',corpus) visualize('t-sne','count',corpus,alpha = 0.5) visualize('t-sne','tfidf',corpus,labels =False) visualize('umap','tfidf',corpus) visualize('umap','tfidf',corpus,labels = False) visualize('umap','count',corpus,metric= 'cosine')
examples/Sangarshanan/comparing_corpus_visualizers.ipynb
pdamodaran/yellowbrick
apache-2.0
1.3. Chemistry Scheme Scope Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Atmospheric domains covered by the atmospheric chemistry model
# PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.key_properties.chemistry_scheme_scope') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "troposhere" # "stratosphere" # "mesosphere" # "mesosphere" # "whole atmosphere" # "Other: [...
notebooks/noaa-gfdl/cmip6/models/gfdl-esm4/atmoschem.ipynb
ES-DOC/esdoc-jupyterhub
gpl-3.0
1.4. Basic Approximations Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Basic approximations made in the atmospheric chemistry model
# PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.key_properties.basic_approximations') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") DOC.set_value("Lumped higher hydrocarbon species and oxidation products, parameterized source of Cly and Bry in stratosphere, short-lived species not advecte...
notebooks/noaa-gfdl/cmip6/models/gfdl-esm4/atmoschem.ipynb
ES-DOC/esdoc-jupyterhub
gpl-3.0
1.6. Number Of Tracers Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Number of advected tracers in the atmospheric chemistry model
# PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.key_properties.number_of_tracers') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) DOC.set_value(82)
notebooks/noaa-gfdl/cmip6/models/gfdl-esm4/atmoschem.ipynb
ES-DOC/esdoc-jupyterhub
gpl-3.0
1.8. Coupling With Chemical Reactivity Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Atmospheric chemistry transport scheme turbulence is couple with chemical reactivity?
# PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.key_properties.coupling_with_chemical_reactivity') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False DOC.set_value(True)
notebooks/noaa-gfdl/cmip6/models/gfdl-esm4/atmoschem.ipynb
ES-DOC/esdoc-jupyterhub
gpl-3.0
3. Key Properties --&gt; Timestep Framework Timestepping in the atmospheric chemistry model 3.1. Method Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Mathematical method deployed to solve the evolution of a given variable
# PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.key_properties.timestep_framework.method') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Operator splitting" # "Integrated" # "Other: [Please specify]" DOC.set_value("Operator splitting")
notebooks/noaa-gfdl/cmip6/models/gfdl-esm4/atmoschem.ipynb
ES-DOC/esdoc-jupyterhub
gpl-3.0
3.2. Split Operator Advection Timestep Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Timestep for chemical species advection (in seconds)
# PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.key_properties.timestep_framework.split_operator_advection_timestep') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) DOC.set_value(30)
notebooks/noaa-gfdl/cmip6/models/gfdl-esm4/atmoschem.ipynb
ES-DOC/esdoc-jupyterhub
gpl-3.0
3.3. Split Operator Physical Timestep Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Timestep for physics (in seconds).
# PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.key_properties.timestep_framework.split_operator_physical_timestep') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) DOC.set_value(30)
notebooks/noaa-gfdl/cmip6/models/gfdl-esm4/atmoschem.ipynb
ES-DOC/esdoc-jupyterhub
gpl-3.0
10. Emissions Concentrations --&gt; Surface Emissions ** 10.1. Sources Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N Sources of the chemical species emitted at the surface that are taken into account in the emissions scheme
# PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.emissions_concentrations.surface_emissions.sources') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "Vegetation" # "Soil" # "Sea surface" # "Anthropogenic" # "Biomass burning" # "...
notebooks/noaa-gfdl/cmip6/models/gfdl-esm4/atmoschem.ipynb
ES-DOC/esdoc-jupyterhub
gpl-3.0
10.3. Prescribed Climatology Emitted Species Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 List of chemical species emitted at the surface and prescribed via a climatology, and the nature of the climatology (E.g. CO (monthly), C2H6 (constant))
# PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.emissions_concentrations.surface_emissions.prescribed_climatology_emitted_species') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") DOC.set_value("CO, CH2O, NO, C3H6, isoprene, C2H6, C2H4, C4H10, terpenes, C3H8, acetone, CH3OH, C2H5OH, H2, SO2...
notebooks/noaa-gfdl/cmip6/models/gfdl-esm4/atmoschem.ipynb
ES-DOC/esdoc-jupyterhub
gpl-3.0
10.5. Interactive Emitted Species Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 List of chemical species emitted at the surface and specified via an interactive method
# PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.emissions_concentrations.surface_emissions.interactive_emitted_species') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") DOC.set_value("DMS")
notebooks/noaa-gfdl/cmip6/models/gfdl-esm4/atmoschem.ipynb
ES-DOC/esdoc-jupyterhub
gpl-3.0
11. Emissions Concentrations --&gt; Atmospheric Emissions TO DO 11.1. Sources Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N Sources of chemical species emitted in the atmosphere that are taken into account in the emissions scheme.
# PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.emissions_concentrations.atmospheric_emissions.sources') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "Aircraft" # "Biomass burning" # "Lightning" # "Volcanos" # "Other: [Please specif...
notebooks/noaa-gfdl/cmip6/models/gfdl-esm4/atmoschem.ipynb
ES-DOC/esdoc-jupyterhub
gpl-3.0
11.3. Prescribed Climatology Emitted Species Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 List of chemical species emitted in the atmosphere and prescribed via a climatology (E.g. CO (monthly), C2H6 (constant))
# PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.emissions_concentrations.atmospheric_emissions.prescribed_climatology_emitted_species') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") DOC.set_value("CO, CH2O, NO, C3H6, isoprene, C2H6, C2H4, C4H10, terpenes, C3H8, acetone, CH3OH, C2H5OH, H2,...
notebooks/noaa-gfdl/cmip6/models/gfdl-esm4/atmoschem.ipynb
ES-DOC/esdoc-jupyterhub
gpl-3.0
12. Emissions Concentrations --&gt; Concentrations TO DO 12.1. Prescribed Lower Boundary Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 List of species prescribed at the lower boundary.
# PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.emissions_concentrations.concentrations.prescribed_lower_boundary') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") DOC.set_value("CH4, N2O")
notebooks/noaa-gfdl/cmip6/models/gfdl-esm4/atmoschem.ipynb
ES-DOC/esdoc-jupyterhub
gpl-3.0
13.2. Species Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N Species included in the gas phase chemistry scheme.
# PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.gas_phase_chemistry.species') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "HOx" # "NOy" # "Ox" # "Cly" # "HSOx" # "Bry" # "VOCs" # "isoprene" # "H2O" # ...
notebooks/noaa-gfdl/cmip6/models/gfdl-esm4/atmoschem.ipynb
ES-DOC/esdoc-jupyterhub
gpl-3.0
13.3. Number Of Bimolecular Reactions Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 The number of bi-molecular reactions in the gas phase chemistry scheme.
# PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.gas_phase_chemistry.number_of_bimolecular_reactions') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) DOC.set_value(157)
notebooks/noaa-gfdl/cmip6/models/gfdl-esm4/atmoschem.ipynb
ES-DOC/esdoc-jupyterhub
gpl-3.0
13.4. Number Of Termolecular Reactions Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 The number of ter-molecular reactions in the gas phase chemistry scheme.
# PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.gas_phase_chemistry.number_of_termolecular_reactions') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) DOC.set_value(21)
notebooks/noaa-gfdl/cmip6/models/gfdl-esm4/atmoschem.ipynb
ES-DOC/esdoc-jupyterhub
gpl-3.0
13.8. Number Of Steady State Species Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 The number of gas phase species for which the concentration is updated in the chemical solver assuming photochemical steady state
# PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.gas_phase_chemistry.number_of_steady_state_species') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) DOC.set_value(19)
notebooks/noaa-gfdl/cmip6/models/gfdl-esm4/atmoschem.ipynb
ES-DOC/esdoc-jupyterhub
gpl-3.0
13.10. Wet Deposition Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Is wet deposition included? Wet deposition describes the moist processes by which gaseous species deposit themselves on solid surfaces thus decreasing their concentration in the air.
# PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.gas_phase_chemistry.wet_deposition') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False DOC.set_value(True)
notebooks/noaa-gfdl/cmip6/models/gfdl-esm4/atmoschem.ipynb
ES-DOC/esdoc-jupyterhub
gpl-3.0
13.11. Wet Oxidation Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Is wet oxidation included? Oxidation describes the loss of electrons or an increase in oxidation state by a molecule
# PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.gas_phase_chemistry.wet_oxidation') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False DOC.set_value(True)
notebooks/noaa-gfdl/cmip6/models/gfdl-esm4/atmoschem.ipynb
ES-DOC/esdoc-jupyterhub
gpl-3.0
14.2. Gas Phase Species Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N Gas phase species included in the stratospheric heterogeneous chemistry scheme.
# PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.stratospheric_heterogeneous_chemistry.gas_phase_species') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "Cly" # "Bry" # "NOy" DOC.set_value("Bry") DOC.set_value("Cly") DOC.set_value("NOy")
notebooks/noaa-gfdl/cmip6/models/gfdl-esm4/atmoschem.ipynb
ES-DOC/esdoc-jupyterhub
gpl-3.0
14.3. Aerosol Species Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N Aerosol species included in the stratospheric heterogeneous chemistry scheme.
# PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.stratospheric_heterogeneous_chemistry.aerosol_species') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "Sulphate" # "Polar stratospheric ice" # "NAT (Nitric acid trihydrate)" # "NAD (Nitric aci...
notebooks/noaa-gfdl/cmip6/models/gfdl-esm4/atmoschem.ipynb
ES-DOC/esdoc-jupyterhub
gpl-3.0
14.4. Number Of Steady State Species Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 The number of steady state species in the stratospheric heterogeneous chemistry scheme.
# PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.stratospheric_heterogeneous_chemistry.number_of_steady_state_species') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) DOC.set_value(3)
notebooks/noaa-gfdl/cmip6/models/gfdl-esm4/atmoschem.ipynb
ES-DOC/esdoc-jupyterhub
gpl-3.0
14.5. Sedimentation Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Is sedimentation is included in the stratospheric heterogeneous chemistry scheme or not?
# PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.stratospheric_heterogeneous_chemistry.sedimentation') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False DOC.set_value(True)
notebooks/noaa-gfdl/cmip6/models/gfdl-esm4/atmoschem.ipynb
ES-DOC/esdoc-jupyterhub
gpl-3.0
14.6. Coagulation Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Is coagulation is included in the stratospheric heterogeneous chemistry scheme or not?
# PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.stratospheric_heterogeneous_chemistry.coagulation') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False DOC.set_value(True)
notebooks/noaa-gfdl/cmip6/models/gfdl-esm4/atmoschem.ipynb
ES-DOC/esdoc-jupyterhub
gpl-3.0
15.2. Gas Phase Species Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 List of gas phase species included in the tropospheric heterogeneous chemistry scheme.
# PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.tropospheric_heterogeneous_chemistry.gas_phase_species') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") DOC.set_value("3")
notebooks/noaa-gfdl/cmip6/models/gfdl-esm4/atmoschem.ipynb
ES-DOC/esdoc-jupyterhub
gpl-3.0
15.3. Aerosol Species Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N Aerosol species included in the tropospheric heterogeneous chemistry scheme.
# PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.tropospheric_heterogeneous_chemistry.aerosol_species') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "Sulphate" # "Nitrate" # "Sea salt" # "Dust" # "Ice" # "Organic" # "Bl...
notebooks/noaa-gfdl/cmip6/models/gfdl-esm4/atmoschem.ipynb
ES-DOC/esdoc-jupyterhub
gpl-3.0
15.6. Coagulation Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Is coagulation is included in the tropospheric heterogeneous chemistry scheme or not?
# PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.tropospheric_heterogeneous_chemistry.coagulation') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False DOC.set_value(True)
notebooks/noaa-gfdl/cmip6/models/gfdl-esm4/atmoschem.ipynb
ES-DOC/esdoc-jupyterhub
gpl-3.0
16.2. Number Of Reactions Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 The number of reactions in the photo-chemistry scheme.
# PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.photo_chemistry.number_of_reactions') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) DOC.set_value(39)
notebooks/noaa-gfdl/cmip6/models/gfdl-esm4/atmoschem.ipynb
ES-DOC/esdoc-jupyterhub
gpl-3.0
17. Photo Chemistry --&gt; Photolysis Photolysis scheme 17.1. Method Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Photolysis scheme
# PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.photo_chemistry.photolysis.method') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Offline (clear sky)" # "Offline (with clouds)" # "Online" DOC.set_value("Offline (with clouds)")
notebooks/noaa-gfdl/cmip6/models/gfdl-esm4/atmoschem.ipynb
ES-DOC/esdoc-jupyterhub
gpl-3.0
1 Counter A Counter is a dict subclass for counting hashable objects. It is an unordered collection where elements are stored as dictionary keys and their counts are stored as dictionary values. 1.1 construction
c1 = Counter() c2 = Counter('gaufung') c3 = Counter({'red':4,'blue':10}) c4 = Counter(cats=4,dogs=5)
python-statatics-tutorial/basic-theme/python-language/Collections.ipynb
gaufung/Data_Analytics_Learning_Note
mit
1.2 using key
c = Counter(['dog', 'cat']) c['fox']
python-statatics-tutorial/basic-theme/python-language/Collections.ipynb
gaufung/Data_Analytics_Learning_Note
mit
1.3 delete key Setting a count to zero does not remove an element from a counter. Use del to remove it entirely:
c['dog'] = 0 del c['dog']
python-statatics-tutorial/basic-theme/python-language/Collections.ipynb
gaufung/Data_Analytics_Learning_Note
mit
1.4 elements Return an iterator over elements repeating each as many times as its count.
c = Counter(a=4, b=2, c=0, d=-2) print list(c.elements())
python-statatics-tutorial/basic-theme/python-language/Collections.ipynb
gaufung/Data_Analytics_Learning_Note
mit
1.5 most_common Return a list of the n most common elements and their counts from the most common to the least.
Counter('abracadabra').most_common(3)
python-statatics-tutorial/basic-theme/python-language/Collections.ipynb
gaufung/Data_Analytics_Learning_Note
mit
1.6 subtract([iterable-or-mapping]) Elements are subtracted from an iterable or from another mapping (or counter).
c = Counter(a=4, b=2, c=0, d=-2) d = Counter(a=1, b=2, c=3, d=4) c.subtract(d) c
python-statatics-tutorial/basic-theme/python-language/Collections.ipynb
gaufung/Data_Analytics_Learning_Note
mit
2 deque Deques are a generalization of stacks and queues,Deques support thread-safe, memory efficient appends and pops from either side of the deque with approximately the same O(1) performance in either direction. append(x) Add x to the right side of the deque. appendleft(x) Add x to the left side of the deque. ...
s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)] d = defaultdict(list) for k, v in s: d[k].append(v) d.items()
python-statatics-tutorial/basic-theme/python-language/Collections.ipynb
gaufung/Data_Analytics_Learning_Note
mit
4 namedtuple Named tuples assign meaning to each position in a tuple and allow for more readable, self-documenting code. They can be used wherever regular tuples are used, and they add the ability to access fields by name instead of position index. namedtuple(typename, field_names[, verbose=False][, rename=False])
Point = namedtuple('Point', ['x', 'y'], verbose=True) p = Point(11, y=22) p
python-statatics-tutorial/basic-theme/python-language/Collections.ipynb
gaufung/Data_Analytics_Learning_Note
mit
The module HARK.ConsumptionSaving.ConsIndShockModel concerns consumption-saving models with idiosyncratic shocks to (non-capital) income. All of the models assume CRRA utility with geometric discounting, no bequest motive, and income shocks are fully transitory or fully permanent. ConsIndShockModel includes: 1. A very...
IdiosyncDict={ # Parameters shared with the perfect foresight model "CRRA": 2.0, # Coefficient of relative risk aversion "Rfree": 1.03, # Interest factor on assets "DiscFac": 0.96, # Intertemporal discount factor "LivPrb" : [0.9...
examples/ConsIndShockModel/IndShockConsumerType.ipynb
econ-ark/HARK
apache-2.0
The distribution of permanent income shocks is specified as mean one lognormal, with an age-varying (underlying) standard deviation. The distribution of transitory income shocks is also mean one lognormal, but with an additional point mass representing unemployment; the transitory shocks are adjusted so that the distri...
IndShockExample = IndShockConsumerType(**IdiosyncDict) IndShockExample.cycles = 0 # Make this type have an infinite horizon IndShockExample.solve()
examples/ConsIndShockModel/IndShockConsumerType.ipynb
econ-ark/HARK
apache-2.0
After solving the model, we can examine an element of this type's $\texttt{solution}$:
print(vars(IndShockExample.solution[0]))
examples/ConsIndShockModel/IndShockConsumerType.ipynb
econ-ark/HARK
apache-2.0
The single-period solution to an idiosyncratic shocks consumer's problem has all of the same attributes as in the perfect foresight model, with a couple additions. The solution can include the marginal marginal value of market resources function $\texttt{vPPfunc}$, but this is only constructed if $\texttt{CubicBool}$ ...
print('Consumption function for an idiosyncratic shocks consumer type:') plot_funcs(IndShockExample.solution[0].cFunc,IndShockExample.solution[0].mNrmMin,5) print('Marginal propensity to consume for an idiosyncratic shocks consumer type:') plot_funcs_der(IndShockExample.solution[0].cFunc,IndShockExample.solution[0].mNr...
examples/ConsIndShockModel/IndShockConsumerType.ipynb
econ-ark/HARK
apache-2.0
The lower part of the consumption function is linear with a slope of 1, representing the constrained part of the consumption function where the consumer would like to consume more by borrowing-- his marginal utility of consumption exceeds the marginal value of assets-- but he is prevented from doing so by the artificia...
print('mNrmGrid for unconstrained cFunc is ',IndShockExample.solution[0].cFunc.functions[0].x_list) print('cNrmGrid for unconstrained cFunc is ',IndShockExample.solution[0].cFunc.functions[0].y_list) print('mNrmGrid for borrowing constrained cFunc is ',IndShockExample.solution[0].cFunc.functions[1].x_list) print('cNrmG...
examples/ConsIndShockModel/IndShockConsumerType.ipynb
econ-ark/HARK
apache-2.0
The consumption function in this model is an instance of LowerEnvelope1D, a class that takes an arbitrary number of 1D interpolants as arguments to its initialization method. When called, a LowerEnvelope1D evaluates each of its component functions and returns the lowest value. Here, the two component functions are th...
plot_funcs(IndShockExample.solution[0].cFunc.functions,-0.25,5.)
examples/ConsIndShockModel/IndShockConsumerType.ipynb
econ-ark/HARK
apache-2.0
Simulating the idiosyncratic income shocks model In order to generate simulated data, an instance of IndShockConsumerType needs to know how many agents there are that share these particular parameters (and are thus ex ante homogeneous), the distribution of states for newly "born" agents, and how many periods to simulat...
IndShockExample.track_vars = ['aNrm','mNrm','cNrm','pLvl'] IndShockExample.initialize_sim() IndShockExample.simulate()
examples/ConsIndShockModel/IndShockConsumerType.ipynb
econ-ark/HARK
apache-2.0
We can now look at the simulated data in aggregate or at the individual consumer level. Like in the perfect foresight model, we can plot average (normalized) market resources over time, as well as average consumption:
plt.plot(np.mean(IndShockExample.history['mNrm'],axis=1)) plt.xlabel('Time') plt.ylabel('Mean market resources') plt.show() plt.plot(np.mean(IndShockExample.history['cNrm'],axis=1)) plt.xlabel('Time') plt.ylabel('Mean consumption') plt.show()
examples/ConsIndShockModel/IndShockConsumerType.ipynb
econ-ark/HARK
apache-2.0
We could also plot individual consumption paths for some of the consumers-- say, the first five:
plt.plot(IndShockExample.history['cNrm'][:,0:5]) plt.xlabel('Time') plt.ylabel('Individual consumption paths') plt.show()
examples/ConsIndShockModel/IndShockConsumerType.ipynb
econ-ark/HARK
apache-2.0
Other example specifications of idiosyncratic income shocks consumers $\texttt{IndShockConsumerType}$-- and $\texttt{HARK}$ in general-- can also represent models that are not infinite horizon. Lifecycle example Suppose we wanted to represent consumers with a lifecycle-- parameter values that differ by age, with a fi...
LifecycleDict={ # Click arrow to expand this fairly large parameter dictionary # Parameters shared with the perfect foresight model "CRRA": 2.0, # Coefficient of relative risk aversion "Rfree": 1.03, # Interest factor on assets "DiscFac": 0.96, ...
examples/ConsIndShockModel/IndShockConsumerType.ipynb
econ-ark/HARK
apache-2.0
In this case, we have specified a ten period model in which retirement happens in period $t=7$. Agents in this model are more likely to die as they age, and their permanent income drops by 30\% at retirement. Let's make and solve this lifecycle example, then look at the $\texttt{solution}$ attribute.
LifecycleExample = IndShockConsumerType(**LifecycleDict) LifecycleExample.cycles = 1 # Make this consumer live a sequence of periods -- a lifetime -- exactly once LifecycleExample.solve() print('First element of solution is',LifecycleExample.solution[0]) print('Solution has', len(LifecycleExample.solution),'elements.')
examples/ConsIndShockModel/IndShockConsumerType.ipynb
econ-ark/HARK
apache-2.0
This was supposed to be a ten period lifecycle model-- why does our consumer type have eleven elements in its $\texttt{solution}$? It would be more precise to say that this specification has ten non-terminal periods. The solution to the 11th and final period in the model would be the same for every set of parameters: ...
print('Consumption functions across the lifecycle:') mMin = np.min([LifecycleExample.solution[t].mNrmMin for t in range(LifecycleExample.T_cycle)]) LifecycleExample.unpack('cFunc') # This makes all of the cFuncs accessible in the attribute cFunc plot_funcs(LifecycleExample.cFunc,mMin,5)
examples/ConsIndShockModel/IndShockConsumerType.ipynb
econ-ark/HARK
apache-2.0
"Cyclical" example We can also model consumers who face an infinite horizon, but who do not face the same problem in every period. Consider someone who works as a ski instructor: they make most of their income for the year in the winter, and make very little money in the other three seasons. We can represent this type...
CyclicalDict = { # Click the arrow to expand this parameter dictionary # Parameters shared with the perfect foresight model "CRRA": 2.0, # Coefficient of relative risk aversion "Rfree": 1.03, # Interest factor on assets "DiscFac": 0.96, ...
examples/ConsIndShockModel/IndShockConsumerType.ipynb
econ-ark/HARK
apache-2.0
This consumer type's parameter dictionary is nearly identical to the original infinite horizon type we made, except that each of the time-varying parameters now have four values, rather than just one. Most of these have the same value in each period except for $\texttt{PermGroFac}$, which varies greatly over the four ...
CyclicalExample = IndShockConsumerType(**CyclicalDict) CyclicalExample.cycles = 0 # Make this consumer type have an infinite horizon CyclicalExample.solve() CyclicalExample.unpack('cFunc') print('Quarterly consumption functions:') mMin = min([X.mNrmMin for X in CyclicalExample.solution]) plot_funcs(CyclicalExample.cFu...
examples/ConsIndShockModel/IndShockConsumerType.ipynb
econ-ark/HARK
apache-2.0
A Simple Parser for Term Rewriting This file implements a parser for terms and equations. It uses the parser generator Ply. To install Ply, change the cell below into a code cell and execute it. If the package ply is already installed, this command will only produce a message that the package is already installed. !...
import ply.lex as lex tokens = [ 'NUMBER', 'VAR', 'FCT', 'BACKSLASH' ]
Python/4 Automatic Theorem Proving/Parser.ipynb
karlstroetmann/Artificial-Intelligence
gpl-2.0
The token Number specifies a natural number. Syntactically, numbers are treated a function symbols.
def t_NUMBER(t): r'0|[1-9][0-9]*' return t
Python/4 Automatic Theorem Proving/Parser.ipynb
karlstroetmann/Artificial-Intelligence
gpl-2.0
Variables start with a letter, followed by letters, digits, and underscores. They must be followed by a character that is not an opening parenthesis (.
def t_VAR(t): r'[a-zA-Z][a-zA-Z0-9_]*(?=[^(a-zA-Z0-9_])' return t
Python/4 Automatic Theorem Proving/Parser.ipynb
karlstroetmann/Artificial-Intelligence
gpl-2.0
Function names start with a letter, followed by letters, digits, and underscores. They have to be followed by an opening parenthesis (.
def t_FCT(t): r'[a-zA-Z][a-zA-Z0-9_]*(?=[(])' return t def t_BACKSLASH(t): r'\\' return t
Python/4 Automatic Theorem Proving/Parser.ipynb
karlstroetmann/Artificial-Intelligence
gpl-2.0
Single line comments are supported and work as in C.
def t_COMMENT(t): r'//[^\n]*' t.lexer.lineno += t.value.count('\n') pass
Python/4 Automatic Theorem Proving/Parser.ipynb
karlstroetmann/Artificial-Intelligence
gpl-2.0
The arithmetic operators and a few other symbols are supported.
literals = ['+', '-', '*', '/', '\\', '%', '^', '(', ')', ';', '=', ',']
Python/4 Automatic Theorem Proving/Parser.ipynb
karlstroetmann/Artificial-Intelligence
gpl-2.0
White space, i.e. space characters, tabulators, and carriage returns are ignored.
t_ignore = ' \t\r'
Python/4 Automatic Theorem Proving/Parser.ipynb
karlstroetmann/Artificial-Intelligence
gpl-2.0
Syntactically, newline characters are ignored. However, we still need to keep track of them in order to know which line we are in. This information is needed later for error messages.
def t_newline(t): r'\n' t.lexer.lineno += 1 return
Python/4 Automatic Theorem Proving/Parser.ipynb
karlstroetmann/Artificial-Intelligence
gpl-2.0
Given a token, the function find_colum returns the column where token starts. This is possible, because token.lexer.lexdata stores the string that is given to the scanner and token.lexpos is the number of characters that precede token.
def find_column(token): program = token.lexer.lexdata line_start = program.rfind('\n', 0, token.lexpos) + 1 return (token.lexpos - line_start) + 1
Python/4 Automatic Theorem Proving/Parser.ipynb
karlstroetmann/Artificial-Intelligence
gpl-2.0
The function t_error is called for any token t that can not be scanned by the lexer. In this case, t.value[0] is the first character that can not be recognized by the scanner.
def t_error(t): column = find_column(t) print(f"Illegal character '{t.value[0]}' in line {t.lineno}, column {column}.") t.lexer.skip(1)
Python/4 Automatic Theorem Proving/Parser.ipynb
karlstroetmann/Artificial-Intelligence
gpl-2.0
The next assignment is necessary to make the lexer think that the code given above is part of some file.
__file__ = 'main' lexer = lex.lex() def test_scanner(file_name): with open(file_name, 'r') as handle: program = handle.read() print(program) lexer.input(program) lexer.lineno = 1 return [t for t in lexer]
Python/4 Automatic Theorem Proving/Parser.ipynb
karlstroetmann/Artificial-Intelligence
gpl-2.0
for t in test_scanner('Examples/quasigroup.eqn'): print(t) Specification of the Parser We will use the following grammar to specify the language that our compiler can translate: ``` axioms : equation | axioms equation ; equation : term '=' term ; term: term '+' term | term ...
import ply.yacc as yacc
Python/4 Automatic Theorem Proving/Parser.ipynb
karlstroetmann/Artificial-Intelligence
gpl-2.0
The start variable of our grammar is axioms.
start = 'axioms' precedence = ( ('nonassoc', '='), ('left', '+', '-'), ('left', '*', '/', 'BACKSLASH', '%'), ('right', '^') ) def p_axioms_one(p): "axioms : equation" p[0] = ('axioms', p[1]) def p_axioms_more(p): "axioms : axioms equation" p[0] = p[1] + (p[2],) def p_equation(p):...
Python/4 Automatic Theorem Proving/Parser.ipynb
karlstroetmann/Artificial-Intelligence
gpl-2.0
Setting the optional argument write_tables to False is required to prevent an obscure bug where the parser generator tries to read an empty parse table. As we have used precedence declarations to resolve all shift/reduce conflicts, the action table should contain no conflict.
parser = yacc.yacc(write_tables=False, debug=True)
Python/4 Automatic Theorem Proving/Parser.ipynb
karlstroetmann/Artificial-Intelligence
gpl-2.0
!cat parser.out The notebook AST-2-Dot.ipynb provides the function tuple2dot. This function can be used to visualize the abstract syntax tree that is generated by the function yacc.parse.
%run AST-2-Dot.ipynb
Python/4 Automatic Theorem Proving/Parser.ipynb
karlstroetmann/Artificial-Intelligence
gpl-2.0
The function parse takes a file_name as its sole argument. The file is read and parsed. The resulting parse tree is visualized using graphviz. It is important to reset the attribute lineno of the scanner, for otherwise error messages will not have the correct line numbers.
def test_parse(file_name): lexer.lineno = 1 with open(file_name, 'r') as handle: program = handle.read() ast = yacc.parse(program) print(ast) return tuple2dot(ast)
Python/4 Automatic Theorem Proving/Parser.ipynb
karlstroetmann/Artificial-Intelligence
gpl-2.0
!cat Examples/quasigroup.eqn test_parse('Examples/quasigroup.eqn') The function indent is used to indent the generated assembler commands by preceding them with 8 space characters.
def parse_file(file_name): lexer.lineno = 1 with open(file_name, 'r') as handle: program = handle.read() AST = yacc.parse(program) if AST: _, *L = AST return L return None
Python/4 Automatic Theorem Proving/Parser.ipynb
karlstroetmann/Artificial-Intelligence
gpl-2.0
parse_file('Examples/group-theory.eqn')
def parse_equation(s): lexer.lineno = 1 AST = yacc.parse(s + ';') if AST: _, *L = AST return L[0] return None
Python/4 Automatic Theorem Proving/Parser.ipynb
karlstroetmann/Artificial-Intelligence
gpl-2.0
parse_equation('i(x) * x = 1')
def parse_term(s): lexer.lineno = 1 AST = yacc.parse(s + '= 1;') if AST: _, *L = AST return L[0][1] return None
Python/4 Automatic Theorem Proving/Parser.ipynb
karlstroetmann/Artificial-Intelligence
gpl-2.0
parse_term('i(x) * x')
def to_str(t): if isinstance(t, set): return '{' + ', '.join({ f'{to_str(eq)}' for eq in t }) + '}' if isinstance(t, list): return '[' + ', '.join([ f'{to_str(eq)}' for eq in t ]) + ']' if isinstance(t, dict): return '{' + ', '.join({ f'{k}: {to_str(v)}' for k, v in t.items() }) + '}...
Python/4 Automatic Theorem Proving/Parser.ipynb
karlstroetmann/Artificial-Intelligence
gpl-2.0
To do: Get temperature for Guatemala Fetch rainfall for Afghanistan between 1980 and 1999
url = 'http://climatedataapi.worldbank.org/climateweb/rest/v1/country/cru/tas/GTM.csv' response = requests.get(url ) # gets the get function from the request library to find the url and put it in a loop etc if response.status_code != 200: print ('Failed to get data: ', response.status_code) else: print ('Fir...
Untitled1.ipynb
WillRhB/PythonLesssons
mit
Using the csv library instead
import csv with open ('test01.csv', 'r') as rawdata: csvdata = csv.reader(rawdata) for record in csvdata: print (record) url = 'http://climatedataapi.worldbank.org/climateweb/rest/v1/country/cru/tas/year/GTM.csv' response = requests.get(url ) # gets the get function from the request library to f...
Untitled1.ipynb
WillRhB/PythonLesssons
mit
We provide you with some helper functions to deal with images, since for this part of the assignment we're dealing with real JPEGs, not CIFAR-10 data.
def preprocess(img, size=512): transform = T.Compose([ T.Scale(size), T.ToTensor(), T.Normalize(mean=SQUEEZENET_MEAN.tolist(), std=SQUEEZENET_STD.tolist()), T.Lambda(lambda x: x[None]), ]) return transform(img) def deprocess(img): transform = T.Compos...
CS231n/assignment3/StyleTransfer-PyTorch.ipynb
UltronAI/Deep-Learning
mit
As in the last assignment, we need to set the dtype to select either the CPU or the GPU
dtype = torch.FloatTensor # Uncomment out the following line if you're on a machine with a GPU set up for PyTorch! # dtype = torch.cuda.FloatTensor # Load the pre-trained SqueezeNet model. cnn = torchvision.models.squeezenet1_1(pretrained=True).features cnn.type(dtype) # We don't want to train the model any further,...
CS231n/assignment3/StyleTransfer-PyTorch.ipynb
UltronAI/Deep-Learning
mit
Computing Loss We're going to compute the three components of our loss function now. The loss function is a weighted sum of three terms: content loss + style loss + total variation loss. You'll fill in the functions that compute these weighted terms below. Content loss We can generate an image that reflects the content...
def content_loss(content_weight, content_current, content_original): """ Compute the content loss for style transfer. Inputs: - content_weight: Scalar giving the weighting for the content loss. - content_current: features of the current image; this is a PyTorch Tensor of shape (1, C_l, H_...
CS231n/assignment3/StyleTransfer-PyTorch.ipynb
UltronAI/Deep-Learning
mit