Unnamed: 0
int64
0
16k
text_prompt
stringlengths
110
62.1k
code_prompt
stringlengths
37
152k
1,300
Given the following text description, write Python code to implement the functionality described below step by step Description: Example shape parameterisation Step1: Parameterising shapes Three options to parameterise shapes are given below; from raw coordinates, from an RT-DICOM file, or from a Monaco® 5.10 tel...
Python Code: import re import numpy as np import dicom import matplotlib.pyplot as plt %matplotlib inline from electroninserts import ( parameterise_single_insert, display_parameterisation) print("All modules and functions successfully imported.") # !pip install --upgrade version_information # %load_ext version_inf...
1,301
Given the following text description, write Python code to implement the functionality described below step by step Description: Parallel computing using REBOUND and IPython/Jupyter In this tutorial, we'll use IPython for parallel and distributed REBOUND simulations. With IPython, we can execute code on multi-core mac...
Python Code: from IPython.parallel import Client rc = Client() print "Cluster size: %d" % len(rc.ids) lv = rc.load_balanced_view() lv.block = True Explanation: Parallel computing using REBOUND and IPython/Jupyter In this tutorial, we'll use IPython for parallel and distributed REBOUND simulations. With IPython, we can ...
1,302
Given the following text description, write Python code to implement the functionality described below step by step Description: Colaboratory Before you start When you open a new Colab from Github (like this one), you cannot save changes. So it's usually best to store the Colab in you personal drive "File > Save a ...
Python Code: # YOUR ACTION REQUIRED: # Execute this cell first using <CTRL-ENTER> and then using <SHIFT-ENTER>. # Note the difference in which cell is selected after execution. print('Hello world!') Explanation: Colaboratory Before you start When you open a new Colab from Github (like this one), you cannot save changes...
1,303
Given the following text description, write Python code to implement the functionality described below step by step Description: Setup Software Environment Step1: Download the Cincinnati 311 (Non-Emergency) Service Requests data Dataset Description Example of downloading a *.csv file progamatically using urllib2 Step...
Python Code: from Cincinnati311CSVDataParser import Cincinnati311CSVDataParser from csv import DictReader import os import re import urllib2 Explanation: Setup Software Environment End of explanation data_dir = "./Data" csv_file_path = os.path.join(data_dir, "cincinnati311.csv") if not os.path.exists(csv_file_path): ...
1,304
Given the following text description, write Python code to implement the functionality described below step by step Description: Higgs Boson Analysis with CMS Open Data This is an example analysis of the Higgs boson detection via the decay channel H &rarr; ZZ* &rarr; 4l From the decay products measured at the CMS expe...
Python Code: # Run this if you need to install Apache Spark (PySpark) # !pip install pyspark # Install sparkhistogram # Note: if you cannot install the package, create the computeHistogram # function as detailed at the end of this notebook. !pip install sparkhistogram # Run this to download the dataset # See further d...
1,305
Given the following text description, write Python code to implement the functionality described below step by step Description: entities Step1: posting to twitter Step2: getting access tokens for yourself
Python Code: response=twitter.search(q="data journalism",result_type="recent",count=20) first=response['statuses'][0] first.keys() first['entities'] for item in first['entities']['urls']: print(item['expanded_url']) for item in first['entities']['user_mentions']: print(item['screen_name']) cursor = twitter.curs...
1,306
Given the following text description, write Python code to implement the functionality described below step by step Description: Chem 30324, Spring 2020, Homework 1 Due on January 22, 2020 Problem 1 Step1: 1. How many different 5-card hands are there? (Remember, in poker the order in which the cards are received doe...
Python Code: import numpy as np from scipy import linalg #contains certain operators you may need for class import matplotlib.pyplot as plt #contains everything you need to create plots import sympy as sy from scipy.integrate import quad Explanation: Chem 30324, Spring 2020, Homework 1 Due on January 22, 202...
1,307
Given the following text description, write Python code to implement the functionality described. Description: Rotate a Linked List Link list node ; This function rotates a linked list counter - clockwise and updates the head . The function assumes that k is smaller than size of linked list . ; Let us understand the be...
Python Code: class Node : def __init__(self ) : self . data = 0 self . next = None   def rotate(head_ref , k ) : if(k == 0 ) : return  current = head_ref while(current . next != None ) : current = current . next  current . next = head_ref current = head_ref for i in range(k - 1 ) : c...
1,308
Given the following text description, write Python code to implement the functionality described below step by step Description: Hello, LSTM! In this project we'd like to explore the basic usage of LSTM (Long Short-Term Memory) which is a flavor of RNN (Recurrent Neural Network). A nice theorerical tutorial is Underst...
Python Code: %matplotlib inline import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np mpl.rc('image', interpolation='nearest', cmap='gray') mpl.rc('figure', figsize=(20,10)) Explanation: Hello, LSTM! In this project we'd like to explore the basic usage of LSTM (Long Short-Term Memory) which is a f...
1,309
Given the following text description, write Python code to implement the functionality described below step by step Description: Serializing STIX Objects The string representation of all STIX classes is a valid STIX JSON object. Step1: New in 3.0.0 Step2: If you need performance but also need human-readable output, ...
Python Code: from stix2 import Indicator indicator = Indicator(name="File hash for malware variant", pattern_type="stix", pattern="[file:hashes.md5 = 'd41d8cd98f00b204e9800998ecf8427e']") print(indicator.serialize(pretty=True)) Explanation: Serializing STIX Objects The string...
1,310
Given the following text description, write Python code to implement the functionality described below step by step Description: Beispiel Credit Data - Aufgabe - Klassifikation Step1: https Step2: Warum sollte man <b>%matplotlib inline</b> ausführen ? Recherchieren Sie !<br> Fügen Sie<br> <b>%matplotlib inline</b> <...
Python Code: # hier Ihren Code einfügen und aufüühren Explanation: Beispiel Credit Data - Aufgabe - Klassifikation: AI, Machine Learning & Data Science Author list: Ramon Rank Die in KNIME durchgeführte Klassifikation der Kreditdaten soll mit Python umgesetzt werden. Die Zellen für die Klassifikation sind bereits vorbe...
1,311
Given the following text description, write Python code to implement the functionality described below step by step Description: First BERT Experiments In this notebook we do some first experiments with BERT Step1: Data We use the same data as for all our previous experiments. Here we load the training, development a...
Python Code: import torch from pytorch_transformers.tokenization_bert import BertTokenizer from pytorch_transformers.modeling_bert import BertForSequenceClassification BERT_MODEL = 'bert-base-uncased' BATCH_SIZE = 16 if "base" in BERT_MODEL else 2 GRADIENT_ACCUMULATION_STEPS = 1 if "base" in BERT_MODEL else 8 tokenizer...
1,312
Given the following text description, write Python code to implement the functionality described below step by step Description: First neural network We will build a simple feed forward neural network with Keras. We will start with a two layer neural network for simplicity. Import all necessary python packages Step1: ...
Python Code: # For simple array operations import numpy as np # To construct the model from keras.models import Sequential from keras.layers import Dense, Activation from keras.optimizers import SGD # Some utility for splitting data and printing the classification report from sklearn.cross_validation import train_test...
1,313
Given the following text description, write Python code to implement the functionality described below step by step Description: ES-DOC CMIP6 Model Properties - Aerosol MIP Era Step1: Document Authors Set document authors Step2: Document Contributors Specify document contributors Step3: Document Publication Specify...
Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'csir-csiro', 'sandbox-3', 'aerosol') Explanation: ES-DOC CMIP6 Model Properties - Aerosol MIP Era: CMIP6 Institute: CSIR-CSIRO Source ID: SANDBOX-3 Topic: Aerosol Sub-Topics: Transpor...
1,314
Given the following text description, write Python code to implement the functionality described below step by step Description: http Step1: Prova arrays Step2: Riproduco cose fatte con numpy Inizializzazioni matrici costanti Step3: Inizializzazioni ranges e reshaping Step4: Operazioni matriciali elementwise (somm...
Python Code: #basic python x = 35 y = x + 5 print(y) #basic TF #x = tf.random_uniform([1, 2], -1.0, 1.0) x = tf.constant(35, name = 'x') y = tf.Variable(x+5, name = 'y') model = tf.global_variables_initializer() sess = tf.Session() sess.run(model) print(sess.run(y)) #per scrivere il grafo #writer = tf.summary.FileWrite...
1,315
Given the following text description, write Python code to implement the functionality described below step by step Description: Parsing Los Angeles County's precinct-level results from the 2014 general election. Step1: Load the PDF in PDFPlumber Step2: Let's look at the first 15 characters on the first page of the ...
Python Code: import pandas as pd import pdfplumber import re Explanation: Parsing Los Angeles County's precinct-level results from the 2014 general election. End of explanation pdf = pdfplumber.open("2014-bulletin-first-10-pages.pdf") print(len(pdf.pages)) Explanation: Load the PDF in PDFPlumber: End of explanation fir...
1,316
Given the following text description, write Python code to implement the functionality described below step by step Description: A Parse Table for a Shift-Reduce Parser This notebook contains the parse table that is needed for a shift reduce parser that parses the following grammar Step1: Next, we define the action t...
Python Code: r1 = ('E', ('E', '+', 'P')) r2 = ('E', ('E', '-', 'P')) r3 = ('E', ('P')) r4 = ('P', ('P', '*', 'F')) r5 = ('P', ('P', '/', 'F')) r6 = ('P', ('F')) r7 = ('F', ('(', 'E', ')')) r8 = ('F', ('NUMBER',)) Explanation: A Parse Table for a Shift-Reduce Parser This notebook contains the parse table that is needed ...
1,317
Given the following text description, write Python code to implement the functionality described below step by step Description: Wrangling OpenStreetMap Data with MongoDB by Duc Vu in fulfillment of Udacity’s Data Analyst Nanodegree, Project 3 OpenStreetMap is an open project that lets eveyone use and create a free ...
Python Code: from IPython.display import HTML HTML('<iframe width="425" height="350" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" \ src="http://www.openstreetmap.org/export/embed.html?bbox=-71.442,42.1858,-70.6984,42.4918&amp;layer=mapnik"></iframe><br/>') Explanation: Wrangling OpenStreetMap Data ...
1,318
Given the following text description, write Python code to implement the functionality described below step by step Description: Bayesian analysis of the Curtis Flowers trials Copyright 2020 Allen B. Downey License Step1: On September 5, 2020, prosecutors in Mississippi dropped charges against Curtis Flowers, freeing...
Python Code: # If we're running on Colab, install empiricaldist # https://pypi.org/project/empiricaldist/ import sys IN_COLAB = 'google.colab' in sys.modules if IN_COLAB: !pip install empiricaldist # Get utils.py import os if not os.path.exists('utils.py'): !wget https://github.com/AllenDowney/ThinkBayes2/raw/m...
1,319
Given the following text description, write Python code to implement the functionality described below step by step Description: AveragePooling3D [pooling.AveragePooling3D.0] input 4x4x4x2, pool_size=(2, 2, 2), strides=None, padding='valid', data_format='channels_last' Step1: [pooling.AveragePooling3D.1] input 4x4x4x...
Python Code: data_in_shape = (4, 4, 4, 2) L = AveragePooling3D(pool_size=(2, 2, 2), strides=None, padding='valid', data_format='channels_last') layer_0 = Input(shape=data_in_shape) layer_1 = L(layer_0) model = Model(inputs=layer_0, outputs=layer_1) # set weights to random (use seed for reproducibility) np.random.seed(2...
1,320
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Predizione sul sesso dei maratoneti di Boston I dati si riferiscono alla maratona di Boston del 2016 e sono stati recuperato da Kaggle. Utilizzo della libreria Pandas La lettura e la ...
Python Code: import pandas as pd # E` necessario convertire il tempo di gara in secondi, per poterlo confrontare nelle regressioni bm = pd.read_csv('./data/marathon_results_2016.csv') bm[:3] type(bm) bm[['Age', 'Official Time']][:3] bm.info() # Vorremmo predire il sesso (label) in base all'età e al tempo ufficiale (cov...
1,321
Given the following text description, write Python code to implement the functionality described below step by step Description: Evaluate classification accuracy This notebook demonstrates how to evaluate classification accuracy of "cross-validated" simulated communities. Due to the unique nature of this analysis, the...
Python Code: from tax_credit.framework_functions import (novel_taxa_classification_evaluation, extract_per_level_accuracy) from tax_credit.eval_framework import parameter_comparisons from tax_credit.plotting_functions import (pointplot_from_data_frame, ...
1,322
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction to Python part XII (And a discussion of stochastic differential equations) Activity 1 Step2: Programs like the Firefox browser are full of assertions Step3: The preconditions ...
Python Code: numbers = [1.5, 2.3, 0.7, -0.001, 4.4] total = 0.0 for num in numbers: assert num > 0.0, 'Data should only contain positive values' total += num print('total is:', total) Explanation: Introduction to Python part XII (And a discussion of stochastic differential equations) Activity 1: Discussion stoc...
1,323
Given the following text description, write Python code to implement the functionality described below step by step Description: Demo Gaussian Generation Illustrate the generation of a d-dimensional Gaussian image Description The sequence below shows a technique to a d-dimensional Gaussian image, understanding the dif...
Python Code: %matplotlib inline import matplotlib.pyplot as plt import matplotlib.image as mpimg import numpy as np import sys,os ia898path = os.path.abspath('/etc/jupyterhub/ia898_1s2017/') if ia898path not in sys.path: sys.path.append(ia898path) import ia898.src as ia # First case: unidimensional # x: single valu...
1,324
Given the following text description, write Python code to implement the functionality described below step by step Description: Inclusive ML - Understanding Bias Learning Objectives Invoke the What-if Tool against a deployed Model Explore attributes of the dataset Examine aspects of bias in model results Evaluate how...
Python Code: !pip freeze | grep httplib2==0.18.1 || pip install httplib2==0.18.1 import os import warnings warnings.filterwarnings('ignore') import numpy as np import pandas as pd import witwidget from witwidget.notebook.visualization import ( WitWidget, WitConfigBuilder, ) pd.options.display.max_columns = 50 ...
1,325
Given the following text problem statement, write Python code to implement the functionality described below in problem statement Problem: I'm using scipy.optimize.minimize to solve a complex reservoir optimization model (SQSLP and COBYLA as the problem is constrained by both bounds and constraint equations). There is ...
Problem: import numpy as np from scipy.optimize import minimize def function(x): return -1*(18*x[0]+16*x[1]+12*x[2]+11*x[3]) I=np.array((20,50,50,80)) x0=I cons=[] steadystate={'type':'eq', 'fun': lambda x: x.sum()-I.sum() } cons.append(steadystate) def f(a): def g(x): return x[a] return g for t in ...
1,326
Given the following text description, write Python code to implement the functionality described below step by step Description: Transfer Learning Most of the time you won't want to train a whole convolutional network yourself. Modern ConvNets training on huge datasets like ImageNet take weeks on multiple GPUs. Instea...
Python Code: from urllib.request import urlretrieve from os.path import isfile, isdir from tqdm import tqdm vgg_dir = 'tensorflow_vgg/' # Make sure vgg exists if not isdir(vgg_dir): raise Exception("VGG directory doesn't exist!") class DLProgress(tqdm): last_block = 0 def hook(self, block_num=1, block_size=...
1,327
Given the following text description, write Python code to implement the functionality described below step by step Description: Simple RNN In ths notebook, we're going to train a simple RNN to do time-series prediction. Given some set of input data, it should be able to generate a prediction for the next time step! <...
Python Code: import torch from torch import nn import numpy as np import matplotlib.pyplot as plt %matplotlib inline plt.figure(figsize=(8,5)) # how many time steps/data pts are in one batch of data seq_length = 20 # generate evenly spaced data pts time_steps = np.linspace(0, np.pi, seq_length + 1) data = np.sin(time_s...
1,328
Given the following text description, write Python code to implement the functionality described below step by step Description: Two Phase Predictions Design Pattern The Two Phased Prediction design pattern provides a way to address the problem of keeping models for specific use cases sophisticated and performant when...
Python Code: import numpy as np import pandas as pd import tensorflow_hub as hub import tensorflow as tf import os import pathlib import matplotlib.pyplot as plt from scipy import signal from scipy.io import wavfile Explanation: Two Phase Predictions Design Pattern The Two Phased Prediction design pattern provides a wa...
1,329
Given the following text description, write Python code to implement the functionality described below step by step Description: The Meterstick package provides a concise and flexible syntax to describe and execute routine data analysis tasks. The easiest way to learn to use Meterstick is by example. For External user...
Python Code: !pip install meterstick Explanation: The Meterstick package provides a concise and flexible syntax to describe and execute routine data analysis tasks. The easiest way to learn to use Meterstick is by example. For External users You can open this notebook in Google Colab. Installation You can install from ...
1,330
Given the following text description, write Python code to implement the functionality described below step by step Description: Using custom containers with Vertex AI Training Learning Objectives Step1: Configure environment settings Set location paths, connections strings, and other environment settings. Make sure ...
Python Code: !pip freeze | grep google-cloud-aiplatform || pip install google-cloud-aiplatform import os import time from google.cloud import aiplatform from google.cloud import bigquery import pandas as pd from sklearn.compose import ColumnTransformer from sklearn.linear_model import SGDClassifier from sklearn.pipelin...
1,331
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Patient Data Analysis Dataset gathered from stroke patients TODO ADD DETAILS ABOUT STROKE PATIENTS Step2: Reaction Time & Accuracy Here we include the reaction time and accuracy metr...
Python Code: Environment setup %matplotlib inline %cd /lang_dec import warnings; warnings.filterwarnings('ignore') import hddm import numpy as np import matplotlib.pyplot as plt from utils import model_tools # Import patient data (as pandas dataframe) patients_data = hddm.load_csv('/lang_dec/data/patients_clean.csv') E...
1,332
Given the following text description, write Python code to implement the functionality described below step by step Description: Cavity flow with Navier-Stokes The final two steps will both solve the Navier–Stokes equations in two dimensions, but with different boundary conditions. The momentum equation in vector form...
Python Code: import numpy as np from matplotlib import pyplot, cm %matplotlib inline nx = 41 ny = 41 nt = 1000 nit = 50 c = 1 dx = 1. / (nx - 1) dy = 1. / (ny - 1) x = np.linspace(0, 1, nx) y = np.linspace(0, 1, ny) Y, X = np.meshgrid(x, y) rho = 1 nu = .1 dt = .001 u = np.zeros((nx, ny)) v = np.zeros((nx, ny)) p = np...
1,333
Given the following text description, write Python code to implement the functionality described below step by step Description: <!--BOOK_INFORMATION--> <img align="left" style="padding-right Step1: As discussed in Computation on NumPy Arrays Step2: But this abstraction can become less efficient when computing compo...
Python Code: import numpy as np rng = np.random.RandomState(42) x = rng.rand(1000000) y = rng.rand(1000000) %timeit x + y Explanation: <!--BOOK_INFORMATION--> <img align="left" style="padding-right:10px;" src="figures/PDSH-cover-small.png"> This notebook contains an excerpt from the Python Data Science Handbook by Jake...
1,334
Given the following text description, write Python code to implement the functionality described below step by step Description: Advanced Step1: Interactivity Options When running in an interactive Python session, PHOEBE updates all constraints and runs various checks after each command. Although this is convenient,...
Python Code: !pip install -I "phoebe>=2.2,<2.3" import phoebe b = phoebe.default_binary() Explanation: Advanced: Optimizing Performance with PHOEBE Setup Let's first make sure we have the latest version of PHOEBE 2.2 installed. (You can comment out this line if you don't use pip for your installation or don't want to u...
1,335
Given the following text description, write Python code to implement the functionality described below step by step Description: Loops Loops are a way to repeatedly execute some code. Here's an example Step1: The for loop specifies - the variable name to use (in this case, planet) - the set of values to loop over (i...
Python Code: planets = ['Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune'] for planet in planets: print(planet, end=' ') # print all on same line Explanation: Loops Loops are a way to repeatedly execute some code. Here's an example: End of explanation multiplicands = (2, 2, 2, 3, 3, 5) p...
1,336
Given the following text description, write Python code to implement the functionality described below step by step Description: Ausnahmen (Exceptions) Was sind Ausnahmen? Wir haben schon mehrfach festgestellt, dass beim Ausführen von Programmen Fehler aufgetreten sind, die zum Abbruch des Programms geführt haben. Das...
Python Code: names = ['Otto', 'Hugo', 'Maria'] names[3] Explanation: Ausnahmen (Exceptions) Was sind Ausnahmen? Wir haben schon mehrfach festgestellt, dass beim Ausführen von Programmen Fehler aufgetreten sind, die zum Abbruch des Programms geführt haben. Das passiert beispielsweise, wenn wir auf ein nicht existierende...
1,337
Given the following text description, write Python code to implement the functionality described below step by step Description: Data Visualization with Python The following notebook serves as an introduction to data visualization with Python for the course "Data Mining". For any comments or suggestions you can contac...
Python Code: # Import all three librairies import matplotlib.pyplot as plt import pandas as pd import seaborn as sns # For displaying the plots inside Notebook %matplotlib inline Explanation: Data Visualization with Python The following notebook serves as an introduction to data visualization with Python for the cours...
1,338
Given the following text description, write Python code to implement the functionality described below step by step Description: ES-DOC CMIP6 Model Properties - Atmoschem MIP Era Step1: Document Authors Set document authors Step2: Document Contributors Specify document contributors Step3: Document Publication Speci...
Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'cnrm-cerfacs', 'sandbox-3', 'atmoschem') Explanation: ES-DOC CMIP6 Model Properties - Atmoschem MIP Era: CMIP6 Institute: CNRM-CERFACS Source ID: SANDBOX-3 Topic: Atmoschem Sub-Topics...
1,339
Given the following text description, write Python code to implement the functionality described below step by step Description: Cell Cycle genes Using Gene Ontologies (GO), create an up-to-date list of all human protein-coding genes that are know to be associated with cell cycle. 1. Download Ontologies, if necessary ...
Python Code: # Get http://geneontology.org/ontology/go-basic.obo from goatools.base import download_go_basic_obo obo_fname = download_go_basic_obo() Explanation: Cell Cycle genes Using Gene Ontologies (GO), create an up-to-date list of all human protein-coding genes that are know to be associated with cell cycle. 1. Do...
1,340
Given the following text description, write Python code to implement the functionality described below step by step Description: SC 1 through 5 Model Comparisons Previous analyses have been pairwise classifications (linear vs. lineage, early/late vs split/coalescence, rectangular vs. square neighbor models). Here, we...
Python Code: import numpy as np import networkx as nx import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import cPickle as pickle from copy import deepcopy from sklearn.utils import shuffle import sklearn_mmadsen.graphs as skmg import sklearn_mmadsen.graphics as skmplt %matplotlib inline # plt.st...
1,341
Given the following text description, write Python code to implement the functionality described below step by step Description: Kecerdasan Buatan Tugas 2 Step1: 1. Eksplorasi Awal Data (10 poin) Pada bagian ini, Anda diminta untuk mengeksplorasi data latih yang diberikan. Selalu gunakan data ini kecuali diberitahuka...
Python Code: from __future__ import print_function, division # Gunakan print(...) dan bukan print ... import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns from sklearn.datasets import load_digits from sklearn.cluster import KMeans from sklearn.metrics import accuracy_score, confu...
1,342
Given the following text description, write Python code to implement the functionality described below step by step Description: Table of Contents <p><div class="lev1 toc-item"><a href="#Project-1 Step1: The data The data consists of total population and total number of deaths due to TB (excluding HIV) in 2013 in eac...
Python Code: # Print platform info of Python exec env. import sys sys.version import warnings warnings.simplefilter('ignore', FutureWarning) from pandas import * show_versions() Explanation: Table of Contents <p><div class="lev1 toc-item"><a href="#Project-1:-Deaths-by-tuberculosis" data-toc-modified-id="Project-1:-Dea...
1,343
Given the following text description, write Python code to implement the functionality described below step by step Description: ES-DOC CMIP6 Model Properties - Seaice MIP Era Step1: Document Authors Set document authors Step2: Document Contributors Specify document contributors Step3: Document Publication Specify ...
Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'inm', 'sandbox-1', 'seaice') Explanation: ES-DOC CMIP6 Model Properties - Seaice MIP Era: CMIP6 Institute: INM Source ID: SANDBOX-1 Topic: Seaice Sub-Topics: Dynamics, Thermodynamics,...
1,344
Given the following text description, write Python code to implement the functionality described below step by step Description: Matrix generation Init symbols for sympy Step1: Lame params Step2: Metric tensor ${\displaystyle \hat{G}=\sum_{i,j} g^{ij}\vec{R}_i\vec{R}_j}$ Step3: ${\displaystyle \hat{G}=\sum_{i,j} g_...
Python Code: from sympy import * from geom_util import * from sympy.vector import CoordSys3D N = CoordSys3D('N') alpha1, alpha2, alpha3 = symbols("alpha_1 alpha_2 alpha_3", real = True, positive=True) init_printing() %matplotlib inline %reload_ext autoreload %autoreload 2 %aimport geom_util Explanation: Matrix generati...
1,345
Given the following text description, write Python code to implement the functionality described below step by step Description: <img src="http Step1: VSTOXX Futures & Options Data We start by loading VSTOXX data from a pandas HDFStore into DataFrame objects (source Step2: VSTOXX index for the first quarter of 2014....
Python Code: from dx import * import numpy as np import pandas as pd from pylab import plt plt.style.use('seaborn') Explanation: <img src="http://hilpisch.com/tpq_logo.png" alt="The Python Quants" width="45%" align="right" border="4"> Implied Volatilities and Model Calibration This setion of the documentation illustrat...
1,346
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2020 The TensorFlow Authors. Step1: 使用内置方法进行训练和评估 <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https Step2: 简介 本指南涵盖使用内置 API 进行训练和验证时的训练、...
Python Code: #@title 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # dist...
1,347
Given the following text description, write Python code to implement the functionality described below step by step Description: kafkaReceiveDataPy This notebook receives data from Kafka on the topic 'test', and stores it in the 'time_test' table of Cassandra (created by cassandra_init.script in startup_script.sh). ``...
Python Code: import os os.environ['PYSPARK_SUBMIT_ARGS'] = '--conf spark.ui.port=4040 --packages org.apache.spark:spark-streaming-kafka-0-8_2.11:2.0.0,com.datastax.spark:spark-cassandra-connector_2.11:2.0.0-M3 pyspark-shell' import time Explanation: kafkaReceiveDataPy This notebook receives data from Kafka on the topic...
1,348
Given the following text description, write Python code to implement the functionality described below step by step Description: Step2: Q-learning is a reinforcement learning paradigm in which we learn a function Step4: Let's run this on a dummy problem - a 5 state linear grid world with the rewards Step5: Does it s...
Python Code: %matplotlib inline # Standard imports. import numpy as np import pylab import scipy import pandas as pd import seaborn as sns import matplotlib.pyplot as plt # Resize plots. pylab.rcParams['figure.figsize'] = 12, 7 def qlearning(reward_transition_function, policy_function, gam...
1,349
Given the following text description, write Python code to implement the functionality described below step by step Description: CasADi demo What is CasADi? A tool for quick & efficient implementation of algorithms for dynamic optimization Open source, LGPL-licensed, <a href="http Step1: Note 1 Step2: Functions o...
Python Code: from pylab import * from casadi import * from casadi.tools import * # for dotdraw %matplotlib inline x = SX.sym("x") # scalar symbolic primitives y = SX.sym("y") z = x*sin(x+y) # common mathematical operators print z dotdraw(z,direction="BT") J = jacobian(z,x) print J dotdraw(J,direction="BT") Explanat...
1,350
Given the following text description, write Python code to implement the functionality described below step by step Description: Plotting topographic arrowmaps of evoked data Load evoked data and plot arrowmaps along with the topomap for selected time points. An arrowmap is based upon the Hosaka-Cohen transformation a...
Python Code: # Authors: Sheraz Khan <sheraz@khansheraz.com> # # License: BSD (3-clause) import numpy as np import mne from mne.datasets import sample from mne.datasets.brainstorm import bst_raw from mne import read_evokeds from mne.viz import plot_arrowmap print(__doc__) path = sample.data_path() fname = path + '/MEG/s...
1,351
Given the following text description, write Python code to implement the functionality described below step by step Description: <a name="top"></a> <div style="width Step1: Case Study Data There are a number of different sites that you can utilize to access past model output analyses and even forecasts. The most robu...
Python Code: from datetime import datetime import cartopy.crs as ccrs import cartopy.feature as cfeature from netCDF4 import Dataset, num2date import numpy as np from scipy.ndimage import gaussian_filter from siphon.catalog import TDSCatalog from siphon.ncss import NCSS import matplotlib.pyplot as plt import metpy.calc...
1,352
Given the following text description, write Python code to implement the functionality described below step by step Description: Reading QM outputs - EDA and COVP calculations Step1: Normally, one would want a very generalized way of reading in output files (like an argparse input argument with nargs='+' that gets lo...
Python Code: from __future__ import print_function from __future__ import division import numpy as np Explanation: Reading QM outputs - EDA and COVP calculations End of explanation outputfilepath = "../qm_files/drop_0001_1qm_2mm_eda_covp.out" Explanation: Normally, one would want a very generalized way of reading in ou...
1,353
Given the following text description, write Python code to implement the functionality described below step by step Description: UpSampling1D [convolutional.UpSampling1D.0] size 2 upsampling on 3x5 input Step1: [convolutional.UpSampling1D.1] size 3 upsampling on 4x4 input Step2: export for Keras.js tests
Python Code: data_in_shape = (3, 5) L = UpSampling1D(size=2) layer_0 = Input(shape=data_in_shape) layer_1 = L(layer_0) model = Model(inputs=layer_0, outputs=layer_1) # set weights to random (use seed for reproducibility) np.random.seed(230) data_in = 2 * np.random.random(data_in_shape) - 1 result = model.predict(np.arr...
1,354
Given the following text description, write Python code to implement the functionality described below step by step Description: Matriks dengan Numpy Matriks dengan Numpy Numpy, sebagai salah satu library yang saling penting di pemrograman yang menggunakan matematika dan angka, memberikan kemudahan dalam melakukan ope...
Python Code: import numpy as np Explanation: Matriks dengan Numpy Matriks dengan Numpy Numpy, sebagai salah satu library yang saling penting di pemrograman yang menggunakan matematika dan angka, memberikan kemudahan dalam melakukan operasi aljabar matriks. Bila deklarasi array a = [[1,0],[0,1]] memberikan array 2D bias...
1,355
Given the following text description, write Python code to implement the functionality described below step by step Description: KNN $$ a(x, X^l) = \arg \max_{y \in Y} \sum_{i = 1}^{l}[y_i = y] ~ w(i, x) $$ Step1: Wine
Python Code: np.random.seed(13) n = 100 df = pd.DataFrame( np.vstack([ np.random.normal(loc=0, scale=1, size=(n, 2)), np.random.normal(loc=3, scale=2, size=(n, 2)) ]), columns=['x1', 'x2']) df['target'] = np.hstack([np.ones(n), np.zeros(n)]).T plt.scatter(df.x1, df.x2, c=df.target, s=100, edgeco...
1,356
Given the following text description, write Python code to implement the functionality described below step by step Description: Registration Errors, Terminology and Interpretation <a href="https Step1: FLE, FRE, TRE empirical experimentation In the following cell you will use a user interface to experiment with the ...
Python Code: import SimpleITK as sitk import numpy as np import copy %matplotlib notebook from gui import PairedPointDataManipulation, display_errors import matplotlib.pyplot as plt from registration_utilities import registration_errors Explanation: Registration Errors, Terminology and Interpretation <a href="https://m...
1,357
Given the following text description, write Python code to implement the functionality described below step by step Description: You are currently looking at version 1.2 of this notebook. To download notebooks and datafiles, as well as get help on Jupyter notebooks in the Coursera platform, visit the Jupyter Notebook ...
Python Code: import pandas as pd df = pd.read_csv('olympics.csv', index_col=0, skiprows=1) for col in df.columns: if col[:2]=='01': df.rename(columns={col:'Gold'+col[4:]}, inplace=True) if col[:2]=='02': df.rename(columns={col:'Silver'+col[4:]}, inplace=True) if col[:2]=='03': df.ren...
1,358
Given the following text description, write Python code to implement the functionality described below step by step Description: Train a ready to use TensorFlow model with a simple pipeline Step1: BATCH_SIZE might be increased for modern GPUs with lots of memory (4GB and higher). Step2: Create a dataset MNIST is a d...
Python Code: import os import sys import warnings warnings.filterwarnings("ignore") import numpy as np import matplotlib.pyplot as plt # the following line is not required if BatchFlow is installed as a python package. sys.path.append("../..") from batchflow import Pipeline, B, C, D, F, V from batchflow.opensets import...
1,359
Given the following text description, write Python code to implement the functionality described below step by step Description: Translating between Currencies Step1: Translating between currencies requires a number of different choices do you want to consider the relative value of two currencies based on Market Exch...
Python Code: from salamanca.currency import Translator Explanation: Translating between Currencies End of explanation xltr = Translator() Explanation: Translating between currencies requires a number of different choices do you want to consider the relative value of two currencies based on Market Exchange Rates or Purc...
1,360
Given the following text description, write Python code to implement the functionality described below step by step Description: ES-DOC CMIP6 Model Properties - Land MIP Era Step1: Document Authors Set document authors Step2: Document Contributors Specify document contributors Step3: Document Publication Specify do...
Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'mpi-m', 'icon-esm-lr', 'land') Explanation: ES-DOC CMIP6 Model Properties - Land MIP Era: CMIP6 Institute: MPI-M Source ID: ICON-ESM-LR Topic: Land Sub-Topics: Soil, Snow, Vegetation,...
1,361
Given the following text description, write Python code to implement the functionality described below step by step Description: Stochastic Matrices These guys are matrices that predict a probability distribution iteratively. You present a "current" distribution, then you multiply by the "transition matrix" and it te...
Python Code: # # define a transition matrix # T = np.array([[0.1, 0.2, 0.3], [0.5,0.3,0.6], [0.4,0.5,0.1]]) T # # Start out with a random prob distribution vector # x0 = np.array([np.random.rand(3)]).T x0 = x0/x0.sum() x0 x1 = T.dot(x0) x1 x2 = T.dot(x1) x2 x3 = T.dot(x2) x3 xn = x3 for i in r...
1,362
Given the following text description, write Python code to implement the functionality described below step by step Description: Predicting the house prices data set for king county Loading graphlab Step1: Load some house sales data Dataset is from house sales in King County, the region where the city of Seattle, WA ...
Python Code: import graphlab Explanation: Predicting the house prices data set for king county Loading graphlab End of explanation sales = graphlab.SFrame('home_data.gl/') sales.head(5) Explanation: Load some house sales data Dataset is from house sales in King County, the region where the city of Seattle, WA is locate...
1,363
Given the following text description, write Python code to implement the functionality described below step by step Description: Simplified Selenium Functions For example, if you are using Selenium in your automated functional tests, instead of coding directly in Selenium like this Step1: You can alternatively use Ma...
Python Code: from selenium import webdriver browser = webdriver.Firefox() browser.get('https://python.org.') download = browser.find_element_by_link_text('Downloads') download.click() download = browser.find_element_by_id('downloads') ul = download.find_element_by_tag_name('ul') lis = ul.find_elements_by_tag_name('li')...
1,364
Given the following text description, write Python code to implement the functionality described below step by step Description: Access a Database with Python - Iris Dataset The Iris dataset is a popular dataset especially in the Machine Learning community, it is a set of features of 50 Iris flowers and their classif...
Python Code: import os data_iris_folder_content = os.listdir("./iris-species") error_message = "Error: sqlite file not available, check instructions above to download it" assert "database.sqlite" in data_iris_folder_content, error_message Explanation: Access a Database with Python - Iris Dataset The Iris dataset is a p...
1,365
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2018 The TensorFlow Authors. Step1: Rock, Paper & Scissors with TensorFlow Hub - TFLite <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https...
Python Code: #@title 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # dist...
1,366
Given the following text description, write Python code to implement the functionality described below step by step Description: Regression This notebook covers multi-variate "linear regression". We'll be going over how to use the scikit-learn regression model, as well as how to train the regressor using the fit() met...
Python Code: import numpy as np import pandas as pd from pandas import Series, DataFrame import matplotlib.pyplot as plt import seaborn as sns sns.set_style('whitegrid') %matplotlib inline Explanation: Regression This notebook covers multi-variate "linear regression". We'll be going over how to use the scikit-learn reg...
1,367
Given the following text description, write Python code to implement the functionality described below step by step Description: Team Step1: Import non-standard libraries (install as needed) Step2: Optional directory creation Step3: Is the ESRI Shapefile driver available? Step4: Define a function which will create...
Python Code: from numpy import mean import os from os import makedirs,chdir from os.path import exists Explanation: Team: Satoshi Nakamoto <br> Names: Alex Levering & Hèctor Muro <br> Lesson 10 Exercise solution Import standard libraries End of explanation from osgeo import ogr,osr import folium import simplekml Explan...
1,368
Given the following text description, write Python code to implement the functionality described below step by step Description: This demo shows the method proposed in "Zhou, Bolei, et al. "Learning Deep Features for Discriminative Localization." arXiv preprint arXiv Step1: Set the image you want to test and the clas...
Python Code: # -*- coding: UTF-8 –*- import matplotlib.pyplot as plt %matplotlib inline from IPython import display import os ROOT_DIR = '.' import sys sys.path.insert(0, os.path.join(ROOT_DIR, 'lib')) import cv2 import numpy as np import mxnet as mx import matplotlib.pyplot as plt Explanation: This demo shows the meth...
1,369
Given the following text description, write Python code to implement the functionality described below step by step Description: E-Commerce data with Neural network In this note, I am going to use neural network to analyze a e-commerce data. The data is from Udemy Step1: The 2nd and 3rd column is numeric and need to ...
Python Code: import numpy as np import pandas as pd import matplotlib.pyplot as plt # Plotting library from sklearn.utils import shuffle # Allow matplotlib to plot inside this notebook %matplotlib inline # Set the seed of the numpy random number generator so that the result is reproducable np.random.seed(seed=1) # che...
1,370
Given the following text description, write Python code to implement the functionality described below step by step Description: The MNIST dataset The MNIST database of handwritten digits, available at Yann Lecun web site, has a training set of 60,000 examples, and a test set of 10,000 examples. It is a subset of a la...
Python Code: # import the mnist class from mnist import MNIST # init with the 'data' dir mndata = MNIST('./data') # Load data mndata.load_training() mndata.load_testing() # The number of pixels per side of all images img_side = 28 # Each input is a raw vector. # The number of units of the network # corresponds t...
1,371
Given the following text description, write Python code to implement the functionality described below step by step Description: Background information on filtering Here we give some background information on filtering in general, and how it is done in MNE-Python in particular. Recommended reading for practical applic...
Python Code: import numpy as np from numpy.fft import fft, fftfreq from scipy import signal import matplotlib.pyplot as plt from mne.time_frequency.tfr import morlet from mne.viz import plot_filter, plot_ideal_filter import mne sfreq = 1000. f_p = 40. flim = (1., sfreq / 2.) # limits for plotting Explanation: Backgrou...
1,372
Given the following text description, write Python code to implement the functionality described below step by step Description: Comparing CHIRPS and ARC2 Precipitation Data in Kenya In this demo we are comparing two historical precipitation datasets - CHIRPS and ARC2. Climate Hazards Group InfraRed Precipitation with...
Python Code: %matplotlib notebook import numpy as np from dh_py_access import package_api import dh_py_access.lib.datahub as datahub import xarray as xr import matplotlib.pyplot as plt from mpl_toolkits.basemap import Basemap from po_data_process import get_data_in_pandas_dataframe, make_plot,get_comparison_graph impor...
1,373
Given the following text description, write Python code to implement the functionality described below step by step Description: Blue Sky Run Engine Contents Step1: The Run Engine processes messages A message has four parts Step2: Moving a motor and reading it back is boring. Let's add a detector. Step4: There is t...
Python Code: from bluesky import Mover, SynGauss, Msg, RunEngine motor = Mover('motor', ['pos']) det = SynGauss('det', motor, 'pos', center=0, Imax=1, sigma=1) Explanation: Blue Sky Run Engine Contents: The Run Engine processes messages There is two-way communication between the message generator and the Run Engine Con...
1,374
Given the following text description, write Python code to implement the functionality described below step by step Description: Numpy Step1: If we want to multiply each number in that list by 3, we can certainly do it by looping through and multiplying each individual number by 3, but that seems like way too much wo...
Python Code: a = [1,2,3] b = 3*a print b Explanation: Numpy: "number" + "python" Numpy is a Python package that is commonly used by scientists. You can already do some math in Python by itself, but Numpy makes things even easier. We've already seen that Python has data structures such as lists, tuples, and dictionaries...
1,375
Given the following text description, write Python code to implement the functionality described below step by step Description: Experiment Step1: Load and check data Step2: ## Analysis Experiment Details Step3: What are optimal levels of hebbian and weight pruning Step4: No relevant difference
Python Code: %load_ext autoreload %autoreload 2 import sys sys.path.append("../../") from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import glob import tabulate import pprint import click import numpy as np import pandas as pd from ray.tune.commands...
1,376
Given the following text description, write Python code to implement the functionality described below step by step Description: Capacity of the Binary-Input AWGN (BI-AWGN) Channel This code is provided as supplementary material of the OFC short course SC468 This code illustrates * Calculating the capacity of the bina...
Python Code: import numpy as np import scipy.integrate as integrate import matplotlib.pyplot as plt Explanation: Capacity of the Binary-Input AWGN (BI-AWGN) Channel This code is provided as supplementary material of the OFC short course SC468 This code illustrates * Calculating the capacity of the binary input AWGN cha...
1,377
Given the following text description, write Python code to implement the functionality described below step by step Description: Idea Get data - Calculate the name length - Calculate the chr set - Calculate the chr set length - Calculate the ratio for the chr set length and the name length - Remove the duplicate lette...
Python Code: names_df = pd.read_csv("./IMA_mineral_names.txt", sep=',', header=None, names=['names']) names_df['names'] = names_df['names'].str.strip().str.lower() names_df['len'] = names_df['names'].str.len() names_df['tuple'] = names_df['names'].apply(lambda x: tuple(sorted(set(x)))) names_df['setlen'] = names_df['tu...
1,378
Given the following text description, write Python code to implement the functionality described below step by step Description: Metacritic and ROI Analysis Step1: Load Dataset Step2: Metacritic Ratings Representation Step3: ROI Representation Step4: Save Dataset Step5: Metacritic VS. ROI Step6: We can see that ...
Python Code: %matplotlib inline import configparser import os import requests from tqdm import tqdm import numpy as np import pandas as pd import matplotlib.pyplot as plt import matplotlib.mlab as mlab from scipy import sparse, stats, spatial import scipy.sparse.linalg from sklearn import preprocessing, decomposition i...
1,379
Given the following text description, write Python code to implement the functionality described below step by step Description: L7CA - Lesson7 CAM 2018/1/23 02 Step1: The version of resnet that happens to be the best is the preact resnet. They have different internal orderings of conv,pool,res,bn,relu,etc. We want t...
Python Code: %reload_ext autoreload %autoreload 2 %matplotlib inline from fastai.imports import * from fastai.transforms import * from fastai.conv_learner import * from fastai.model import * from fastai.dataset import * from fastai.sgdr import * PATH = 'data/dogscats/' sz = 224 arch = resnet34 bs = 32 m = arch(True) m ...
1,380
Given the following text description, write Python code to implement the functionality described below step by step Description: <a id='intro'></a> Introduction The overall goal of this project is to build a word recognizer for American Sign Language video sequences, demonstrating the power of probabalistic models. I...
Python Code: import math import numpy as np import pandas as pd from asl_data import AslDb asl = AslDb() # initializes the database asl.df.head() # displays the first five rows of the asl database, indexed by video and frame asl.df.ix[98,1] # look at the data available for an individual frame Explanation: <a id='intro...
1,381
Given the following text description, write Python code to implement the functionality described below step by step Description: Wi-Fi Fingerprinting Experiments Import modules and set up the environment Step1: Helper Functions Step2: Load the model classes A class responsible for loading a JSON file (or all the JSO...
Python Code: # Python Standard Library import getopt import os import sys import math import time import collections import random # IPython from IPython.display import display # pandas import pandas as pd pd.set_option("display.max_rows", 10000) pd.set_option("display.max_columns", 10000) # Matplotlib %matplotlib inli...
1,382
Given the following text description, write Python code to implement the functionality described below step by step Description: Training a ConvNet PyTorch In this notebook, you'll learn how to use the powerful PyTorch framework to specify a conv net architecture and train it on the CIFAR-10 dataset. Step2: What's th...
Python Code: import torch import torch.nn as nn import torch.optim as optim from torch.autograd import Variable from torch.utils.data import DataLoader from torch.utils.data import sampler import torchvision.datasets as dset import torchvision.transforms as T import numpy as np import timeit import os os.chdir(os.getcw...
1,383
Given the following text description, write Python code to implement the functionality described below step by step Description: CM360 Report Create a CM report from a JSON definition. License Copyright 2020 Google LLC, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in...
Python Code: !pip install git+https://github.com/google/starthinker Explanation: CM360 Report Create a CM report from a JSON definition. License Copyright 2020 Google LLC, 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 co...
1,384
Given the following text description, write Python code to implement the functionality described below step by step Description: From Tensor SkFlow Step1: Load Iris Data Step2: Initialize a deep neural network autoencoder Step3: Fit with Iris data
Python Code: from __future__ import absolute_import from __future__ import division from __future__ import print_function import random from sklearn.pipeline import Pipeline from chainer import optimizers from commonml.skchainer import MeanSquaredErrorRegressor, AutoEncoder from tensorflow.contrib.learn import datasets...
1,385
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Convolutional Networks So far we have worked with deep fully-connected networks, using them to explore different optimization strategies and network architectures. Fully-connected net...
Python Code: # As usual, a bit of setup import numpy as np import matplotlib.pyplot as plt from cs231n.classifiers.cnn import * from cs231n.data_utils import get_CIFAR10_data from cs231n.gradient_check import eval_numerical_gradient_array, eval_numerical_gradient from cs231n.layers import * from cs231n.fast_layers impo...
1,386
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: script available on GitHub Installation and Setup Installation Refer to this how-to. Manage Python Packages Python has its own package manager "pip" to keep Python self-contained. pip...
Python Code: # I don't know how to write a program but I am charming, # so I will write down the equations to be implemented # and find a friend to write it :) It is annoying to have to start each comment with a #, triple quotation allows multi-line comments. It is always a good idea to write lots of comment...
1,387
Given the following text description, write Python code to implement the functionality described below step by step Description: Artificial Intelligence & Machine Learning Tugas 3 Step1: 1. Dynamic Programming (5 poin) Seorang pria di Australia pada tahun 2017 memesan 200 McNuggets melalui drive-through hingga dilipu...
Python Code: import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns plt.rcParams = plt.rcParamsOrig Explanation: Artificial Intelligence & Machine Learning Tugas 3: Search & Reinforcement Learning Mekanisme Anda hanya diwajibkan untuk mengumpulkan file ini saja ke uploader yang dis...
1,388
Given the following text description, write Python code to implement the functionality described below step by step Description: \title{myHDL Sawtooth Wave Generator based on the Phase Accumulation method} \author{Steven K Armour} \maketitle This is a simple SawTooth wave generator based on the phase accumulation meth...
Python Code: from myhdl import * import pandas as pd from myhdlpeek import Peeker import numpy as np import matplotlib.pyplot as plt %matplotlib inline from sympy import * init_printing() Explanation: \title{myHDL Sawtooth Wave Generator based on the Phase Accumulation method} \author{Steven K Armour} \maketitle This ...
1,389
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Now let's look at some classification methods. Nearest Neighbor Step2: Exercise Step3: Exercise Step4: Now write a loop that does this using 100 different randomly generated datas...
Python Code: # adapted from http://scikit-learn.org/stable/auto_examples/neighbors/plot_classification.html#example-neighbors-plot-classification-py n_neighbors = 30 # step size in the mesh # Create color maps cmap_light = ListedColormap(['#FFAAAA', '#AAFFAA']) cmap_bold = ListedColormap(['#FF0000', '#00FF00']) clf = ...
1,390
Given the following text description, write Python code to implement the functionality described below step by step Description: Continuous training pipeline with Kubeflow Pipeline and AI Platform Learning Objectives Step6: NOTE Step7: The custom components execute in a container image defined in base_image/Dockerfi...
Python Code: !grep 'BASE_IMAGE =' -A 5 pipeline/covertype_training_pipeline.py Explanation: Continuous training pipeline with Kubeflow Pipeline and AI Platform Learning Objectives: 1. Learn how to use Kubeflow Pipeline (KFP) pre-build components (BiqQuery, AI Platform training and predictions) 1. Learn how to use KFP l...
1,391
Given the following text description, write Python code to implement the functionality described below step by step Description: Introducing the Keras Functional API Learning Objectives 1. Understand embeddings and how to create them with the feature column API 1. Understand Deep and Wide models and when to use th...
Python Code: import datetime import os import shutil import numpy as np import pandas as pd import tensorflow as tf from matplotlib import pyplot as plt from tensorflow import feature_column as fc from tensorflow import keras from tensorflow.keras import Model from tensorflow.keras.callbacks import TensorBoard from ten...
1,392
Given the following text description, write Python code to implement the functionality described below step by step Description: Proteins example recreated in python from https Step1: note numpy also has recfromcsv() and pandas can read_csv, with pandas DF.values giving a numpy array Step2: Samples clustering using ...
Python Code: import numpy as np from numpy import genfromtxt data = genfromtxt('http://www.biz.uiowa.edu/faculty/jledolter/DataMining/protein.csv',delimiter=',',names=True,dtype=float) Explanation: Proteins example recreated in python from https://rstudio-pubs-static.s3.amazonaws.com/33876_1d7794d9a86647ca90c4f182df93f...
1,393
Given the following text description, write Python code to implement the functionality described below step by step Description: Modelos Bayesianos Aplicar um modelo estatístico a um conjunto de dados significa interpretá-lo como um conjunto de realizações de um experimento randomizado. Isso permite associar o conjunt...
Python Code: # Inicializacao %matplotlib inline import numpy as np from matplotlib import pyplot as plt # Abrindo conjunto de dados import csv with open("biometria.csv", 'rb') as f: dados = list(csv.reader(f)) rotulos_volei = [d[0] for d in dados[1:-1] if d[0] is 'V'] rotulos_futebol = [d[0] for d in dados[1:-...
1,394
Given the following text description, write Python code to implement the functionality described below step by step Description: Bayesian model selection and linear regression This notebook uses Bayesian selection for linear regression with basis functions in order to (partially) answer question #2231975 in Math Stack...
Python Code: import sys sys.path.append("../src/") from Hypotheses import * from ModelSelection import LinearRegression from Plots import updateMAPFitPlot, updateProbabilitiesPlot import numpy as np from sklearn import preprocessing import matplotlib.pyplot as pl %matplotlib notebook Explanation: Bayesian model selecti...
1,395
Given the following text description, write Python code to implement the functionality described below step by step Description: How to defer evaluation of f-strings It seems that one solution is to use lambdas, which are explored below. What other solutions are there? Imagine that one wants to format a string selecti...
Python Code: year, month, day = 'hello', -1, 0 date_formats = { 'iso': f'{year}-{month:02d}-{day:02d}', 'us': f'{month}/{day}/{year}', 'other': f'{day} {month} {year}', } Explanation: How to defer evaluation of f-strings It seems that one solution is to use lambdas, which are explored below. What other solu...
1,396
Given the following text description, write Python code to implement the functionality described below step by step Description: Creating a model from scratch We describe here how to generate a simple history file for computation with Noddy using the functionality of pynoddy. If possible, it is advisable to generate t...
Python Code: from matplotlib import rc_params from IPython.core.display import HTML css_file = 'pynoddy.css' HTML(open(css_file, "r").read()) import sys, os import matplotlib.pyplot as plt # adjust some settings for matplotlib from matplotlib import rcParams # print rcParams rcParams['font.size'] = 15 # determine path ...
1,397
Given the following text description, write Python code to implement the functionality described below step by step Description: Computing a covariance matrix Many methods in MNE, including source estimation and some classification algorithms, require covariance estimations from the recordings. In this tutorial we cov...
Python Code: import os.path as op import mne from mne.datasets import sample Explanation: Computing a covariance matrix Many methods in MNE, including source estimation and some classification algorithms, require covariance estimations from the recordings. In this tutorial we cover the basics of sensor covariance compu...
1,398
Given the following text description, write Python code to implement the functionality described below step by step Description: Intro The TV show Silicon Valley had an app called "See Food" that promised to identify food. In this notebook, you will write code using and comparing pre-trained models to choose one as a...
Python Code: import os from os.path import join hot_dog_image_dir = '../input/hot-dog-not-hot-dog/seefood/train/hot_dog' hot_dog_paths = [join(hot_dog_image_dir,filename) for filename in ['1000288.jpg', '127117.jpg']] not_hot_dog_image_dir = '../input/hot-dog-no...
1,399
Given the following text description, write Python code to implement the functionality described below step by step Description: Ordinary Differential Equations Exercise 1 Imports Step2: Lorenz system The Lorenz system is one of the earliest studied examples of a system of differential equations that exhibits chaotic...
Python Code: %matplotlib inline import matplotlib.pyplot as plt import numpy as np from scipy.integrate import odeint from IPython.html.widgets import interact, fixed Explanation: Ordinary Differential Equations Exercise 1 Imports End of explanation def lorentz_derivs(yvec, t, sigma, rho, beta): Compute the the der...