Unnamed: 0
int64
0
16k
text_prompt
stringlengths
110
62.1k
code_prompt
stringlengths
37
152k
4,800
Given the following text description, write Python code to implement the functionality described below step by step Description: Kernel Density Estimation by Parijat Mazumdar (GitHub ID Step1: Now, we will apply KDE to estimate the actual pdf using the samples. Using KDE in Shogun is a 3 stage process Step2: We hav...
Python Code: import numpy as np import scipy.stats as stats import matplotlib.pyplot as plt %matplotlib inline import os import shogun as sg SHOGUN_DATA_DIR=os.getenv('SHOGUN_DATA_DIR', '../../../data') # generates samples from the distribution def generate_samples(n_samples,mu1,sigma1,mu2,sigma2): samples1 = np.ra...
4,801
Given the following text description, write Python code to implement the functionality described below step by step Description: The Examples Rankine Cycle 8.1,8.2 Michael J. Moran, Howard N. Shapiro, Daisie D. Boettner, Margaret B. Bailey. Fundamentals of Engineering Thermodynamics(7th Edition). John Wiley & Sons, I...
Python Code: from seuif97 import * # State 1 p1 = 8.0 # in MPa t1 = px2t(p1, 1) h1 = px2h(p1, 1) # h1 = 2758.0 From table A-3 kj/kg s1 = px2s(p1, 1) # s1 = 5.7432 From table A-3 kj/kg.k # State 2 ,p2=0.008 p2 = 0.008 s2 = s1 t2 = ps2t(p2, s2) h2 = ps2h(p2, s2) # State 3 is saturated liquid ...
4,802
Given the following text description, write Python code to implement the functionality described below step by step Description: Predicting the outcome of a US presidential election using Bayesian optimal experimental design In this tutorial, we explore the use of optimal experimental design techniques to create an op...
Python Code: # Data path BASE_URL = "https://d2hg8soec8ck9v.cloudfront.net/datasets/us_elections/" import pandas as pd import torch from urllib.request import urlopen electoral_college_votes = pd.read_pickle(urlopen(BASE_URL + "electoral_college_votes.pickle")) print(electoral_college_votes.head()) ec_votes_tensor = t...
4,803
Given the following text description, write Python code to implement the functionality described below step by step Description: SpaCy Step1: Let's start out with a short string from our reading and see what happens. Step2: We've downloaded the English model, and now we just have to load it. This model will do every...
Python Code: from datascience import * import spacy Explanation: SpaCy: Industrial-Strength NLP The tradtional NLP library has always been NLTK. While NLTK is still very useful for linguistics analysis and exporation, spacy has become a nice option for easy and fast implementation of the NLP pipeline. What's the NLP pi...
4,804
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', 'ncc', 'sandbox-3', 'atmos') Explanation: ES-DOC CMIP6 Model Properties - Atmos MIP Era: CMIP6 Institute: NCC Source ID: SANDBOX-3 Topic: Atmos Sub-Topics: Dynamical Core, Radiation, T...
4,805
Given the following text description, write Python code to implement the functionality described below step by step Description: Transect Groupby and transform allow me to combine rows into a single 'transect' row. Or, use a multiIndex, a hierarchical index, so I can target specific cells using id and type. The index ...
Python Code: %matplotlib inline import sys import numpy as np import pandas as pd import json import matplotlib.pyplot as plt from io import StringIO print(sys.version) print("Pandas:", pd.__version__) df = pd.read_csv('C:/Users/Peter/Documents/atlas/atlasdata/obs_types/transect.csv', parse_dates=['date']) df = df.asty...
4,806
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction Here I test the idea of binary, or very discrete, coding in an adaption of Larry Abbott's FORCE learning [0]. I want to make sense of a world where the neural code is binary [6...
Python Code: import pylab as plt import numpy as np %matplotlib inline from __future__ import division from scipy.integrate import odeint,ode from numpy import zeros,ones,eye,tanh,dot,outer,sqrt,linspace,cos,pi,hstack,zeros_like,abs,repeat from numpy.random import uniform,normal,choice %config InlineBackend.figure_form...
4,807
Given the following text description, write Python code to implement the functionality described below step by step Description: An overview of feature engineering for regression and machine learning algorithms Step1: A simple example to illustrate the intuition behind dummy variables Step2: Now we have a matrix of ...
Python Code: import pandas as pd %matplotlib inline Explanation: An overview of feature engineering for regression and machine learning algorithms End of explanation df = pd.DataFrame({'key':['b','b','a','c','a','b'],'data1':range(6)}) df pd.get_dummies(df['key'],prefix='key') Explanation: A simple example to illustrat...
4,808
Given the following text description, write Python code to implement the functionality described below step by step Description: A Physicist's Crash Course on Artificial Neural Network What is a Neuron What a neuron does is to response when a stimulation is given. This response could be strong or weak or even null. If...
Python Code: import numpy as np print np.linspace(0,9,10), np.exp(-np.linspace(0,9,10)) Explanation: A Physicist's Crash Course on Artificial Neural Network What is a Neuron What a neuron does is to response when a stimulation is given. This response could be strong or weak or even null. If I would draw a figure, of th...
4,809
Given the following text description, write Python code to implement the functionality described below step by step Description: An interactive introduction to Noodles Step1: Now we can create a workflow composing several calls to this function. Step2: That looks easy enough; the funny thing is though, that nothing ...
Python Code: from noodles import schedule @schedule def add(x, y): return x + y @schedule def mul(x,y): return x * y Explanation: An interactive introduction to Noodles: translating Poetry Noodles is there to make your life easier, in parallel! The reason why Noodles can be easy and do parallel Python at the sa...
4,810
Given the following text description, write Python code to implement the functionality described below step by step Description: <h1>Compare shapes of molecules Step1: We'd like to compare the shape of heroin with other molecules. ODDT supports three methods of molecular shape comparison Step2: To compute the shape ...
Python Code: from __future__ import print_function, division, unicode_literals import oddt from oddt.shape import usr, usr_similarity print(oddt.__version__) Explanation: <h1>Compare shapes of molecules End of explanation heroin = oddt.toolkit.readstring('smi', 'CC(=O)Oc1ccc2c3c1O[C@@H]4[C@]35CC[NH+]([C@H](C2)[C@@...
4,811
Given the following text description, write Python code to implement the functionality described below step by step Description: ES-DOC CMIP6 Model Properties - Ocean MIP Era Step1: Document Authors Set document authors Step2: Document Contributors Specify document contributors Step3: Document Publication Specify d...
Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'bnu', 'sandbox-3', 'ocean') Explanation: ES-DOC CMIP6 Model Properties - Ocean MIP Era: CMIP6 Institute: BNU Source ID: SANDBOX-3 Topic: Ocean Sub-Topics: Timestepping Framework, Adve...
4,812
Given the following text description, write Python code to implement the functionality described below step by step Description: Building your Deep Neural Network Step2: 2 - Outline of the Assignment To build your neural network, you will be implementing several "helper functions". These helper functions will be used...
Python Code: import numpy as np import h5py import matplotlib.pyplot as plt from testCases import * from dnn_utils import sigmoid, sigmoid_backward, relu, relu_backward %matplotlib inline plt.rcParams['figure.figsize'] = (5.0, 4.0) # set default size of plots plt.rcParams['image.interpolation'] = 'nearest' plt.rcParams...
4,813
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: # Installs additional packages import pip import IPython def import_or_install(package): try: __import__(package) except ImportError: pip.main(['install', package]) app = IPython.Application.instance() app.kernel.do_shutdown(True) import_or_install('lightg...
4,814
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', 'nims-kma', 'sandbox-2', 'land') Explanation: ES-DOC CMIP6 Model Properties - Land MIP Era: CMIP6 Institute: NIMS-KMA Source ID: SANDBOX-2 Topic: Land Sub-Topics: Soil, Snow, Vegetatio...
4,815
Given the following text description, write Python code to implement the functionality described below step by step Description: Polyglot Unconference This notebook holds a project conducting data analysis and visualization of the 2017 Polyglot Vancouver Un-Conference. See the README in this repository for background ...
Python Code: # Imports import sys import pandas as pd import csv %matplotlib inline import matplotlib.pyplot as plt plt.rcParams['figure.figsize'] = (20.0, 10.0) # %load util.py #!/usr/bin/python # Util file to import in all of the notebooks to allow for easy code re-use # Calculate Percent of Attendees that did not sp...
4,816
Given the following text description, write Python code to implement the functionality described below step by step Description: Greatest Common Divisor Now, the greatest common divisor (GCD) is the largest natural number $d$ that divides $a$ and $b$ in a fraction $\frac{a}{b}$ without a remainder. For example, the G...
Python Code: def naive_gcd(a, b): gcd = 0 if a < b: n = a else: n = a for d in range(1, n + 1): if not a % d and not b % d: gcd = d return gcd print('In: 1/1,', 'Out:', naive_gcd(1, 1)) print('In: 1/2,', 'Out:', naive_gcd(1, 2)) print('In: 3/9,', 'Out:', naive_gcd...
4,817
Given the following text description, write Python code to implement the functionality described below step by step Description: Combine an MLP with a GP Modified from https Step1: Data Step2: Deep kernel We transform the (1d) input using an MLP and then pass it to a Matern kernel. Step3: Shallow kernel
Python Code: %%capture import os try: from tinygp import kernels, transforms, GaussianProcess except ModuleNotFoundError: %pip install -qq tinygp from tinygp import kernels, transforms, GaussianProcess try: import flax.linen as nn except ModuleNotFoundError: %pip install -qq flax import flax.lin...
4,818
Given the following text description, write Python code to implement the functionality described below step by step Description: 1. Load blast hits Step1: 2. Process blastp results 2.1 Extract ORF stats from fasta file Step2: 2.2 Annotate blast hits with orf stats Step3: 2.3 Extract best hit for each ORF ( q_cov > ...
Python Code: #Load blast hits blastp_hits = pd.read_csv("2_blastp_hits.csv") blastp_hits.head() #Filter out Metahit 2010 hits, keep only Metahit 2014 blastp_hits = blastp_hits[blastp_hits.db != "metahit_pep"] Explanation: 1. Load blast hits End of explanation #Assumes the Fasta file comes with the header format of EMBO...
4,819
Given the following text description, write Python code to implement the functionality described below step by step Description: Partial Differential Equations of Groundwater Flow How to interpret the equations If you are mathematically minded, then the groundwater flow equation by itself give you a really good feel f...
Python Code: %matplotlib inline ''' This is a function to calculate the gradient at a point in a long line of points. You feed it coordinates (X), values (H) and - optional - boundary conditions. It returns the gradient. ''' def gradx(X, H, leftbc=None, rightbc=None): size = len(H) gradP = z...
4,820
Given the following text description, write Python code to implement the functionality described below step by step Description: Python Visualization Landscape Step1: Note Using cleaned data from Data Cleaning Notebook. See Notebook for details. Step2: BQPlot Examples here are shamelessly stolen from the amazing Ste...
Python Code: from IPython.lib.display import YouTubeVideo YouTubeVideo("FytuB8nFHPQ", width=400, height=300) from __future__ import absolute_import, division, print_function %matplotlib inline import matplotlib.pyplot as plt import seaborn as sns sns.set_context('poster') sns.set_style('whitegrid') # sns.set_style('da...
4,821
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction to Logistic Regression Using TF 2.0 Learning Objectives Build a model, Train this model on example data, and Use the model to make predictions about unknown data. Introduction I...
Python Code: import os import matplotlib.pyplot as plt import tensorflow as tf print(f"TensorFlow version: {tf.__version__}") print(f"Eager execution: {tf.executing_eagerly()}") Explanation: Introduction to Logistic Regression Using TF 2.0 Learning Objectives Build a model, Train this model on example data, and Use the...
4,822
Given the following text description, write Python code to implement the functionality described below step by step Description: Aggregation (via pymongo) Step1: Do An Aggregation Basic process to convert pipelines from a JavaScript array to a Python list Convert all comments (from "//" to "#") Title-case all true/fa...
Python Code: # import pymongo from pymongo import MongoClient from pprint import pprint # Create client client = MongoClient('mongodb://localhost:32768') # Connect to database db = client['fifa'] # Get collection my_collection = db['player'] Explanation: Aggregation (via pymongo) End of explanation def print_docs(pipel...
4,823
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: In this notebook, we will use LSTM layers to develop time series forecasting models. The dataset used for the examples of this notebook is on air pollution measured by concentration o...
Python Code: from __future__ import print_function import os import sys import pandas as pd import numpy as np %matplotlib inline from matplotlib import pyplot as plt import seaborn as sns import datetime #set current working directory os.chdir('D:/Practical Time Series') #Read the dataset into a pandas.DataFrame df = ...
4,824
Given the following text description, write Python code to implement the functionality described below step by step Description: For the testing we will use a standard DSI acqusition scheme with 514 gradient directions and 1 S0. There's also the alternative of having a scheme with 4195 directions. In the case of the s...
Python Code: btable = np.loadtxt(get_data('dsi515btable')) #btable = np.loadtxt(get_data('dsi4169btable')) gtab['test'] = gradient_table(btable[:, 0], btable[:, 1:], big_delta=gtab['train'].big_delta, small_delta=gtab['train'].small_delta) gtab['test'].info Explanation: For the testing we ...
4,825
Given the following text description, write Python code to implement the functionality described below step by step Description: Duffing Oscillator Solution Using Frequency Domain Residuals This notebook uses the newer solver. This solver minimizes frequency domain error. hb_freq can also ignore the constant term ($\o...
Python Code: %matplotlib inline %load_ext autoreload %autoreload 2 import scipy as sp import numpy as np import matplotlib.pyplot as plt import mousai as ms from scipy import pi, sin # Test that all is working. # f_tol adjusts accuracy. This is smaller than reasonable, but illustrative of usage. t, x, e, amps, phases...
4,826
Given the following text description, write Python code to implement the functionality described below step by step Description: Looking at KIC 8462852 (Boyajian's star) with gPhoton Using the time-tagged photon data from GALEX, available with gPhoton, lets make some light curves of "Tabby's Star" Step1: Searching fo...
Python Code: %matplotlib inline import numpy as np import pandas as pd import matplotlib.pyplot as plt import matplotlib.cm as cm import matplotlib from gPhoton import gFind from gPhoton import gAperture from gPhoton import gMap from gPhoton.gphoton_utils import read_lc import datetime from astropy.time import Time fro...
4,827
Given the following text description, write Python code to implement the functionality described below step by step Description: Project Step1: Step 1 Step2: Total number of columns is 14 + 1 target Step3: Step 2 Step4: Step 3 Step5: Logistic Regression Step6: KNN Step7: Random Forest Step8: Naive Bayes Step9:...
Python Code: # imports import pandas as pd import dateutil.parser from sklearn import preprocessing from sklearn.model_selection import train_test_split from sklearn.linear_model import LogisticRegression from sklearn.naive_bayes import BernoulliNB from sklearn.naive_bayes import GaussianNB from sklearn.naive_bayes imp...
4,828
Given the following text description, write Python code to implement the functionality described below step by step Description: Calculate Coupling Coefficients Two split rings are placed in a broadside coupled configuration. The scalar model of each resonator is augmented by additional coefficients representing the c...
Python Code: # setup 2D and 3D plotting %matplotlib inline from openmodes.ipython import matplotlib_defaults matplotlib_defaults() import matplotlib.pyplot as plt import numpy as np import os.path as osp import openmodes from openmodes.constants import c, eta_0 from openmodes.model import EfieModelMutualWeight from op...
4,829
Given the following text description, write Python code to implement the functionality described below step by step Description: Работа 2.4. Определение вязкости воздуха по скорости течения через тонкие трубки Цель работы Step1: Первые 7 точек укладываются на прямую, оставшиеся нет. Значит, примерно при $Q = 10^{-4}~...
Python Code: import pandas PQn = pandas.read_excel('lab-2-3.xlsx', 't-1') PQn.head(len(PQn)) x = PQn.values[:, 6] / 3600 y = PQn.values[:, 8] dx = PQn.values[:, 7] / 3600 dy = PQn.values[:, 9] xl = x[:7] yl = y[:7] import numpy k, b = numpy.polyfit(xl, yl, deg=1) grid = numpy.linspace(0.04 / 3600, 0.0001) import matplo...
4,830
Given the following text description, write Python code to implement the functionality described below step by step Description: Example 2 Step1: Visualize data Step2: Interactive pandas Dataframe Using qgrid it is possible to modify the tables in place as following Step3: Grid and potential field We can see the po...
Python Code: # Importing import theano.tensor as T import sys, os sys.path.append("../GeMpy") # Importing GeMpy modules import GeMpy # Reloading (only for development purposes) import importlib importlib.reload(GeMpy) # Usuful packages import numpy as np import pandas as pn import matplotlib.pyplot as plt # This was to...
4,831
Given the following text description, write Python code to implement the functionality described below step by step Description: Baseline is static, a straight line for each input - Test Step1: Baseline is static, a straight line for each input - Train (small) Step2: Baseline is static, a straight line for each inpu...
Python Code: bltest = MyBaseline(npz_path=npz_test) bltest.getMSE() bltest.renderMSEs() plt.show() bltest.getHuberLoss() bltest.renderHuberLosses() plt.show() %%time bltest.get_dtw() bltest.renderRandomTargetVsPrediction() plt.show() Explanation: Baseline is static, a straight line for each input - Test End of explanat...
4,832
Given the following text description, write Python code to implement the functionality described below step by step Description: Challenge of processing large amounts of data <ul> <li>How to process is quickly? <li>So how do we go about making the problem map so that it can be distributed computation? <li> Distributed...
Python Code: def cube(x): return x*x*x map(cube,range(1,11)) Explanation: Challenge of processing large amounts of data <ul> <li>How to process is quickly? <li>So how do we go about making the problem map so that it can be distributed computation? <li> Distributed/Parrallel Programming is hard </ul> Mapreduce addresses...
4,833
Given the following text description, write Python code to implement the functionality described below step by step Description: KeplerLightCurveCelerite.ipynb ‹ KeplerLightCurve.ipynb › Copyright (C) ‹ 2017 › ‹ Anna Scaife - anna.scaife@manchester.ac.uk › This program is free software Step1: Import some libraries St...
Python Code: %matplotlib inline Explanation: KeplerLightCurveCelerite.ipynb ‹ KeplerLightCurve.ipynb › Copyright (C) ‹ 2017 › ‹ Anna Scaife - anna.scaife@manchester.ac.uk › This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free ...
4,834
Given the following text problem statement, write Python code to implement the functionality described below in problem statement Problem: I am having a problem with minimization procedure. Actually, I could not create a correct objective function for my problem.
Problem: import scipy.optimize import numpy as np np.random.seed(42) a = np.random.rand(3,5) x_true = np.array([10, 13, 5, 8, 40]) y = a.dot(x_true ** 2) x0 = np.array([2, 3, 1, 4, 20]) def residual_ans(x, a, y): s = ((y - a.dot(x**2))**2).sum() return s out = scipy.optimize.minimize(residual_ans, x0=x0, args=(...
4,835
Given the following text description, write Python code to implement the functionality described below step by step Description: Inference Step1: The uniform prior, $U\sim(a, b)$, here with $a=-10$ and $b=15$. When this function is called, its log density is returned. Step2: To plot the density, we take the exponent...
Python Code: import pints import numpy as np import matplotlib.pyplot as plt Explanation: Inference: Log priors This example notebook illustrates some of the functionality that is available for LogPrior objects that are currently available within PINTS. End of explanation uniform_log_prior = pints.UniformLogPrior(-10, ...
4,836
Given the following text description, write Python code to implement the functionality described below step by step Description: Python data types Python can be a little strange in providing lots of data types, dynamic type allocation, and some interconversion. Numbers Integers, Floating point numbers, and complex nu...
Python Code: f = 1.0 i = 1 print f, i print print "Value of f is {}, value of i is {}".format(f,i) print print "Value of f is {:f}, value of i is {:f}".format(f,i) ## BUT !! print "Value of f is {:d}, value of i is {:f}".format(f,i) c = 0.0 + 1.0j print c print "Value of c is {:f}".format(c) print "Value of c**2 is ...
4,837
Given the following text description, write Python code to implement the functionality described below step by step Description: Save this file as studentid1_studentid2_lab#.ipynb (Your student-id is the number shown on your student card.) E.g. if you work with 3 people, the notebook should be named Step1: Lab 1 Step...
Python Code: NAME = "Laura Ruis" NAME2 = "Fredie Haver" NAME3 = "Lukás Jelínek" EMAIL = "lauraruis@live.nl" EMAIL2 = "frediehaver@hotmail.com" EMAIL3 = "lukas.jelinek1@gmail.com" Explanation: Save this file as studentid1_studentid2_lab#.ipynb (Your student-id is the number shown on your student card.) E.g. if you work ...
4,838
Given the following text description, write Python code to implement the functionality described below step by step Description: Demonstration of accessing lepton information Import what we need from Matplotlib and ROOT Step1: Create a "chain" of files (but just one file for now) Step2: This is how we plotted the pT...
Python Code: import pylab import matplotlib.pyplot as plt %matplotlib inline pylab.rcParams['figure.figsize'] = 12,8 from ROOT import TChain Explanation: Demonstration of accessing lepton information Import what we need from Matplotlib and ROOT: End of explanation data = TChain("mini"); # "mini" is the name of the TTr...
4,839
Given the following text problem statement, write Python code to implement the functionality described below in problem statement Problem: I am trying to find col duplicates rows in a pandas dataframe.
Problem: import pandas as pd df=pd.DataFrame(data=[[1,1,2,5],[1,3,4,1],[4,1,2,5],[5,1,4,9],[1,1,2,5]],columns=['val', 'col1','col2','3col']) def g(df): cols = list(df.filter(like='col')) df['index_original'] = df.groupby(cols)[cols[0]].transform('idxmin') return df[df.duplicated(subset=cols, keep='first')] ...
4,840
Given the following text description, write Python code to implement the functionality described below step by step Description: 2A.eco - Mise en pratique des séances 1 et 2 - Utilisation de pandas et visualisation Trois exercices pour manipuler les donner, manipulation de texte, données vélib. Step1: Données Les don...
Python Code: from jyquickhelper import add_notebook_menu add_notebook_menu() Explanation: 2A.eco - Mise en pratique des séances 1 et 2 - Utilisation de pandas et visualisation Trois exercices pour manipuler les donner, manipulation de texte, données vélib. End of explanation from pyensae.datasource import download_data...
4,841
Given the following text description, write Python code to implement the functionality described below step by step Description: Preprocessing Step2: Training LeNet First, we will train a simple CNN with a single hidden fully connected layer as a classifier. Step3: Training Random Forests Preprocessing to a fixed si...
Python Code: import os from skimage import io from skimage.color import rgb2gray from skimage import transform from math import ceil IMGSIZE = (100, 100) def load_images(folder, scalefactor=(2, 2), labeldict=None): images = [] labels = [] files = os.listdir(folder) for file in (fname for fname in ...
4,842
Given the following text description, write Python code to implement the functionality described below step by step Description: Look at the hourly data Now on to the real challenge, the hourly data. So, as usual, make some plots, do a bit of anaalysis and try to get a feel for the data. Remaining TO DO Step1: It's q...
Python Code: import numpy as np import pandas as pd import matplotlib.pyplot as plt %matplotlib inline hourly = pd.read_csv('Bike-Sharing-Dataset/hour.csv',header = 0) hourly.head(20) type(hourly) for row_index, row in hourly.iterrows(): print row_index , row['registered'] if (row_index > 5): brea...
4,843
Given the following text description, write Python code to implement the functionality described below step by step Description: Principal Components Analysis on the UCI Image Segmentation Data Set. Kevin Maher <span style="color Step1: Read in the data. Extra header rows in the UCI data file were manually deleted u...
Python Code: %matplotlib inline import pandas as pd from sklearn.ensemble import RandomForestClassifier import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler from sklearn import decomposition from sklearn import metrics Explanation: Princip...
4,844
Given the following text description, write Python code to implement the functionality described below step by step Description: <a href="https Step1: Install dependencies Step2: Clone, compile and set up Tesseract Step3: Grab some things to scrape the RIA corpus Step4: Scrape the RIA corpus Step5: Get the raw co...
Python Code: !wget https://github.com/jimregan/tesseract-gle-uncial/releases/download/v0.1beta2/gle_uncial.traineddata Explanation: <a href="https://colab.research.google.com/github/jimregan/tesseract-gle-uncial/blob/master/Update_gle_uncial_traineddata_for_Tesseract_4.ipynb" target="_parent"><img src="https://colab.re...
4,845
Given the following text description, write Python code to implement the functionality described below step by step Description: &larr; Back to Index Spectral Features For classification, we're going to be using new features in our arsenal Step1: librosa.feature.spectral_bandwidth librosa.feature.spectral_bandwidth S...
Python Code: x, fs = librosa.load('simple_loop.wav') IPython.display.Audio(x, rate=fs) spectral_centroids = librosa.feature.spectral_centroid(x, sr=fs) plt.plot(spectral_centroids[0]) Explanation: &larr; Back to Index Spectral Features For classification, we're going to be using new features in our arsenal: spectral mo...
4,846
Given the following text description, write Python code to implement the functionality described below step by step Description: Make decision tree from iris data Taken from Google's Visualizing a Decision Tree - Machine Learning Recipes #2 Step1: Tensorflow Examples from http Step3: Custom model with TensorFlowEsti...
Python Code: import tensorflow.contrib.learn as skflow from sklearn.datasets import load_iris from sklearn import metrics iris = load_iris() iris.keys() iris.feature_names iris.target_names # Withhold 3 for testing test_idx = [0, 50, 100] train_data = np.delete(iris.data, test_idx, axis=0) train_target = np.delete(iris...
4,847
Given the following text description, write Python code to implement the functionality described below step by step Description: Visualize Evoked data In this tutorial we focus on the plotting functions of Step1: First we read the evoked object from a file. Check out tut_epoching_and_averaging to get to this stage f...
Python Code: import os.path as op import numpy as np import matplotlib.pyplot as plt import mne # sphinx_gallery_thumbnail_number = 9 Explanation: Visualize Evoked data In this tutorial we focus on the plotting functions of :class:mne.Evoked. End of explanation data_path = mne.datasets.sample.data_path() fname = op.joi...
4,848
Given the following text description, write Python code to implement the functionality described below step by step Description: You can use LPVisu to visualize Integer Linear Programming problems in Jupyter notebooks. First import the LPVisu class Step1: You can then define a problem Step2: To draw the polygon, cre...
Python Code: from lp_visu import LPVisu Explanation: You can use LPVisu to visualize Integer Linear Programming problems in Jupyter notebooks. First import the LPVisu class: End of explanation # problem definition A = [[1.0, 0.0], [1.0, 2.0], [2.0, 1.0]] b = [8.0, 15.0, 18.0] c = [-4.0, -3.0] x1_bounds = (0, None) x2_b...
4,849
Given the following text description, write Python code to implement the functionality described below step by step Description: This may be more readable on NBViewer. Step1: As we saw earlier the Dirichlet process describes the distribution of a random probability distribution. The Dirichlet process takes two parame...
Python Code: %matplotlib inline Explanation: This may be more readable on NBViewer. End of explanation from numpy.random import choice from scipy.stats import beta class DirichletProcessSample(): def __init__(self, base_measure, alpha): self.base_measure = base_measure self.alpha = alpha ...
4,850
Given the following text description, write Python code to implement the functionality described below step by step Description: House Prices Estimator Note Step1: Here we have to find the 'NaN' values and fill them with the mean. Probably it's not the best way to complete the info where we have empty values but at l...
Python Code: import numpy as np import pandas as pd #load the files train = pd.read_csv('input/train.csv') test = pd.read_csv('input/test.csv') data = pd.concat([train, test]) #size of training dataset train_samples = train.shape[0] test_samples = test.shape[0] # remove the Id feature data.drop(['Id'],1, inplace=True);...
4,851
Given the following text description, write Python code to implement the functionality described below step by step Description: The Raw data structure Step1: Loading continuous data .. sidebar Step2: As you can see above, Step3: By default, the Step4: Querying the Raw object .. sidebar Step5: <div class="alert...
Python Code: import os import numpy as np import matplotlib.pyplot as plt import mne Explanation: The Raw data structure: continuous data This tutorial covers the basics of working with raw EEG/MEG data in Python. It introduces the :class:~mne.io.Raw data structure in detail, including how to load, query, subselect, ex...
4,852
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2020 The TensorFlow Authors. Step1: Keras の再帰型ニューラルネットワーク(RNN) <table class="tfo-notebook-buttons" align="left"> <td><a target="_blank" href="https Step2: ビルトイン RNN レイヤー Step3:...
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...
4,853
Given the following text description, write Python code to implement the functionality described below step by step Description: Plotting distributions First, import relevant libraries Step1: Then, load the data (takes a few moments) Step2: The code below creates a calls-per-person frequency distribution, which is t...
Python Code: import warnings warnings.filterwarnings('ignore') import numpy as np import pandas as pd %matplotlib inline import matplotlib.pyplot as plt Explanation: Plotting distributions First, import relevant libraries: End of explanation # Load data uda = pd.read_csv("./aws-data/user_dist.txt", sep="\t") # User dis...
4,854
Given the following text description, write Python code to implement the functionality described below step by step Description: Sentiment Analysis with an RNN In this notebook, you'll implement a recurrent neural network that performs sentiment analysis. Using an RNN rather than a feedfoward network is more accurate ...
Python Code: import numpy as np import tensorflow as tf with open('./reviews.txt', 'r') as f: reviews = f.read() with open('./labels.txt', 'r') as f: labels = f.read() reviews[:2000] Explanation: Sentiment Analysis with an RNN In this notebook, you'll implement a recurrent neural network that performs sentiment...
4,855
Given the following text description, write Python code to implement the functionality described below step by step Description: A Parser for Regular Expression This notebook implements a parser for regular expressions. The parser that is implemented in the function parseExpr parses a regular expression according to ...
Python Code: import re Explanation: A Parser for Regular Expression This notebook implements a parser for regular expressions. The parser that is implemented in the function parseExpr parses a regular expression according to the following <em style="color:blue">EBNF grammar</em>. regExp -&gt; product ('+' product)* ...
4,856
Given the following text description, write Python code to implement the functionality described below step by step Description: IMDB Predictive Analytics This notebook explores using data science techniques on a data set of 5000+ movies, and predicting whether a movie will be highly rated on IMDb. The objective of th...
Python Code: # data analysis and wrangling import pandas as pd import numpy as np import random as rnd from scipy.stats import truncnorm # visualization import seaborn as sns import matplotlib.pyplot as plt %matplotlib inline # machine learning from sklearn.linear_model import LogisticRegression from sklearn.svm import...
4,857
Given the following text description, write Python code to implement the functionality described below step by step Description: Receptive Field Estimation and Prediction This example reproduces figures from Lalor et al's mTRF toolbox in matlab Step1: Load the data from the publication First we will load the data co...
Python Code: # Authors: Chris Holdgraf <choldgraf@gmail.com> # Eric Larson <larson.eric.d@gmail.com> # Nicolas Barascud <nicolas.barascud@ens.fr> # # License: BSD (3-clause) import numpy as np import matplotlib.pyplot as plt from scipy.io import loadmat from os.path import join import mne from mne.dec...
4,858
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2020 The TensorFlow Authors. Step1: TensorFlow 애드온 콜백 Step2: 데이터 가져오기 및 정규화 Step3: 간단한 MNIST CNN 모델 빌드하기 Step4: 간단한 TimeStopping 사용법
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...
4,859
Given the following text description, write Python code to implement the functionality described below step by step Description: Excercises Electric Machinery Fundamentals Chapter 5 Problem 5-10 Step1: Description A synchronous machine has a synchronous reactance of $1.0\,\Omega$ per phase and an armature resistance ...
Python Code: %pylab notebook Explanation: Excercises Electric Machinery Fundamentals Chapter 5 Problem 5-10 End of explanation Ea = 460 # [V] EA_angle = -10/180*pi # [rad] EA = Ea * (cos(EA_angle) + 1j*sin(EA_angle)) Vphi = 480 # [V] VPhi_angle = 0/180*pi # [rad] VPhi =...
4,860
Given the following text description, write Python code to implement the functionality described below step by step Description: <a href="https Step1: Map <script type="text/javascript"> localStorage.setItem('language', 'language-py') </script> <table align="left" style="margin-right Step2: Examples In the following...
Python Code: #@title Licensed under the Apache License, Version 2.0 (the "License") # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this fi...
4,861
Given the following text description, write Python code to implement the functionality described below step by step Description: North Atlantic Winter Weather Regimes from a Self-Organizing Map Perspective The four weather regimes typically found over the North Atlantic in winter are identified as * NAO+ (positive NAO...
Python Code: %matplotlib inline import numpy as np import matplotlib.pyplot as plt import xarray as xr import cartopy.crs as ccrs from sompy.sompy import SOMFactory Explanation: North Atlantic Winter Weather Regimes from a Self-Organizing Map Perspective The four weather regimes typically found over the North Atlantic ...
4,862
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', 'nerc', 'sandbox-1', 'seaice') Explanation: ES-DOC CMIP6 Model Properties - Seaice MIP Era: CMIP6 Institute: NERC Source ID: SANDBOX-1 Topic: Seaice Sub-Topics: Dynamics, Thermodynamic...
4,863
Given the following text description, write Python code to implement the functionality described below step by step Description: FloPy MT3D-USGS Example Demonstrates functionality of the flopy MT3D-USGS module using the 'Crank-Nicolson' example distributed with MT3D-USGS. Problem description Step1: Set up model dis...
Python Code: %matplotlib inline import sys import os import platform import string from io import StringIO, BytesIO import math import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt import flopy print(sys.version) print('numpy version: {}'.format(np.__version__)) print('matplotlib version: {}'.for...
4,864
Given the following text description, write Python code to implement the functionality described below step by step Description: xarray with MetPy Tutorial xarray &lt;http Step1: ...and opening some sample data to work with. Step2: While xarray can handle a wide variety of n-dimensional data (essentially anything th...
Python Code: import numpy as np import xarray as xr # Any import of metpy will activate the accessors import metpy.calc as mpcalc from metpy.cbook import get_test_data from metpy.units import units Explanation: xarray with MetPy Tutorial xarray &lt;http://xarray.pydata.org/&gt;_ is a powerful Python package that provid...
4,865
Given the following text description, write Python code to implement the functionality described below step by step Description: Comparing PHOEBE 2 vs PHOEBE Legacy NOTE Step1: As always, let's do imports and initialize a logger and a new bundle. See Building a System for more details. Step2: Adding Datasets and Co...
Python Code: !pip install -I "phoebe>=2.0,<2.1" Explanation: Comparing PHOEBE 2 vs PHOEBE Legacy NOTE: PHOEBE 1.0 legacy is an alternate backend and is not installed with PHOEBE 2.0. In order to run this backend, you'll need to have PHOEBE 1.0 installed. Setup Let's first make sure we have the latest version of PHOEBE...
4,866
Given the following text description, write Python code to implement the functionality described below step by step Description: Clustered Multitask GP (w/ Pyro/GPyTorch High-Level Interface) Introduction In this example, we use the Pyro integration for a GP model with additional latent variables. We are modelling a m...
Python Code: import math import torch import pyro import gpytorch from matplotlib import pyplot as plt %matplotlib inline %load_ext autoreload %autoreload 2 # this is for running the notebook in our testing framework import os smoke_test = ('CI' in os.environ) Explanation: Clustered Multitask GP (w/ Pyro/GPyTorch High-...
4,867
Given the following text description, write Python code to implement the functionality described below step by step Description: Static tumbling neural network Imports Step1: Load and prepare the data Import data from static tumbling csv file Step2: Separate the data into features and targets Step3: Generate global...
Python Code: %matplotlib inline %config InlineBackend.figure_format = 'retina' import pandas as pd import numpy as np import tensorflow as tf import tflearn from tflearn.data_utils import to_categorical import matplotlib.pyplot as plt from itertools import product Explanation: Static tumbling neural network Imports End...
4,868
Given the following text description, write Python code to implement the functionality described below step by step Description: Using python's cartopy package to georeference EASE-Grid 2.0 cube data This notebook demonstrates the following typical tasks you might want to do with CETB EASE-Grid 2.0 cube data Step1: R...
Python Code: %matplotlib notebook import cartopy.crs as ccrs import matplotlib.pyplot as plt from netCDF4 import Dataset import numpy as np geod = ccrs.Geodetic() e2n = ccrs.LambertAzimuthalEqualArea(central_latitude=90.0) Explanation: Using python's cartopy package to georeference EASE-Grid 2.0 cube data This notebook...
4,869
Given the following text description, write Python code to implement the functionality described below step by step Description: ES-DOC CMIP6 Model Properties - Ocean MIP Era Step1: Document Authors Set document authors Step2: Document Contributors Specify document contributors Step3: Document Publication Specify d...
Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'nims-kma', 'sandbox-3', 'ocean') Explanation: ES-DOC CMIP6 Model Properties - Ocean MIP Era: CMIP6 Institute: NIMS-KMA Source ID: SANDBOX-3 Topic: Ocean Sub-Topics: Timestepping Frame...
4,870
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', 'sandbox-1', 'seaice') Explanation: ES-DOC CMIP6 Model Properties - Seaice MIP Era: CMIP6 Institute: CMCC Source ID: SANDBOX-1 Topic: Seaice Sub-Topics: Dynamics, Thermodynamic...
4,871
Given the following text description, write Python code to implement the functionality described below step by step Description: Scraping Webpages with BeautifulSoup Lets try to get a list of all the years of all of Amitabh Bachchan movies! If you don't know, he's kind of the Sean Connery of India. BeautifulSoup lets...
Python Code: import requests r = requests.get('http://www.imdb.com/name/nm0000821') # lets look at Amitabh Bachchan's list of movies Explanation: Scraping Webpages with BeautifulSoup Lets try to get a list of all the years of all of Amitabh Bachchan movies! If you don't know, he's kind of the Sean Connery of India. Be...
4,872
Given the following text problem statement, write Python code to implement the functionality described below in problem statement Problem: use erosion operation first then dilation on the image
Python Code:: import cv2 import numpy as np %matplotlib notebook %matplotlib inline from matplotlib import pyplot as plt img = cv2.imread("hsv_ball.jpg",cv2.IMREAD_GRAYSCALE) _,mask = cv2.threshold(img, 220,255,cv2.THRESH_BINARY_INV) kernal = np.ones((5,5),np.uint8) dilation = cv2.dilate(mask,kernal,iterations = 3) ero...
4,873
Given the following text description, write Python code to implement the functionality described below step by step Description: Repeated measures ANOVA on source data with spatio-temporal clustering This example illustrates how to make use of the clustering functions for arbitrary, self-defined contrasts beyond stand...
Python Code: # Authors: Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr> # Eric Larson <larson.eric.d@gmail.com> # Denis Engemannn <denis.engemann@gmail.com> # # License: BSD (3-clause) import os.path as op import numpy as np from numpy.random import randn import matplotlib.pyplot as plt i...
4,874
Given the following text description, write Python code to implement the functionality described below step by step Description: 20160110-etl-census-with-python Related post Step1: Globals File sources Step2: Extract, transform, and load Data dictionary Step4: PUMS data Step5: PUMS estimates for user verification ...
Python Code: cd ~ # Import standard packages. import collections import functools import os import pdb # Debug with pdb. import subprocess import sys import time # Import installed packages. import numpy as np import pandas as pd # Import local packages. # Insert current directory into module search path. # Autoreload ...
4,875
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2020 Google LLC. Licensed under the Apache License, Version 2.0 (the "License"); Step1: M-layer experiments This notebook trains M-layers on the problems discussed in "Intelligent...
Python Code: # Copyright 2020 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 copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable la...
4,876
Given the following text description, write Python code to implement the functionality described below step by step Description: Structured data prediction using Vertex AI Platform Learning Objectives Create a BigQuery Dataset and Google Cloud Storage Bucket Export from BigQuery to CSVs in GCS Training on Cloud AI Pl...
Python Code: !sudo chown -R jupyter:jupyter /home/jupyter/training-data-analyst !pip install --user google-cloud-bigquery==2.26.0 Explanation: Structured data prediction using Vertex AI Platform Learning Objectives Create a BigQuery Dataset and Google Cloud Storage Bucket Export from BigQuery to CSVs in GCS Training o...
4,877
Given the following text description, write Python code to implement the functionality described below step by step Description: One interesting question for open source communities is whether they are growing. Often the founding members of a community would like to see new participants join and become active in the c...
Python Code: url = "6lo" arx = Archive(url,archive_dir="../archives") arx.data[:1] Explanation: One interesting question for open source communities is whether they are growing. Often the founding members of a community would like to see new participants join and become active in the community. This is important for co...
4,878
Given the following text description, write Python code to implement the functionality described below step by step Description: QuTiP example Step1: Energy spectrum of three coupled qubits Step2: Versions
Python Code: %matplotlib inline import matplotlib.pyplot as plt import numpy as np from numpy import pi from qutip import * Explanation: QuTiP example: Energy-levels of a quantum systems as a function of a single parameter J.R. Johansson and P.D. Nation For more information about QuTiP see http://qutip.org End of expla...
4,879
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction to TensorFlow, now leveraging tensors! In this notebook, we modify our intro to TensorFlow notebook to use tensors in place of our for loop. This is a derivation of Jared Ostmey...
Python Code: import numpy as np np.random.seed(42) import pandas as pd import matplotlib.pyplot as plt %matplotlib inline import tensorflow as tf tf.set_random_seed(42) xs = [0., 1., 2., 3., 4., 5., 6., 7.] ys = [-.82, -.94, -.12, .26, .39, .64, 1.02, 1.] fig, ax = plt.subplots() _ = ax.scatter(xs, ys) m = tf.Variabl...
4,880
Given the following text description, write Python code to implement the functionality described below step by step Description: An Interactive Monty Hall Simulation nbinteract was designed to make interactive explanations easy to create. In this tutorial, we will show the process of writing a simulation from scratch ...
Python Code: from ipywidgets import interact import numpy as np import random PRIZES = ['Car', 'Goat 1', 'Goat 2'] def monty_hall(example_num=0): ''' Simulates one round of the Monty Hall Problem. Outputs a tuple of (result if stay, result if switch, result behind opened door) where each results is one ...
4,881
Given the following text description, write Python code to implement the functionality described below step by step Description: Step5: Tutorial Step6: 2. Harmonic Oscillator Example In this first example we apply the GPFA to spike train data derived from dynamics of a harmonic oscillator defined in a 2-dimensional l...
Python Code: import numpy as np from scipy.integrate import odeint import quantities as pq import neo from elephant.spike_train_generation import inhomogeneous_poisson_process def integrated_oscillator(dt, num_steps, x0=0, y0=1, angular_frequency=2*np.pi*1e-3): Parameters ---------- dt : float ...
4,882
Given the following text description, write Python code to implement the functionality described below step by step Description: Compute MNE inverse solution on evoked data in a mixed source space Create a mixed source space and compute MNE inverse solution on evoked dataset. Step1: Set up our source space. Step2: E...
Python Code: # Author: Annalisa Pascarella <a.pascarella@iac.cnr.it> # # License: BSD (3-clause) import os.path as op import matplotlib.pyplot as plt import mne from mne.datasets import sample from mne import setup_volume_source_space from mne import make_forward_solution from mne.minimum_norm import make_inverse_opera...
4,883
Given the following text description, write Python code to implement the functionality described below step by step Description: Jupyter Notebook -- это удобно! Код организван отдельными болками. Блоки кода можно выполнять в произвольном порядке. Сочетает в себе достоинства полноценных скриптов и интерактивной оболочк...
Python Code: print(math.sqrt(4)) import math Explanation: Jupyter Notebook -- это удобно! Код организван отдельными болками. Блоки кода можно выполнять в произвольном порядке. Сочетает в себе достоинства полноценных скриптов и интерактивной оболочки. Порядок выполнения блоков указан слева от ячейки. End of explanation ...
4,884
Given the following text description, write Python code to implement the functionality described below step by step Description: Analysis of Dataset Variance Data which is collected differently, look differently. This principle extends to all data (that I can think of), and of course MRI is no exception. In the case o...
Python Code: import matplotlib.pyplot as plt %matplotlib inline import numpy as np import nibabel as nb import os from histogram_window import histogram_windowing Explanation: Analysis of Dataset Variance Data which is collected differently, look differently. This principle extends to all data (that I can think of), an...
4,885
Given the following text description, write Python code to implement the functionality described below step by step Description: Building operators Step1: Looks like exactly what we wanted! We can even check that the anticommutation relation holds Step2: It was instructive to build it ourselves, but dynamite actuall...
Python Code: from dynamite.operators import sigmax, sigmay, sigmaz, index_product # product of sigmaz along the spin chain up to index k k = 4 index_product(sigmaz(), size=k) # with that, we can easily build our operator def majorana(i): k = i//2 edge_op = sigmay(k) if (i%2) else sigmax(k) bulk = index_prod...
4,886
Given the following text description, write Python code to implement the functionality described below step by step Description: Labels We want to use the Radio Galaxy Zoo click data as training data. To do this, we first need to convert the raw click data to a useful label &mdash; most likely the $(x, y)$ coordinate ...
Python Code: import collections import operator from pprint import pprint import sqlite3 import sys import warnings import matplotlib.pyplot import numpy import scipy.stats import sklearn.mixture %matplotlib inline sys.path.insert(1, '..') import crowdastro.data import crowdastro.show warnings.simplefilter('ignore', Us...
4,887
Given the following text description, write Python code to implement the functionality described below step by step Description: Grouping all encounter nbrs under respective person nbr Step1: Now grouping other measurements and properties under encounter_nbrs Step2: Aggregating encounter entities under respective pe...
Python Code: encounter_key = 'Enc_Nbr' person_key = 'Person_Nbr' encounters_by_person = {} for df in dfs: if df is not None: df_columns =set(df.columns.values) if encounter_key in df_columns and person_key in df_columns: for row_index, dfrow in df.iterrows(): rowdict = di...
4,888
Given the following text description, write Python code to implement the functionality described below step by step Description: A count of the total number of mitochondria within the bounds (694×1794, 1750×2460, 1004×1379). Step1: We can count annotated mitochondria by referencing the mitochondria channel Step2: We...
Python Code: import ndio.remote.OCP as OCP oo = OCP() token = "kasthuri2015_ramon_v1" Explanation: A count of the total number of mitochondria within the bounds (694×1794, 1750×2460, 1004×1379). End of explanation mito_cutout = oo.get_cutout(token, 'mitochondria', 694, 1794, 1750, 2460, 1004, 1379, resolution=3) Explan...
4,889
Given the following text description, write Python code to implement the functionality described below step by step Description: Retrieve HiC dataset from NCBI We will use data from <a name="ref-1"/>(Stadhouders R, Vidal E, Serra F, Di Stefano B et al. 2018), which comes from mouse cells where Hi-C experiment where co...
Python Code: %%bash mkdir -p FASTQs fastq-dump SRR5344921 --defline-seq '@$ac.$si' -X 100000000 --split-files --outdir FASTQs/ mv FASTQs/SRR5344921_1.fastq FASTQs/mouse_B_rep1_1.fastq mv FASTQs/SRR5344921_2.fastq FASTQs/mouse_B_rep1_2.fastq fastq-dump SRR5344925 --defline-seq '@$ac.$si' -X 100000000 --split-files --out...
4,890
Given the following text description, write Python code to implement the functionality described below step by step Description: Skip-gram word2vec In this notebook, I'll lead you through using TensorFlow to implement the word2vec algorithm using the skip-gram architecture. By implementing this, you'll learn about emb...
Python Code: import time import numpy as np import tensorflow as tf import utils Explanation: Skip-gram word2vec In this notebook, I'll lead you through using TensorFlow to implement the word2vec algorithm using the skip-gram architecture. By implementing this, you'll learn about embedding words for use in natural lang...
4,891
Given the following text description, write Python code to implement the functionality described below step by step Description: Algebra Lineal con Python Esta notebook fue creada originalmente como un blog post por Raúl E. López Briega en Mi blog sobre Python. El contenido esta bajo la licencia BSD. <img alt="Algebra...
Python Code: # Vector como lista de Python v1 = [2, 4, 6] v1 # Vectores con numpy import numpy as np v2 = np.ones(3) # vector de solo unos. v2 v3 = np.array([1, 3, 5]) # pasando una lista a las arrays de numpy v3 v4 = np.arange(1, 8) # utilizando la funcion arange de numpy v4 Explanation: Algebra Lineal con Python Esta...
4,892
Given the following text description, write Python code to implement the functionality described below step by step Description: Anna KaRNNa In this notebook, I'll build a character-wise RNN trained on Anna Karenina, one of my all-time favorite books. It'll be able to generate new text based on the text from the book....
Python Code: import time from collections import namedtuple import numpy as np import tensorflow as tf Explanation: Anna KaRNNa In this notebook, I'll build a character-wise RNN trained on Anna Karenina, one of my all-time favorite books. It'll be able to generate new text based on the text from the book. This network ...
4,893
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction to Plotting with Matplotlib Matplotlib is a standard plotting package for python. Autor Step1: Import several modules which will be useful for doing plots. Step2: Scatter Plot...
Python Code: %matplotlib inline Explanation: Introduction to Plotting with Matplotlib Matplotlib is a standard plotting package for python. Autor: George Privon Preliminaries Show plots in the notebook. End of explanation import matplotlib.pyplot as plt import numpy as np Explanation: Import several modules which will ...
4,894
Given the following text description, write Python code to implement the functionality described below step by step Description: <h2>Analisi comparativa dei metodi di dosaggio degli anticorpi anti recettore del TSH</h2> <h3>Metodo Routine Step1: <h4>Importazione del file con i dati </h4> Step2: Varibili d'ambiete in...
Python Code: %matplotlib inline #importo le librerie import pandas as pd import os from __future__ import print_function,division import numpy as np import seaborn as sns os.environ["NLS_LANG"] = "ITALIAN_ITALY.UTF8" Explanation: <h2>Analisi comparativa dei metodi di dosaggio degli anticorpi anti recettore del TSH</h2>...
4,895
Given the following text description, write Python code to implement the functionality described below step by step Description: Logistic Regression (scikit-learn) Experiment Versioning & Registry <a href="https Step1: This example features Step2: Phase 1 Step3: Prepare data Step4: Prepare hyperparameters Step5: ...
Python Code: # restart your notebook if prompted on Colab try: import verta except ImportError: !pip install verta Explanation: Logistic Regression (scikit-learn) Experiment Versioning & Registry <a href="https://colab.research.google.com/github/VertaAI/modeldb/blob/master/client/workflows/demos/census-experime...
4,896
Given the following text description, write Python code to implement the functionality described below step by step Description: Homework 2, part 1 (40 points) This warm-up problem set is provided to help you get used to PyTorch. Please, only fill parts marked with "Your code here". Step1: To learn best practices $-$...
Python Code: import numpy as np import math import matplotlib.pyplot as plt %matplotlib inline import torch assert torch.__version__ >= '1.0.0' import tqdm Explanation: Homework 2, part 1 (40 points) This warm-up problem set is provided to help you get used to PyTorch. Please, only fill parts marked with "Your code her...
4,897
Given the following text description, write Python code to implement the functionality described below step by step Description: VarData Speed Calculation Comparison Notebook for calculation a VarData Test Case and have a Unit Number for Comparison For more speed calculations see VarData Speed Calculations Step1: Tes...
Python Code: import math import datetime def varData_speedCalc_comparison(test_case, test_title, test_description, test_time=None, cups_speed=250.0, substrate_size_mm=None, substrate_size_px=None, dpi_image=[360.0,360.0]): inch2mm = 25.4 # mm/inch bpp = 4.0 # bit/px if test_time == Non...
4,898
Given the following text description, write Python code to implement the functionality described below step by step Description: Notes Permuation matrices and graphs $P$ obtained by permuting rows of an identity matrix. $N!$ possile permutations possible of an identity matrix. $PA$ permutes the $i^{th}$ row of A to $\...
Python Code: from IPython.display import IFrame IFrame("./projection_onto_bistochastic_matrices.pdf", width=800, height=500) Explanation: Notes Permuation matrices and graphs $P$ obtained by permuting rows of an identity matrix. $N!$ possile permutations possible of an identity matrix. $PA$ permutes the $i^{th}$ row of...
4,899
Given the following text description, write Python code to implement the functionality described below step by step Description: Sparse Linear Inverse Demo with AMP In this demo, we illustrate how to use the vampyre package for a simple sparse linear inverse problem. The problem is to estimate a sparse vector z0 fro...
Python Code: import os import sys vp_path = os.path.abspath('../../') if not vp_path in sys.path: sys.path.append(vp_path) import vampyre as vp Explanation: Sparse Linear Inverse Demo with AMP In this demo, we illustrate how to use the vampyre package for a simple sparse linear inverse problem. The problem is to ...