Unnamed: 0
int64
0
16k
text_prompt
stringlengths
110
62.1k
code_prompt
stringlengths
37
152k
7,300
Given the following text description, write Python code to implement the functionality described below step by step Description: NBA Free throw analysis Now let's see some of these methods in action on real world data. I'm not a basketball guru by any means, but I thought it would be fun to see whether we can find pla...
Python Code: from __future__ import division import pandas as pd import numpy as np import scipy as sp import scipy.stats import toyplot as tp Explanation: NBA Free throw analysis Now let's see some of these methods in action on real world data. I'm not a basketball guru by any means, but I thought it would be fun to s...
7,301
Given the following text description, write Python code to implement the functionality described below step by step Description: Short intro to the SCT library of AutoGraph Work in progress, use with care and expect changes. The pyct module packages the source code transformation APIs used by AutoGraph. This tutorial ...
Python Code: !pip install tf-nightly Explanation: Short intro to the SCT library of AutoGraph Work in progress, use with care and expect changes. The pyct module packages the source code transformation APIs used by AutoGraph. This tutorial is just a preview - there is no PIP package yet, and the API has not been finali...
7,302
Given the following text description, write Python code to implement the functionality described below step by step Description: Sucesión de Fibonacci La sucesión de Fibonacci se usa para modelar crecimiento de poblaciones de bichos. Por ejemplo Step1: Polinomio característico Como $\lambda$ es un valor propio de $A$...
Python Code: # importamos bibliotecas cómputo de matrices import numpy as np A = np.matrix([[1, 1], [1, 0]]) # para k=3 A se multiplica por sí misma tres veces: A*A*A u0 = [1, 0] # u3 np.dot(A*A*A, u0) Explanation: Sucesión de Fibonacci La sucesión de Fibonacci se usa para modelar crecimient...
7,303
Given the following text description, write Python code to implement the functionality described below step by step Description: Functions As in any other language Python allows for the definition of functions. Functions are a set of sequence of instructions that receive well define inputs and produce some outputs. To...
Python Code: def square(a): return a*a print(square(1), square(2), square(5)) square('a') # This should give an error def minimum(a, b): if a<b: return a elif b<a: return b else: return a minimum(4,5) minimum(4,0) Explanation: Functions As in any other language Python allows for ...
7,304
Given the following text description, write Python code to implement the functionality described below step by step Description: Use different base estimators for optimization Sigurd Carlen, September 2019. Reformatted by Holger Nahrstaedt 2020 .. currentmodule Step1: Toy example Let assume the following noisy functi...
Python Code: print(__doc__) import numpy as np np.random.seed(1234) import matplotlib.pyplot as plt Explanation: Use different base estimators for optimization Sigurd Carlen, September 2019. Reformatted by Holger Nahrstaedt 2020 .. currentmodule:: skopt To use different base_estimator or create a regressor with differe...
7,305
Given the following text description, write Python code to implement the functionality described below step by step Description: 5. Model the Solution Preprocessing to get the tidy dataframe Step1: Question 3 Step2: PRINCIPLE Step3: PRINCIPLE Step4: PRINCIPLE Step5: Question 4 Step6: Now we can fit an ARIMA mode...
Python Code: # Import the library we need, which is Pandas and Matplotlib import pandas as pd import numpy as np import matplotlib.pyplot as plt %matplotlib inline # Set some parameters to get good visuals - style to ggplot and size to 15,10 plt.style.use('ggplot') plt.rcParams['figure.figsize'] = (15, 10) # Read the c...
7,306
Given the following text description, write Python code to implement the functionality described below step by step Description: Explore the uncertainity in the resistance of a sample circuit http Step1: For this simple circuit the questions are 1. what is the end-to-end resistance and its uncertainity? 1. What are ...
Python Code: Image("res4.gif") Explanation: Explore the uncertainity in the resistance of a sample circuit http://www.electronics-tutorials.ws/resistor/res_5.html End of explanation import numpy as np import matplotlib.pyplot as plt import pymc3 as pm import pandas as pd import seaborn as sns sns.set() %matplotlib inli...
7,307
Given the following text description, write Python code to implement the functionality described below step by step Description: LAB 3a Step1: Verify tables exist Run the following cells to verify that we previously created the dataset and data tables. If not, go back to lab 1b_prepare_data_babyweight to create them....
Python Code: %%bash sudo pip freeze | grep google-cloud-bigquery==1.6.1 || \ sudo pip install google-cloud-bigquery==1.6.1 Explanation: LAB 3a: BigQuery ML Model Baseline. Learning Objectives Create baseline model with BQML Evaluate baseline model Calculate RMSE of baseline model Introduction In this notebook, we will...
7,308
Given the following text description, write Python code to implement the functionality described below step by step Description: Finding data story Goals Find a data story Narrow down fields of dataset to explore Imports and helper functions Step3: Current visualization ideas Show map and as user searches highlight o...
Python Code: %matplotlib inline import matplotlib.pyplot as plt import sqlite3 import pandas as pd import seaborn as sns sns.set_style("white") conn = sqlite3.connect('../data/output/database.sqlite') c = conn.cursor() def execute(sql): ''' Executes a SQL command on the 'c' cursor and returns the results ''...
7,309
Given the following text description, write Python code to implement the functionality described below step by step Description: Skip-gram word2vec In this notebook, I'll lead you through using TensorFlow to implement the word2vec algorithm using the skip-gram architecture. By implementing this, you'll learn about emb...
Python Code: !pip install tqdm import time import numpy as np import tensorflow as tf import utils Explanation: Skip-gram word2vec In this notebook, I'll lead you through using TensorFlow to implement the word2vec algorithm using the skip-gram architecture. By implementing this, you'll learn about embedding words for u...
7,310
Given the following text description, write Python code to implement the functionality described below step by step Description: ES-DOC CMIP6 Model Properties - Ocean MIP Era Step1: Document Authors Set document authors Step2: Document Contributors Specify document contributors Step3: Document Publication Specify d...
Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'snu', 'sandbox-2', 'ocean') Explanation: ES-DOC CMIP6 Model Properties - Ocean MIP Era: CMIP6 Institute: SNU Source ID: SANDBOX-2 Topic: Ocean Sub-Topics: Timestepping Framework, Adve...
7,311
Given the following text description, write Python code to implement the functionality described below step by step Description: Inheritance Inheritance means extending the properties of one class by another. Inheritance implies code reusability, because of which client classes do not need to implement everything from...
Python Code: class Person: # Constructor def __init__(self, name, age): self.name = name self.age = age def __str__(self): return 'name = {}\nage = {}'.format(self.name,self.age) # Inherited or Sub class class Employee(Person): def __init__(self, name, age, em...
7,312
Given the following text description, write Python code to implement the functionality described below step by step Description: Examples and Exercises from Think Stats, 2nd Edition http Step1: Scatter plots I'll start with the data from the BRFSS again. Step2: The following function selects a random subset of a Dat...
Python Code: from __future__ import print_function, division %matplotlib inline import numpy as np import brfss import thinkstats2 import thinkplot Explanation: Examples and Exercises from Think Stats, 2nd Edition http://thinkstats2.com Copyright 2016 Allen B. Downey MIT License: https://opensource.org/licenses/MIT End...
7,313
Given the following text description, write Python code to implement the functionality described below step by step Description: ES-DOC CMIP6 Model Properties - Landice 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', 'noaa-gfdl', 'gfdl-am4', 'landice') Explanation: ES-DOC CMIP6 Model Properties - Landice MIP Era: CMIP6 Institute: NOAA-GFDL Source ID: GFDL-AM4 Topic: Landice Sub-Topics: Glaciers, Ic...
7,314
Given the following text description, write Python code to implement the functionality described below step by step Description: 4 ways to print in GAlgebra Step1: Printing in plain text Step2: Enhanced Console Printing If called Eprint() upfront, print() will do Enhanced Console Printing(colored printing with ANSI ...
Python Code: from sympy import * from galgebra.ga import Ga from galgebra.printer import Eprint, Format, xpdf cga3d = Ga(r'e_1 e_2 e_3 e e_{0}',g='1 0 0 0 0,0 1 0 0 0,0 0 1 0 0,0 0 0 0 -1,0 0 0 -1 0') Explanation: 4 ways to print in GAlgebra End of explanation print(cga3d.I()) Explanation: Printing in plain text End of...
7,315
Given the following text description, write Python code to implement the functionality described below step by step Description: Title Step1: Create Text Data Step2: Create Bag Of Words Step3: Create Target Vector Step4: Train Multinomial Naive Bayes Classifier Step5: Create Previously Unseen Observation Step6: ...
Python Code: # Load libraries import numpy as np from sklearn.naive_bayes import MultinomialNB from sklearn.feature_extraction.text import CountVectorizer Explanation: Title: Multinomial Naive Bayes Classifier Slug: multinomial_naive_bayes_classifier Summary: How to train a Multinomial naive bayes classifer in Sciki...
7,316
Given the following text description, write Python code to implement the functionality described below step by step Description: Configurar las credenciales para acceder al API de Twitter Step1: Esta es la molona librería que vamos a utilizar Step2: 1 . Recoger tweets a partir de un id Step3: 2. Recoger tweets de u...
Python Code: config = ConfigParser() config.read(join(pardir,'src','credentials.ini')) APP_KEY = config['twitter']['app_key'] APP_SECRET = config['twitter']['app_secret'] OAUTH_TOKEN = config['twitter']['oauth_token'] OAUTH_TOKEN_SECRET = config['twitter']['oauth_token_secret'] from twitter import oauth, Twitter, Twi...
7,317
Given the following text description, write Python code to implement the functionality described below step by step Description: ANÁLISIS ESTADÍSTICO DE DATOS Step1: PARA RECORDAR Distribución binomial Se denomina proceso de Bernoulli aquel experimento que consiste en repetir n veces una prueba, cada una independient...
Python Code: dado = np.array([5, 3, 3, 2, 5, 1, 2, 3, 6, 2, 1, 3, 6, 6, 2, 2, 5, 6, 4, 2, 1, 3, 4, 2, 2, 5, 3, 3, 2, 2, 2, 1, 6, 2, 2, 6, 1, 3, 3, 3, 4, 4, 6, 6, 1, 2, 2, 6, 1, 4, 2, 5, 3, 6, 6, 3, 5, 2, 2, 4, 2, 2, 4, 4, 3, 3, 1, 2, 6, 1, 3, 3, 5, 4, 6, 6, 4, 2, 5, 6, 1, 4, 5, 4, 3, 5,...
7,318
Given the following text description, write Python code to implement the functionality described below step by step Description: Groupby El metodo groupby nos permite agrupar informacion y aplicar funciones de agregacion Step1: Ahora ya podemos usar la funcion .groupby() para agrupar la informacion en base a los nomb...
Python Code: #%% librerias import pandas as pd # Crear un dataFrame data = {'Company':['GOOG','GOOG','MSFT','MSFT','FB','FB'], 'Person':['Sam','Charlie','Amy','Vanessa','Carl','Sarah'], 'Sales':[200,120,340,124,243,350]} df = pd.DataFrame(data) df Explanation: Groupby El metodo groupby nos permite agrupar...
7,319
Given the following text description, write Python code to implement the functionality described below step by step Description: <div align="center"><img width="50%" src="https Step1: You can also run a cell with Ctrl+Enter or Shift+Enter. Experiment a bit with that. Tab Completion One of the most useful things about...
Python Code: import pandas as pd print("Hi! This is a cell. Click on it and press the ▶ button above to run it") Explanation: <div align="center"><img width="50%" src="https://raw.githubusercontent.com/jupyter/jupyter/master/docs/source/_static/_images/jupyter.png"></div> Jupyter Notebook This notebook was adapted from...
7,320
Given the following text description, write Python code to implement the functionality described below step by step Description: State Space Discretization From the previous notebook you probably end up thinking about the fact that the states and action we were dealing with on the Frozen Lake environment were discrete...
Python Code: import numpy as np import pandas as pd import matplotlib.pyplot as plt import tempfile import base64 import pprint import json import sys import gym import io from gym import wrappers from subprocess import check_output from IPython.display import HTML Explanation: State Space Discretization From the previ...
7,321
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2019 The TensorFlow Authors. Step1: Dogs vs Cats Image Classification Without Image Augmentation <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" hr...
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...
7,322
Given the following text description, write Python code to implement the functionality described below step by step Description: All API's Step1: After writing a code that returns a result, now automating that for the various dates using a function Step2: 2) What are all the different book categories the NYT ranked ...
Python Code: #API Key: 0c3ba2a8848c44eea6a3443a17e57448 import requests bestseller_response = requests.get('http://api.nytimes.com/svc/books/v2/lists/2009-05-10/hardcover-fiction?api-key=0c3ba2a8848c44eea6a3443a17e57448') bestseller_data = bestseller_response.json() print("The type of bestseller_data is:", type(bestsel...
7,323
Given the following text description, write Python code to implement the functionality described below step by step Description: Before we get started, a couple of reminders to keep in mind when using iPython notebooks Step1: Fixing Data Types Step2: Note when running the above cells that we are actively changing th...
Python Code: import unicodecsv ## Longer version of code (replaced with shorter, equivalent version below) # enrollments = [] # f = open('enrollments.csv', 'rb') # reader = unicodecsv.DictReader(f) # for row in reader: # enrollments.append(row) # f.close() def open_file(filename): with open(filename, 'rb') as f...
7,324
Given the following text description, write Python code to implement the functionality described below step by step Description: Nearest Neighbors When exploring a large set of documents -- such as Wikipedia, news articles, StackOverflow, etc. -- it can be useful to get a list of related material. To find relevant doc...
Python Code: import graphlab import matplotlib.pyplot as plt import numpy as np %matplotlib inline Explanation: Nearest Neighbors When exploring a large set of documents -- such as Wikipedia, news articles, StackOverflow, etc. -- it can be useful to get a list of related material. To find relevant documents you typical...
7,325
Given the following text problem statement, write Python code to implement the functionality described below in problem statement Problem: import a gpt2 tokenizer to tokenize my text dataset
Python Code:: from transformers import GPT2Tokenizer tokenizer = GPT2Tokenizer.from_pretrained("gpt2")
7,326
Given the following text description, write Python code to implement the functionality described below step by step Description: Use BlackJAX with TFP BlackJAX can take any log-probability function as long as it is compatible with JAX's JIT. In this notebook we show how we can use tensorflow-probability as a modeling ...
Python Code: import jax import jax.numpy as jnp import numpy as np from tensorflow_probability.substrates import jax as tfp tfd = tfp.distributions import blackjax Explanation: Use BlackJAX with TFP BlackJAX can take any log-probability function as long as it is compatible with JAX's JIT. In this notebook we show how w...
7,327
Given the following text description, write Python code to implement the functionality described below step by step Description: Machine Learning with Python Speaker Step1: $$ \hat{\theta} = (\mathbf{X}^T \cdot \mathbf{X})^{-1} \cdot \mathbf{X}^T \cdot \mathbf{y} $$ Step2: which is the same result. However ... Norma...
Python Code: # prepare some data import numpy as np np.random.seed(42) # only if you want reproduceable result X = 2 * np.random.rand(100, 1) y = 4 + 3 * X + np.random.randn(100, 1) %matplotlib inline import matplotlib.pyplot as plt plt.scatter(X, y) # calculate inverse of the matrix X using inv() function # from NumP...
7,328
Given the following text description, write Python code to implement the functionality described below step by step Description: Dinámica del Amor El modelo describe el estado emotivo de Laura, Petrarca y la Inspración de Petrarca, al paso del tiempo. <table> <tr> <td> <img src="https Step1: T...
Python Code: # Para hacer experimentos numéricos importamos numpy import numpy as np #import pandas as pd # y biblioteca para plotear import matplotlib import matplotlib.pyplot as plt %matplotlib inline # cómputo simbólico con sympy from sympy import * init_printing() Explanation: Dinámica del Amor El modelo describe e...
7,329
Given the following text description, write Python code to implement the functionality described below step by step Description: <IMG SRC="https Step1: Step 2. Reading the time series The next step is to import the time series data. Three series are used in this example; the observed groundwater head, the rainfall an...
Python Code: import numpy as np import pandas as pd import os import matplotlib.pyplot as plt import pastas as ps ps.set_log_level("ERROR") %matplotlib inline # This notebook has been developed using Pastas version 0.9.9 and Python 3.7 print("Pastas version: {}".format(ps.__version__)) print("Pandas version: {}".format...
7,330
Given the following text description, write Python code to implement the functionality described below step by step Description: NumPy Numerical Python Provides an efficient way to store and manipulate arrays. Numpy is all about VECTORIZATION. Mental model is different than regular python and works with Step1: Examp...
Python Code: import random class RandomWalker(object): def __init__(self): self.position = 0 def walk(self, n): self.position = 0 for i in range(n): yield self.position self.position += 2*random.randint(0,1) - 1 Explan...
7,331
Given the following text description, write Python code to implement the functionality described. Description: Program for sum of cosh ( x ) series upto Nth term function to return the factorial of a number ; function to return the Sum of the series ; Driver code
Python Code: def fact(n ) : i , fac = 1 , 1 for i in range(1 , n + 1 ) : fac = fac * i  return fac  def log_Expansion(x , n ) : Sum = 0 i = 0 for i in range(n ) : Sum = Sum + pow(x , 2 * i ) / fact(2 * i )  return Sum  x = 1 n = 10 print(log_Expansion(x , n ) )
7,332
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2021 The TensorFlow Authors. Step1: TensorFlow Lite Metadata Writer API <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https Step2: Create ...
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...
7,333
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Face Generation In this project, you'll use generative adversarial networks to generate new images of faces. Get the Data You'll be using two datasets in this project Step3: Explore ...
Python Code: data_dir = './data' # FloydHub - Use with data ID "R5KrjnANiKVhLWAkpXhNBe" #data_dir = '/input' DON'T MODIFY ANYTHING IN THIS CELL import helper helper.download_extract('mnist', data_dir) helper.download_extract('celeba', data_dir) Explanation: Face Generation In this project, you'll use generative adversa...
7,334
Given the following text description, write Python code to implement the functionality described below step by step Description: Brewing Logistic Regression then Going Deeper While Caffe is made for deep networks it can likewise represent "shallow" models like logistic regression for classification. We'll do simple lo...
Python Code: import numpy as np import matplotlib.pyplot as plt %matplotlib inline import os os.chdir('..') import sys sys.path.insert(0, './python') import caffe import os import h5py import shutil import tempfile import sklearn import sklearn.datasets import sklearn.linear_model import pandas as pd Explanation: Brewi...
7,335
Given the following text description, write Python code to implement the functionality described. Description: Minimum lines to cover all points Utility method to get gcd of a and b ; method returns reduced form of dy / dx as a pair ; get sign of result ; method returns minimum number of lines to cover all points where...
Python Code: def gcd(a , b ) : if(b == 0 ) : return a  return gcd(b , a % b )  def getReducedForm(dy , dx ) : g = gcd(abs(dy ) , abs(dx ) ) sign =(dy < 0 ) ^(dx < 0 ) if(sign ) : return(- abs(dy ) // g , abs(dx ) // g )  else : return(abs(dy ) // g , abs(dx ) // g )   def minLinesToCover...
7,336
Given the following text description, write Python code to implement the functionality described below step by step Description: 확률론적 언어 모형 확률론적 언어 모형(Probabilistic Language Model)은 $m$개의 단어 $w_1, w_2, \ldots, w_m$ 열(word sequence)이 주어졌을 때 문장으로써 성립될 확률 $P(w_1, w_2, \ldots, w_m)$ 을 출력함으로써 이 단어 열이 실제로 현실에서 사용될 수 있는 문장(s...
Python Code: from nltk.corpus import movie_reviews # 문서를 문장으로 분리 sentences = list(movie_reviews.sents()) import random # 섞는다. random.seed(1) random.shuffle(sentences) sentences[0] Explanation: 확률론적 언어 모형 확률론적 언어 모형(Probabilistic Language Model)은 $m$개의 단어 $w_1, w_2, \ldots, w_m$ 열(word sequence)이 주어졌을 때 문장으로써 성립될 확률 $P(...
7,337
Given the following text description, write Python code to implement the functionality described below step by step Description: Contextual Bandits (incomplete) Step1: Query by Committee Step2: Stochastic Gradient Descent Step3: Random selection of data points at each iteration. Step4: SVM with Random Sampling Ste...
Python Code: import numpy as np import pandas as pd import pickle import seaborn as sns from pandas import DataFrame, Index from sklearn import metrics from sklearn.linear_model import SGDClassifier from sklearn.svm import SVC from sklearn.kernel_approximation import RBFSampler, Nystroem from sklearn.linear_model impor...
7,338
Given the following text description, write Python code to implement the functionality described below step by step Description: Repeatable splitting Learrning Objectives * explore the impact of different ways of creating train/valid/test splits Overview Repeatability is important in machine learning. If you do the s...
Python Code: from google.cloud import bigquery Explanation: Repeatable splitting Learrning Objectives * explore the impact of different ways of creating train/valid/test splits Overview Repeatability is important in machine learning. If you do the same thing now and 5 minutes from now and get different answers, then i...
7,339
Given the following text description, write Python code to implement the functionality described below step by step Description: <center> Doing Math with Python </center> <center> <p> <b>Amit Saha</b> <p>May 30, PyCon US 2016 <p>Portland, Oregon </center> ## About me - Software Engineer at [Freelancer.com](https Step1...
Python Code: # Create graphs from algebraic expressions from sympy import Symbol, plot x = Symbol('x') p = plot(2*x**2 + 2*x + 2) # Solve equations from sympy import solve, Symbol x = Symbol('x') solve(2*x + 1) # Limits from sympy import Symbol, Limit, sin x = Symbol('x') Limit(sin(x)/x, x, 0).doit() # Derivative from ...
7,340
Given the following text description, write Python code to implement the functionality described below step by step Description: First, we'll download the dataset to our local machine. The data consists of characters rendered in a variety of fonts on a 28x28 image. The labels are limited to 'A' through 'J' (10 classes...
Python Code: # These are all the modules we'll be using later. Make sure you can import them # before proceeding further. from __future__ import print_function import matplotlib.pyplot as plt import numpy as np import os import sys import tarfile from IPython.display import display, Image from scipy import ndimage from...
7,341
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2020 The TensorFlow Authors. Step1: Integrating MinDiff with MinDiffModel <div class="devsite-table-wrapper"><table class="tfo-notebook-buttons" align="left"> <td><a target="_bl...
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...
7,342
Given the following text description, write Python code to implement the functionality described below step by step Description: 2 samples permutation test on source data with spatio-temporal clustering Tests if the source space data are significantly different between 2 groups of subjects (simulated here using one su...
Python Code: # Authors: Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr> # Eric Larson <larson.eric.d@gmail.com> # License: BSD (3-clause) import os.path as op import numpy as np from scipy import stats as stats import mne from mne import spatial_src_connectivity from mne.stats import spatio_tempor...
7,343
Given the following text description, write Python code to implement the functionality described below step by step Description: Application Step1: Download prediction files We release four groups of predictions Step2: Finally, load the occupations data from the U.S. Bureau of Labor Statistics, which we'll use to co...
Python Code: #@title Import libraries and multibootstrap code import re import os import numpy as np import pandas as pd import sklearn.metrics import scipy.stats from tqdm.notebook import tqdm # for progress indicator import multibootstrap #@title Import and configure plotting libraries import matplotlib from matplot...
7,344
Given the following text description, write Python code to implement the functionality described below step by step Description: Solving convection-coupled melting with adaptive mixed finite elements This Jupyter notebook shows how to solve the convection-coupled melting benchmark with the general approach of [5], usi...
Python Code: import fenics Explanation: Solving convection-coupled melting with adaptive mixed finite elements This Jupyter notebook shows how to solve the convection-coupled melting benchmark with the general approach of [5], using mixed finite elements in FEniCS with goal-oriented adaptive mesh refinement (AMR) as pr...
7,345
Given the following text description, write Python code to implement the functionality described below step by step Description: <h1>Table of Contents<span class="tocSkip"></span></h1> <div class="toc"><ul class="toc-item"><li><span><a href="#Collaborative-Filtering-for-Implicit-Feedback-Datasets" data-toc-modified-id...
Python Code: # code for loading the format for the notebook import os # path : store the current path to convert back to it later path = os.getcwd() os.chdir(os.path.join('..', 'notebook_format')) from formats import load_style load_style(css_style = 'custom2.css', plot_style = False) os.chdir(path) # 1. magic to print...
7,346
Given the following text description, write Python code to implement the functionality described below step by step Description: 07- Feature Selection by Alejandro Correa Bahnsen version 0.2, May 2016 Part of the class Machine Learning for Security Informatics This notebook is licensed under a Creative Commons Attribu...
Python Code: import pandas as pd import numpy as np import zipfile with zipfile.ZipFile('../datasets/titanic.csv.zip', 'r') as z: f = z.open('titanic.csv') titanic = pd.read_csv(f, sep=',', index_col=0) titanic.head() titanic.Age.fillna(titanic.Age.median(), inplace=True) titanic.loc[titanic.Embarked.isnull(), ...
7,347
Given the following text description, write Python code to implement the functionality described below step by step Description: Priklad vyber autributov pomocou filtra a ukazka toho, preco PCA nie je vyber atributov Step1: Skusme najskor priklad toho ako by sme z nejakeho datasetu vyberali najdolezitejsie atributy p...
Python Code: %matplotlib inline import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn plt.rcParams['figure.figsize'] = 9, 6 Explanation: Priklad vyber autributov pomocou filtra a ukazka toho, preco PCA nie je vyber atributov End of explanation from sklearn import datasets, svm from sklea...
7,348
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Example of the $k$-point sampling for TBtrans. Step2: Run these two executables
Python Code: chain = sisl.Geometry([0]*3, sisl.Atom(1, R=1.), sc=[1, 1, 10]) chain.set_nsc([3, 3, 1]) # Transport along y-direction chain = chain.tile(20, 0) He = sisl.Hamiltonian(chain) He.construct(([0.1, 1.1], [0, -1])) Hd = He.tile(20, 1) He.write('ELEC.nc') Hd.write('DEVICE.nc') with open('RUN.fdf', 'w') as f: ...
7,349
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Filtering of Data in Insights Parsers and Rules In this tutorial we will investigate filters in insights-core, what they are, how they affect your components and how you can use them ...
Python Code: Some imports used by all of the code in this tutorial import sys sys.path.insert(0, "../..") from __future__ import print_function import os from insights import run from insights.specs import SpecSet from insights.core import IniConfigFile from insights.core.plugins import parser, rule, make_fail from i...
7,350
Given the following text description, write Python code to implement the functionality described below step by step Description: last lesson we wrote code to plot some values from our inflammation data. but we have a dozen we want to do same for how to repeat things? Step1: This is a bad appoach b/c Step2: uses a fo...
Python Code: #example task: print each character in a word #one way to do is use a series of print statements word = 'lead' print(word[0]) print(word[1]) print(word[2]) print(word[3]) Explanation: last lesson we wrote code to plot some values from our inflammation data. but we have a dozen we want to do same for how to...
7,351
Given the following text description, write Python code to implement the functionality described below step by step Description: 3A.mr - Random Walk with Restart (système de recommandations) Si la méthode de factorisation de matrices est la méthode la plus connue pour faire des recommandations, ce n'est pas la seule. ...
Python Code: import numpy as np from numpy.linalg import det P = np.matrix ( [[ 0,0.5,0,0.5],[0.5,0,0.5,0],[1./3,1./3,0,1./3],[0.1,0.9,0,0]]) P c = 0.15 I = np.identity(4) e = np.matrix( [[ 0., 1., 0., 0. ]]).T pi = ((I-P.T*(1-c))).I * e * c pi Explanation: 3A.mr - Random Walk with Restart (système de recommandations) ...
7,352
Given the following text description, write Python code to implement the functionality described below step by step Description: Handwritten Number Recognition with TFLearn and MNIST In this notebook, we'll be building a neural network that recognizes handwritten numbers 0-9. This kind of neural network is used in a ...
Python Code: # Import Numpy, TensorFlow, TFLearn, and MNIST data import numpy as np import tensorflow as tf import tflearn import tflearn.datasets.mnist as mnist Explanation: Handwritten Number Recognition with TFLearn and MNIST In this notebook, we'll be building a neural network that recognizes handwritten numbers 0-...
7,353
Given the following text description, write Python code to implement the functionality described below step by step Description: Chapter 13 Examples and Exercises from Think Stats, 2nd Edition http Step1: Survival analysis If we have an unbiased sample of complete lifetimes, we can compute the survival function from ...
Python Code: from os.path import basename, exists def download(url): filename = basename(url) if not exists(filename): from urllib.request import urlretrieve local, _ = urlretrieve(url, filename) print("Downloaded " + local) download("https://github.com/AllenDowney/ThinkStats2/raw/master...
7,354
Given the following text description, write Python code to implement the functionality described below step by step Description: Variational Equations For a complete introduction to variational equations, please read the paper by Rein and Tamayo (2016). For this tutorial, we work with a two planet system. We vary the ...
Python Code: import rebound import numpy as np %matplotlib inline import matplotlib; import matplotlib.pyplot as plt Explanation: Variational Equations For a complete introduction to variational equations, please read the paper by Rein and Tamayo (2016). For this tutorial, we work with a two planet system. We vary the ...
7,355
Given the following text description, write Python code to implement the functionality described below step by step Description: Simple script to transform exported GeoModeller 3-D regular grid into MOOSE grid Note Step3: Load exported GeoModeller file We use here simply the export functionality of GeoModeller (note ...
Python Code: # some basic imports: import numpy as np import os import matplotlib.pyplot as plt # for 3-D visualisation: import ipyvolume.pylab as p3 Explanation: Simple script to transform exported GeoModeller 3-D regular grid into MOOSE grid Note: we don't create a proper FE mesh here, but simply perform a "mapping" ...
7,356
Given the following text description, write Python code to implement the functionality described below step by step Description: Sebastian Raschka last updated Step1: <br> <br> <a name='plotting_data'></a> Plotting the sample data To get an intuitive idea of how our data looks like, let us visualize it in a simple s...
Python Code: import numpy as np np.random.seed(123456) # Generate 100 random patterns for class1 mu_vec1 = np.array([[0],[0]]) cov_mat1 = np.array([[3,0],[0,3]]) x1_samples = np.random.multivariate_normal(mu_vec1.ravel(), cov_mat1, 100) # Generate 100 random patterns for class2 mu_vec2 = np.array([[9],[0]]) cov_mat2 = ...
7,357
Given the following text description, write Python code to implement the functionality described below step by step Description: Example reading THREDDS NCSS as point in Python Step1: First generate a sample RESTful URL using the NCSS Web Form Step2: Once you have a sample URL, it's easy to create a different URL pr...
Python Code: %matplotlib inline import pandas as pd Explanation: Example reading THREDDS NCSS as point in Python End of explanation url = 'http://data.ncof.co.uk/thredds/ncss/METOFFICE-NWS-AF-WAV-HOURLY?var=VHM0&var=VHM0_SW1&var=VHM0_WW&latitude=61.15&longitude=-9.5&time_start=2017-06-02T00%3A00%3A00Z&time_end=2017-06-...
7,358
Given the following text description, write Python code to implement the functionality described below step by step Description: Chapter 21 Modeling and Simulation in Python Copyright 2021 Allen Downey License Step1: In the previous chapter we simulated a penny falling in a vacuum, that is, without air resistance. Bu...
Python Code: # install Pint if necessary try: import pint except ImportError: !pip install pint # download modsim.py if necessary from os.path import exists filename = 'modsim.py' if not exists(filename): from urllib.request import urlretrieve url = 'https://raw.githubusercontent.com/AllenDowney/ModSim/...
7,359
Given the following text description, write Python code to implement the functionality described below step by step Description: K-Means Clustering Example Let's make some fake data that includes people clustered by income and age, randomly Step1: We'll use k-means to rediscover these clusters in unsupervised learnin...
Python Code: from numpy import random, array #Create fake income/age clusters for N people in k clusters def createClusteredData(N, k): random.seed(10) pointsPerCluster = float(N)/k X = [] for i in range (k): incomeCentroid = random.uniform(20000.0, 200000.0) ageCentroid = random.uniform...
7,360
Given the following text description, write Python code to implement the functionality described below step by step Description: Python Flight Mechanics Engine This installs pyfme to be run in this online notebook Step1: Aircraft In order to perform a simulation, the first thing we need is an aircraft Step2: Aircraf...
Python Code: !pip install git+https://github.com/AeroPython/PyFME.git Explanation: Python Flight Mechanics Engine This installs pyfme to be run in this online notebook End of explanation from pyfme.aircrafts import Cessna172 aircraft = Cessna172() Explanation: Aircraft In order to perform a simulation, the first thing ...
7,361
Given the following text description, write Python code to implement the functionality described below step by step Description: Post Training Integer Quantization <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https Step1: Train and export the model Step2: For the example, we ...
Python Code: ! pip uninstall -y tensorflow ! pip install -U tf-nightly import tensorflow as tf tf.enable_eager_execution() ! git clone --depth 1 https://github.com/tensorflow/models import sys import os if sys.version_info.major >= 3: import pathlib else: import pathlib2 as pathlib # Add `models` to the python ...
7,362
Given the following text description, write Python code to implement the functionality described below step by step Description: Predicting crime in San Francisco with machine learning (Kaggle 2015) Notice Step1: Raw data Step2: View composing & feature engineering Step3: Garbage Collection Step4: Draw samples Ste...
Python Code: import datetime import gc import zipfile import matplotlib as mpl import numpy as np import pandas as pd import seaborn as sns import sklearn as sk from pandas.tseries.holiday import USFederalHolidayCalendar from sklearn.cross_validation import KFold, cross_val_score from sklearn.ensemble import RandomFore...
7,363
Given the following text description, write Python code to implement the functionality described below step by step Description: server/udp/podCommands.js - from node.js /JavaScript to Python (object) Step1: The reactGS folder "mimics" the actual react-groundstation github repository, only copying the file directory ...
Python Code: # find out where we are on the file directory import os, sys print( os.getcwd()) print( os.listdir(os.getcwd())) Explanation: server/udp/podCommands.js - from node.js /JavaScript to Python (object) End of explanation wherepodCommandsis = os.getcwd()+'/reactGS/server/udp/' print(wherepodCommandsis) Explana...
7,364
Given the following text description, write Python code to implement the functionality described below step by step Description: Chapter 2 Modeling and Simulation in Python Copyright 2021 Allen Downey License Step1: This chapter presents a simple model of a bike share system and demonstrates the features of Python we...
Python Code: # install Pint if necessary try: import pint except ImportError: !pip install pint # download modsim.py if necessary from os.path import exists filename = 'modsim.py' if not exists(filename): from urllib.request import urlretrieve url = 'https://raw.githubusercontent.com/AllenDowney/ModSim/...
7,365
Given the following text description, write Python code to implement the functionality described below step by step Description: <a href='http Step1: Train Test Split Step2: Estimators Let's show you how to use the simpler Estimator interface! Step3: Feature Columns Step4: Input Function Step5: Model Evaluation ...
Python Code: import pandas as pd df = pd.read_csv('iris.csv') df.head() df.columns = ['sepal_length','sepal_width','petal_length','petal_width','target'] X = df.drop('target',axis=1) y = df['target'].apply(int) Explanation: <a href='http://www.pieriandata.com'> <img src='../Pierian_Data_Logo.png' /></a> Tensorflow with...
7,366
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction In the last notebook, I showed you how easy it is to connect jQAssistant/neo4j with Python Pandas/py2neo. In this notebook, I show you a (at first glance) simple analysis of the...
Python Code: import py2neo import pandas as pd import matplotlib.pyplot as plt # display graphics directly in the notebook %matplotlib inline Explanation: Introduction In the last notebook, I showed you how easy it is to connect jQAssistant/neo4j with Python Pandas/py2neo. In this notebook, I show you a (at first glanc...
7,367
Given the following text description, write Python code to implement the functionality described below step by step Description: Input from the keyboard In Pytho, the keyboard is the default input device. <a id='input'></a> 1. Input from the code Step1: <a id='prompt'></a> 2. Input from the OS prompt Step2: Another ...
Python Code: a = input('Please, enter something: ') print('You entered:', a) Explanation: Input from the keyboard In Pytho, the keyboard is the default input device. <a id='input'></a> 1. Input from the code End of explanation !cat argparse_example.py !python argparse_example.py -h !python argparse_example.py -i abc Ex...
7,368
Given the following text description, write Python code to implement the functionality described below step by step Description: Searching for packages As explained in "Uploading a Package", packages are managed using registries. There is a one local registry on your machine, and potentially many remote registries els...
Python Code: import quilt3 # list local packages list(quilt3.list_packages()) # list remote packages list(quilt3.list_packages("s3://quilt-example")) Explanation: Searching for packages As explained in "Uploading a Package", packages are managed using registries. There is a one local registry on your machine, and poten...
7,369
Given the following text description, write Python code to implement the functionality described below step by step Description: Machine Learning Engineer Nanodegree Model Evaluation & Validation Project 1 Step1: Statistical Analysis and Data Exploration In this first section of the project, you will quickly investig...
Python Code: # Importing a few necessary libraries # python standard library import warnings # third party import numpy as np import numpy import matplotlib.pyplot as pl from matplotlib import pylab import pandas import seaborn from sklearn import datasets from sklearn.tree import DecisionTreeRegressor # Make matplotli...
7,370
Given the following text description, write Python code to implement the functionality described below step by step Description: WAve Models (WAM) Usage Example WAM wave models are most widely used wave models in the world. This notebook illustrates ways of using WAM models data via Planet OS Datahub API, including S...
Python Code: %matplotlib notebook import urllib.request import numpy as np import simplejson as json import pandas as pd from netCDF4 import Dataset, date2num, num2date import ipywidgets as widgets from IPython.display import display, clear_output import dateutil.parser import matplotlib.pyplot as plt from mpl_toolkits...
7,371
Given the following text description, write Python code to implement the functionality described below step by step Description: Changes in religious affiliation and attendance Analysis based on data from the CIRP Freshman Survey Copyright Allen Downey MIT License Step1: Read the data. Note Step2: Compute time vari...
Python Code: %matplotlib inline import numpy as np import pandas as pd import matplotlib.pyplot as plt from utils import decorate, savefig import statsmodels.formula.api as smf import warnings warnings.filterwarnings('error') Explanation: Changes in religious affiliation and attendance Analysis based on data from the C...
7,372
Given the following text description, write Python code to implement the functionality described below step by step Description: Apply logistic regression to categorize whether a county had high mortality rate due to contamination 1. Import the necessary packages to read in the data, plot, and create a logistic regres...
Python Code: import pandas as pd %matplotlib inline import numpy as np from sklearn.linear_model import LogisticRegression Explanation: Apply logistic regression to categorize whether a county had high mortality rate due to contamination 1. Import the necessary packages to read in the data, plot, and create a logistic ...
7,373
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="#Générer-des-fausses-citations-latines-du-Roi-Loth,-avec-Python,-Wikiquote-et-des-chaînes-de-Markov" data-toc-modified-id="Générer-de...
Python Code: citation = citation_aleatoire(italic=True) display(Markdown("> {}".format(citation))) Explanation: Table of Contents <p><div class="lev1 toc-item"><a href="#Générer-des-fausses-citations-latines-du-Roi-Loth,-avec-Python,-Wikiquote-et-des-chaînes-de-Markov" data-toc-modified-id="Générer-des-fausses-citation...
7,374
Given the following text description, write Python code to implement the functionality described below step by step Description: Chapter 14 Step1: Python also has a module called types, which has the definitions of the basic types of the interpreter. Example Step2: Through introspection, it is possible to determine ...
Python Code: trospection or reflection is the ability of software to identify and report their own internal structures, such as types, variabl# Getting some information # about global objects in the program from types import ModuleType def info(n_obj): # Create a referênce to the object obj = globals()[n_obj] ...
7,375
Given the following text description, write Python code to implement the functionality described below step by step Description: Полезные практики, неочевидные моменты Неоднозная грамматика Есть примитивная рекурсивная грамматика Step1: Число вариантов быстро растёт. Для строки "a x 10", парсер переберёт 89 разборов....
Python Code: from yargy.parser import prepare_trees from yargy import Parser, or_, rule A = or_( rule('a'), rule('a', 'a') ) B = A.repeatable() display(B.normalized.as_bnf) parser = Parser(B) matches = parser.extract('a a a') for match in matches: # кроме 3-х полных разборов, парсёр найдёт ещё 7 частичн...
7,376
Given the following text description, write Python code to implement the functionality described below step by step Description: BigQuery Dataset Create and permission a dataset in BigQuery. License Copyright 2020 Google LLC, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file exc...
Python Code: !pip install git+https://github.com/google/starthinker Explanation: BigQuery Dataset Create and permission a dataset in BigQuery. 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 obtai...
7,377
Given the following text description, write Python code to implement the functionality described below step by step Description: Pôle Emploi Agencies Date Step1: OK, this sounds pretty cool. However there are a lot of fields (63) so let's check them vertically Step2: OK, it's a bit easier to read, but not enough to ...
Python Code: import os from os import path import pandas as pd import seaborn as _ DATA_FOLDER = os.getenv('DATA_FOLDER') agencies = pd.read_csv(path.join(DATA_FOLDER, 'pole-emploi-agencies.csv')) agencies.head() Explanation: Pôle Emploi Agencies Date: 2017-11-19 Author: Pascal pascal@bayesimpact.org In Pôle emploi Ope...
7,378
Given the following text description, write Python code to implement the functionality described below step by step Description: Composite Glyph One or more actual glyphs that have been grouped together to represent some set of data, which respond to some standardized set of graphics operations. In a chart, a composit...
Python Code: bar = BarGlyph(label='a', values=[1]) bar.data Explanation: Composite Glyph One or more actual glyphs that have been grouped together to represent some set of data, which respond to some standardized set of graphics operations. In a chart, a composite glyph is generated for each group of data. For example,...
7,379
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: TV Script Generation In this project, you'll generate your own Simpsons TV scripts using RNNs. You'll be using part of the Simpsons dataset of scripts from 27 seasons. The Neural Ne...
Python Code: DON'T MODIFY ANYTHING IN THIS CELL import helper data_dir = './data/simpsons/moes_tavern_lines.txt' text = helper.load_data(data_dir) # Ignore notice, since we don't use it for analysing the data text = text[81:] Explanation: TV Script Generation In this project, you'll generate your own Simpsons TV script...
7,380
Given the following text description, write Python code to implement the functionality described below step by step Description: Title Step1: Create dataframe Step2: Create a pivot table of group means, by company and regiment Step3: Create a pivot table of group score counts, by company and regimensts
Python Code: import pandas as pd Explanation: Title: Pivot Tables In Pandas Slug: pandas_pivot_tables Summary: Pivot Tables In Pandas Date: 2016-05-01 12:00 Category: Python Tags: Data Wrangling Authors: Chris Albon import modules End of explanation raw_data = {'regiment': ['Nighthawks', 'Nighthawks', 'Nighthawks', '...
7,381
Given the following text description, write Python code to implement the functionality described below step by step Description: Skewness and symmetry By Evgenia "Jenny" Nitishinskaya and Delaney Granizo-Mackenzie Part of the Quantopian Lecture Series Step1: A distribution which is not symmetric is called <i>skewed</...
Python Code: import matplotlib.pyplot as plt import numpy as np import scipy.stats as stats # Plot a normal distribution with mean = 0 and standard deviation = 2 xs = np.linspace(-6,6, 300) normal = stats.norm.pdf(xs) plt.plot(xs, normal); Explanation: Skewness and symmetry By Evgenia "Jenny" Nitishinskaya and Delaney ...
7,382
Given the following text description, write Python code to implement the functionality described below step by step Description: Text Classification using TensorFlow and Google Cloud - Part 4 This bigquery-public-data Step1: Importing libraries Step2: 1. Define Metadata Step3: 2. Define Input Function Step4: 3. Cr...
Python Code: import os class Params: pass # Set to run on GCP Params.GCP_PROJECT_ID = 'ksalama-gcp-playground' Params.REGION = 'europe-west1' Params.BUCKET = 'ksalama-gcs-cloudml' Params.PLATFORM = 'local' # local | GCP Params.DATA_DIR = 'data/news' if Params.PLATFORM == 'local' else 'gs://{}/data/news'.format(Par...
7,383
Given the following text description, write Python code to implement the functionality described below step by step Description: Structure and Angular Momentum Step1: Adding Structure So far we've looked at simple 2 and 3 level systems, but to accurately model a physical system we may need to consider complex structu...
Python Code: import numpy as np Explanation: Structure and Angular Momentum End of explanation print(np.sqrt(1/6/3)) print(np.sqrt(1/2/3)) Explanation: Adding Structure So far we've looked at simple 2 and 3 level systems, but to accurately model a physical system we may need to consider complex structures. For example,...
7,384
Given the following text description, write Python code to implement the functionality described below step by step Description: Scroll down the the analysis section to see the actual analysis Step1: Loading files Step2: Analysis Step3: Some thing seems to be up with the month of September in this data Step4: This...
Python Code: 1+1 import pandas as pd import numpy as np import glob import os Explanation: Scroll down the the analysis section to see the actual analysis End of explanation path=os.path.expanduser("~/Documents/TaxiTripData/2013taxi_trip_data/") files=glob.glob(path+'*.csv.zip.gz') countlist=[] cunk=100000 for i in fil...
7,385
Given the following text description, write Python code to implement the functionality described below step by step Description: Predicting sentiment from product reviews Fire up GraphLab Create Step1: Read some product review data Loading reviews for a set of baby products. Step2: Let's explore this data together D...
Python Code: import graphlab Explanation: Predicting sentiment from product reviews Fire up GraphLab Create End of explanation products = graphlab.SFrame('amazon_baby.gl/') Explanation: Read some product review data Loading reviews for a set of baby products. End of explanation products.head() Explanation: Let's explor...
7,386
Given the following text description, write Python code to implement the functionality described below step by step Description: Earth temperature over time Is global temperature rising? How much? This is a question of burning importance in today's world! Data about global temperatures are available from several sourc...
Python Code: from IPython.display import YouTubeVideo YouTubeVideo('gGOzHVUQCw0') Explanation: Earth temperature over time Is global temperature rising? How much? This is a question of burning importance in today's world! Data about global temperatures are available from several sources: NASA, the National Climatic Dat...
7,387
Given the following text description, write Python code to implement the functionality described below step by step Description: ES-DOC CMIP6 Model Properties - Ocnbgchem 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', 'cams', 'sandbox-3', 'ocnbgchem') Explanation: ES-DOC CMIP6 Model Properties - Ocnbgchem MIP Era: CMIP6 Institute: CAMS Source ID: SANDBOX-3 Topic: Ocnbgchem Sub-Topics: Tracers. Prop...
7,388
Given the following text description, write Python code to implement the functionality described below step by step Description: Simulating CSTR Here a CSTR model simulation is demoed with pure surface phase mechanism focussed on Ammonia dehydrogenation. The mechanims consists of 18 species and 7 reactions. In convent...
Python Code: import os import matplotlib as mpl mpl.rcParams['figure.dpi'] = 500 import numpy as np import pandas as pd import matplotlib.pyplot as plt %matplotlib inline %config InlineBackend.figure_format = 'retina' Explanation: Simulating CSTR Here a CSTR model simulation is demoed with pure surface phase mechanism...
7,389
Given the following text description, write Python code to implement the functionality described below step by step Description: <h1>Table of Contents<span class="tocSkip"></span></h1> <div class="toc"><ul class="toc-item"><li><span><a href="#Tuning-Spark-Partitions" data-toc-modified-id="Tuning-Spark-Partitions-1"><s...
Python Code: # code for loading the format for the notebook import os # path : store the current path to convert back to it later path = os.getcwd() os.chdir(os.path.join('..', 'notebook_format')) from formats import load_style load_style(plot_style=False) os.chdir(path) # 1. magic to print version # 2. magic so that t...
7,390
Given the following text description, write Python code to implement the functionality described below step by step Description: <img align="left" src="imgs/logo.jpg" width="50px" style="margin-right Step1: Loading the Corpus Next, we load and pre-process the corpus of documents. Configuring a DocPreprocessor We'll s...
Python Code: %load_ext autoreload %autoreload 2 %matplotlib inline import os # Connect to the database backend and initalize a Snorkel session from lib.init import * # Here, we just set how many documents we'll process for automatic testing- you can safely ignore this! n_docs = 1000 if 'CI' in os.environ else 2591 Expl...
7,391
Given the following text description, write Python code to implement the functionality described below step by step Description: healpy tutorial See the Jupyter Notebook version of this tutorial at https Step1: NSIDE and ordering Maps are simply numpy arrays, where each array element refers to a location in the sky a...
Python Code: import matplotlib.pyplot as plt %matplotlib inline import numpy as np import healpy as hp Explanation: healpy tutorial See the Jupyter Notebook version of this tutorial at https://github.com/healpy/healpy/blob/master/doc/healpy_tutorial.ipynb See a executed version of the notebook with embedded plots at ht...
7,392
Given the following text description, write Python code to implement the functionality described below step by step Description: Sentiment analysis with TFLearn In this notebook, we'll continue Andrew Trask's work by building a network for sentiment analysis on the movie review data. Instead of a network written with ...
Python Code: import pandas as pd import numpy as np import tensorflow as tf import tflearn from tflearn.data_utils import to_categorical Explanation: Sentiment analysis with TFLearn In this notebook, we'll continue Andrew Trask's work by building a network for sentiment analysis on the movie review data. Instead of a n...
7,393
Given the following text description, write Python code to implement the functionality described below step by step Description: ES-DOC CMIP6 Model Properties - Atmos MIP Era Step1: Document Authors Set document authors Step2: Document Contributors Specify document contributors Step3: Document Publication Specify d...
Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'ec-earth-consortium', 'ec-earth3-gris', 'atmos') Explanation: ES-DOC CMIP6 Model Properties - Atmos MIP Era: CMIP6 Institute: EC-EARTH-CONSORTIUM Source ID: EC-EARTH3-GRIS Topic: Atmo...
7,394
Given the following text description, write Python code to implement the functionality described below step by step Description: Lecture 8 Step1: In this example, we switched the ordering of the arguments between the two function calls; consequently, the ordering of the arguments inside the function were also flipped...
Python Code: def pet_names(name1, name2): print("Pet 1: ", name1) print("Pet 2: ", name2) pet1 = "King" pet2 = "Reginald" pet_names(pet1, pet2) # pet1 variable, then pet2 variable pet_names(pet2, pet1) # notice we've switched the order in which they're passed to the function Explanation: Lecture 8: Functions ...
7,395
Given the following text description, write Python code to implement the functionality described below step by step Description: Assignment 5 This assignment has weighting $1.5$. Model tuning and evaluation Step1: Dataset We will use the Wisconsin breast cancer dataset for the following questions Step2: K-fold valid...
Python Code: # Added version check for recent scikit-learn 0.18 checks from distutils.version import LooseVersion as Version from sklearn import __version__ as sklearn_version Explanation: Assignment 5 This assignment has weighting $1.5$. Model tuning and evaluation End of explanation import pandas as pd wdbc_source = ...
7,396
Given the following text description, write Python code to implement the functionality described below step by step Description: This notebook will use a simple model to predict ratings for a user, anime pair Step1: Let's plot the objective and see how it decreases. Step2: So by 50 iterations, the model hits a bend ...
Python Code: import matplotlib.pyplot as plt import matplotlib %matplotlib inline matplotlib.style.use('seaborn') from animerec.data import get_data users, anime = get_data() from sklearn.model_selection import train_test_split train, test = train_test_split(users, test_size = 0.1) #let's split up the dataset into a tr...
7,397
Given the following text description, write Python code to implement the functionality described below step by step Description: <a id='top'> </a> Author Step1: Cosmic-ray composition clustering Table of contents Define analysis free parameters Data preprocessing Fitting random forest Fraction correctly identified Sp...
Python Code: %load_ext watermark %watermark -u -d -v -p numpy,matplotlib,scipy,pandas,sklearn,mlxtend Explanation: <a id='top'> </a> Author: James Bourbeau End of explanation import sys sys.path.append('/home/jbourbeau/cr-composition') print('Added to PYTHONPATH') %matplotlib inline from __future__ import division, pri...
7,398
Given the following text description, write Python code to implement the functionality described below step by step Description: Drive LEDs with the Raspberry Pi GPIO pins This notebook will walk you through using the Raspberry Pi General Purpose Input/Output (GPIO) pins to make a LED light burn. The GPIO pins are the...
Python Code: #load GPIO library import RPi.GPIO as GPIO #Set BCM (Broadcom) mode for the pin numbering GPIO.setmode(GPIO.BCM) Explanation: Drive LEDs with the Raspberry Pi GPIO pins This notebook will walk you through using the Raspberry Pi General Purpose Input/Output (GPIO) pins to make a LED light burn. The GPIO pin...
7,399
Given the following text description, write Python code to implement the functionality described below step by step Description: Использование глубокого обучения в NLP Смотрите в этой серии Step1: Познакомимся с данными Бывший kaggle-конкурс про выявление нежелательного контента. Описание конкурса есть тут - https St...
Python Code: low_RAM_mode = True very_low_RAM = False #если у вас меньше 3GB оперативки, включите оба флага import pandas as pd import numpy as np import matplotlib.pyplot as plt %matplotlib inline Explanation: Использование глубокого обучения в NLP Смотрите в этой серии: * Простые способы работать с текстом, bag of ...