Unnamed: 0
int64
0
16k
text_prompt
stringlengths
110
62.1k
code_prompt
stringlengths
37
152k
12,200
Given the following text description, write Python code to implement the functionality described below step by step Description: File systems proxies This notebook demonstrates file system proxies to folders and directories, which are basically strings (paths) with additional methods for creation, opening moving, dele...
Python Code: from spectrocrunch.io import fs,localfs,h5fs,nxfs Explanation: File systems proxies This notebook demonstrates file system proxies to folders and directories, which are basically strings (paths) with additional methods for creation, opening moving, deleting, renaming, linking and browsing. Three file syste...
12,201
Given the following text description, write Python code to implement the functionality described below step by step Description: Linear classifier on sensor data with plot patterns and filters Here decoding, a.k.a MVPA or supervised machine learning, is applied to M/EEG data in sensor space. Fit a linear classifier wi...
Python Code: # Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr> # Romain Trachel <trachelr@gmail.com> # Jean-Remi King <jeanremi.king@gmail.com> # # License: BSD (3-clause) import mne from mne import io, EvokedArray from mne.datasets import sample from mne.decoding import Vectorizer, get_coef...
12,202
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: Euler's method Euler's method is the simplest numerical approach for solving a first order ODE numerically. Given the differential ...
Python Code: %matplotlib inline import matplotlib.pyplot as plt import numpy as np import seaborn as sns from scipy.integrate import odeint from IPython.html.widgets import interact, fixed Explanation: Ordinary Differential Equations Exercise 1 Imports End of explanation def solve_euler(derivs, y0, x): Solve a 1d O...
12,203
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', 'messy-consortium', 'emac-2-53-vol', 'land') Explanation: ES-DOC CMIP6 Model Properties - Land MIP Era: CMIP6 Institute: MESSY-CONSORTIUM Source ID: EMAC-2-53-VOL Topic: Land Sub-Topic...
12,204
Given the following text description, write Python code to implement the functionality described below step by step Description: Insights from Baby Names Data Author Information Step1: II- Predictive Analysis II-1 Most popular name of all time Step2: Now, let's find the most popular male and female names of all time...
Python Code: import os from mpl_toolkits.basemap import Basemap import numpy as np import matplotlib.pyplot as plt %matplotlib inline data_folder = os.path.join('data') file_names = [] for f in os.listdir(data_folder): file_names.append(os.path.join(data_folder,f)) del file_names[file_names.index(os.path.join(data_...
12,205
Given the following text description, write Python code to implement the functionality described below step by step Description: Ardumoto Example This example shows how to use the Ardumoto on the board. Ardumoto supports two DC motor driving. There are also instructions on how to hook up the shield. Motor A and Moto...
Python Code: from pynq.overlays.base import BaseOverlay base = BaseOverlay("base.bit") Explanation: Ardumoto Example This example shows how to use the Ardumoto on the board. Ardumoto supports two DC motor driving. There are also instructions on how to hook up the shield. Motor A and Motor B are connected as below to ...
12,206
Given the following text description, write Python code to implement the functionality described below step by step Description: Bayesian deep-learning Launch in Google Colab Bayesian deep-learning network using dropout layers to perform Monte Carlo approximations for quantifying model uncertainty. Overview This noteb...
Python Code: %tensorflow_version 2.x import os import numpy as np import tensorflow as tf from tqdm import tqdm from matplotlib import pyplot %matplotlib inline print("Tensorflow version " + tf.__version__) Explanation: Bayesian deep-learning Launch in Google Colab Bayesian deep-learning network using dropout layers to...
12,207
Given the following text description, write Python code to implement the functionality described below step by step Description: Comparison of batchflow performance with tf and torch Models Firstly, we comapre torch and tf versions of VGG16. Train them on MNIST. TensorFlow model Step1: ... then restart kernel to clea...
Python Code: %%time %run ./tf_model.py Explanation: Comparison of batchflow performance with tf and torch Models Firstly, we comapre torch and tf versions of VGG16. Train them on MNIST. TensorFlow model End of explanation %%time %run ./torch_model.py Explanation: ... then restart kernel to clear GPU Torch model End of ...
12,208
Given the following text description, write Python code to implement the functionality described below step by step Description: Using Yellow Brick to Explore and Model the Famous Iris Dataset Exploration Notebook by Step1: Terminology 150 observations (n=150) Step2: Import the Good Stuff Step3: Feature Exploration...
Python Code: # read the iris data into a DataFrame import pandas as pd url = 'http://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data' col_names = ['sepal_length', 'sepal_width', 'petal_length', 'petal_width', 'species'] iris = pd.read_csv(url, header=None, names=col_names) iris.head() Explanation: Usin...
12,209
Given the following text description, write Python code to implement the functionality described below step by step Description: Perform a 4-terminal calculation with 2 crossed Carbon chains. Running a two-terminal calculation with TranSiesta is a breeze compared to running $N>2$-electrode calculations. When performin...
Python Code: chain = sisl.Geometry([[0,0,0]], atoms=sisl.Atom[6], sc=[1.4, 1.4, 11]) elec_x = chain.tile(4, axis=0).add_vacuum(11 - 1.4, 1) elec_x.write('ELEC_X.fdf') elec_y = chain.tile(4, axis=1).add_vacuum(11 - 1.4, 0) elec_y.write('ELEC_Y.fdf') chain_x = elec_x.tile(4, axis=0) chain_y = elec_y.tile(4, axis=1) chain...
12,210
Given the following text description, write Python code to implement the functionality described below step by step Description: Gradient Checking Welcome to the final assignment for this week! In this assignment you will learn to implement and use gradient checking. You are part of a team working to make mobile paym...
Python Code: # Packages import numpy as np from testCases import * from gc_utils import sigmoid, relu, dictionary_to_vector, vector_to_dictionary, gradients_to_vector Explanation: Gradient Checking Welcome to the final assignment for this week! In this assignment you will learn to implement and use gradient checking. ...
12,211
Given the following text description, write Python code to implement the functionality described below step by step Description: El vecindario racista Step1: Supongamos que tenemos un vecindario. Este vecindario es una matriz o casillero, en el que cada vecino puede ocupar una casilla. Step2: Aquí podemos ver un peq...
Python Code: %matplotlib inline import numpy as np import matplotlib.pyplot as plt import vecindario as vc Explanation: El vecindario racista: el modelo de segregación de Schelling La segregación racial es un problema en muchas partes del mundo desde hace mucho tiempo. A pesar de que ciertos colectivos han realizado un...
12,212
Given the following text description, write Python code to implement the functionality described below step by step Description: Compute seed based time-frequency connectivity in sensor space Computes the connectivity between a seed-gradiometer close to the visual cortex and all other gradiometers. The connectivity is...
Python Code: # Author: Martin Luessi <mluessi@nmr.mgh.harvard.edu> # # License: BSD (3-clause) import numpy as np import mne from mne import io from mne.connectivity import spectral_connectivity, seed_target_indices from mne.datasets import sample from mne.time_frequency import AverageTFR print(__doc__) Explanation: Co...
12,213
Given the following text description, write Python code to implement the functionality described below step by step Description: Neural Network Learning Objectives Step1: Next, we'll load our data set. Step2: Examine the data It's a good idea to get to know your data a little bit before you work with it. We'll print...
Python Code: import math import shutil import numpy as np import pandas as pd import tensorflow as tf tf.logging.set_verbosity(tf.logging.INFO) pd.options.display.max_rows = 10 pd.options.display.float_format = '{:.1f}'.format Explanation: Neural Network Learning Objectives: * Use the DNNRegressor class in TensorFlow...
12,214
Given the following text description, write Python code to implement the functionality described below step by step Description: What is NetCDF? <img src='http Step1: mode='r' is the default. mode='a' opens an existing file and allows for appending (does not clobber existing data) format can be one of NETCDF3_CLASSIC...
Python Code: import os path_to_file = os.path.join(os.pardir, 'data', 'new.nc') Explanation: What is NetCDF? <img src='http://www.unidata.ucar.edu/images/logos/netcdf-50x50.png'> NetCDF (network Common Data Form) is a set of interfaces for array-oriented data access and a freely distributed collection of data access li...
12,215
Given the following text description, write Python code to implement the functionality described below step by step Description: SciPy Što je SciPy? SciPy je nadgradnja NumPy paketa, i sadrži veliki broj numeričkih algoritama za cijeli niz područja. Ovdje su pobrojana neka nama zanimljivija Step1: Narvno, možemo učit...
Python Code: from scipy import * Explanation: SciPy Što je SciPy? SciPy je nadgradnja NumPy paketa, i sadrži veliki broj numeričkih algoritama za cijeli niz područja. Ovdje su pobrojana neka nama zanimljivija: Specijalne funkcije (scipy.special) Integracija (scipy.integrate) Optimizacija (scipy.optimize) Interpolacija ...
12,216
Given the following text description, write Python code to implement the functionality described below step by step Description: DAT210x - Programming with Python for DS Module5- Lab7 Step1: A Convenience Function This method is for your visualization convenience only. You aren't expected to know how to put this toge...
Python Code: import random, math import pandas as pd import numpy as np import scipy.io from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt matplotlib.style.use('ggplot') # Look Pretty # Leave this alone until indicated: Test_PCA = False Explanation: DAT210x - Programming with Python for DS Module5-...
12,217
Given the following text description, write Python code to implement the functionality described below step by step Description: Sveučilište u Zagrebu Fakultet elektrotehnike i računarstva Strojno učenje 2018/2019 http Step1: Zadatci 1. Jednostavna regresija Zadan je skup primjera $\mathcal{D}={(x^{(i)},y^{(i)})}_{...
Python Code: # Učitaj osnovne biblioteke... import numpy as np import sklearn import matplotlib.pyplot as plt import scipy as sp %pylab inline Explanation: Sveučilište u Zagrebu Fakultet elektrotehnike i računarstva Strojno učenje 2018/2019 http://www.fer.unizg.hr/predmet/su Laboratorijska vježba 1: Regresija Verzija...
12,218
Given the following text description, write Python code to implement the functionality described below step by step Description: Dataset handling Scikit-multilearn provides methods to load, save and manipulate multi-label data sets in two formats Step1: Loading scikit-multilearn data format is easier as it stores mor...
Python Code: from skmultilearn.dataset import load_dataset_dump, save_dataset_dump Explanation: Dataset handling Scikit-multilearn provides methods to load, save and manipulate multi-label data sets in two formats: a scikit-multilearn pickle of data set in scipy sparse format the traditional ARFF file format The functi...
12,219
Given the following text description, write Python code to implement the functionality described below step by step Description: LCS Demo 1 LCS Workshop- Educational LCS - eLCS Outcome Step1: Display final population Step2: Visualise classifiers
Python Code: import numpy as np import matplotlib.pyplot as plt headerList = np.array([]) dataList = [] arraylist = np.array([]) # Open the file for reading. with open('ExampleRun_eLCS_10000_RulePop.txt', 'r') as infile: headerList = infile.readline().rstrip('\n').split('\t') #strip off first row for line in ...
12,220
Given the following text description, write Python code to implement the functionality described below step by step Description: Sentiment Analysis on "Jallikattu" with Twitter Data Feed <h3 style="color Step1: We will create a Twitter API handle for fetching data Inorder to qualify for a Twitter API handle you need ...
Python Code: # import tweepy for twitter datastream and textblob for processing tweets import tweepy import textblob # wordcloud package is used to produce the cool masked tag cloud above from wordcloud import WordCloud # pickle to serialize/deserialize python objects import pickle # regex package to extract hasttags f...
12,221
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction A mass on a spring experiences a force described by Hookes law. For a displacment $x$, the force is $$F=-kx,$$ where $k$ is the spring constant with units of N/m. The equation o...
Python Code: import matplotlib.pyplot as plt %matplotlib inline from IPython.html import widgets def make_plot(t): fig, ax = plt.subplots() x,y = 0,0 plt.plot(x, y, 'k.') plt.plot(x + 0.3 * t, y, 'bo') plt.xlim(-1,1) plt.ylim(-1,1) widgets.interact(make_plot, t=(-1,1,0.1)) Explanation: Introduct...
12,222
Given the following text description, write Python code to implement the functionality described below step by step Description: Modeling and Simulation in Python Experiments with different ODE solvers Copyright 2019 Allen Downey License Step1: Glucose minimal model Read the data. Step2: Interpolate the insulin data...
Python Code: # Configure Jupyter so figures appear in the notebook %matplotlib inline # Configure Jupyter to display the assigned value after an assignment %config InteractiveShell.ast_node_interactivity='last_expr_or_assign' # import functions from the modsim.py module from modsim import * init = State(y = 2) system =...
12,223
Given the following text description, write Python code to implement the functionality described below step by step Description: CrowdTruth vs. MACE vs. Majority Vote for Recognizing Textual Entailment Annotation This notebook contains a comparative analysis on the task of recognizing textual entailment between three ...
Python Code: #Read the input file into a pandas DataFrame import pandas as pd test_data = pd.read_csv("../data/rte.standardized.csv") test_data.head() Explanation: CrowdTruth vs. MACE vs. Majority Vote for Recognizing Textual Entailment Annotation This notebook contains a comparative analysis on the task of recognizing...
12,224
Given the following text description, write Python code to implement the functionality described below step by step Description: Deep dive into the Qumulo API python bindings <span style="background-color Step1: Inspect all of the Qumulo python bindings and show methods Step2: Create a new python REST client instanc...
Python Code: !pip show qumulo_api import qumulo import os import io import glob import re import time from datetime import datetime import dateutil.parser as date_parser from qumulo.rest_client import RestClient %%javascript // this will prevent the large output window below from being boxed in. IPython.OutputArea.auto...
12,225
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Andrews Curves D. F. Andrews introduced 'Andrews Curves' in his 1972 paper for plotthing high dimensional data in two dimeion. The underlying principle is simple Step2: Andrews Curve...
Python Code: def andrews_curves(data, granularity=1000): Parameters ----------- data : array like ith row is the ith observation jth column is the jth feature Size (m, n) => m replicats with n features granularity : int linspace granularity for the...
12,226
Given the following text description, write Python code to implement the functionality described below step by step Description: <header class="w3-container w3-teal"> <img src="images/utfsm.png" alt="" height="100px" align="left"/> <img src="images/mat.png" alt="" height="100px" align="right"/> </header> <br/><br/><br...
Python Code: %%bash head data/x01.txt -n 60 import numpy as np from matplotlib import pyplot as plt # Plot of data data = np.loadtxt("data/x01.txt", skiprows=33) x = data[:,1] y = data[:,2] plt.figure(figsize=(16,8)) plt.plot(x, y, 'rs') plt.xlabel("brain weight") plt.ylabel("body weight") plt.show() import numpy as np...
12,227
Given the following text description, write Python code to implement the functionality described below step by step Description: <h1>Network Analysis with Python</h1> <li>Networks are connected bi-directional graphs <li>Nodes mark the entities in a network <li>Edges mark the relationships in a network <h2>Examples of ...
Python Code: import networkx as nx %matplotlib inline import numpy as np import matplotlib.pyplot as plt simple_network = nx.Graph() nodes = [1,2,3,4,5,6,7,8] edges = [(1,2),(2,3),(1,3),(4,5),(2,7),(1,9),(3,4),(4,5),(4,9),(5,6),(7,8),(8,9)] simple_network.add_nodes_from(nodes) simple_network.add_edges_from(edges) nx.dr...
12,228
Given the following text description, write Python code to implement the functionality described below step by step Description: Mean reversion By Evgenia "Jenny" Nitishinskaya and Delaney Granizo-Mackenzie Notebook released under the Creative Commons Attribution 4.0 License. Mean-reversion strategies are those relyin...
Python Code: import numpy as np import matplotlib.pyplot as plt import pandas as pd # Load the pricing data for a stock start = '2012-01-01' end = '2015-01-01' pricing = get_pricing('MCD', fields='price', start_date=start, end_date=end) # Compute the cumulative moving average of the price mu = [pricing[:i].mean() for i...
12,229
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', 'hammoz-consortium', 'sandbox-1', 'landice') Explanation: ES-DOC CMIP6 Model Properties - Landice MIP Era: CMIP6 Institute: HAMMOZ-CONSORTIUM Source ID: SANDBOX-1 Topic: Landice Sub-To...
12,230
Given the following text description, write Python code to implement the functionality described below step by step Description: Input and output Currently, the only supported approach for loading and saving ensembles in medusa is via pickle. pickle is the Python module that serializes and de-serializes Python objects...
Python Code: import medusa from pickle import load with open("../medusa/test/data/Staphylococcus_aureus_ensemble.pickle", 'rb') as infile: ensemble = load(infile) Explanation: Input and output Currently, the only supported approach for loading and saving ensembles in medusa is via pickle. pickle is the Python modul...
12,231
Given the following text description, write Python code to implement the functionality described below step by step Description: Getting a config parser The pypmj-module uses a configuration file in which all information about the JCMsuite-installation, data storage, servers and so on are set. This makes pypmj very fl...
Python Code: import config_tools as ct Explanation: Getting a config parser The pypmj-module uses a configuration file in which all information about the JCMsuite-installation, data storage, servers and so on are set. This makes pypmj very flexible, as you can generate as many configuration files as you like. Here, we ...
12,232
Given the following text description, write Python code to implement the functionality described below step by step Description: Example Step1: First start by seeing that there does exist a SparkContext object in the sc variable Step2: Now let's load an RDD with some interesting data. We have the GDELT event data se...
Python Code: import findspark import os findspark.init('/home/ubuntu/shortcourse/spark-1.5.1-bin-hadoop2.6') from pyspark import SparkContext, SparkConf conf = SparkConf().setAppName("pyspark-example").setMaster("local[2]") sc = SparkContext(conf=conf) Explanation: Example: Use pyspark to process GDELT event data GDELT...
12,233
Given the following text description, write Python code to implement the functionality described below step by step Description: There is a lot of room for feature engineering the 8 qualitative features, but we'll reserve it for later Step1: From now we try a range of estimators and use GridSearch to iteratively tune...
Python Code: #Drop quantitative features for which most samples take 0 or 1 for cols in quan: if train_c[cols].mean() < 0.01 or train_c[cols].mean() > 0.99: train_c.drop(cols, inplace=True, axis=1) test_c.drop(cols, inplace=True, axis=1) #For now we only use the quantitative features left to make pr...
12,234
Given the following text description, write Python code to implement the functionality described below step by step Description: Simple Dendritic Gated Networks in numpy This colab implements a Dendritic Gated Network (DGN) solving a regression (using quadratic loss) or a binary classification problem (using Bernoulli...
Python Code: # Copyright 2021 DeepMind Technologies Limited. All rights reserved. # # # 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 ...
12,235
Given the following text description, write Python code to implement the functionality described below step by step Description: EfficientNetV2 Tutorial Step1: 0.2 View graph in TensorBoard Step2: 1. inference Step3: 2. Finetune EfficientNetV2 on CIFAR10.
Python Code: %%capture #@title !pip install tensorflow_addons import os import sys import tensorflow.compat.v1 as tf # Download source code. if "efficientnetv2" not in os.getcwd(): !git clone --depth 1 https://github.com/google/automl os.chdir('automl/efficientnetv2') sys.path.append('.') else: !git pull def do...
12,236
Given the following text description, write Python code to implement the functionality described below step by step Description: <div align="right">Python [conda env Step1: <a id="globals" name="globals"></a> Using globals() and .items() to get Names Step2: <a id="__name__" name="__name__"></a> name of Methods Step3...
Python Code: from dill.source import getname # run this cell first before any cells below peg1 = [1,2] peg2 = [3] peg3 = [5,4] # this example shows what at first would appear to be unexpected behavior # it illustrates some concepts though later cells of this notebook show how to effectively use dill.getname def move...
12,237
Given the following text description, write Python code to implement the functionality described below step by step Description: IRIS Dataset Processes selected samples from the iris dataset to fit the specifications of the sliding windows used in images from the FLIR thermal camera. Step1: A reference image we gathe...
Python Code: import matplotlib.pyplot as plt import numpy as np import os from skimage import data from skimage import io from skimage.transform import resize from skimage.color import rgb2gray from scipy.misc import bytescale %matplotlib inline WINDOW_WIDTH = 18 WINDOW_HEIGHT = 26 sample_iris_frame = data.imread('exte...
12,238
Given the following text description, write Python code to implement the functionality described below step by step Description: 1A.1 - Intégrale et la méthode des rectangles - correction Approximation du calcul d'une intégrale par la méthode des rectangles. Step1: Calcul de l'intégrale Step2: Il faut écrire la fonc...
Python Code: %matplotlib inline from jyquickhelper import add_notebook_menu add_notebook_menu() Explanation: 1A.1 - Intégrale et la méthode des rectangles - correction Approximation du calcul d'une intégrale par la méthode des rectangles. End of explanation a = -2 b = 3 n = 20 import math f = lambda x: x * math.cos (x)...
12,239
Given the following text description, write Python code to implement the functionality described below step by step Description: Parameter space coverage 3D graphs See the parameter-space-coverage notebook for more information. Step1: Set the sample size Step2: Uniform Step3: Stepped Set the step size. I'm using a ...
Python Code: import random import numpy as np import plotly.plotly as py import plotly.graph_objs as go import plotly.offline as offline offline.init_notebook_mode(connected=True) Explanation: Parameter space coverage 3D graphs See the parameter-space-coverage notebook for more information. End of explanation sample_si...
12,240
Given the following text description, write Python code to implement the functionality described below step by step Description: A jupyter notebook is a browser-based environment that integrates Step1: Create a variable Step2: Print out the value of the variable Step3: or even easier Step4: Datatypes In computer p...
Python Code: print("Hello World!") # lines that begin with a # are treated as comment lines and not executed # print("This line is not printed") print("This line is printed") Explanation: A jupyter notebook is a browser-based environment that integrates: A Kernel (python) Text Executable code Plots and images Rendered ...
12,241
Given the following text problem statement, write Python code to implement the functionality described below in problem statement Problem: build your model
Python Code:: from tensorflow.keras import Sequential from tensorflow.keras.layers import Dense, Input, Flatten model = Sequential([ Input(shape=(28,28,1,)), Flatten(), Dense(units=84, activation="relu"), Dense(units=10, activation="softmax"), ]) print (model.summary())
12,242
Given the following text description, write Python code to implement the functionality described below step by step Description: Hands-on LH1 Step1: Scattering parameters measurement The following figure illustrates the measurement setup, and the adopted port indexing convention. <img src="./LH1_Mode-Converter_data/...
Python Code: # This line configures matplotlib to show figures embedded in the notebook, # and also import the numpy library %pylab %matplotlib inline Explanation: Hands-on LH1: the $\mathrm{TE}{10}$-$\mathrm{TE}{30}$ Mode Converter Introduction The Tore Supra Lower Hybrid Launchers are equiped by $\mathrm{TE}{10}$...
12,243
Given the following text description, write Python code to implement the functionality described below step by step Description: Spring 2017 Data Bootcamp Final Project by Colleen Jin dj928, Yingying Chen yc1875 Analysis On Relation Between News Sentiment And Market Portfolio In this project, we use two sets of data t...
Python Code: %matplotlib inline # import necessary packages import pandas as pd import matplotlib.pyplot as plt from pandas_datareader import data from datetime import datetime import numpy as np from textblob import TextBlob import csv from wordcloud import WordCloud,Im...
12,244
Given the following text description, write Python code to implement the functionality described below step by step Description: Simulation Progress Christian Kongsgaard RIBuild Meeting 19-09-2019 Simulated Projects Step1: Simulation Time Stats Step2: Compute Resources 500 - 1000 cores available 250 - 500 Delphin Jo...
Python Code: current_projects = get_simulated_projects_count() print(f'There are currently {current_projects} simulated Delphin projects in the database') Explanation: Simulation Progress Christian Kongsgaard RIBuild Meeting 19-09-2019 Simulated Projects End of explanation times = get_simulation_time() for key in times...
12,245
Given the following text description, write Python code to implement the functionality described below step by step Description: Mass Maps From Mass-Luminosity Inference Posterior In this notebook we start to explore the potential of using a mass-luminosity relation posterior to refine mass maps. Content Step2: Prob...
Python Code: %matplotlib inline import matplotlib.pyplot as plt from matplotlib import rc rc('text', usetex=True) from bigmali.grid import Grid from bigmali.prior import TinkerPrior from bigmali.hyperparameter import get import numpy as np from scipy.stats import lognorm from numpy.random import normal #globals that fu...
12,246
Given the following text description, write Python code to implement the functionality described below step by step Description: Float $Y_i$ & Float $\alpha_{MLT}$ First, we load the appropriate libraries and data file. MCMC trials where all quantities are permitted to float happened during Run 05. Note that the metal...
Python Code: %matplotlib inline import numpy as np import matplotlib.pyplot as plt data = np.genfromtxt('data/run05_kde_props_tmp3.txt') data = np.array([x for x in data if x[30] > -0.5]) # remove stars that our outside of the model grid Explanation: Float $Y_i$ & Float $\alpha_{MLT}$ First, we load the appropriate lib...
12,247
Given the following text description, write Python code to implement the functionality described below step by step Description: Disaggregation and Metrics Step1: Dividing data into train and test set Step2: Let us use building 1 for demo purposes Step3: Let's split data at April 30th Step4: REDD data set has got ...
Python Code: from __future__ import print_function, division import time from matplotlib import rcParams import matplotlib.pyplot as plt %matplotlib inline rcParams['figure.figsize'] = (13, 6) plt.style.use('ggplot') from nilmtk import DataSet, TimeFrame, MeterGroup, HDFDataStore from nilmtk.disaggregate import Combina...
12,248
Given the following text description, write Python code to implement the functionality described below step by step Description: Support Vector Machines Step1: Kernel SVMs Predictions in a kernel-SVM are made using the formular $$ \hat{y} = \alpha_0 + \alpha_1 y_1 k(\mathbf{x^{(1)}}, \mathbf{x}) + ... + \alpha_n y_n ...
Python Code: from sklearn.datasets import load_digits from sklearn.cross_validation import train_test_split digits = load_digits() X_train, X_test, y_train, y_test = train_test_split(digits.data / 16., digits.target % 2, random_state=2) from sklearn.svm import LinearSVC, SVC linear_svc = LinearSVC(loss="hinge").fit(X_t...
12,249
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2019 The Google Research Authors. 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 ...
Python Code: # Uses pip3 to install necessary package (lightgbm) !pip3 install lightgbm # Resets the IPython kernel to import the installed package. import IPython app = IPython.Application.instance() app.kernel.do_shutdown(True) import os from git import Repo # Current working directory repo_dir = os.getcwd() + '/re...
12,250
Given the following text description, write Python code to implement the functionality described below step by step Description: Analyzing patient data Words are useful, but what’s more useful are the sentences and stories we build with them. A lot of powerful tools are built into languages like Python, even more live...
Python Code: import numpy Explanation: Analyzing patient data Words are useful, but what’s more useful are the sentences and stories we build with them. A lot of powerful tools are built into languages like Python, even more live in the libraries they are used to build We need to import a library called NumPy Use this ...
12,251
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Grid algorithm for a beta-binomial hierarchical model Bayesian Inference with PyMC Copyright 2021 Allen B. Downey License Step2: Heart Attack Data This example is based on Chapter 10...
Python Code: # If we're running on Colab, install libraries import sys IN_COLAB = 'google.colab' in sys.modules if IN_COLAB: !pip install pymc3 !pip install arviz !pip install empiricaldist # PyMC generates a FutureWarning we don't need to deal with yet import warnings warnings.filterwarnings("ignore", cate...
12,252
Given the following text description, write Python code to implement the functionality described below step by step Description: Python Coffee, November 5, 2015 Import required libraries Step1: The previous import code requires that you have pandas, numpy and matplotlib installed. If you are using conda you already h...
Python Code: import pandas as pd import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D %matplotlib inline Explanation: Python Coffee, November 5, 2015 Import required libraries End of explanation import plotly.tools as tls import plotly.plotly as py import cufflinks as cf import plo...
12,253
Given the following text description, write Python code to implement the functionality described below step by step Description: Exercise Introduction We will return to the automatic rotation problem you worked on in the previous exercise. But we'll add data augmentation to improve your model. The model specification ...
Python Code: from tensorflow.keras.applications import ResNet50 from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense, Flatten, GlobalAveragePooling2D num_classes = 2 resnet_weights_path = '../input/resnet50/resnet50_weights_tf_dim_ordering_tf_kernels_notop.h5' my_new_model = Sequenti...
12,254
Given the following text description, write Python code to implement the functionality described below step by step Description: Convolutional Autoencoder on MNIST dataset Learning Objective 1. Build an autoencoder architecture (consisting of an encoder and decoder) in Keras 2. Define the loss using the reconstructive...
Python Code: import glob import os import time import imageio import matplotlib.pyplot as plt import numpy as np import PIL import tensorflow as tf from IPython import display from tensorflow.keras import layers Explanation: Convolutional Autoencoder on MNIST dataset Learning Objective 1. Build an autoencoder architect...
12,255
Given the following text description, write Python code to implement the functionality described below step by step Description: 1A.algo - Programmation dynamique et plus court chemin La programmation dynamique est une façon des calculs qui revient dans beaucoup d'algorithmes. Elle s'applique dès que ceux-ci peuvent s...
Python Code: from jyquickhelper import add_notebook_menu add_notebook_menu() Explanation: 1A.algo - Programmation dynamique et plus court chemin La programmation dynamique est une façon des calculs qui revient dans beaucoup d'algorithmes. Elle s'applique dès que ceux-ci peuvent s'écrire de façon récurrente. End of expl...
12,256
Given the following text description, write Python code to implement the functionality described below step by step Description: What is NLP? Natural Language Processing (NLP) is often taught at the academic level from the perspective of computational linguists. However, as data scientists, we have a richer view of th...
Python Code: # Take a moment to explore what is in this directory dir(nltk) Explanation: What is NLP? Natural Language Processing (NLP) is often taught at the academic level from the perspective of computational linguists. However, as data scientists, we have a richer view of the natural language world - unstructured d...
12,257
Given the following text description, write Python code to implement the functionality described below step by step Description: RNNs tutorial Step1: An LSTM/RNN overview Step2: Note that when we create the builder, it adds the internal RNN parameters to the model. We do not need to care about them, but they will be...
Python Code: # we assume that we have the dynet module in your path. # OUTDATED: we also assume that LD_LIBRARY_PATH includes a pointer to where libcnn_shared.so is. from dynet import * Explanation: RNNs tutorial End of explanation model = Model() NUM_LAYERS=2 INPUT_DIM=50 HIDDEN_DIM=10 builder = LSTMBuilder(NUM_LAYERS...
12,258
Given the following text description, write Python code to implement the functionality described below step by step Description: 1 Simple Octave/MATLAB Function As a quick warm up, create a function to return a 5x5 identity matrix. Step1: 2 Linear Regression with One Variable In this part of this exercise, you will i...
Python Code: A = np.eye(5) print(A) Explanation: 1 Simple Octave/MATLAB Function As a quick warm up, create a function to return a 5x5 identity matrix. End of explanation datafile = 'ex1\\ex1data1.txt' df = pd.read_csv(datafile, header=None, names=['Population', 'Profit']) def plot_data(x, y): plt.figure(figsize=(1...
12,259
Given the following text description, write Python code to implement the functionality described below step by step Description: <header class="w3-container w3-teal"> <img src="images/utfsm.png" alt="" height="100px" align="left"/> <img src="images/mat.png" alt="" height="100px" align="right"/> </header> <br/><br/><br...
Python Code: #Configuracion para recargar módulos y librerías cada vez %reload_ext autoreload %autoreload 2 ...
12,260
Given the following text description, write Python code to implement the functionality described below step by step Description: Verification of the FUSED-Wind wrapper common inputs Step2: FUSED-Wind implementation Step3: pure python implementation Step4: Asserting new implementation Step5: There was a bug correct...
Python Code: wf.WindFarm? v80 = wt.WindTurbine('Vestas v80 2MW offshore','V80_2MW_offshore.dat',70,40) HR1 = wf.WindFarm(name='Horns Rev 1',yml='hornsrev.yml')#,v80) WD = range(0,360,1) Explanation: Verification of the FUSED-Wind wrapper common inputs End of explanation ##Fused inputs inputs = dict( wind_speed=8.0,...
12,261
Given the following text description, write Python code to implement the functionality described below step by step Description: Contents This notebook covers the basics of creating TransferFunction object, obtaining time and energy resolved responses, plotting them and using IO methods available. Finally, artificial ...
Python Code: import numpy as np from matplotlib import pyplot as plt %matplotlib inline Explanation: Contents This notebook covers the basics of creating TransferFunction object, obtaining time and energy resolved responses, plotting them and using IO methods available. Finally, artificial responses are introduced whic...
12,262
Given the following text description, write Python code to implement the functionality described below step by step Description: Basic usage of Sklearn Step1: Text processing with Scikit learn We can use CountVectorizer to extract a bag of words representation from a collection of documents, using the SciKit-Learn me...
Python Code: import sklearn import numpy as np import matplotlib.pyplot as plt data = np.array([[1,2], [2,3], [3,4], [4,5], [5,6]]) x = data[:,0] y = data[:,1] data, x, y Explanation: Basic usage of Sklearn End of explanation from sklearn.feature_extraction.text import CountVectorizer vectorizer = CountVectorizer(min_d...
12,263
Given the following text description, write Python code to implement the functionality described below step by step Description: Config files with specifications Epoch files Epoch files are config files which specify a set of options repeatedly on different date/times, represented by sections of the config file. When ...
Python Code: %cat epochs_spec.cfg %cat epochs.cfg Explanation: Config files with specifications Epoch files Epoch files are config files which specify a set of options repeatedly on different date/times, represented by sections of the config file. When a value for an option for a given date is requested, the value in t...
12,264
Given the following text problem statement, write Python code to implement the functionality described below in problem statement Problem: Lists have a very simple method to insert elements:
Problem: import numpy as np a = np.array([[1,2],[3,4]]) pos = [1, 2] element = np.array([[3, 5], [6, 6]]) pos = np.array(pos) - np.arange(len(element)) a = np.insert(a, pos, element, axis=0)
12,265
Given the following text description, write Python code to implement the functionality described below step by step Description: Peak Magnetic Field Strength Magnetic models of young stars have their peak magnetic field strength prescribed where $R = 0.5 R_{\star}$. This works well and permits models of young stars wi...
Python Code: %matplotlib inline import matplotlib.pyplot as plt import numpy as np radial_points = np.arange(0.01, 1.0, 0.01) # units of Rstar bfield_scaling = radial_points**(-3.0) # see equation (1) bfield_surface = np.arange(0.5, 4.1, 0.5) # units of kiloGauss Explanation: Peak Magnetic Field Strength Mag...
12,266
Given the following text description, write Python code to implement the functionality described below step by step Description: Download the list of occultation periods from the MOC at Berkeley. Note that the occultation periods typically only are stored at Berkeley for the future and not for the past. So this is onl...
Python Code: fname = io.download_occultation_times(outdir='../data/') print(fname) Explanation: Download the list of occultation periods from the MOC at Berkeley. Note that the occultation periods typically only are stored at Berkeley for the future and not for the past. So this is only really useful for observation pl...
12,267
Given the following text description, write Python code to implement the functionality described below step by step Description: The Image Mark Image is a Mark object, used to visualize images in standard format (png, jpg etc...), in a bqplot Figure It takes as input an ipywidgets Image widget The ipywidgets Image Ste...
Python Code: import os import ipywidgets as widgets import bqplot.pyplot as plt from bqplot import LinearScale image_path = os.path.abspath('../../data_files/trees.jpg') with open(image_path, 'rb') as f: raw_image = f.read() ipyimage = widgets.Image(value=raw_image, format='jpg') ipyimage Explanation: The Image Mar...
12,268
Given the following text description, write Python code to implement the functionality described below step by step Description: Visualize channel over epochs as images in sensor topography This will produce what is sometimes called event related potential / field (ERP/ERF) images. One sensor topography plot is produc...
Python Code: # Authors: Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr> # Denis Engemann <denis.engemann@gmail.com> # # License: BSD (3-clause) import matplotlib.pyplot as plt import mne from mne import io from mne.datasets import sample print(__doc__) data_path = sample.data_path() Explanation: V...
12,269
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction to Python 2 Command-Line Programs <section class="objectives panel panel-warning"> <div class="panel-heading"> <h2 id="learning-objectives"><span class="fa fa-certificate"></spa...
Python Code: import sys import numpy def main(): script = sys.argv[0] filename = sys.argv[1] data = numpy.loadtxt(filename, delimiter=',') for m in data.mean(axis=1): print(m) Explanation: Introduction to Python 2 Command-Line Programs <section class="objectives panel panel-warning"> <div class=...
12,270
Given the following text description, write Python code to implement the functionality described below step by step Description: Image features exercise Complete and hand in this completed worksheet (including its outputs and any supporting code outside of the worksheet) with your assignment submission. For more detai...
Python Code: import random import numpy as np from cs231n.data_utils import load_CIFAR10 import matplotlib.pyplot as plt from __future__ import print_function %matplotlib inline plt.rcParams['figure.figsize'] = (10.0, 8.0) # set default size of plots plt.rcParams['image.interpolation'] = 'nearest' plt.rcParams['image.c...
12,271
Given the following text description, write Python code to implement the functionality described below step by step Description: .. _tut_intro_pyton Step1: If you come from a background of matlab, remember that indexing in python starts from zero
Python Code: a = 3 print(type(a)) b = [1, 2.5, 'This is a string'] print(type(b)) c = 'Hello world!' print(type(c)) Explanation: .. _tut_intro_pyton: Introduction to Python Python is a modern, general-purpose, object-oriented, high-level programming language. First make sure you have a working python environment and de...
12,272
Given the following text description, write Python code to implement the functionality described below step by step Description: Two particle equilibrium If you haven't read the One particle equilibrium notebook yet, go and read it now. In the previous notebook we showed that we can use Magpy to compute the correct th...
Python Code: import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import axes3d from tqdm import tqdm_notebook #import tqdm import magpy as mp %matplotlib inline Explanation: Two particle equilibrium If you haven't read the One particle equilibrium notebook yet, go and read it now. In the previo...
12,273
Given the following text description, write Python code to implement the functionality described below step by step Description: Data in Quilt is organized in terms of data packages. A data package is a logical group of files, directories, and metadata. Initializing a package To edit a new empty package, use the packa...
Python Code: import quilt3 p = quilt3.Package() Explanation: Data in Quilt is organized in terms of data packages. A data package is a logical group of files, directories, and metadata. Initializing a package To edit a new empty package, use the package constructor: End of explanation quilt3.Package.install( "examp...
12,274
Given the following text description, write Python code to implement the functionality described below step by step Description: RNNs tutorial Step1: An LSTM/RNN overview Step2: Note that when we create the builder, it adds the internal RNN parameters to the ParameterCollection. We do not need to care about them, bu...
Python Code: # we assume that we have the dynet module in your path. # OUTDATED: we also assume that LD_LIBRARY_PATH includes a pointer to where libcnn_shared.so is. import dynet as dy Explanation: RNNs tutorial End of explanation pc = dy.ParameterCollection() NUM_LAYERS=2 INPUT_DIM=50 HIDDEN_DIM=10 builder = dy.LSTMBu...
12,275
Given the following text description, write Python code to implement the functionality described below step by step Description: Bayesian Imputation Real-world datasets often contain many missing values. In those situations, we have to either remove those missing data (also known as "complete case") or replace them by...
Python Code: !pip install -q numpyro@git+https://github.com/pyro-ppl/numpyro # first, we need some imports import os from IPython.display import set_matplotlib_formats from matplotlib import pyplot as plt import numpy as np import pandas as pd from jax import numpy as jnp from jax import random from jax.scipy.special i...
12,276
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', 'nerc', 'sandbox-2', 'landice') Explanation: ES-DOC CMIP6 Model Properties - Landice MIP Era: CMIP6 Institute: NERC Source ID: SANDBOX-2 Topic: Landice Sub-Topics: Glaciers, Ice. Prop...
12,277
Given the following text description, write Python code to implement the functionality described below step by step Description: <span style="color Step1: <span style="color Step2: <span style="color Step3: <span style="color Step4: <span style="color Step5: <span style="color
Python Code: import pandas as pd import numpy as np import matplotlib.pyplot as plt import matplotlib as mpl pd.set_option('max_columns', 50) mpl.rcParams['lines.linewidth'] = 2 %matplotlib inline Explanation: <span style="color:black; font-family:Helvetica; font-size:2.5em;">Practical Code to Calculating Customer Life...
12,278
Given the following text description, write Python code to implement the functionality described below step by step Description: Basic Input and Output Basic Output - print() In Python, we talk about the terminal - by this we really just mean the screen, or maybe a window on the screen. Python 3 can output to the term...
Python Code: print(42) print('Boris') pint[47 print'Jane Explanation: Basic Input and Output Basic Output - print() In Python, we talk about the terminal - by this we really just mean the screen, or maybe a window on the screen. Python 3 can output to the terminal using the print() function. In the very early days of c...
12,279
Given the following text description, write Python code to implement the functionality described below step by step Description: CrowdTruth for Sparse Multiple Choice Tasks Step1: Declaring a pre-processing configuration The pre-processing configuration defines how to interpret the raw crowdsourcing input. To do this...
Python Code: import pandas as pd test_data = pd.read_csv("../data/event-text-sparse-multiple-choice.csv") test_data.head() Explanation: CrowdTruth for Sparse Multiple Choice Tasks: Event Extraction In this tutorial, we will apply CrowdTruth metrics to a sparse multiple choice crowdsourcing task for Event Extraction fro...
12,280
Given the following text description, write Python code to implement the functionality described below step by step Description: <small><i>This notebook was prepared by Donne Martin. Source and license info is on GitHub.</i></small> Challenge Notebook Problem Step1: Unit Test The following unit test is expected to fa...
Python Code: def list_of_chars(list_chars): # TODO: Implement me if li return list_chars[::-1] Explanation: <small><i>This notebook was prepared by Donne Martin. Source and license info is on GitHub.</i></small> Challenge Notebook Problem: Implement a function to reverse a string (a list of characters)...
12,281
Given the following text description, write Python code to implement the functionality described below step by step Description: Intro to deep learning in Chainer Welcome - this interactive tutorial will introduce you to deep learning in Chainer, to prepare for the DIY practical tutorial. 0. iPython First off, you nee...
Python Code: a = 100 print("a is", a) a + 200 Explanation: Intro to deep learning in Chainer Welcome - this interactive tutorial will introduce you to deep learning in Chainer, to prepare for the DIY practical tutorial. 0. iPython First off, you need to know how to run code & see the results. When you see Exercise, it ...
12,282
Given the following text description, write Python code to implement the functionality described below step by step Description: Hypocycloid definition and animation Deriving the parametric equations of a hypocycloid On May 11 @fermatslibrary posted a gif file, https Step1: We refer to the figure in the above cell to...
Python Code: from IPython.display import Image Image(filename='generate-hypocycloid.png') Explanation: Hypocycloid definition and animation Deriving the parametric equations of a hypocycloid On May 11 @fermatslibrary posted a gif file, https://twitter.com/fermatslibrary/status/862659602776805379, illustrating the motio...
12,283
Given the following text description, write Python code to implement the functionality described below step by step Description: Rock Paper Scissors with Python Here's a couple of versions. The first is the most verbose, most explicit version. It plays best two of three. Step1: This version removes the explicit ties ...
Python Code: import random choices = ["Rock", "Paper", "Scissors"] def choice(): selection = random.choice(choices) return selection def winner(player1, player2): if player1 == "Rock" and player2 == "Rock": result = "Tie" elif player1 == "Rock" and player2 == "Paper": result = "Player 2 ...
12,284
Given the following text description, write Python code to implement the functionality described below step by step Description: wk1.4 warm-up Instructions Step1: Testing membership Step2: Subsets and supersets Step3: Removing items Step4: Iterating over sets Big takeaway Step5: Set operations Intersection Any el...
Python Code: # How to make a set a = {1, 2, 3} type(a) # Getting a set from a list b = set([1, 2, 3]) a == b # How to make a frozen set a = frozenset({1, 2, 3}) # Getting a set from a list b = frozenset([1, 2, 3]) # Getting a set from a string set("obtuse") # Getting a set from a dictionary c = set({'a':1, 'b':2}) type...
12,285
Given the following text description, write Python code to implement the functionality described below step by step Description: 阅读笔记 作者:方跃文 Email Step1: ndarray 是 同构数据多维容器,that is to say, 所有元素必须是同类型的。 每个数组都有一个 shape (一个表示各维度大小的元祖)和一个 dtype (一个用于说明数组数据类型的对象): Step2: 虽然大多数数据分析工作不需要深入理解Numpy,但是精通面向数组的编程和思维方式是成为 Pyt...
Python Code: import numpy.random as nrandom data = nrandom.randn(3,2) data data*10 data + data Explanation: 阅读笔记 作者:方跃文 Email: fyuewen@gmail.com 时间:始于2017年9月12日, 结束写作于 第四章笔记始于2017年10月17日,结束于2018年1月6日 第四章 Numpy基础:数组和矢量计算 时间: 2017年10月17日早晨 Numpy,即 numerical python的简称,是高性能科学计算和数据分析的基础包。它是本书所介绍的几乎所有高级工具的构建基础。其部分功能如...
12,286
Given the following text description, write Python code to implement the functionality described below step by step Description: Overlays Spatial overlays allow you to compare two GeoDataFrames containing polygon or multipolygon geometries and create a new GeoDataFrame with the new geometries representing the spatial...
Python Code: %matplotlib inline from shapely.geometry import Point from geopandas import datasets, GeoDataFrame, read_file from geopandas.tools import overlay # NYC Boros zippath = datasets.get_path('nybb') polydf = read_file(zippath) # Generate some circles b = [int(x) for x in polydf.total_bounds] N = 10 polydf2 = Ge...
12,287
Given the following text description, write Python code to implement the functionality described below step by step Description: Algorithms Exercise 2 Imports Step2: Peak finding Write a function find_peaks that finds and returns the indices of the local maxima in a sequence. Your function should Step3: Here is a st...
Python Code: %matplotlib inline from matplotlib import pyplot as plt import seaborn as sns import numpy as np Explanation: Algorithms Exercise 2 Imports End of explanation def find_peaks(a): Find the indices of the local maxima in a sequence. n = 0 x = [] if a[n] > a[n+1]: x.append(n) while ...
12,288
Given the following text description, write Python code to implement the functionality described below step by step Description: Cross-Validation on the Iris Dataset Here is an example on you to split the data on the iris dataset. Let's re-use the results of the 2D PCA of the iris dataset in order to explore clusterin...
Python Code: # all of this is taken from the notebook '04_iris_clustering.ipynb' import numpy as np from sklearn.datasets import load_iris iris = load_iris() X = iris.data y = iris.target n_samples, n_features = iris.data.shape print n_samples Explanation: Cross-Validation on the Iris Dataset Here is an example on you ...
12,289
Given the following text description, write Python code to implement the functionality described below step by step Description: Your first neural network In this project, you'll build your first neural network and use it to predict daily bike rental ridership. We've provided some of the code, but left the implementat...
Python Code: %matplotlib inline #%config InlineBackend.figure_format = 'retina' import numpy as np import pandas as pd import matplotlib.pyplot as plt Explanation: Your first neural network In this project, you'll build your first neural network and use it to predict daily bike rental ridership. We've provided some of ...
12,290
Given the following text description, write Python code to implement the functionality described below step by step Description: A Simple Autoencoder We'll start off by building a simple autoencoder to compress the MNIST dataset. With autoencoders, we pass input data through an encoder that makes a compressed represen...
Python Code: %matplotlib inline import numpy as np import tensorflow as tf import matplotlib.pyplot as plt from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets('MNIST_data', validation_size=0) img = mnist.train.images[2] plt.imshow(img.reshape((28, 28)), cmap='Greys_r') Explanati...
12,291
Given the following text description, write Python code to implement the functionality described below step by step Description: XCS Tutorial This is the official tutorial for the xcs package for Python 3. You can find the latest release and get updates on the project's status at the project home page. What is XCS? XC...
Python Code: import logging logging.root.setLevel(logging.INFO) Explanation: XCS Tutorial This is the official tutorial for the xcs package for Python 3. You can find the latest release and get updates on the project's status at the project home page. What is XCS? XCS is a Python 3 implementation of the XCS algorithm a...
12,292
Given the following text description, write Python code to implement the functionality described below step by step Description: <center> <img src="../img/ods_stickers.jpg"> Открытый курс по машинному обучению </center> Автор материала Step1: Основными структурами данных в Pandas являются классы Series и DataFrame. П...
Python Code: # Python 2 and 3 compatibility # pip install future from __future__ import (absolute_import, division, print_function, unicode_literals) # отключим предупреждения Anaconda import warnings warnings.simplefilter('ignore') import pandas as pd import numpy as np %matplotlib inline impor...
12,293
Given the following text description, write Python code to implement the functionality described below step by step Description: Duhamel Integral Problem Data Step1: Natural Frequency, Damped Frequency Step2: Computation Preliminaries We chose a time step and we compute a number of constants of the integration proce...
Python Code: M = 600000 T = 0.6 z = 0.10 p0 = 400000 t0, t1, t2, t3 = 0.0, 1.0, 3.0, 6.0 Explanation: Duhamel Integral Problem Data End of explanation wn = 2*np.pi/T wd = wn*np.sqrt(1-z**2) Explanation: Natural Frequency, Damped Frequency End of explanation dt = 0.05 edt = np.exp(-z*wn*dt) fac = dt/(2*M*wd) Explanation...
12,294
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: 클러스터링된 모델 정의하기 전체 모델 클러스터링(순차적 ...
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...
12,295
Given the following text description, write Python code to implement the functionality described below step by step Description: Iterators and Generators In this section of the course we will be learning about the difference between iteration and generation in Python and how to construct our own Generators with the yi...
Python Code: # Generator function for the cube of numbers (power of 3) def gencubes(n): for num in range(n): yield num**3 for x in gencubes(10): print x Explanation: Iterators and Generators In this section of the course we will be learning about the difference between iteration and generation in Python...
12,296
Given the following text description, write Python code to implement the functionality described below step by step Description: Parallel Monto-Carlo options pricing This notebook shows how to use IPython.parallel to do Monte-Carlo options pricing in parallel. We will compute the price of a large number of options for...
Python Code: %pylab inline import sys import time from IPython.parallel import Client import numpy as np Explanation: Parallel Monto-Carlo options pricing This notebook shows how to use IPython.parallel to do Monte-Carlo options pricing in parallel. We will compute the price of a large number of options for different s...
12,297
Given the following text description, write Python code to implement the functionality described below step by step Description: Atherosclerosis of the Aorta Also known as heart disease or hardening of the arteries. This disease is the number one killer of Americans. Step1: Peptic Ulcers There have been long-standin...
Python Code: print_synonyms('dx::440.0', model) Explanation: Atherosclerosis of the Aorta Also known as heart disease or hardening of the arteries. This disease is the number one killer of Americans. End of explanation #Crohn's Disease print_synonyms('dx::555.9', model) Explanation: Peptic Ulcers There have been long-...
12,298
Given the following text description, write Python code to implement the functionality described below step by step Description: adrasteia 01 Gaia Universe Model Step1: Read in the data Step2: I had to modify the raw data to get it to read in conveniently. I try not to modify raw data formats (for reproducibility p...
Python Code: import numpy as np import matplotlib.pyplot as plt import seaborn as sns %matplotlib inline %config InlineBackend.figure_format = "retina" import pandas as pd sns.set_context("talk") Explanation: adrasteia 01 Gaia Universe Model: Milky Way Sample gully March 2016 Tasks: - Read in the data - Make a plot End...
12,299
Given the following text description, write Python code to implement the functionality described below step by step Description: Evaluation, Cross-Validation, and Model Selection By Heiko Strathmann - <a href="mailto Step1: Types of splitting strategies As said earlier Cross-validation is based upon splitting the dat...
Python Code: %pylab inline %matplotlib inline # include all Shogun classes from modshogun import * # generate some ultra easy training data gray() n=20 title('Toy data for binary classification') X=hstack((randn(2,n), randn(2,n)+1)) Y=hstack((-ones(n), ones(n))) _=scatter(X[0], X[1], c=Y , s=100) p1 = Rectangle((0, 0),...