Unnamed: 0
int64
0
16k
text_prompt
stringlengths
110
62.1k
code_prompt
stringlengths
37
152k
12,700
Given the following text description, write Python code to implement the functionality described below step by step Description: <table> <tr align=left><td><img align=left src="./images/CC-BY.png"> <td>Text provided under a Creative Commons Attribution license, CC-BY. All code is made available under the FSF-approve...
Python Code: %matplotlib inline import numpy as np import scipy.linalg as la import matplotlib.pyplot as plt Explanation: <table> <tr align=left><td><img align=left src="./images/CC-BY.png"> <td>Text provided under a Creative Commons Attribution license, CC-BY. All code is made available under the FSF-approved MIT li...
12,701
Given the following text description, write Python code to implement the functionality described below step by step Description: Rossmann Data preparation / Feature engineering In addition to the provided data, we will be using external datasets put together by participants in the Kaggle competition. You can download ...
Python Code: PATH=Config().data_path()/Path('rossmann/') table_names = ['train', 'store', 'store_states', 'state_names', 'googletrend', 'weather', 'test'] tables = [pd.read_csv(PATH/f'{fname}.csv', low_memory=False) for fname in table_names] train, store, store_states, state_names, googletrend, weather, test = tables l...
12,702
Given the following text description, write Python code to implement the functionality described below step by step Description: Performing Maximum Likelihood Estimates (MLEs) in IPython By Delaney Granizo-Mackenzie and Andrei Kirilenko. This notebook developed in collaboration with Prof. Andrei Kirilenko as part of t...
Python Code: import math import matplotlib.pyplot as plt import numpy as np import scipy import scipy.stats Explanation: Performing Maximum Likelihood Estimates (MLEs) in IPython By Delaney Granizo-Mackenzie and Andrei Kirilenko. This notebook developed in collaboration with Prof. Andrei Kirilenko as part of the Master...
12,703
Given the following text description, write Python code to implement the functionality described below step by step Description: <a href='http Step1: Concatenation Concatenation basically glues together DataFrames. Keep in mind that dimensions should match along the axis you are concatenating on. You can use pd.conca...
Python Code: import pandas as pd df1 = pd.DataFrame({'A': ['A0', 'A1', 'A2', 'A3'], 'B': ['B0', 'B1', 'B2', 'B3'], 'C': ['C0', 'C1', 'C2', 'C3'], 'D': ['D0', 'D1', 'D2', 'D3']}, index = [0, 1, 2, 3]) df2 = pd.DataFrame({'A': ['A4', 'A5', 'A...
12,704
Given the following text description, write Python code to implement the functionality described below step by step Description: Working with BigQuery tables and the Genomics API Case Study Step1: Next we're going to need to authenticate using the service account on the Datalab host. Step2: Now we can create a clien...
Python Code: !pip install --upgrade google-api-python-client==1.4.2 Explanation: Working with BigQuery tables and the Genomics API Case Study: BRAF V600 mutations in CCLE cell-lines In this notebook we'll show you how you might combine information available in BigQuery tables with sequence-reads that have been imported...
12,705
Given the following text description, write Python code to implement the functionality described below step by step Description: Load Data In order to expediate the testing process, I added a debug flag to the pipeline method in our pipeline file which outputs the fixed and moving images prior to registration Step1: ...
Python Code: import sys sys.path.append('../code/functions') sys.path.append('/home/simpleElastix/build/SimpleITK-build/Wrapping/Python') import pickle import cv2 import time import SimpleITK as sitk import numpy as np import matplotlib.pyplot as plt import nibabel as nib from cluster import Cluster from tiffIO import ...
12,706
Given the following text description, write Python code to implement the functionality described below step by step Description: Excercises Electric Machinery Fundamentals Chapter 1 Problem 1-16 Step1: Description The core shown in Figure P1-2 Step2: Sketch the voltage present at the terminals of the coil. SOLUTION ...
Python Code: %pylab notebook Explanation: Excercises Electric Machinery Fundamentals Chapter 1 Problem 1-16 End of explanation N = 500 dphi = array([0.010, -0.020, 0.010, 0.010]) # [Wb] dt = array([2e-3 , 3e-3, 2e-3, 1e-3]) # [s] Explanation: Description The core shown in Figure P1-2: <img src="figs/FigC_P1-2.jp...
12,707
Given the following text description, write Python code to implement the functionality described below step by step Description: Using grlc from python Being written in python itself, it is easy to use grlc from python. Here we show how to use grlc to run a SPARQL query which is stored on github. First we start by imp...
Python Code: import json import pandas as pd from io import StringIO import grlc import grlc.utils as utils import grlc.swagger as swagger Explanation: Using grlc from python Being written in python itself, it is easy to use grlc from python. Here we show how to use grlc to run a SPARQL query which is stored on github....
12,708
Given the following text description, write Python code to implement the functionality described below step by step Description: Sections Introduction to Sequential Backward Selection Further Reading Iris Example Wine Data Example Gridsearch Example 1 Gridsearch Example 2 Introduction to Sequential Backward Selection ...
Python Code: from mlxtend.sklearn import SBS from sklearn.neighbors import KNeighborsClassifier from sklearn.datasets import load_iris iris = load_iris() X = iris.data y = iris.target knn = KNeighborsClassifier(n_neighbors=4) sbs = SBS(knn, k_features=2, scoring='accuracy', cv=5) sbs.fit(X, y) print('Indices of selecte...
12,709
Given the following text description, write Python code to implement the functionality described below step by step Description: Load IPython support for working with MPI tasks Step1: Let's also load the plotting and numerical libraries so we have them ready for visualization later on. Step2: Now, we load the MPI li...
Python Code: from ipyparallel import Client, error cluster = Client() view = cluster[:] Explanation: Load IPython support for working with MPI tasks End of explanation %matplotlib inline import numpy as np import matplotlib.pyplot as plt Explanation: Let's also load the plotting and numerical libraries so we have them ...
12,710
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction This notebook demonstrates how BioThings Explorer can be used to answer the following query Step1: Step 2 Step2: The df object contains the full output from BioThings Explorer...
Python Code: from biothings_explorer.hint import Hint ht = Hint() prdx1 = ht.query("PRDX1")['Gene'][0] prdx1 Explanation: Introduction This notebook demonstrates how BioThings Explorer can be used to answer the following query: &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"Finding Marketed Drugs that Might Tre...
12,711
Given the following text description, write Python code to implement the functionality described below step by step Description: 1A.2 - Deviner la langue d'un texte (correction) Calcul d'un score pour détecter la langue d'un texte. Ce notebook aborde les dictionnaires, les fichiers et les graphiques (correction). Step...
Python Code: from jyquickhelper import add_notebook_menu add_notebook_menu() %matplotlib inline Explanation: 1A.2 - Deviner la langue d'un texte (correction) Calcul d'un score pour détecter la langue d'un texte. Ce notebook aborde les dictionnaires, les fichiers et les graphiques (correction). End of explanation def re...
12,712
Given the following text description, write Python code to implement the functionality described below step by step Description: Tables to Networks, Networks to Tables Networks can be represented in a tabular form in two ways Step1: At this point, we have our stations and trips data loaded into memory. How we constr...
Python Code: # This block of code checks to make sure that a particular directory is present. if "divvy_2013" not in os.listdir('datasets/'): print('Unzip the divvy_2013.zip file in the datasets folder.') stations = pd.read_csv('datasets/divvy_2013/Divvy_Stations_2013.csv', parse_dates=['online date'], index_col='i...
12,713
Given the following text description, write Python code to implement the functionality described below step by step Description: Transform EEG data using current source density (CSD) This script shows an example of how to use CSD [1] [2] [3]_. CSD takes the spatial Laplacian of the sensor signal (derivative in both x ...
Python Code: # Authors: Alex Rockhill <aprockhill206@gmail.com> # # License: BSD (3-clause) import numpy as np import matplotlib.pyplot as plt import mne from mne.datasets import sample print(__doc__) data_path = sample.data_path() Explanation: Transform EEG data using current source density (CSD) This script shows an ...
12,714
Given the following text description, write Python code to implement the functionality described below step by step Description: Images Step1: Get the Header-Data-Units (hdu's) from a fits file. This particular one only has 1. Step2: This 4x3x2 matrix can actually also be generated from scratch using basic numpy Ste...
Python Code: %matplotlib inline import matplotlib.pyplot as plt import numpy as np # import pyfits as fits # deprecated from astropy.io import fits Explanation: Images: rows, columns and all that jazzy mess.... Two dimensional data arrays are normally stored in column-major or row-major order. In...
12,715
Given the following text description, write Python code to implement the functionality described below step by step Description: Strategies The strategy object describes the behaviour of an agent, given its vocabulary. The main algorithms that vary among strategies are Step1: Let's create a strategy. We will also nee...
Python Code: import naminggamesal.ngstrat as ngstrat import naminggamesal.ngvoc as ngvoc Explanation: Strategies The strategy object describes the behaviour of an agent, given its vocabulary. The main algorithms that vary among strategies are: * how to choose a link (meaning-word) to enact, * how to guess a meaning fr...
12,716
Given the following text description, write Python code to implement the functionality described below step by step Description: Chapter02 1 Discrete random variable 1.1 (0-1) distribution $P(X=k)=p^k(1-p)^{1-k}, k=0,1 \space (0<p<1)$ 1.2 binomial distribution $P(X=k)=C_n^kp^k(1-p)^{n-k}, \space k=0,1,\ldots,n \space ...
Python Code: import numpy as np import matplotlib.pyplot as plt plt.plot([1,2], [1,1], linewidth=2,c='k') plt.plot([1,1], [0,1],'k--', linewidth=2) plt.plot([2,2], [0,1],'k--', linewidth=2) plt.plot([0,1], [1,1],'k--') plt.xticks([1,2],[r'$a$',r'$b$']) plt.yticks([1],[r'$\frac{1}{b-a}$']) plt.xlabel('x') plt.ylabel(r'$...
12,717
Given the following text description, write Python code to implement the functionality described below step by step Description: Inverse Kinematics (2D) Step1: Coordinate Transformation Step2: Parameters of robot arm Step3: Forward Kinematics Step4: Inverse Kinematics Numerical Solution with Jacobian NOTE
Python Code: %matplotlib notebook from matplotlib import pylab as plt from numpy import sin, cos, pi, matrix, random, linalg, asarray from scipy.linalg import pinv from __future__ import division from math import atan2 from IPython import display from ipywidgets import interact, fixed Explanation: Inverse Kinematics (2...
12,718
Given the following text description, write Python code to implement the functionality described below step by step Description: Pivoted document length normalization It is seen that in many cases normalizing the tfidf weights for each terms tends to favor weight of terms of the documents with shorter length. Pivoted ...
Python Code: %matplotlib inline from sklearn.linear_model import LogisticRegression from gensim.corpora import Dictionary from gensim.sklearn_api.tfidf import TfIdfTransformer from gensim.matutils import corpus2csc import numpy as np import matplotlib.pyplot as py import gensim.downloader as api # This function returns...
12,719
Given the following text description, write Python code to implement the functionality described below step by step Description: Powering a Machine Learning Data Store with Redis Labs Cloud This notebook demonstrates how to use the Machine Learning API for automatically analyzing each column of the IRIS dataset. In th...
Python Code: # Setup the Sci-pype environment import sys, os # Only Redis Labs is needed for this notebook: os.environ["ENV_DEPLOYMENT_TYPE"] = "RedisLabs" # Load the Sci-pype PyCore as a named-object called "core" and environment variables from src.common.load_ipython_env import * Explanation: Powering a Machine Learn...
12,720
Given the following text description, write Python code to implement the functionality described below step by step Description: Analysing Smartwatch Data This notebook gives an overview of how to use HeartPy in the analysis of raw PPG data taken from a commercial (Samsung) smartwatch device. A signal measured this wa...
Python Code: import numpy as np import heartpy as hp import pandas as pd import matplotlib.pyplot as plt df = pd.read_csv('raw_ppg.csv') df.keys() Explanation: Analysing Smartwatch Data This notebook gives an overview of how to use HeartPy in the analysis of raw PPG data taken from a commercial (Samsung) smartwatch dev...
12,721
Given the following text description, write Python code to implement the functionality described below step by step Description: Don't forget to delete the hdmi_out and hdmi_in when finished Image Overlay 256 Color Filter Example In this notebook, we will overlay an image on the output videofeed. By default, an image ...
Python Code: from pynq.drivers.video import HDMI from pynq import Bitstream_Part from pynq.board import Register from pynq import Overlay Overlay("demo.bit").download() Explanation: Don't forget to delete the hdmi_out and hdmi_in when finished Image Overlay 256 Color Filter Example In this notebook, we will overlay an ...
12,722
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction This IPython notebook illustrates how to select the best learning based matcher. First, we need to import py_entitymatching package and other libraries as follows Step1: Then, ...
Python Code: # Import py_entitymatching package import py_entitymatching as em import os import pandas as pd # Set the seed value seed = 0 !ls $datasets_dir # Get the datasets directory datasets_dir = em.get_install_path() + os.sep + 'datasets' path_A = datasets_dir + os.sep + 'dblp_demo.csv' path_B = datasets_dir + o...
12,723
Given the following text description, write Python code to implement the functionality described below step by step Description: Pydiffexp The pydiffexp package is meant to provide an interface between R and Python to do differential expression analysis. Imports Step1: Load Data Each DEAnalysis object (DEA) operates ...
Python Code: import pandas as pd from pydiffexp import DEAnalysis Explanation: Pydiffexp The pydiffexp package is meant to provide an interface between R and Python to do differential expression analysis. Imports End of explanation test_path = "/Users/jfinkle/Documents/Northwestern/MoDyLS/Python/sprouty/data/raw_data/a...
12,724
Given the following text description, write Python code to implement the functionality described below step by step Description: pyIAST example (N$_2$, CO$_2$, H$_2$O) data from Mason et al. here construct models for pure-component adsorption isotherms Step1: binary (CO$_2$/N$_2$ adsorption) CO$_2$ partial pressure S...
Python Code: df_N2 = pd.read_csv("N2.csv", skiprows=1) N2_isotherm = pyiast.ModelIsotherm(df_N2, loading_key="Loading(mmol/g)", pressure_key="P(bar)", model='Henry') pyiast.plot_isotherm(N2_isotherm) N2_isotherm.print_params() df_CO2 = pd.read_csv("CO2.csv", skiprows=1) CO2_iso...
12,725
Given the following text description, write Python code to implement the functionality described below step by step Description: Profiling BatchFlow code A profile is a set of statistics that describes how often and for how long various parts of the program executed. This notebooks shows how to profile various parts o...
Python Code: import sys sys.path.append("../../..") from batchflow import B, V, W from batchflow.opensets import MNIST from batchflow.models.torch import ResNet18 dataset = MNIST() Explanation: Profiling BatchFlow code A profile is a set of statistics that describes how often and for how long various parts of the progr...
12,726
Given the following text description, write Python code to implement the functionality described below step by step Description: Bayesian MLP for MNIST using preconditioned SGLD We use the Jax Bayes library by James Vuckovic to fit an MLP to MNIST using SGD, and SGLD (with RMS preconditioning). Code is based on Ste...
Python Code: %%capture !pip install git+https://github.com/deepmind/dm-haiku !pip install git+https://github.com/jamesvuc/jax-bayes import haiku as hk import jax.numpy as jnp from jax.experimental import optimizers import jax import jax_bayes import sys, os, math, time import numpy as onp import numpy as np from functo...
12,727
Given the following text description, write Python code to implement the functionality described below step by step Description: Imports and setup Imports Step4: Common functions Step5: Get charges Calculate RESP charges using Gaussian through submit_gaussian for use with GAFF. Step6: Parameterize molecule in GAFF ...
Python Code: import re, os, sys, shutil import shlex, subprocess import glob import pandas as pd import panedr import numpy as np import MDAnalysis as mda import nglview import matplotlib.pyplot as plt import parmed as pmd import py import scipy from scipy import stats from importlib import reload from thtools import c...
12,728
Given the following text description, write Python code to implement the functionality described below step by step Description: Pandas CLEPY - August Module of the month Anurag Saxena @_asaxena Pandas - Python Data Analysis Library pandas.pydata.org Open Source High Performance Easy to use Data Structures and Data An...
Python Code: import pandas as pd import numpy as np Explanation: Pandas CLEPY - August Module of the month Anurag Saxena @_asaxena Pandas - Python Data Analysis Library pandas.pydata.org Open Source High Performance Easy to use Data Structures and Data Analysis Tools End of explanation obj = pd.Series([1,3,4,5,6,7,8,9]...
12,729
Given the following text description, write Python code to implement the functionality described below step by step Description: Simple implementation of network propagation from Vanunu et. al. Author Step1: Load the interactome from Barabasi paper Interactome downloaded from supplemental materials of http Step2: Lo...
Python Code: # import some useful packages import numpy as np import matplotlib.pyplot as plt import seaborn import networkx as nx import pandas as pd import random # latex rendering of text in graphs import matplotlib as mpl mpl.rc('text', usetex = False) mpl.rc('font', family = 'serif') import sys #sys.path.append('/...
12,730
Given the following text description, write Python code to implement the functionality described below step by step Description: Functions from Stream to Stream This module describes one way of creating functions from a single stream to a single stream. Other ways of mapping a single input stream to a single output st...
Python Code: import os import sys sys.path.append("../") from IoTPy.core.stream import Stream, run from IoTPy.agent_types.op import map_element from IoTPy.agent_types.basics import fmap_e from IoTPy.helper_functions.recent_values import recent_values @fmap_e def f(v): return v+10 # f is a function that maps a stream to...
12,731
Given the following text description, write Python code to implement the functionality described below step by step Description: Planning Algorithms Do you remember on lesson 2 and 3 we discussed algorithms that basically solve MDPs? That is, find a policy given a exact representation of the environment. In this secti...
Python Code: import numpy as np import pandas as pd import tempfile import pprint import json import sys import gym from gym import wrappers from subprocess import check_output from IPython.display import HTML Explanation: Planning Algorithms Do you remember on lesson 2 and 3 we discussed algorithms that basically solv...
12,732
Given the following text description, write Python code to implement the functionality described below step by step Description: Parallelization emcee supports parallelization out of the box. The algorithmic details are given in the paper but the implementation is very simple. The parallelization is applied across the...
Python Code: import emcee3 import numpy as np def log_prob(x): return -0.5 * np.sum(x ** 2) ndim, nwalkers = 10, 100 with emcee3.pools.InterruptiblePool() as pool: ensemble = emcee3.Ensemble(log_prob, np.random.randn(nwalkers, ndim), pool=pool) sampler = emcee3.Sampler() sampler.run(ensemble, 1000) Expl...
12,733
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction to pandas by Maxwell Margenot Part of the Quantopian Lecture Series Step1: With pandas, it is easy to store, visualize, and perform calculations on your data. With only a few l...
Python Code: import numpy as np import pandas as pd import matplotlib.pyplot as plt Explanation: Introduction to pandas by Maxwell Margenot Part of the Quantopian Lecture Series: www.quantopian.com/lectures github.com/quantopian/research_public pandas is a Python library that provides a collection of powerful data stru...
12,734
Given the following text description, write Python code to implement the functionality described below step by step Description: IPython & D3 Let's start with a few techniques for working with data in ipython and then build a d3 network graph. Step1: JS with IPython? The nice thing about IPython is that we can write ...
Python Code: # import requirments from IPython.display import Image from IPython.display import display from IPython.display import HTML from datetime import * import json from copy import * from pprint import * import pandas as pd import numpy as np import matplotlib.pyplot as plt import json from ggplot import * imp...
12,735
Given the following text description, write Python code to implement the functionality described below step by step Description: This example demonstrated that Flexx apps can be run interactively in the notebook. Step1: Any widget can be shown by using it as a cell output Step2: Because apps are really just Widgets,...
Python Code: from flexx import app, ui, react app.init_notebook() # A bit of boilerplate to import an example app import sys #sys.path.insert(0, r'C:\Users\almar\dev\flexx\examples\ui') sys.path.insert(0, '/home/almar/dev/pylib/flexx/examples/ui') from twente_temperature import Twente Explanation: This example demonstr...
12,736
Given the following text description, write Python code to implement the functionality described below step by step Description: PyBPS Tutorial 1. Initialization The first thing to do is obviously to import the pybps package. At the same time, we also import other useful packages. Step1: Once the pybps is imported in...
Python Code: import pybps import os import sys import re import sqlite3 import pandas as pd from pandas.io import sql import matplotlib.pyplot as plt Explanation: PyBPS Tutorial 1. Initialization The first thing to do is obviously to import the pybps package. At the same time, we also import other useful packages. End ...
12,737
Given the following text description, write Python code to implement the functionality described below step by step Description: Data Preparation Let's get a look on our Pokémons. The function below will plot all the sprites of a specific Pokémon on screen. That way we can have an idea of what kind of problem we can f...
Python Code: %matplotlib inline from utility.plot import plot_all #Plotting Bulbassaur ID = 1 plot_all(1) #Plotting Charmander ID = 4 plot_all(4) #Plotting Squirtle ID = 7 plot_all(7) Explanation: Data Preparation Let's get a look on our Pokémons. The function below will plot all the sprites of a specific Pokémon on sc...
12,738
Given the following text description, write Python code to implement the functionality described below step by step Description: K Means Clustering with Python K Means Clustering is an unsupervised learning algorithm that tries to cluster data based on their similarity. Unsupervised learning means that there is no out...
Python Code: import seaborn as sns import matplotlib.pyplot as plt %matplotlib inline Explanation: K Means Clustering with Python K Means Clustering is an unsupervised learning algorithm that tries to cluster data based on their similarity. Unsupervised learning means that there is no outcome to be predicted, and the a...
12,739
Given the following text description, write Python code to implement the functionality described below step by step Description: Playing with the Gaussian Distribution There was a statement I saw online Step1: I created a function that takes the observation, mean and standard deviation and returns the z-score. Notic...
Python Code: def z_score(x, m, s): return (x - m) / s Explanation: Playing with the Gaussian Distribution There was a statement I saw online: "I don't know anyone with an IQ above 7 that respects Hillary Clinton." Of course, the person is trying to sound smart and snarky but I don't think they pull it off very well...
12,740
Given the following text description, write Python code to implement the functionality described below step by step Description: VisPy colormaps This notebook illustrates the colormap API provided by VisPy. List all colormaps Step1: Discrete colormaps Discrete colormaps can be created by giving a list of colors, and ...
Python Code: import numpy as np from vispy.color import (get_colormap, get_colormaps, Colormap) from IPython.display import display_html for cmap in get_colormaps(): display_html('<h3>%s</h3>' % cmap, raw=True) display_html(get_colormap(cmap)) Explanation: VisPy colormaps This notebook illustrates the colormap ...
12,741
Given the following text description, write Python code to implement the functionality described below step by step Description: Estimation of a Categorical distribution Maximum Likelihood Estimation We observe a dataset ${x^{(n)}}_{n=1\dots N}$. The model for a single observation is a categorical distribution with pa...
Python Code: # %load template_equations.py from IPython.display import display, Math, Latex, HTML import notes_utilities as nut from importlib import reload reload(nut) Latex('$\DeclareMathOperator{\trace}{Tr}$') L = nut.pdf2latex_dirichlet(x=r'\pi', a=r'a',N=r'I', i='i') display(HTML(nut.eqs2html_table(L))) Explanatio...
12,742
Given the following text description, write Python code to implement the functionality described below step by step Description: Batch Serving Design Pattern This notebook demonstrates the Batch Serving design pattern using BigQuery Simple text classification model Let's use the same model that was used in serving_fun...
Python Code: !find export/probs/ %%bash LOCAL_DIR=$(find export/probs | head -2 | tail -1) BUCKET=ai-analytics-solutions-kfpdemo gsutil rm -rf gs://${BUCKET}/mlpatterns/batchserving gsutil cp -r $LOCAL_DIR gs://${BUCKET}/mlpatterns/batchserving gsutil ls gs://${BUCKET}/mlpatterns/batchserving Explanation: Batch Serving...
12,743
Given the following text description, write Python code to implement the functionality described below step by step Description: Lab 2 - Logistic Regression (LR) with MNIST This lab corresponds to Module 2 of the "Deep Learning Explained" course. We assume that you have successfully completed Lab 1 (Downloading the MN...
Python Code: # Figure 1 Image(url= "http://3.bp.blogspot.com/_UpN7DfJA0j4/TJtUBWPk0SI/AAAAAAAAABY/oWPMtmqJn3k/s1600/mnist_originals.png", width=200, height=200) Explanation: Lab 2 - Logistic Regression (LR) with MNIST This lab corresponds to Module 2 of the "Deep Learning Explained" course. We assume that you have succ...
12,744
Given the following text description, write Python code to implement the functionality described below step by step Description: Cython The Cython language is a superset of the Python language that additionally supports calling C functions and declaring C types on variables and class attributes. This allows the comp...
Python Code: import numpy as np Explanation: Cython The Cython language is a superset of the Python language that additionally supports calling C functions and declaring C types on variables and class attributes. This allows the compiler to generate very efficient C code from Cython code. Write Python code that call...
12,745
Given the following text description, write Python code to implement the functionality described below step by step Description: Data passing tutorial Data passing is the most important aspect of Pipelines. In Kubeflow Pipelines, the pipeline authors compose pipelines by creating component instances (tasks) and connec...
Python Code: from typing import NamedTuple import kfp from kfp.components import InputPath, InputTextFile, OutputPath, OutputTextFile from kfp.components import func_to_container_op from kfp_tekton.compiler import TektonCompiler import os os.environ["DEFAULT_ACCESSMODES"] = "ReadWriteMany" os.environ["DEFAULT_STORAGE_S...
12,746
Given the following text description, write Python code to implement the functionality described below step by step Description: First, here's the SPA power function Step1: Here are two helper functions for computing the dot product over space, and for plotting the results Step2: So, that lets us take a vector and t...
Python Code: def power(s, e): x = np.fft.ifft(np.fft.fft(s.v) ** e).real return spa.SemanticPointer(data=x) Explanation: First, here's the SPA power function: End of explanation def spatial_dot(v, X, Y, Z, xs, ys, transform=1): if isinstance(v, spa.SemanticPointer): v = v.v vs = np.zeros((len(ys...
12,747
Given the following text description, write Python code to implement the functionality described below step by step Description: DV360 Report To BigQuery Move existing DV360 reports into a BigQuery table. License Copyright 2020 Google LLC, Licensed under the Apache License, Version 2.0 (the "License"); you may not use...
Python Code: !pip install git+https://github.com/google/starthinker Explanation: DV360 Report To BigQuery Move existing DV360 reports into a BigQuery table. License Copyright 2020 Google LLC, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License....
12,748
Given the following text problem statement, write Python code to implement the functionality described below in problem statement Problem: i am trying to do hyperparemeter search with using scikit-learn's GridSearchCV on XGBoost. During gridsearch i'd like it to early stop, since it reduce search time drastically and (...
Problem: import numpy as np import pandas as pd import xgboost.sklearn as xgb from sklearn.model_selection import GridSearchCV from sklearn.model_selection import TimeSeriesSplit gridsearch, testX, testY, trainX, trainY = load_data() assert type(gridsearch) == sklearn.model_selection._search.GridSearchCV assert type(tr...
12,749
Given the following text description, write Python code to implement the functionality described below step by step Description: Iterables Some steps in a neuroimaging analysis are repetitive. Running the same preprocessing on multiple subjects or doing statistical inference on multiple files. To prevent the creation ...
Python Code: from nipype import Node, Workflow from nipype.interfaces.fsl import BET, IsotropicSmooth # Initiate a skull stripping Node with BET skullstrip = Node(BET(mask=True, in_file='/data/ds000114/sub-01/ses-test/anat/sub-01_ses-test_T1w.nii.gz'), name="skullstrip") Explanat...
12,750
Given the following text description, write Python code to implement the functionality described below step by step Description: About This notebook demonstrates classifiers, which are provided by Reproducible experiment platform (REP) package. <br /> REP contains following classifiers * scikit-learn * TMVA * XGBoost...
Python Code: !cd toy_datasets; wget -O MiniBooNE_PID.txt -nc MiniBooNE_PID.txt https://archive.ics.uci.edu/ml/machine-learning-databases/00199/MiniBooNE_PID.txt import numpy, pandas from rep.utils import train_test_split from sklearn.metrics import roc_auc_score data = pandas.read_csv('toy_datasets/MiniBooNE_PID.txt', ...
12,751
Given the following text description, write Python code to implement the functionality described below step by step Description: Regression Timothy Helton <a id='toc'></a> Table of Contents Imports Framework Correlation Grid Function Correlation Heatmap Function Plot Regression Function Plot Residuals Function Predict...
Python Code: from collections import OrderedDict import itertools import os import os.path as osp import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns import statsmodels.api as sm import statsmodels.formula.api as smf import statsmodels.graphics.regressionplots as smrp import sta...
12,752
Given the following text description, write Python code to implement the functionality described below step by step Description: ASE Analysis Step1: General This is Table S8 from the 2015 GTEx paper. Total sites ≥30 reads | Sites 30 reads ASE p &lt; 0.005 | Sites 30 reads ASE p &lt; 0.005 (%) Minimum ...
Python Code: import cPickle import glob import gzip import os import random import shutil import subprocess import sys import cdpybio as cpb import matplotlib.pyplot as plt import numpy as np import pandas as pd pd.options.mode.chained_assignment = None import pybedtools as pbt from scipy.stats import fisher_exact impo...
12,753
Given the following text description, write Python code to implement the functionality described below step by step Description: Population rate model of generalized integrate-and-fire neurons This script simulates a finite network of generalized integrate-and-fire (GIF) neurons directly on the mesoscopic population l...
Python Code: %matplotlib inline import matplotlib import numpy as np import matplotlib.pyplot as plt import nest Explanation: Population rate model of generalized integrate-and-fire neurons This script simulates a finite network of generalized integrate-and-fire (GIF) neurons directly on the mesoscopic population level...
12,754
Given the following text description, write Python code to implement the functionality described below step by step Description: First approach Write a function that reads an xyz trajectory file in. We are going to need to be able to separate numbers from atomic symbols; an XYZ trajectory file looks like Step1: CODIN...
Python Code: def skeleton_naive_xyz_parser(path): ''' Simple xyz parser. ''' # Read in file lines = None with open(path) as f: lines = f.readlines() # Process lines # ... # Return processed lines # ... return lines lines = skeleton_naive_xyz_parser(xyz_path) lines...
12,755
Given the following text description, write Python code to implement the functionality described below step by step Description: <font color='blue'>Data Science Academy - Python Fundamentos - Capítulo 14</font> Download Step1: Web Scraping
Python Code: # Versão da Linguagem Python from platform import python_version print('Versão da Linguagem Python Usada Neste Jupyter Notebook:', python_version()) Explanation: <font color='blue'>Data Science Academy - Python Fundamentos - Capítulo 14</font> Download: http://github.com/dsacademybr End of explanation # Bi...
12,756
Given the following text description, write Python code to implement the functionality described below step by step Description: Cython, que no CPython No, no nos hemos equivocado en el título, hoy vamos a hablar de Cython. ¿Qué es Cython? Cython son dos cosas Step1: Creamos una matriz cuadrada relativamente grande (...
Python Code: import numpy as np import matplotlib.pyplot as plt %matplotlib inline Explanation: Cython, que no CPython No, no nos hemos equivocado en el título, hoy vamos a hablar de Cython. ¿Qué es Cython? Cython son dos cosas: Por una parte, Cython es un lenguaje de programación (un superconjunto de Python) que une P...
12,757
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction to Non-Personalized Recommenders The recommendation problem Recommenders have been around since at least 1992. Today we see different flavours of recommenders, deployed across d...
Python Code: from IPython.core.display import Image Image(filename='./imgs/recsys_arch.png') Explanation: Introduction to Non-Personalized Recommenders The recommendation problem Recommenders have been around since at least 1992. Today we see different flavours of recommenders, deployed across different verticals: Am...
12,758
Given the following text description, write Python code to implement the functionality described below step by step Description: A Simple Autoencoder We'll start off by building a simple autoencoder to compress the MNIST dataset. With autoencoders, we pass input data through an encoder that makes a compressed represen...
Python Code: %matplotlib inline import numpy as np import tensorflow as tf import matplotlib.pyplot as plt from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets('MNIST_data', validation_size=0) Explanation: A Simple Autoencoder We'll start off by building a simple autoencoder to c...
12,759
Given the following text description, write Python code to implement the functionality described below step by step Description: After Funding Funding이 시작되기 전에는 예측이 어려웠다면 Funding이 시작된 이후에는 예측을 할 수 있을까? Funding이 시작된 이후 5일까지 각 날짜별로 얼마만큼의 금액이 펀딩되어야 최종적으로 성공할 것인지 예측 Attributes Step1: 1. Distribution Test Step2: 성공/실패 프...
Python Code: from sklearn.neighbors import KNeighborsClassifier from sklearn.naive_bayes import GaussianNB from sklearn.ensemble import RandomForestClassifier from sklearn.cross_validation import cross_val_score from sklearn.cross_validation import KFold from sklearn.cross_validation import StratifiedKFold from sklearn...
12,760
Given the following text description, write Python code to implement the functionality described below step by step Description: Tutorial Step1: We create a three-dimansional vector field with domain that spans between Step2: Now, we can create a vector field object and initialise it so that Step3: Please note, tha...
Python Code: from oommffield import Field, read_oommf_file Explanation: Tutorial: Manipulating OOMMF vector field files In this tutorial, reading and writing of OOMMF vector field files (omf and ohf) are demonstrated. As usual, we need to import the Field class, but this time also the read_oommf_file function. End of e...
12,761
Given the following text description, write Python code to implement the functionality described below step by step Description: Transform QCLCD Data Function Step1: Load The Data as CSV This is QCLCD data for PDX. It is what will be used to train the model. Step2: Run The Model and Fit Predictions
Python Code: # downloaded weather data from http://www.ncdc.noaa.gov/qclcd/QCLCD def load_weather_frame(filename): #load the weather data and make a date data_raw = pd.read_csv(filename, dtype={'Time': str, 'Date': str}) data_raw['WetBulbCelsius'] = data_raw['WetBulbCelsius'].astype(float) times = [] ...
12,762
Given the following text description, write Python code to implement the functionality described below step by step Description: Matplotlib Introduction Matplotlib is a library for producing publication-quality figures. mpl (for short) was designed from the bottom-up to serve dual-purposes. First, to allow for interac...
Python Code: import matplotlib print(matplotlib.__version__) print(matplotlib.get_backend()) Explanation: Matplotlib Introduction Matplotlib is a library for producing publication-quality figures. mpl (for short) was designed from the bottom-up to serve dual-purposes. First, to allow for interactive, cross-platform con...
12,763
Given the following text description, write Python code to implement the functionality described below step by step Description: Chapter 5 Step1: 5-1-3. モデルの評価 性能を測るといっても,その目的によって指標を変える必要がある. どのような問題で,どのような指標を用いることが一般的か?という問いに対しては,先行研究を確認することを勧める. また,指標それぞれの特性(数学的な意味)を知っていることもその役に立つだろう. 参考文献 Step2: 5-2. 問題に合わせたコーディ...
Python Code: # 1. データセットを用意する from sklearn import datasets iris = datasets.load_iris() # ここではIrisデータセットを読み込む print(iris.data[0], iris.target[0]) # 1番目のサンプルのデータとラベル # 2.学習用データとテスト用データに分割する from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(iris.data, iris.target) # 3...
12,764
Given the following text description, write Python code to implement the functionality described below step by step Description: In this notebook, we will use Long Short Term Memory RNN to develop a time series forecasting model. The dataset used for the examples of this notebook is on air pollution measured by concen...
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 #Read the dataset into a pandas.DataFrame df = pd.read_csv('datasets/PRSA_data_2010.1.1-2014.12.31.csv') print('Sha...
12,765
Given the following text description, write Python code to implement the functionality described below step by step Description: FDMS TME3 Kaggle How Much Did It Rain? II Florian Toque & Paul Willot Notes We tried different model, like SVM regression, MLP, Random Forest and KNN as recommanded by the winning team of ...
Python Code: # from __future__ import exam_success from __future__ import absolute_import from __future__ import print_function %matplotlib inline import sklearn import matplotlib.pyplot as plt import seaborn as sns import numpy as np import random import pandas as pd import scipy.stats as stats # Sk cheatsfrom sklearn...
12,766
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2019 The TensorFlow Authors. Step1: 훈련 후 정수 양자화 <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https Step2: TensorFlow 모델 생성하기 MNIST 데이터세트에...
Python Code: #@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # dist...
12,767
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Lesson 6 - Supervised Learning Machine learning (ML) The sentiment analysis program we wrote earlier (in session 1) adopts a non-machine learning algorithm. That is, it tries to defin...
Python Code: def feature_extractor(word): Extract the features for a given word and return a dictonary of the features start_letter = word[0] last_letter = word[-1] return {'start_letter' : start_letter,'last_letter' : last_letter} def main(): print(feature_extractor('poonacha')) main() E...
12,768
Given the following text description, write Python code to implement the functionality described below step by step Description: Calculation of Equilibrium Concentrations in Competitive Binding Experiment This notebook uses analytical solution of equilibrium expressions for 2 ligands competing for 1 population of prot...
Python Code: import matplotlib.pyplot as plt import numpy as np import seaborn as sns from IPython.display import display, Math, Latex #Do we even need this anymore? %pylab inline Explanation: Calculation of Equilibrium Concentrations in Competitive Binding Experiment This notebook uses analytical solution of equilibri...
12,769
Given the following text description, write Python code to implement the functionality described below step by step Description: Simply use the metric we created to define the quality of a app. If the weighted rating is no less than 4.0, it can be seen as a good app. If the weighted rating is no more than 2.5, it is a...
Python Code: good_app = app.loc[app['weighted_rating'] >=4.0] bad_app = app.loc[app['weighted_rating'] <=2.5] good_app = good_app.reset_index(drop=True) bad_app = bad_app.reset_index(drop=True) category = app['category'] cate_list = [] for i in category.unique(): cate = i.lower() cate_list.append(cate) Explanat...
12,770
Given the following text description, write Python code to implement the functionality described below step by step Description: SINGA Core Classes <img src="http Step1: NOTE Step2: Tensor A tensor instance represents a multi-dimensional array allocated on a device instance. It provides linear algbra operations, lik...
Python Code: from singa import device default_dev = device.get_default_device() gpu = device.create_cuda_gpu() # the first gpu device gpu Explanation: SINGA Core Classes <img src="http://singa.apache.org/en/_static/images/singav1-sw.png" width="500px"/> Device A device instance represents a hardware device with multip...
12,771
Given the following text description, write Python code to implement the functionality described below step by step Description: <img src="../../../../images/qiskit-heading.gif" alt="Note Step1: In this section, we first judge the version of Python and import the packages of qiskit, math to implement the following co...
Python Code: # import math lib from math import pi # import Qiskit from qiskit import Aer, IBMQ, execute from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister # import basic plot tools from qiskit.tools.visualization import plot_histogram # To use local qasm simulator backend = Aer.get_backend('qasm_sim...
12,772
Given the following text description, write Python code to implement the functionality described below step by step Description: Logic This Jupyter notebook acts as supporting material for topics covered in Chapter 6 Logical Agents, Chapter 7 First-Order Logic and Chapter 8 Inference in First-Order Logic of the book A...
Python Code: from utils import * from logic import * from notebook import psource Explanation: Logic This Jupyter notebook acts as supporting material for topics covered in Chapter 6 Logical Agents, Chapter 7 First-Order Logic and Chapter 8 Inference in First-Order Logic of the book Artificial Intelligence: A Modern Ap...
12,773
Given the following text description, write Python code to implement the functionality described below step by step Description: 先说明一下,特殊方法的存在是为了被 Python 解释器调用的,我们自己不需要调用它。也就是说没有 my_object.__len__() 这种写法,而是应该使用 len(my_object)。一般来说,通过内置函数(len, iter, str 等等)来使用特殊方法是最好的选择,这些内置函数不仅会调用特殊方法,通常还会提供特殊的好处。而且对于内置类来说,它的速度更快。 实现向...
Python Code: from math import hypot class Vector: def __init__(self, x = 0, y = 0): self.x = x self.y = y def __repr__(self): # %r 获取对象各个属性标准字符串表现形式,这是个好习惯,它说明了一个关键点,Vector(1,2) 和 vector('1','2') 是不一样的 # 后者会在定义的时候报错,因为对象的构造只接收数值,不接受字符串 return "Vector(%r, %r)" % (self...
12,774
Given the following text description, write Python code to implement the functionality described below step by step Description: Estructuras de datos Python posee además de los tipos de datos básicos, otros tipos de datos más complejos. Se trata de las tuplas, las listas y los diccionarios. Estos tres tipos, pueden al...
Python Code: # Ejemplo de lista, los valores van entre corchetes una_lista = [4, "Hola", 6.0, 99 ] # Ejemplo de tupla, los valores van entre paréntesis una_tupla = (4, "Hola", 6.0, 99) print ("Lista: " , una_lista) print ("Tupla: " , una_tupla) # Las tuplas y las listas aceptan operadores de comparación y devuelven un ...
12,775
Given the following text description, write Python code to implement the functionality described below step by step Description: Tree 定义 一棵二叉树的定义如下。key可以存储任意的对象,亦即每棵树也可以是其他树的子树。 Step1: 遍历 前序 中序 后序 Step2: 二叉堆实现优先队列 二叉堆是队列的一种实现方式。 二叉堆可以用完全二叉树来实现。所谓完全二叉树(complete binary tree),有定义如下: A complete binary tree is a binary t...
Python Code: class BinaryTree(): def __init__(self, root_obj): self.key = root_obj self.left_child = None self.right_child = None def insert_left(self, new_node): # if the tree do not have a left child # then create a node: one tree without children if self.l...
12,776
Given the following text description, write Python code to implement the functionality described below step by step Description: Is Augmentation Necessary? In this notebook, we will check how the network trained on ordinary data copes with the augmented data and what will happen if it is learned from the augmented dat...
Python Code: import sys import numpy as np import matplotlib.pyplot as plt from tqdm import tqdm_notebook as tqn %matplotlib inline sys.path.append('../../..') sys.path.append('../../utils') import utils from secondbatch import MnistBatch from simple_conv_model import ConvModel from batchflow import V, B from batchflow...
12,777
Given the following text description, write Python code to implement the functionality described below step by step Description: In this notebook, we will show how to load pre-trained models and draw things with sketch-rnn Step3: define the path of the model you want to load, and also the path of the dataset Step4: ...
Python Code: # import the required libraries import numpy as np import time import random import cPickle import codecs import collections import os import math import json import tensorflow as tf from six.moves import xrange # libraries required for visualisation: from IPython.display import SVG, display import PIL fro...
12,778
Given the following text description, write Python code to implement the functionality described below step by step Description: Domain DPAPI Backup Key Extraction Metadata | | | | Step1: Download & Process Mordor Dataset Step2: Analytic I Monitor for any SecretObject with the string BCKUPKEY in...
Python Code: from openhunt.mordorutils import * spark = get_spark() Explanation: Domain DPAPI Backup Key Extraction Metadata | | | |:------------------|:---| | collaborators | ['@Cyb3rWard0g', '@Cyb3rPandaH'] | | creation date | 2019/06/20 | | modification date | 2020/09/20 | | playbook rel...
12,779
Given the following text description, write Python code to implement the functionality described below step by step Description: This notebook is a brief sketch of how to use Grover's algorithm. We start by declaring all necessary imports. Step1: Grover's algorithm can be used to amplify the probability of an oracle-...
Python Code: from itertools import product from mock import patch from grove.amplification.grover import Grover Explanation: This notebook is a brief sketch of how to use Grover's algorithm. We start by declaring all necessary imports. End of explanation target_bitstring = '010' bit = ("0", "1") bitstring_map = {} targ...
12,780
Given the following text description, write Python code to implement the functionality described below step by step Description: Bayesian Linear Regression Computational bayes final project. Nathan Yee Uma Desai First example to gain understanding is taken from Cypress Frankenfeld. http Step1: Load data from csv fi...
Python Code: from __future__ import print_function, division % matplotlib inline import warnings warnings.filterwarnings('ignore') import math import numpy as np from thinkbayes2 import Pmf, Cdf, Suite, Joint, EvalNormalPdf import thinkplot import pandas as pd import matplotlib.pyplot as plt Explanation: Bayesian Linea...
12,781
Given the following text description, write Python code to implement the functionality described below step by step Description: This script shows how to use the existing code in opengrid to create a baseload electricity consumption benchmark. Step1: Script settings Step2: We create one big dataframe, the columns ar...
Python Code: import os, sys import inspect import numpy as np import datetime as dt import time import pytz import pandas as pd import pdb script_dir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) # add the path to opengrid to sys.path sys.path.append(os.path.join(script_dir, os.pardir, os....
12,782
Given the following text description, write Python code to implement the functionality described below step by step Description: Fitting Models Exercise 1 Imports Step1: Fitting a quadratic curve For this problem we are going to work with the following model Step2: First, generate a dataset using this model using th...
Python Code: %matplotlib inline import matplotlib.pyplot as plt import numpy as np import scipy.optimize as opt Explanation: Fitting Models Exercise 1 Imports End of explanation a_true = 0.5 b_true = 2.0 c_true = -4.0 Explanation: Fitting a quadratic curve For this problem we are going to work with the following model:...
12,783
Given the following text description, write Python code to implement the functionality described below step by step Description: Analysis of DSLWP-B 2018-08-12 SSDV transmission This notebook analyzes SSDV transmissions made by DSLWP-B from the Moon. Step1: We load a file containing the relevant GMSK transmission. Th...
Python Code: %matplotlib inline import numpy as np import scipy.signal import matplotlib.pyplot as plt Explanation: Analysis of DSLWP-B 2018-08-12 SSDV transmission This notebook analyzes SSDV transmissions made by DSLWP-B from the Moon. End of explanation x = np.fromfile('/home/daniel/Descargas/DSLWP-B_PI9CAM_2018-08-...
12,784
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: <H2>Distance from a point to a line</H2> \begin{equation} \frac{|Ax+By+C|}{\sqrt{A^2+B^2}}. \end{equation} Step3: <H2>Distance from a point the identity line</H2> \begin{equation} \...
Python Code: def distance(mypoint, myline): Calculates the distance from a point to a line x, y = mypoint A, B, C = myline return np.abs(A*x + B*y + C) / np.sqrt(np.power(A,2)+np.power(B,2)) mypoint = (5,1) myline = (3,-1, 1) distance(mypoint, myline) # 15/np.sqrt(10) ...
12,785
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Fully-Connected Neural Nets In the previous homework you implemented a fully-connected two-layer neural network on CIFAR-10. The implementation was simple but not very modular since t...
Python Code: # As usual, a bit of setup from __future__ import print_function import time import numpy as np import matplotlib.pyplot as plt from cs231n.classifiers.fc_net import * from cs231n.data_utils import get_CIFAR10_data from cs231n.gradient_check import eval_numerical_gradient, eval_numerical_gradient_array fro...
12,786
Given the following text description, write Python code to implement the functionality described below step by step Description: Comparing collections (Part Two) Motivation Review Part I Describe what we want Kendall's tau Rank-biased overlap Apply to data Inspired by "A Similarity Measure for Indefinite Rankings", ht...
Python Code: import yaml import time import operator import string import re import csv import random import nltk.tokenize from sklearn.feature_extraction import text import twitter import scipy Explanation: Comparing collections (Part Two) Motivation Review Part I Describe what we want Kendall's tau Rank-biased overla...
12,787
Given the following text description, write Python code to implement the functionality described below step by step Description: <div class="alert alert-block alert-info" style="margin-top Step1: Set the random seed Step2: Use this function for plotting Step3: <a id="ref0"></a> <h2 align=center>Make Some Data </h2>...
Python Code: from torch import nn,optim import torch import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from torch.utils.data import Dataset, DataLoader Explanation: <div class="alert alert-block alert-info" style="margin-top: 20px"> <a href="http://cocl.us/pytorch_link_top"><im...
12,788
Given the following text description, write Python code to implement the functionality described below step by step Description: Correlation of DCO2 and weight-corrected DCO2 with PCO2 This file contains the code used for data processing, statistical analysis and visualization described in the following paper Step1: ...
Python Code: import pandas as pd import numpy as np import matplotlib.pyplot as plt import os import re import operator import warnings from pandas import Series, DataFrame from scipy.stats.stats import pearsonr from scipy.stats import ttest_rel from datetime import datetime, timedelta from pprint import pprint %matplo...
12,789
Given the following text description, write Python code to implement the functionality described below step by step Description: The Lorenz63 model implemented in FABM The equations read Step1: Import pyfabm - the python module that contains the Fortran based FABM Step2: Configuration The model configuration is done...
Python Code: import numpy import scipy.integrate Explanation: The Lorenz63 model implemented in FABM The equations read: $ \frac{dx}{dt} = \sigma ( y - x ) - \beta x y$ $ \frac{dy}{dt} = x ( \rho - z ) - y$ $ \frac{dz}{dt} = x y - \beta z$ For further information see Import standard python packages and pyfabm End of ex...
12,790
Given the following text description, write Python code to implement the functionality described below step by step Description: Validation Playground Watch a short tutorial video or read the written tutorial This notebook assumes that you created at least one expectation suite in your project. Here you will learn how...
Python Code: import json import great_expectations as ge import great_expectations.jupyter_ux from great_expectations.datasource.types import BatchKwargs import datetime Explanation: Validation Playground Watch a short tutorial video or read the written tutorial This notebook assumes that you created at least one expec...
12,791
Given the following text description, write Python code to implement the functionality described below step by step Description: Visualization with Matplotlib Learning Objectives Step1: Overview The following conceptual organization is simplified and adapted from Benjamin Root's AnatomyOfMatplotlib tutorial. Figures ...
Python Code: %matplotlib inline import matplotlib.pyplot as plt import numpy as np Explanation: Visualization with Matplotlib Learning Objectives: Learn how to make basic plots using Matplotlib's pylab API and how to use the Matplotlib documentation. This notebook focuses only on the Matplotlib API, rather that the bro...
12,792
Given the following text problem statement, write Python code to implement the functionality described below in problem statement Problem: I've read several posts about how to convert Pandas columns to float using pd.to_numeric as well as applymap(locale.atof).
Problem: import pandas as pd s = pd.Series(['2,144.78', '2,036.62', '1,916.60', '1,809.40', '1,711.97', '6,667.22', '5,373.59', '4,071.00', '3,050.20', '-0.06', '-1.88', '', '-0.13', '', '-0.14', '0.07', '0', '0'], index=['2016-10-31', '2016-07-31', '2016-04-30', '2016-01-31', '2015-10-31', '2016-01-31', ...
12,793
Given the following text description, write Python code to implement the functionality described below step by step Description: Computing various MNE solutions This example shows example fixed- and free-orientation source localizations produced by the minimum-norm variants implemented in MNE-Python Step1: Fixed orie...
Python Code: # Author: Eric Larson <larson.eric.d@gmail.com> # # License: BSD-3-Clause import mne from mne.datasets import sample from mne.minimum_norm import make_inverse_operator, apply_inverse print(__doc__) data_path = sample.data_path() subjects_dir = data_path + '/subjects' # Read data (just MEG here for speed, t...
12,794
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_v2 import * from dnn_utils_v2 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.rc...
12,795
Given the following text description, write Python code to implement the functionality described below step by step Description: Performing Scenario Discovery in Python The purpose of example is to demonstrate how one can do scenario discovery in python. I will demonstrate how we can perform both PRIM in an interactiv...
Python Code: import pandas as pd data = pd.read_csv("./data/bryant et al 2010 data.csv", index_col=False) x = data.iloc[:, 2:11] y = data.iloc[:, 15].values Explanation: Performing Scenario Discovery in Python The purpose of example is to demonstrate how one can do scenario discovery in python. I will demonstrate how w...
12,796
Given the following text description, write Python code to implement the functionality described below step by step Description: Análisis de los datos obtenidos Uso de ipython para el análsis y muestra de los datos obtenidos durante la producción.Se implementa un regulador experto. Los datos analizados son del día 13 ...
Python Code: #Importamos las librerías utilizadas import numpy as np import pandas as pd import seaborn as sns #Mostramos las versiones usadas de cada librerías print ("Numpy v{}".format(np.__version__)) print ("Pandas v{}".format(pd.__version__)) print ("Seaborn v{}".format(sns.__version__)) #Abrimos el fichero csv co...
12,797
Given the following text description, write Python code to implement the functionality described below step by step Description: 課題1 1900年から2200年までのうるう年を教えてくれるプログラムを書いてください。 ただし、うるう年は下記のルールで決定されるものとします。 西暦が4で割り切れる年は閏年である。 ただし、100で割り切れる年は閏年ではない。 ただし、400で割り切れる年は閏年である。 課題2 任意の西暦年を渡すと、うるう年か否かを判定してくれる関数を、def機能を使って実装してく...
Python Code: def leap_year(y): if y < 0: print("Please input positive number.") return if y%4 == 0: if y%400 == 0: print("%d is leap year."%y) return elif y%100 == 0: print("%d is NOT leap year."%y) return print("%d is lea...
12,798
Given the following text description, write Python code to implement the functionality described below step by step Description: <img src="../../images/qiskit-heading.gif" alt="Note Step1: First we set up an empty program for one qubit. Step2: We don't want to do anything to the qubit, so we'll skip straight to read...
Python Code: import qiskit Explanation: <img src="../../images/qiskit-heading.gif" alt="Note: In order for images to show up in this jupyter notebook you need to select File => Trusted Notebook" width="500 px" align="left"> Doing nothing with Qiskit Terra We are going to use Qiskit to do nothing. End of explanation qr ...
12,799
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2019 The TensorFlow Authors. Step1: Text classification with TensorFlow Lite Model Maker <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="http...
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...