Unnamed: 0
int64
0
16k
text_prompt
stringlengths
110
62.1k
code_prompt
stringlengths
37
152k
3,300
Given the following text description, write Python code to implement the functionality described below step by step Description: Convección en una dimensión Step1: Parámetros Step2: ¡Número de Courant ! Step3: Condiciones iniciales Step4: Un paso en el tiempo Recordemos que queremos implementar $u_i^{n+1} = u_i^n ...
Python Code: %matplotlib inline import scipy as np from matplotlib import pyplot as plt Explanation: Convección en una dimensión End of explanation L = 1.0 # longitud del sistema 1D nx = 42 # nodos espaciales dx = L / (nx-2) # sí, quitamos dos nodos ... x = np.linspace( 0 , L , num=nx ) T= 0.1 ...
3,301
Given the following text description, write Python code to implement the functionality described below step by step Description: Initialization Welcome to the first assignment of "Improving Deep Neural Networks". Training your neural network requires specifying an initial value of the weights. A well chosen initializ...
Python Code: import numpy as np import matplotlib.pyplot as plt import sklearn import sklearn.datasets from init_utils import sigmoid, relu, compute_loss, forward_propagation, backward_propagation from init_utils import update_parameters, predict, load_dataset, plot_decision_boundary, predict_dec %matplotlib inline plt...
3,302
Given the following text description, write Python code to implement the functionality described below step by step Description: Step5: Basic Idea of Count Min sketch We map the input value to multiple points in a relatively small output space. Therefore, the count associated with a given input will be applied to mult...
Python Code: import sys import random import numpy as np import heapq import json import time BIG_PRIME = 9223372036854775783 def random_parameter(): return random.randrange(0, BIG_PRIME - 1) class Sketch: def __init__(self, delta, epsilon, k): Setup a new count-min sketch with parameters delta...
3,303
Given the following text description, write Python code to implement the functionality described below step by step Description: Данные Возьмите данные с https Step1: Сравним по возрасту Step2: Сравним по полу Step3: Сравним по фертильности Step4: <b>Вывод по возрасту Step5: <b>Добавим новые признаки в train</b> ...
Python Code: visual = pd.read_csv('data/CatsAndDogs/TRAIN2.csv') #Сделаем числовой столбец Outcome, показывающий, взяли животное из приюта или нет #Сначала заполним единицами, типа во всех случах хорошо visual['Outcome'] = 'true' #Неудачные случаи занулим visual.loc[visual.OutcomeType == 'Euthanasia', 'Outcome'] = 'fal...
3,304
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction to Pairs Trading By Delaney Mackenzie and Maxwell Margenot Part of the Quantopian Lecture Series Step1: Generating Two Fake Securities We model X's daily returns by drawing fro...
Python Code: import numpy as np import pandas as pd import statsmodels import statsmodels.api as sm from statsmodels.tsa.stattools import coint # just set the seed for the random number generator np.random.seed(107) import matplotlib.pyplot as plt Explanation: Introduction to Pairs Trading By Delaney Mackenzie and Maxw...
3,305
Given the following text description, write Python code to implement the functionality described below step by step Description: Let's train this model on TPU. It's worth it. Imports Step1: TPU detection Step2: Configuration Step3: Read images and labels from TFRecords Step4: training and validation datasets Step5...
Python Code: import os, sys, math import numpy as np from matplotlib import pyplot as plt import tensorflow as tf print("Tensorflow version " + tf.__version__) AUTOTUNE = tf.data.AUTOTUNE Explanation: Let's train this model on TPU. It's worth it. Imports End of explanation try: # detect TPUs tpu = tf.distribute.clu...
3,306
Given the following text description, write Python code to implement the functionality described below step by step Description: Evaluation Python année 2016-2017 - solution Le répertoire data contient deux fichiers csv simulés aléatoirement dont il faudra se servir pour répondre aux 10 questions qui suivent. Chaque q...
Python Code: %matplotlib inline from jyquickhelper import add_notebook_menu add_notebook_menu() Explanation: Evaluation Python année 2016-2017 - solution Le répertoire data contient deux fichiers csv simulés aléatoirement dont il faudra se servir pour répondre aux 10 questions qui suivent. Chaque question vaut deux poi...
3,307
Given the following text description, write Python code to implement the functionality described below step by step Description: Let's use some real data... Step1: Copy the first 2 million rows into a bcolz carray to use for benchmarking. Step2: Out of interest, what chunk size did bcolz choose? Step3: How long doe...
Python Code: callset = h5py.File('/data/coluzzi/ag1000g/data/phase1/release/AR3/variation/main/hdf5/ag1000g.phase1.ar3.pass.h5', mode='r') callset genotype = allel.model.chunked.GenotypeChunkedArray(callset['3L/calldata/genotype']) genotype Explanation: Let's use some real data... End of explanation g = genotype.copy(s...
3,308
Given the following text description, write Python code to implement the functionality described below step by step Description: Transport measurement data analysis This is an example notebook for the analysis class IV_curve of qkit.analysis.IV_curve.py. This handels transport measurment data (focussed of measurements...
Python Code: import numpy as np from uncertainties import ufloat, umath, unumpy as unp from scipy import signal as sig import matplotlib.pyplot as plt import qkit qkit.start() from qkit.analysis.IV_curve import IV_curve as IVC ivc = IVC() Explanation: Transport measurement data analysis This is an example notebook for ...
3,309
Given the following text description, write Python code to implement the functionality described below step by step Description: human judgement data examining some of the human judgement data Step1: data in form left image location, right image location, and a binary variable indicating if the subject chose the left...
Python Code: import matplotlib.pyplot as plt import pandas as pd import numpy as np import matplotlib.image as mpimg from PIL import Image import progressbar human_df = pd.read_csv('human_data.csv') human_df.head() Explanation: human judgement data examining some of the human judgement data End of explanation # data sa...
3,310
Given the following text description, write Python code to implement the functionality described below step by step Description: Load and check data Step1: ## Analysis Experiment Details Step2: Did Hebbian perform better than SET? Step3: No evidence of significant difference. In networks with high sparsity, the imp...
Python Code: exps = ['neurips_1_eval1', ] paths = [os.path.expanduser("~/nta/results/{}".format(e)) for e in exps] df = load_many(paths) df.head(5) df.columns df.shape df.iloc[1] df.groupby('model')['model'].count() Explanation: Load and check data End of explanation # Did any trials failed? df[df["epochs"]<30]["epoch...
3,311
Given the following text description, write Python code to implement the functionality described below step by step Description: Modélisation du modèle Sommaire 1 - Introduction 2 - Polymère 3 - Calcul de la concentration 4 - Table des valeurs 5 - Calcul de c2 6 - Graphiques Introduction Ce programme nous permet de m...
Python Code: import numpy as np import pandas as pd import math import cmath from scipy.optimize import root import matplotlib.pyplot as plt %matplotlib inline Explanation: Modélisation du modèle Sommaire 1 - Introduction 2 - Polymère 3 - Calcul de la concentration 4 - Table des valeurs 5 - Calcul de c2 6 - Graphiques...
3,312
Given the following text description, write Python code to implement the functionality described below step by step Description: Tutorial on how to use timestaps in Field construction Step1: Some NetCDF files, such as for example those from the World Ocean Atlas, have time calendars that can't be parsed by xarray. Th...
Python Code: from parcels import Field from glob import glob import numpy as np Explanation: Tutorial on how to use timestaps in Field construction End of explanation # tempfield = Field.from_netcdf(glob('WOA_data/woa18_decav_*_04.nc'), 't_an', # {'lon': 'lon', 'lat': 'lat', 'time': 'time...
3,313
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', 'messy-consortium', 'emac-2-53-aerchem', 'atmos') Explanation: ES-DOC CMIP6 Model Properties - Atmos MIP Era: CMIP6 Institute: MESSY-CONSORTIUM Source ID: EMAC-2-53-AERCHEM Topic: Atmo...
3,314
Given the following text description, write Python code to implement the functionality described below step by step Description: ES-DOC CMIP6 Model Properties - Toplevel MIP Era Step1: Document Authors Set document authors Step2: Document Contributors Specify document contributors Step3: Document Publication Specif...
Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'mohc', 'hadgem3-gc31-mm', 'toplevel') Explanation: ES-DOC CMIP6 Model Properties - Toplevel MIP Era: CMIP6 Institute: MOHC Source ID: HADGEM3-GC31-MM Sub-Topics: Radiative Forcings. ...
3,315
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="#Notebook-Extensions" data-toc-modified-id="Notebook-Extensions-1">Notebook E...
Python Code: from __future__ import print_function, division import matplotlib as mpl import matplotlib.pyplot as plt %matplotlib inline import numpy as np import pandas as pd import textwrap import os import sys import warnings warnings.filterwarnings('ignore') # special things from pivottablejs import pivot_ui from i...
3,316
Given the following text description, write Python code to implement the functionality described below step by step Description: Search Project for CST 495 CMU Movie Summary Corpus http Step1: now is the time to join the docs together Step2: term freq Step3: start by computing frequncy of entire corpus Step4: now ...
Python Code: import csv import re with open("data/MovieSummaries/plot_summaries.tsv") as f: r = csv.reader(f, delimiter='\t', quotechar='"') tag = re.compile(r'\b[0-9]+\b') rgx = re.compile(r'\b[a-zA-Z]+\b') #docs = [ (' '.join(re.findall(tag, x[0])).lower(), ' '.join(re.findall(rgx, x[1])).lower()) for...
3,317
Given the following text description, write Python code to implement the functionality described below step by step Description: Day 9 - January 6, 2018 Problem 24 A permutation is an ordered arrangement of objects. For example, 3124 is one possible permutation of the digits 1, 2, 3 and 4. If all of the permutations...
Python Code: %%timeit import itertools as i a = [x for x in i.permutations(range(10))] value = a[1000000] moo = '' for x in a[1000000]: moo = moo + str(x) print(moo) %%timeit # with math import math alist = [0,1,2,3,4,5,6,7,8,9] value = '' remain = 1000000 for x in range(9,0,-1): boo = math.factorial(x) ...
3,318
Given the following text description, write Python code to implement the functionality described below step by step Description: Filtering and plotting Here we provide a quick example of how to filter and plot with your data, making the most of the capability provided by pyam's IamDataFrame. Step1: Run MAGICC6. Step2...
Python Code: # NBVAL_IGNORE_OUTPUT from pymagicc import MAGICC6 from pymagicc import rcp26 import matplotlib.pyplot as plt plt.style.use("bmh") Explanation: Filtering and plotting Here we provide a quick example of how to filter and plot with your data, making the most of the capability provided by pyam's IamDataFrame....
3,319
Given the following text description, write Python code to implement the functionality described below step by step Description: Classification of Organisms Using a Digital Dichotomous Key This Juptyer Notebook will allow you to search through different organisms based on their physical characteristics using a tool kn...
Python Code: # Import modules that contain functions we need import pandas as pd import numpy as np %matplotlib inline import matplotlib.pyplot as plt # Our data is the dichotomous key table and is defined as the word 'key'. # key is set equal to the .csv file that is read by pandas. # The .csv file must be in the same...
3,320
Given the following text description, write Python code to implement the functionality described below step by step Description: Fitting Example Step1: Inject into the interpreter the functions. Step2: Construct the histogram containing the input data Step3: Create the function and try to fit it without setting any...
Python Code: import ROOT Explanation: Fitting Example End of explanation %%cpp -d //Define functions for fitting // Quadratic background function double background(double *x, double *par) { return par[0] + par[1]*x[0] + par[2]*x[0]*x[0]; } // Lorenzian Peak function double lorentzianPeak(double *x, double *par) { ...
3,321
Given the following text description, write Python code to implement the functionality described below step by step Description: Embedding a Bokeh server in a Notebook This notebook shows how a Bokeh server application can be embedded inside a Jupyter notebook. Step2: There are various application handlers that can b...
Python Code: import yaml from bokeh.layouts import column from bokeh.models import ColumnDataSource, Slider from bokeh.plotting import figure from bokeh.themes import Theme from bokeh.io import show, output_notebook from bokeh.sampledata.sea_surface_temperature import sea_surface_temperature output_notebook() Explanati...
3,322
Given the following text description, write Python code to implement the functionality described below step by step Description: <a data-flickr-embed="true" href="https Step1: You'll notice the hashing algorithm has already been applied by the time we import this JSON data. I'll be showing you the Python source cod...
Python Code: import pandas as pd import matplotlib.pyplot as plt dinos = pd.read_json("dino_hash.json") Explanation: <a data-flickr-embed="true" href="https://www.flickr.com/photos/kirbyurner/27963484878/in/album-72157693427665102/" title="Barry at Large"><img src="https://farm1.staticflickr.com/969/27963484878_b38f0d...
3,323
Given the following text description, write Python code to implement the functionality described below step by step Description: Chapter 3 - Learning PySpark Resilient Distributed Datasets Creating RDDs There are two ways to create an RDD in PySpark. You can parallelize a list Step1: or read from a repository (a file...
Python Code: data = sc.parallelize( [('Amber', 22), ('Alfred', 23), ('Skye',4), ('Albert', 12), ('Amber', 9)]) Explanation: Chapter 3 - Learning PySpark Resilient Distributed Datasets Creating RDDs There are two ways to create an RDD in PySpark. You can parallelize a list End of explanation data_from_file = s...
3,324
Given the following text description, write Python code to implement the functionality described below step by step Description: A1 Data Curation The goal is to construct, analyze, and publish a dataset of monthly traffic on English Wikipedia from July 1 2008 - September 30 2017 The section below is to establish share...
Python Code: import pprint import requests import json # Global variables pagecounts_url = 'https://wikimedia.org/api/rest_v1/metrics/legacy/{apiname}/aggregate/en.wikipedia.org/{access}/monthly/{start}/{end}' pageviews_url = 'https://wikimedia.org/api/rest_v1/metrics/{apiname}/aggregate/en.wikipedia.org/{access}/{agen...
3,325
Given the following text description, write Python code to implement the functionality described below step by step Description: Notebook arguments sigma (float) Step1: Fitting models Models used to fit the data. 1. Simple Exponential In this model, we define the model function as an exponential transient Step2: 2. ...
Python Code: %matplotlib inline import numpy as np import lmfit import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import models # custom module Explanation: Notebook arguments sigma (float): standard deviation of additive Gaussian noise to be simulated time_window (float): seconds, integration ...
3,326
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction to NumPy Topics Basic Synatx creating vectors matrices special Step1: This code sets up Ipython Notebook environments (lines beginning with %), and loads several libraries and ...
Python Code: %matplotlib inline import math import numpy as np import matplotlib.pyplot as plt ##import seaborn as sbn ##from scipy import * Explanation: Introduction to NumPy Topics Basic Synatx creating vectors matrices special: ones, zeros, identity eye add, product, inverse Mechanics: indexing, slicing, concatenati...
3,327
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2019 The TensorFlow Authors. Step1: Image classification with TensorFlow Lite Model Maker <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="htt...
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...
3,328
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Session 3 Step2: <a name="assignment-synopsis"></a> Assignment Synopsis In the last session we created our first neural network. We saw that in order to create a neural network, we ...
Python Code: # First check the Python version import sys if sys.version_info < (3,4): print('You are running an older version of Python!\n\n' \ 'You should consider updating to Python 3.4.0 or ' \ 'higher as the libraries built for this course ' \ 'have only been tested in Python 3.4 a...
3,329
Given the following text description, write Python code to implement the functionality described below step by step Description: In this notebook, we will work through a simulation of psychophysiological interaction Step1: Load the data generated using the DCM forward model. In this model, there should be a significa...
Python Code: import os,sys import numpy %matplotlib inline import matplotlib.pyplot as plt sys.path.insert(0,'../') from utils.mkdesign import create_design_singlecondition from nipy.modalities.fmri.hemodynamic_models import spm_hrf,compute_regressor from utils.make_data import make_continuous_data from statsmodels.tsa...
3,330
Given the following text description, write Python code to implement the functionality described below step by step Description: Time Series Forecasting In this tutorial, we will demonstrate how to build a model for time series forecasting in NumPyro. Specifically, we will replicate the Seasonal, Global Trend (SGT) mo...
Python Code: !pip install -q numpyro@git+https://github.com/pyro-ppl/numpyro import os import matplotlib.pyplot as plt import pandas as pd from IPython.display import set_matplotlib_formats import jax.numpy as jnp from jax import random import numpyro import numpyro.distributions as dist from numpyro.contrib.control_fl...
3,331
Given the following text description, write Python code to implement the functionality described below step by step Description: Step4: Passive and active colloidal chemotaxis in a microfluidic channel Step5: Below, we plot the mean-square displacement (MSD) of the dimer in cartesian coordinates. There are thus three...
Python Code: %matplotlib inline import h5py import matplotlib.pyplot as plt from matplotlib.figure import SubplotParams import numpy as np from scipy.signal import fftconvolve from scipy.optimize import leastsq, curve_fit from scipy.integrate import simps, cumtrapz from glob import glob plt.rcParams['figure.figsize'] =...
3,332
Given the following text description, write Python code to implement the functionality described below step by step Description: Pandas and Datetimes Pandas helps ease the pain of timezones, even as it provides many useful tools for generating DateTimeIndex based time Series. Step1: Timestamp type (for individual dat...
Python Code: import pandas as pd from pandas import DataFrame, Series import numpy as np rng = pd.date_range('3/9/2012 9:30', periods=6, freq='D') rng type(rng) rng2 = pd.date_range('3/9/2012 9:30', periods=6, freq='M') rng2 ts = Series(np.random.randn(len(rng)), index=rng) type(ts) ts ts.index.tz rng.tz ts_utc = ts.tz...
3,333
Given the following text description, write Python code to implement the functionality described below step by step Description: Ordinary Differential Equations Exercise 3 Imports Step1: Damped, driven nonlinear pendulum The equations of motion for a simple pendulum of mass $m$, length $l$ are Step4: Write a functio...
Python Code: %matplotlib inline import matplotlib.pyplot as plt import numpy as np from scipy.integrate import odeint from IPython.html.widgets import interact, fixed Explanation: Ordinary Differential Equations Exercise 3 Imports End of explanation g = 9.81 # m/s^2 l = 0.5 # length of pendulum, in meters tmax = 5...
3,334
Given the following text description, write Python code to implement the functionality described below step by step Description: Data analytics for home appliances identification by Ayush Garg, Gabriel Vizcaino and Pradeep Somi Ganeshbabu Table of content Loading and processing the PLAID dataset Saving or loading the ...
Python Code: import numpy as np import matplotlib.pyplot as plt import pickle, time, seaborn, random, json, os %matplotlib inline from sklearn import tree from sklearn.model_selection import cross_val_score, train_test_split from sklearn.ensemble import GradientBoostingRegressor, GradientBoostingClassifier, RandomFores...
3,335
Given the following text description, write Python code to implement the functionality described below step by step Description: Background information on filtering Here we give some background information on filtering in general, and how it is done in MNE-Python in particular. Recommended reading for practical applic...
Python Code: import numpy as np from numpy.fft import fft, fftfreq from scipy import signal import matplotlib.pyplot as plt from mne.time_frequency.tfr import morlet from mne.viz import plot_filter, plot_ideal_filter import mne sfreq = 1000. f_p = 40. flim = (1., sfreq / 2.) # limits for plotting Explanation: Backgrou...
3,336
Given the following text description, write Python code to implement the functionality described below step by step Description: Basic read and write operations In this example we will explore how to create and read a simple Lightning Memory-Mapped Database (LMDB) using pyxis. Writing data Step1: Let's start by creat...
Python Code: from __future__ import print_function import time import numpy as np import pyxis as px np.random.seed(1234) Explanation: Basic read and write operations In this example we will explore how to create and read a simple Lightning Memory-Mapped Database (LMDB) using pyxis. Writing data End of explanation nb_s...
3,337
Given the following text description, write Python code to implement the functionality described below step by step Description: This notebook was created by Sergey Tomin (sergey.tomin@desy.de). Source and license info is on GitHub. April 2020. Tutorial N6. Coupler Kick. Second order tracking with coupler kick in TESL...
Python Code: # the output of plotting commands is displayed inline within frontends, # directly below the code cell that produced it %matplotlib inline from time import time # this python library provides generic shallow (copy) # and deep copy (deepcopy) operations from copy import deepcopy # import from Ocelot mai...
3,338
Given the following text description, write Python code to implement the functionality described below step by step Description: \title{Digital Arithmetic Cells with myHDL} \author{Steven K Armour} \maketitle <h1>Table of Contents<span class="tocSkip"></span></h1> <div class="toc"><ul class="toc-item"><li><span><a hre...
Python Code: from myhdl import * from myhdlpeek import Peeker import numpy as np import pandas as pd import matplotlib.pyplot as plt %matplotlib inline from sympy import * init_printing() import random #https://github.com/jrjohansson/version_information %load_ext version_information %version_information myhdl, myhdlpee...
3,339
Given the following text description, write Python code to implement the functionality described below step by step Description: Title Step1: Create an example dataframe Step2: Rename Column Names
Python Code: # Import modules import pandas as pd # Set ipython's max row display pd.set_option('display.max_row', 1000) # Set iPython's max column width to 50 pd.set_option('display.max_columns', 50) Explanation: Title: Rename Multiple Pandas Dataframe Column Names At Once Slug: pandas_rename_multiple_columns Summary:...
3,340
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: wk4.0 Even more OOP Step2: Pure functions Step3: The function creates a new MyTime object and returns a reference to the new object. This is called a pure function because it does n...
Python Code: class MyTime: def __init__(self, hrs=0, mins=0, secs=0): Create a MyTime object initialized to hrs, mins, secs self.hours = hrs self.minutes = mins self.seconds = secs def __str__(self): return "{h}:{m}:{s}".format(h=self.hours, m=self.minutes, s=s...
3,341
Given the following text problem statement, write Python code to implement the functionality described below in problem statement Problem: I have a data set like below:
Problem: import pandas as pd df = pd.DataFrame({'name': ['matt', 'james', 'adam'], 'status': ['active', 'active', 'inactive'], 'number': [12345, 23456, 34567], 'message': ['[job: , money: none, wife: none]', '[group: band, wife: ye...
3,342
Given the following text description, write Python code to implement the functionality described below step by step Description: A Shift-Reduce Parser for Arithmetic Expressions In this notebook we implement a generic shift reduce parser. The parse table that we use will implement the following grammar for arithmetic...
Python Code: import re Explanation: A Shift-Reduce Parser for Arithmetic Expressions In this notebook we implement a generic shift reduce parser. The parse table that we use will implement the following grammar for arithmetic expressions: $$ \begin{eqnarray} \mathrm{expr} & \rightarrow & \mathrm{expr}\;\;\t...
3,343
Given the following text description, write Python code to implement the functionality described below step by step Description: Exploring extracting data from the EPA web service https Step1: Example REST query Step2: I can use this to extract the table data Step3: Before we go further, we'll want to know the size...
Python Code: import requests import io import pandas from itertools import chain Explanation: Exploring extracting data from the EPA web service https://www.epa.gov/enviro/web-services I am using the Python Requests http://docs.python-requests.org/en/master/) library to scrape quantitative data from the EPA web service...
3,344
Given the following text description, write Python code to implement the functionality described below step by step Description: Lecture des données Quand j'explore/analyse des données, la première chose que je fais est toujours Step1: Pour information/rappel, Step2: Pour lire un fichier CSV, nous utilisons la bien...
Python Code: import pandas as pd Explanation: Lecture des données Quand j'explore/analyse des données, la première chose que je fais est toujours : End of explanation pd.__version__ Explanation: Pour information/rappel, End of explanation pd.read_csv('data/enfants.csv') Explanation: Pour lire un fichier CSV, nous utili...
3,345
Given the following text description, write Python code to implement the functionality described below step by step Description: Computing dead time 2 source method Techniques for Nuclear and Particle Physics Experiments A How-to Approach Authors Step1: Generate some data Step2: So what are the errors in each measur...
Python Code: %matplotlib inline from pprint import pprint import matplotlib import matplotlib.pyplot as plt import numpy as np import pandas as pd import pymc3 as mc import spacepy.toolbox as tb import spacepy.plot as spp import tqdm from scipy import stats import seaborn as sns sns.set() %matplotlib inline Explanation...
3,346
Given the following text description, write Python code to implement the functionality described below step by step Description: Overview Step1: OCR for reading a volunteer list Step2: Play with Maps
Python Code: from PIL import Image import pytesseract pytesseract.pytesseract.tesseract_cmd = 'c:/Tesseract-OCR/tesseract' path = 'c:/learnPython/tess/mm_address.jpg' path2 = 'mm_address.jpg' img = Image.open(path2) text = pytesseract.image_to_string(img) print(text) name = text.splitlines()[0] street = text.splitlin...
3,347
Given the following text description, write Python code to implement the functionality described below step by step Description: An IPython Introduction to Using TEA for C. elegans researchers All of the code below was written by David Angeles-Albores. Should you find any errors, typos, or just have general comments, ...
Python Code: import tissue_enrichment_analysis as tea #the main library for this tutorial import pandas as pd import os import importlib as imp import numpy as np import seaborn as sns import matplotlib.pyplot as plt #to make IPython plot inline, not req'd if you're not working with an Ipython notebook %matplotlib inli...
3,348
Given the following text description, write Python code to implement the functionality described below step by step Description: TODO Step1: Plot histogram of metabolites at m/z give bin size of x ppm Step2: Repeat at 5ppm Step3: Let's try to plot histogram # of isomers vs. m/z
Python Code: # namespace - at the top of file. fucks with every tag. # very annoying, so name all tags ns + tag ns = '{http://www.hmdb.ca}' nsmap = {None : ns} # If you're within a metabolite tag count = 0 seen_mass = 0 d = {} for event, element in etree.iterparse(xml_file, tag=ns+'metabolite'): tree = etree.Elemen...
3,349
Given the following text description, write Python code to implement the functionality described below step by step Description: Time series prediction This is a full example of how to do time series prediction with TensorFlow high level APIs. We'll use the weather dataset available at big query and can be generated w...
Python Code: # tensorflow import tensorflow as tf # rnn common functions from tensorflow.contrib.learn.python.learn.estimators import rnn_common # visualization import seaborn as sns import matplotlib.pyplot as plt # helpers import numpy as np import pandas as pd import csv # enable tensorflow logs tf.logging.set_verbo...
3,350
Given the following text description, write Python code to implement the functionality described below step by step Description: Fast Lomb-Scargle Periodograms in Python The Lomb-Scargle Periodogram is a well-known method of finding periodicity in irregularly-sampled time-series data. The common implementation of the ...
Python Code: %matplotlib inline import numpy as np import matplotlib.pyplot as plt # use seaborn's default plotting styles for matplotlib import seaborn; seaborn.set() Explanation: Fast Lomb-Scargle Periodograms in Python The Lomb-Scargle Periodogram is a well-known method of finding periodicity in irregularly-sampled ...
3,351
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: Посмотрим на Seaborn сразу в действии на данных по моделям месяца по версии...
Python Code: %matplotlib inline import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt plt.rcParams['figure.figsize'] = (10, 6) Explanation: <center> <img src="../img/ods_stickers.jpg"> Открытый курс по машинному обучению </center> Автор материала: программист-исследователь Mail.ru...
3,352
Given the following text description, write Python code to implement the functionality described below step by step Description: INF-482, v0.01, Claudio Torres, ctorres@inf.utfsm.cl. DI-UTFSM Textbook Step1: Mairhuber-Curtis Theorem Step2: Halton points vs pseudo-random points in 2D Step3: Interpolation with Distan...
Python Code: import numpy as np import ghalton import matplotlib.pyplot as plt %matplotlib inline from ipywidgets import interact from scipy.spatial import distance_matrix from mpl_toolkits.mplot3d import Axes3D from matplotlib import cm from matplotlib.ticker import LinearLocator, FormatStrFormatter from ipywidgets im...
3,353
Given the following text description, write Python code to implement the functionality described below step by step Description: This Notebook implements the TensorFlow advanced tutorial which uses a Multilayer Convolutional Network on the MNIST dataset Step1: Import MNIST Data Step2: Look at sizes of training, vali...
Python Code: import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data import matplotlib.pyplot as plt import time Explanation: This Notebook implements the TensorFlow advanced tutorial which uses a Multilayer Convolutional Network on the MNIST dataset End of explanation mnist = input_data.read...
3,354
Given the following text description, write Python code to implement the functionality described below step by step Description: Best practices Let's start with pep8 (https Step1: Pivot Tables w/ pandas http Step2: Keyboard shortcuts Step3: Floating Table of Contents Creates a new button on the toolbar that pops up...
Python Code: # Best practice for loading libraries? # Couldn't find what to do with 'magic' imports at the top %load_ext autoreload %autoreload 2 %matplotlib inline %config InlineBackend.figure_format='retina' from __future__ import division from itertools import combinations import string from IPython.display import ...
3,355
Given the following text description, write Python code to implement the functionality described below step by step Description: Database RDMS(Relational Database Management System Open Sourse - MySQL(php and web application) - PostgreSQl(huge web applications) - SQLITE (android applications) Proprietary - MSSQL - O...
Python Code: import sqlite3 #import the driver ##psycopg2 for protsgeSQL # pymysql for MySQL conn = sqlite3.connect('example.sqlite3') #connecting to sqlite 3 and makes a new database file if file not already present cur = conn.cursor() #makes a file cursor we can make multiple cursors as well cur.execute('CREATE TABLE...
3,356
Given the following text description, write Python code to implement the functionality described below step by step Description: The utils Package As the name says, this package brings some extra functionalities that you might need while using Maybrain. Let's start by importing it and initialising a Brain Step1: Info...
Python Code: from maybrain import utils from maybrain import resources as rr from maybrain import brain as mbt a = mbt.Brain() a.import_adj_file(rr.DUMMY_ADJ_FILE_500) a.import_spatial_info(rr.MNI_SPACE_COORDINATES_500) a.apply_threshold() Explanation: The utils Package As the name says, this package brings some extra ...
3,357
Given the following text description, write Python code to implement the functionality described below step by step Description: Given the following LP $\begin{gather} \min\quad -x_1 - 4x_2\ \begin{aligned} s.a. 2x_1 - x_2 &\geq 0\ x_1 - 3x_2 &\leq 0 \ x_1 + x_2 &\leq 4 \ \quad x_1, x_2 & \geq 0 \ \end{...
Python Code: x = np.linspace(0, 4, 100) y1 = 2*x y2 = x/3 y3 = 4 - x plt.figure(figsize=(8, 6)) plt.plot(x, y1) plt.plot(x, y2) plt.plot(x, y3) plt.xlim((0, 3.5)) plt.ylim((0, 4)) plt.xlabel('x1') plt.ylabel('x2') y5 = np.minimum(y1, y3) plt.fill_between(x[:-25], y2[:-25], y5[:-25], color='red', alpha=0.5) Explana...
3,358
Given the following text description, write Python code to implement the functionality described below step by step Description: Visualization using matplotlib and seaborn Visualization strategy Step1: Visualization for a single continuous variable Step2: Visualization for single categorical variable - frequency pl...
Python Code: import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns from matplotlib.mlab import normpdf %matplotlib inline plt.rcParams['figure.figsize'] = 10, 6 df = pd.read_csv("http://www-bcf.usc.edu/~gareth/ISL/Auto.data", sep=r"\s+") df.head(10) df.info() df["year"].unique() d...
3,359
Given the following text description, write Python code to implement the functionality described below step by step Description: Exploring Climate Data Step1: Above Step2: One way to interface with the GDP is with the interactive web interface, shown below. In this interface, you can upload a shapefile or draw on t...
Python Code: from IPython.core.display import Image Image('http://www-tc.pbs.org/kenburns/dustbowl/media/photos/s2571-lg.jpg') Explanation: Exploring Climate Data: Past and Future Roland Viger, Rich Signell, USGS First presented at the 2012 Unidata Workshop: Navigating Earth System Science Data, 9-13 July. What if you ...
3,360
Given the following text description, write Python code to implement the functionality described below step by step Description: 変数名とデータの内容メモ CENSUS Step1: 成約時点別×市区町村別の件数を集計 Step2: 成約時点別×地域ブロック別の件数を集計 Step3: Histogram 価格(真数) Step4: 価格(自然対数) Step5: 建築後年数 Step6: Plot 件数の推移 Step7: Main Analysis OLS part Step8: 青が...
Python Code: print(data['CITY_NAME'].value_counts()) Explanation: 変数名とデータの内容メモ CENSUS: 市区町村コード(9桁) P: 成約価格 S: 専有面積 L: 土地面積 R: 部屋数 RW: 前面道路幅員 CY: 建築年 A: 建築後年数(成約時) TS: 最寄駅までの距離 TT: 東京駅までの時間 ACC: ターミナル駅までの時間 WOOD: 木造ダミー SOUTH: 南向きダミー RSD: 住居系地域ダミー C...
3,361
Given the following text description, write Python code to implement the functionality described below step by step Description: Pygraphistry Viz Step1: --------------------------- Step2: df.head() Retrieve citations data citations = pd.read_csv('citations.txt', names = ['source', 'target', 'label']) Dedupe Citation...
Python Code: # Imports import graphistry import numpy as np import pandas as pd from py2neo import Graph, Path graphistry.register(key='48a82a78fdd442482cec24fe06051c905e2a382d581852a4ba645927c736acbcfe7256e22873a5c97cff6b8bd37c836b') Explanation: Pygraphistry Viz End of explanation # Static - Connect to the database #...
3,362
Given the following text description, write Python code to implement the functionality described below step by step Description: ES-DOC CMIP6 Model Properties - Seaice MIP Era Step1: Document Authors Set document authors Step2: Document Contributors Specify document contributors Step3: Document Publication Specify ...
Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'cmcc', 'cmcc-cm2-vhr4', 'seaice') Explanation: ES-DOC CMIP6 Model Properties - Seaice MIP Era: CMIP6 Institute: CMCC Source ID: CMCC-CM2-VHR4 Topic: Seaice Sub-Topics: Dynamics, Therm...
3,363
Given the following text description, write Python code to implement the functionality described below step by step Description: Stock market analysis project Step1: Plotting the open price Step2: Plotting the volume traded Step3: Finding the timestamp of highest traded volume Step4: Creating 'Total Traded' value ...
Python Code: import numpy as np import pandas as pd from datetime import datetime import matplotlib.pyplot as plt %matplotlib inline tesla = pd.read_csv('Tesla_Stock.csv', parse_dates= True, index_col='Date') tesla.head() ford = pd.read_csv('Ford_Stock.csv', parse_dates= True, index_col='Date') ford.head() gm = pd.re...
3,364
Given the following text description, write Python code to implement the functionality described below step by step Description: Basic demonstration of creating and using masks for bright sources Author Step1: You may have to set up your $CSCRATCH environment variable so that Python can find it, e.g. Step2: These ar...
Python Code: %matplotlib inline import matplotlib.pyplot as plt import os import numpy as np import fitsio from desitarget import desi_mask, brightmask Explanation: Basic demonstration of creating and using masks for bright sources Author: Adam D. Myers, University of Wyoming Getting Started Everything should work fine...
3,365
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', 'cccr-iitm', 'iitm-esm', 'atmos') Explanation: ES-DOC CMIP6 Model Properties - Atmos MIP Era: CMIP6 Institute: CCCR-IITM Source ID: IITM-ESM Topic: Atmos Sub-Topics: Dynamical Core, Ra...
3,366
Given the following text description, write Python code to implement the functionality described below step by step Description: Assignment CIE 5703 - week 6 Import libraries Step1: Rotterdam rain gauge dataset 10 min data from 2003 - 2013 Read in data Step2: Convert the dates to a readable format... Step3: Plot al...
Python Code: import matplotlib.pyplot as plt import pandas as pd import numpy as np %matplotlib inline plt.style.use('ggplot') Explanation: Assignment CIE 5703 - week 6 Import libraries End of explanation data = pd.read_csv('rotterdam_rg_2003-2014.csv', skipinitialspace=True) Explanation: Rotterdam rain gauge dataset 1...
3,367
Given the following text description, write Python code to implement the functionality described below step by step Description: Tricks of the trade Step1: Introducing randomized search We have already built a random forest classifier, tuned using grid search, to predict spam emails (here). Grid search exhaustively s...
Python Code: import wget import pandas as pd import numpy as np from sklearn.cross_validation import train_test_split # Import the dataset data_url = 'https://raw.githubusercontent.com/nslatysheva/data_science_blogging/master/datasets/spam/spam_dataset.csv' dataset = wget.download(data_url) dataset = pd.read_csv(datase...
3,368
Given the following text description, write Python code to implement the functionality described below step by step Description: scikit-learn提 了几种交验方法 1、cross_val_score默认Stratified K Fold方法切分数据 Step1: 设置n_neighbors 不对的取值对应的结果 %matplotlib inline
Python Code: from sklearn.cross_validation import cross_val_score estimator = KNeighborsClassifier()#默认取的是邻近的5个 scores = cross_val_score(estimator, X, Y, scoring='accuracy') average_accuracy = np.mean(scores) * 100 print("The average accuracy is {0:.1f}%".format(average_accuracy)) Explanation: scikit-learn提 了几种交验方法 1、...
3,369
Given the following text description, write Python code to implement the functionality described below step by step Description: PyTreeReader Step1: This is to create an histogram and read a tree. Step2: Traditional looping Now we establish the baseline Step3: Enters the PyTreeReader This is how we use for the firs...
Python Code: import ROOT from PyTreeReader import PyTreeReader Explanation: PyTreeReader: Looping on TTrees in Python, fast. <hr style="border-top-width: 4px; border-top-color: #34609b;"> The PyTreeReader class solves the problem of looping in a performant way on TTrees in Python. This is achieved just in time compilin...
3,370
Given the following text description, write Python code to implement the functionality described below step by step Description: Iris Scatterplot A simple example of using a bl.ock as the basis for a D3 visualization in Jupyter Using this bl.ocks example as a template, we will construct a scatterplot of the canonical ...
Python Code: from IPython.core.display import display, HTML from string import Template import pandas as pd import json, random HTML('<script src="lib/d3/d3.min.js"></script>') Explanation: Iris Scatterplot A simple example of using a bl.ock as the basis for a D3 visualization in Jupyter Using this bl.ocks example as a...
3,371
Given the following text description, write Python code to implement the functionality described below step by step Description: 3D Animation This is harder than we would like to do in a workshop. But, just for fun, let's do a 3D animation. We will draw a torus that deforms into a knot. Let try to animate. We start wi...
Python Code: %matplotlib inline from numpy import * from matplotlib.pyplot import * from mpl_toolkits.mplot3d import Axes3D from matplotlib import animation from IPython.display import HTML Explanation: 3D Animation This is harder than we would like to do in a workshop. But, just for fun, let's do a 3D animation. We wi...
3,372
Given the following text description, write Python code to implement the functionality described below step by step Description: Building a Supervised Machine Learning Model The objective of this hands-on activity is to create and evaluate a Real-Bogus classifier using ZTF alert data. We will be using the same data f...
Python Code: import numpy as np from sklearn.preprocessing import Imputer from sklearn.preprocessing import MinMaxScaler, StandardScaler %matplotlib inline import matplotlib.pyplot as plt import pandas as pd import seaborn as sns Explanation: Building a Supervised Machine Learning Model The objective of this hands-on a...
3,373
Given the following text description, write Python code to implement the functionality described below step by step Description: Hello world In this unit you will learn how to use Python to implement the first ever program that every programmer starts with. Introduction Here is the traditional first programming exerci...
Python Code: print("hello") print("bye bye") print("hey", "you") print("one") print("two") Explanation: Hello world In this unit you will learn how to use Python to implement the first ever program that every programmer starts with. Introduction Here is the traditional first programming exercise, called "Hello world". ...
3,374
Given the following text description, write Python code to implement the functionality described below step by step Description: Variational Inference Step1: Model specification A neural network is quite simple. The basic unit is a perceptron which is nothing more than logistic regression. We use many of these in par...
Python Code: %matplotlib inline import theano floatX = theano.config.floatX import pymc3 as pm import theano.tensor as T import sklearn import numpy as np import matplotlib.pyplot as plt import seaborn as sns sns.set_style('white') from sklearn import datasets from sklearn.preprocessing import scale from sklearn.cross_...
3,375
Given the following text description, write Python code to implement the functionality described below step by step Description: Pattern Matching Experiments Step1: Networks We give two sets of networks. One of them allows for all parameters. The other is identical except it only uses essential parameters. Step2: Fu...
Python Code: from DSGRN import * Explanation: Pattern Matching Experiments End of explanation network_strings = [ ["SWI4 : (NDD1)(~YOX1)", "HCM1 : SWI4", "NDD1 : HCM1", "YOX1 : SWI4"], ["SWI4 : (NDD1)(~YOX1)", "HCM1 : SWI4", "NDD1 : HCM1", "YOX1 : (SWI4)(HCM1)"], ["SWI4 : (NDD1)(~YOX1)", "HCM1 : SWI4", "NDD1 : HCM1", ...
3,376
Given the following text description, write Python code to implement the functionality described below step by step Description: <center>Structural Analysis and Visualization of Networks</center> <center>Final Mid-term Assignment</center> <center>Student Step1: <hr/> Step2: The mixing coefficient for a numerical nod...
Python Code: import numpy as np import networkx as nx from matplotlib import pyplot as plt %matplotlib inline import warnings warnings.filterwarnings( 'ignore' ) def fw( A, pi = None ) : if pi is None : pi = A.copy( ) pi[ A == 0 ] = np.inf np.fill_diagonal( pi, 0 ) for k in xrange( A.sha...
3,377
Given the following text description, write Python code to implement the functionality described below step by step Description: Map of Flights Taken The goal of this post is to visualize flights taken from Google location data using Python * This post utilizes code from Tyler Hartley's visualizing location history bl...
Python Code: import json import time import datetime import numpy as np import pandas as pd import matplotlib.pyplot as plt from matplotlib.collections import PatchCollection from IPython.display import Image import fiona from shapely.prepared import prep from descartes import PolygonPatch from mpl_toolkits.basemap imp...
3,378
Given the following text description, write Python code to implement the functionality described below step by step Description: <h2>HW #5</h2> Matt Buchovecky Astro 283 Step1: <h2> Problem 1 </h2> $$p\left(x\mid \alpha,\beta\right) = \left{ \begin{array}{ll} \alpha^{-1}\exp{\left(-\frac{x+\beta}{\alpha}\right)I_0\...
Python Code: # import modules import numpy as np from matplotlib import pyplot %matplotlib inline from scipy import optimize, stats, special Explanation: <h2>HW #5</h2> Matt Buchovecky Astro 283 End of explanation # define the pdf for the Rice distribution as a subclass of rv_continuous class Rice_dist(stats.rv_conti...
3,379
Given the following text description, write Python code to implement the functionality described below step by step Description: Markov Chains author Step1: Markov chains have log probability, fit, summarize, and from summaries methods implemented. They do not have classification capabilities by themselves, but when ...
Python Code: from pomegranate import * %pylab inline d1 = DiscreteDistribution({'A': 0.10, 'C': 0.40, 'G': 0.40, 'T': 0.10}) d2 = ConditionalProbabilityTable([['A', 'A', 0.10], ['A', 'C', 0.50], ['A', 'G', 0.30], ['A', 'T', ...
3,380
Given the following text description, write Python code to implement the functionality described below step by step Description: Deep Learning Assignment 1 The objective of this assignment is to learn about simple data curation practices, and familiarize you with some of the data we'll be reusing later. This notebook ...
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...
3,381
Given the following text description, write Python code to implement the functionality described below step by step Description: Getting Started This is a simple example of the basic capabilities of aneris. First, model and history data are read in. The model is then harmonized. Finally, output is analyzed. Step1: Th...
Python Code: import pandas as pd import seaborn as sns import matplotlib.pyplot as plt import aneris from aneris.tutorial import load_data %matplotlib inline Explanation: Getting Started This is a simple example of the basic capabilities of aneris. First, model and history data are read in. The model is then harmonized...
3,382
Given the following text description, write Python code to implement the functionality described below step by step Description: Solution of Axelrod 1980 Step1: Implement the five strategies Step2: Write a function that accepts the name of two strategies and competes them in a game of iterated prisoner's dilemma f...
Python Code: import numpy as np Explanation: Solution of Axelrod 1980 End of explanation # We are going to implement five strategies. # Each strategy takes as input the history of the turns played so far # and returns 1 for cooperation and 0 for defection. # 1) Always defect def always_defect(previous_steps): retu...
3,383
Given the following text description, write Python code to implement the functionality described below step by step Description: 数据科学的编程工具 Python使用简介 王成军 wangchengjun@nju.edu.cn 计算传播网 http Step1: Variable Type Step2: dir & help 当你想要了解对象的详细信息时使用 Step3: type 当你想要了解变量类型时使用type Step4: Data Structure list, tuple, set, ...
Python Code: %matplotlib inline import random, datetime import numpy as np import matplotlib.pyplot as plt import matplotlib import statsmodels.api as sm from scipy.stats import norm from scipy.stats.stats import pearsonr Explanation: 数据科学的编程工具 Python使用简介 王成军 wangchengjun@nju.edu.cn 计算传播网 http://computational-communica...
3,384
Given the following text description, write Python code to implement the functionality described below step by step Description: Experiments with entropy, information gain, and decision trees. Iris fact of the day Step1: If you do not have pydot library installed, open your terminal and type either conda install pydo...
Python Code: # This tells matplotlib not to try opening a new window for each plot. %matplotlib inline import matplotlib.pyplot as plt import numpy as np from sklearn.datasets import load_iris from sklearn import tree from sklearn.tree import DecisionTreeClassifier # For producing decision tree diagrams. from IPython.c...
3,385
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', 'awi', 'sandbox-3', 'ocnbgchem') Explanation: ES-DOC CMIP6 Model Properties - Ocnbgchem MIP Era: CMIP6 Institute: AWI Source ID: SANDBOX-3 Topic: Ocnbgchem Sub-Topics: Tracers. Proper...
3,386
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...
3,387
Given the following text description, write Python code to implement the functionality described below step by step Description: Image and feature analysis Let's start by loading the libraries we'll need Step1: Extract Images Included in these workshop materials is a compressed file ("data.tar.gz") containg the image...
Python Code: import cv2 import numpy as np import matplotlib.pyplot as plt import matplotlib.cm as cm %matplotlib inline Explanation: Image and feature analysis Let's start by loading the libraries we'll need: End of explanation rect_image = cv2.imread('data/I/27.png', cv2.IMREAD_GRAYSCALE) circle_image = cv2.imrea...
3,388
Given the following text description, write Python code to implement the functionality described below step by step Description: 5章 誤差逆伝播法 ニューラルネットワークの学習では重みパラメータの勾配(重みパラメータに関する損失関数の勾配)は数値微分によって求めていた。これは実装は簡単だが、計算に時間がかかる。そこで効率よく勾配計算を行なうために「誤差逆伝播法」を用いる。 ここでは数式ではなく、「計算グラフ(computational graph)」を用いて理解を深める。 5.1 計算グラフ 計算グラフ...
Python Code: import matplotlib.pyplot as plt from graphviz import Digraph from matplotlib.image import imread f = Digraph(format="png") f.attr(rankdir='LR', size='8,5') f.attr('node', shape='circle') f.edge('apple', '×2', label='100') f.edge('×2', '×1.1', label='200') f.edge('×1.1', 'cash', label='220') f.render("../do...
3,389
Given the following text description, write Python code to implement the functionality described below step by step Description: Make an MNE-Report with a Slider In this example, MEG evoked data are plotted in an HTML slider. Step1: Do standard folder parsing (this can take a couple of minutes) Step2: Add a custom s...
Python Code: # Authors: Teon Brooks <teon.brooks@gmail.com> # Eric Larson <larson.eric.d@gmail.com> # # License: BSD (3-clause) from mne.report import Report from mne.datasets import sample from mne import read_evokeds from matplotlib import pyplot as plt data_path = sample.data_path() meg_path = data_path + '...
3,390
Given the following text description, write Python code to implement the functionality described below step by step Description: Tensor Flow to create a useless images To learn how to encode a simple image and a GIF Import needed for Tensorflow Step1: Import needed for Jupiter Step2: A function to save a picture Ste...
Python Code: import numpy as np import tensorflow as tf Explanation: Tensor Flow to create a useless images To learn how to encode a simple image and a GIF Import needed for Tensorflow End of explanation %matplotlib notebook import matplotlib import matplotlib.pyplot as plt from IPython.display import Image Explanation...
3,391
Given the following text description, write Python code to implement the functionality described below step by step Description: Deep Crossentropy method In this section we'll extend your CEM implementation with neural networks! You will train a multi-layer neural network to solve simple continuous state space games. ...
Python Code: import sys, os if 'google.colab' in sys.modules and not os.path.exists('.setup_complete'): !wget -q https://raw.githubusercontent.com/yandexdataschool/Practical_RL/master/setup_colab.sh -O- | bash !touch .setup_complete # This code creates a virtual display to draw game images on. # It will have no...
3,392
Given the following text description, write Python code to implement the functionality described below step by step Description: Convergence Description of the UCI protocol Step1: The Speed of Search The number of nodes searched depend linearly on time Step2: So nodes per second is roughly constant Step3: The hasht...
Python Code: %pylab inline ! grep "multipv 1" log2.txt | grep -v lowerbound | grep -v upperbound > log2_g.txt def parse_info(l): D = {} k = l.split() i = 0 assert k[i] == "info" i += 1 while i < len(k): if k[i] == "depth": D[k[i]] = int(k[i+1]) i += 2 eli...
3,393
Given the following text description, write Python code to implement the functionality described below step by step Description: Circuitos de Segunda Ordem Gerais (Genéricos) Jupyter Notebook desenvolvido por Gustavo S.S. Dado um circuito de segunda ordem, determinamos sua resposta a um degrau x(t) (que pode ser tensã...
Python Code: print("Exemplo 8.9\n") from sympy import * t = symbols('t') V = 12 C = 1/2 L = 1 #Para t < 0 i0 = 0 v0 = V print("i(0):",i0,"A") print("v(0):",v0,"V") #Para t = oo i_f = V/(4 + 2) vf = V*2/(4 + 2) print("i(oo):",i_f,"A") print("v(oo):",vf,"V") #Para t > 0 #desativar fontes independentes #i = v/2 + C*dv/dt ...
3,394
Given the following text description, write Python code to implement the functionality described below step by step Description: WebGL problems Drag around canvas is shifted down, cut off at top spilling over bottom. Bad in 0.12.14 and 0.12.15dev3 Good in 0.12.10 Step1: Responsive in notebook Spills a scroll bar. Not...
Python Code: N = 10000 x = np.random.normal(0, np.pi, N) y = np.sin(x) + np.random.normal(0, 0.2, N) p = figure(webgl=True) p.scatter(x, y, alpha=0.1) show(p) Explanation: WebGL problems Drag around canvas is shifted down, cut off at top spilling over bottom. Bad in 0.12.14 and 0.12.15dev3 Good in 0.12.10 End of explan...
3,395
Given the following text problem statement, write Python code to implement the functionality described below in problem statement Problem: I have a dataframe that looks like this:
Problem: import pandas as pd df = pd.DataFrame({'product': [1179160, 1066490, 1148126, 1069104, 1069105, 1160330, 1069098, 1077784, 1193369, 1179741], 'score': [0.424654, 0.424509, 0.422207, 0.420455, 0.414603, 0.168784, 0.168749, 0.168738, 0.168703, 0.168684]}) products = [[1069104, 1069105], [10664...
3,396
Given the following text description, write Python code to implement the functionality described below step by step Description: Experiments with Crop Improvements This notebook experiments advances in image cropping. This performs the following steps determine dimensions of the image determine the center of the image...
Python Code: import os import skimage from skimage import io, util from skimage.draw import circle import numpy as np import matplotlib.pyplot as plt %matplotlib inline import math Explanation: Experiments with Crop Improvements This notebook experiments advances in image cropping. This performs the following steps det...
3,397
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction Idea The claim was that the directory structure would be very similar to each other over a period of time. We want to identify this time span by using a time-based analysis on t...
Python Code: import glob file_list = glob.glob(r'C:/dev/forensic/data/**/*.txt', recursive=True) file_list = [x.replace("\\", "/") for x in file_list] file_list[:5] Explanation: Introduction Idea The claim was that the directory structure would be very similar to each other over a period of time. We want to identify th...
3,398
Given the following text description, write Python code to implement the functionality described below step by step Description: Clase 9 Step1: 2. Uso de Pandas para descargar datos de precios de cierre Bajar datos en forma de función Step2: Una vez cargados los paquetes, es necesario definir los tickers de las acci...
Python Code: #importar los paquetes que se van a usar import pandas as pd import pandas_datareader.data as web import numpy as np import datetime from datetime import datetime import scipy.stats as stats import scipy as sp import scipy.optimize as scopt import matplotlib.pyplot as plt import seaborn as sns import sklea...
3,399
Given the following text description, write Python code to implement the functionality described below step by step Description: Generative Adversarial Network In this notebook, we'll be building a generative adversarial network (GAN) trained on the MNIST dataset. From this, we'll be able to generate new handwritten d...
Python Code: %matplotlib inline import pickle as pkl 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') Explanation: Generative Adversarial Network In this notebook, we'll be building a gen...