Unnamed: 0
int64
0
16k
text_prompt
stringlengths
110
62.1k
code_prompt
stringlengths
37
152k
8,900
Given the following text description, write Python code to implement the functionality described below step by step Description: Custom Factors When we first looked at factors, we explored the set of built-in factors. Frequently, a desired computation isn't included as a built-in factor. One of the most powerful featu...
Python Code: from quantopian.pipeline import CustomFactor import numpy Explanation: Custom Factors When we first looked at factors, we explored the set of built-in factors. Frequently, a desired computation isn't included as a built-in factor. One of the most powerful features of the Pipeline API is that it allows us t...
8,901
Given the following text description, write Python code to implement the functionality described below step by step Description: Visualising statistical significance thresholds on EEG data MNE-Python provides a range of tools for statistical hypothesis testing and the visualisation of the results. Here, we show a few ...
Python Code: import numpy as np import matplotlib.pyplot as plt from scipy.stats import ttest_ind import mne from mne.channels import find_ch_adjacency, make_1020_channel_selections from mne.stats import spatio_temporal_cluster_test np.random.seed(0) # Load the data path = mne.datasets.kiloword.data_path() + '/kword_me...
8,902
Given the following text description, write Python code to implement the functionality described below step by step Description: Table of Contents <p><div class="lev1 toc-item"><a href="#YOUR-NAME-(NEPTUN)" data-toc-modified-id="YOUR-NAME-(NEPTUN)-1"><span class="toc-item-num">1&nbsp;&nbsp;</span>YOUR NAME (NEPTUN)</a...
Python Code: import pandas as pd if pd.__version__ < '1': print("WARNING: Pandas version older than 1.0.0: {}".format(pd.__version__)) else: print("Pandas version OK: {}".format(pd.__version__)) Explanation: Table of Contents <p><div class="lev1 toc-item"><a href="#YOUR-NAME-(NEPTUN)" data-toc-modified-id="YOUR...
8,903
Given the following text description, write Python code to implement the functionality described below step by step Description: <h3>artcontrol gallery</h3> Create gallery for artcontrol artwork. Uses Year / Month / Day format. Create blog post for each day there is a post. It will need to list the files for that day...
Python Code: import os import arrow import getpass raw = arrow.now() myusr = getpass.getuser() galpath = ('/home/{}/git/artcontrolme/galleries/'.format(myusr)) galpath = ('/home/{}/git/artcontrolme/galleries/'.format(myusr)) popath = ('/home/{}/git/artcontrolme/posts/'.format(myusr)) class DayStuff(): def g...
8,904
Given the following text description, write Python code to implement the functionality described below step by step Description: Vertex client library Step1: Install the latest GA version of google-cloud-storage library as well. Step2: Restart the kernel Once you've installed the Vertex client library and Google clo...
Python Code: import os import sys # Google Cloud Notebook if os.path.exists("/opt/deeplearning/metadata/env_version"): USER_FLAG = "--user" else: USER_FLAG = "" ! pip3 install -U google-cloud-aiplatform $USER_FLAG Explanation: Vertex client library: AutoML tabular classification model for batch prediction with ...
8,905
Given the following text description, write Python code to implement the functionality described below step by step Description: Understanding the vanishing gradient problem through visualization There're reasons why deep neural network could work very well, while few people get a promising result or make it possible ...
Python Code: import sys sys.path.append('./mnist/') from train_mnist import * Explanation: Understanding the vanishing gradient problem through visualization There're reasons why deep neural network could work very well, while few people get a promising result or make it possible by simply make their neural network dee...
8,906
Given the following text description, write Python code to implement the functionality described below step by step Description: Preparing Data In this step, we are going to load data from disk to the memory and properly format them so that we can processing them in the next "preprocessing" stage. Step1: Loading Toke...
Python Code: # Loading metadata from trainning database con = sqlite3.connect("F:/FMR/data.sqlite") db_documents = pd.read_sql_query("SELECT * from documents", con) db_authors = pd.read_sql_query("SELECT * from authors", con) data = db_documents # just a handy alias data.head() Explanation: Preparing Data In this step,...
8,907
Given the following text description, write Python code to implement the functionality described below step by step Description: Working with sEEG data MNE-Python supports working with more than just MEG and EEG data. Here we show some of the functions that can be used to facilitate working with stereoelectroencephalo...
Python Code: # Authors: Eric Larson <larson.eric.d@gmail.com> # Adam Li <adam2392@gmail.com> # Alex Rockhill <aprockhill@mailbox.org> # # License: BSD-3-Clause import os.path as op import numpy as np import matplotlib.pyplot as plt import mne from mne.datasets import fetch_fsaverage # paths to mne dat...
8,908
Given the following text description, write Python code to implement the functionality described below step by step Description: Q1 In this question, you'll be introduced to the scikit-image package. Only a small portion of the package will be explored; you're encouraged to check it out if this interests you! A scikit...
Python Code: import matplotlib.pyplot as plt import numpy as np import skimage.data ### BEGIN SOLUTION ### END SOLUTION Explanation: Q1 In this question, you'll be introduced to the scikit-image package. Only a small portion of the package will be explored; you're encouraged to check it out if this interests you! A sci...
8,909
Given the following text description, write Python code to implement the functionality described below step by step Description: Effect Size Credits Step1: To explore statistics that quantify effect size, we'll look at the difference in height between men and women. I used data from the Behavioral Risk Factor Survei...
Python Code: from __future__ import print_function, division import numpy import scipy.stats import matplotlib.pyplot as pyplot from IPython.html.widgets import interact, fixed from IPython.html import widgets # seed the random number generator so we all get the same results numpy.random.seed(17) # some nice colors fro...
8,910
Given the following text description, write Python code to implement the functionality described below step by step Description: Diffusion Class Step1: Self-diffusion of water The self-diffusion coefficient of water (in micrometers<sup>2</sup>/millisecond) is dependent on the temperature and pressure. Several groups ...
Python Code: %pylab inline rcParams["figure.figsize"] = (8, 6) rcParams["axes.grid"] = True from IPython.display import display, clear_output from mpl_toolkits.axes_grid1 import make_axes_locatable from time import sleep from __future__ import division def cart2pol(x, y): theta = arctan2(y, x) r = sqrt(x ** 2 +...
8,911
Given the following text description, write Python code to implement the functionality described. Description: Add two numbers x and y This is how the function will work: add(2, 3) 5 This is how the function will work: add(5, 7) 12
Python Code: def add(x: int, y: int): return x + y
8,912
Given the following text description, write Python code to implement the functionality described below step by step Description: Cleaning Step1: 2. Print data summaries including the number of null values. Should we drop or try to correct any of the null values? Step2: Gender and year of birth have nulls, I don't th...
Python Code: import pandas as pd import numpy as np sets = ['station', 'trip', 'weather'] cycle = {} for s in sets: cycle[s] = pd.read_csv('cycle_share/' + s + '.csv') cycle['trip'].head() Explanation: Cleaning: Cycle Share There are 3 datasets that provide data on the stations, trips, and weather from 2014-2016. S...
8,913
Given the following text description, write Python code to implement the functionality described below step by step Description: CHAPTER 4 4.2 Algorithms Step1: Imports, logging, and data On top of doing the things we already know, we now additionally import also the CollaborativeFiltering algorithm, which is, as sho...
Python Code: import sys sys.path.append('../..') Explanation: CHAPTER 4 4.2 Algorithms: Collaborative filtering Having understood the basics of how an algorithm is configured, married with data, and deployed in bestPy, we are now ready to move from a baseline recommendation to something more inolved. In particular, we ...
8,914
Given the following text description, write Python code to implement the functionality described below step by step Description: Pima Indian Diabetes Prediction (with Model Reload) Import some basic libraries. * Pandas - provided data frames * matplotlib.pyplot - plotting support Use Magic %matplotlib to display graph...
Python Code: import pandas as pd # pandas is a dataframe library import matplotlib.pyplot as plt # matplotlib.pyplot plots data %matplotlib inline Explanation: Pima Indian Diabetes Prediction (with Model Reload) Import some basic libraries. * Pandas - provided data frames * matplotlib.pyplot - plot...
8,915
Given the following text description, write Python code to implement the functionality described below step by step Description: One Port Tiered Calibration Intro A one-port network analyzer can be used to measure a two-port device, provided that the device is reciprocal. This is accomplished by performing two calibra...
Python Code: from IPython.display import SVG SVG('images/boxDiagram.svg') Explanation: One Port Tiered Calibration Intro A one-port network analyzer can be used to measure a two-port device, provided that the device is reciprocal. This is accomplished by performing two calibrations, which is why its called a tiered cal...
8,916
Given the following text description, write Python code to implement the functionality described below step by step Description: Image compression with K-means K-means is a clustering algorithm which defines K cluster centroids in the feature space and, by making use of an appropriate distance function, iteratively as...
Python Code: from scipy import misc pic = misc.imread('media/irobot.png') Explanation: Image compression with K-means K-means is a clustering algorithm which defines K cluster centroids in the feature space and, by making use of an appropriate distance function, iteratively assigns each example to the closest cluster c...
8,917
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Image Classification In this project, you'll classify images from the CIFAR-10 dataset. The dataset consists of airplanes, dogs, cats, and other objects. You'll preprocess the images...
Python Code: DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE from urllib.request import urlretrieve from os.path import isfile, isdir from tqdm import tqdm import problem_unittests as tests import tarfile cifar10_dataset_folder_path = 'cifar-10-batches-py' # Use Floyd's cifar-10 dataset if present floyd_cifa...
8,918
Given the following text description, write Python code to implement the functionality described below step by step Description: Guided Project 1 Learning Objectives Step1: Step 1. Environment setup skaffold tool setup Step2: Modify the PATH environment variable so that skaffold is available Step3: Environment vari...
Python Code: import os Explanation: Guided Project 1 Learning Objectives: Learn how to generate a standard TFX template pipeline using tfx template Learn how to modify and run a templated TFX pipeline Note: This guided project is adapted from Create a TFX pipeline using templates). End of explanation PATH=%env PATH %e...
8,919
Given the following text description, write Python code to implement the functionality described below step by step Description: Puerto Rico water quality measurements-results data Adapted from ODM2 API Step1: odm2api version used to run this notebook Step2: Connect to the ODM2 SQLite Database This example uses an O...
Python Code: %matplotlib inline import os import matplotlib.pyplot as plt from shapely.geometry import Point import pandas as pd import geopandas as gpd import folium from folium.plugins import MarkerCluster import odm2api from odm2api.ODMconnection import dbconnection import odm2api.services.readService as odm2rs pd._...
8,920
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2021 The TF-Agents Authors. Step1: 再生バッファ <table class="tfo-notebook-buttons" align="left"> <td><a target="_blank" href="https Step2: 再生バッファ API 再生バッファのクラスには、次の定義とメソッドがあります。 ``...
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...
8,921
Given the following text description, write Python code to implement the functionality described below step by step Description: Title Step1: Create an example dataframe Step2: Create a function to assign letter grades
Python Code: import pandas as pd import numpy as np Explanation: Title: Create A Pandas Column With A For Loop Slug: pandas_create_column_with_loop Summary: Create A Pandas Column With A For Loop Date: 2016-05-01 12:00 Category: Python Tags: Data Wrangling Authors: Chris Albon Preliminaries End of explanation raw_dat...
8,922
Given the following text description, write Python code to implement the functionality described below step by step Description: SED fitting with naima In this notebook we will carry out a fit of an IC model to the HESS spectrum of RX J1713.7-3946 with the naima wrapper around emcee. This tutorial will follow loosely ...
Python Code: import naima import numpy as np from astropy.io import ascii import astropy.units as u %matplotlib inline import matplotlib.pyplot as plt hess_spectrum = ascii.read('RXJ1713_HESS_2007.dat', format='ipac') fig = naima.plot_data(hess_spectrum) Explanation: SED fitting with naima In this notebook we will carr...
8,923
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Impedance or reflectivity Trying to see how to combine G with a derivative operator to get from the impedance model to the data with one forward operator. Step2: Construct the model ...
Python Code: import numpy as np import numpy.linalg as la import matplotlib.pyplot as plt from utils import plot_all %matplotlib inline from scipy import linalg as spla def convmtx(h, n): Equivalent of MATLAB's convmtx function, http://www.mathworks.com/help/signal/ref/convmtx.html. Makes the convolut...
8,924
Given the following text description, write Python code to implement the functionality described below step by step Description: Week 8 - Advanced Machine Learning During the course we have covered a variety of different tasks and algorithms. These were chosen for their broad applicability and ease of use with many im...
Python Code: import matplotlib.pyplot as plt %matplotlib inline plt.gray() from keras.datasets import mnist (X_train, y_train), (X_test, y_test) = mnist.load_data() fig, axes = plt.subplots(3,5, figsize=(12,8)) for i, ax in enumerate(axes.flatten()): ax.imshow(X_train[i], interpolation='nearest') plt.show() from ke...
8,925
Given the following text description, write Python code to implement the functionality described below step by step Description: Data frames 3 Step1: lang Step2: lang Step3: lang Step4: lang Step5: lang Step7: 予習課題 Step8: lang
Python Code: # データをCVSファイルから読み込みます。 Read the data from CSV file. df = pd.read_csv('data/15-July-2019-Tokyo-hourly.csv') print("データフレームの行数は %d" % len(df)) print(df.dtypes) df.head() Explanation: Data frames 3: 簡単なデータの変換 (Simple data manipulation) ``` ASSIGNMENT METADATA assignment_id: "DataFrame3" ``` lang:en In this un...
8,926
Given the following text description, write Python code to implement the functionality described below step by step Description: Fitting Gaussian Mixture Models with EM In this assignment you will * implement the EM algorithm for a Gaussian mixture model * apply your implementation to cluster images * explore clusteri...
Python Code: import graphlab as gl import numpy as np import matplotlib.pyplot as plt import copy from scipy.stats import multivariate_normal %matplotlib inline Explanation: Fitting Gaussian Mixture Models with EM In this assignment you will * implement the EM algorithm for a Gaussian mixture model * apply your implem...
8,927
Given the following text description, write Python code to implement the functionality described below step by step Description: https Step1: 52N IOOS SOS Stable Demo -- network offering (multi-station) data request Create pyoos "collector" that connects to the SOS end point and parses GetCapabilities (offerings) Ste...
Python Code: from datetime import datetime, timedelta import pandas as pd from pyoos.collectors.ioos.swe_sos import IoosSweSos # convenience function to build record style time series representation def flatten_element(p): rd = {'time':p.time} for m in p.members: rd[m['standard']] = m['value'] retur...
8,928
Given the following text description, write Python code to implement the functionality described below step by step Description: <h1 align="center">TensorFlow Neural Network Lab</h1> <img src="image/notmnist.png"> In this lab, you'll use all the tools you learned from Introduction to TensorFlow to label images of Engl...
Python Code: import hashlib import os import pickle from urllib.request import urlretrieve import numpy as np from PIL import Image from sklearn.model_selection import train_test_split from sklearn.preprocessing import LabelBinarizer from sklearn.utils import resample from tqdm import tqdm from zipfile import ZipFile p...
8,929
Given the following text description, write Python code to implement the functionality described below step by step Description: LeNet Lab Source Step1: The MNIST data that TensorFlow pre-loads comes as 28x28x1 images. However, the LeNet architecture only accepts 32x32xC images, where C is the number of color channel...
Python Code: from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("MNIST_data/", reshape=False) X_train, y_train = mnist.train.images, mnist.train.labels X_validation, y_validation = mnist.validation.images, mnist.validation.labels X_test, y_test = mnist.tes...
8,930
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: <a href="https Step2: Model (for cifar10) Setting up hyperparams Step3: This model is a hierarchical model with multiple stochastic blocks with multiple deterministic layers. You ca...
Python Code: from google.colab import auth auth.authenticate_user() project_id = "probml" !gcloud config set project {project_id} this should be the format of the checkpoint filetree: checkpoint_path >> model(optimizer)_checkpoint_file. checkpoint_path_ema >> ema_checkpoint_file checkpoint_path = "/content/vdvae_ci...
8,931
Given the following text description, write Python code to implement the functionality described below step by step Description: List Comprehensions List comprehensions are quick and concise way to create lists. List comprehensions comprises of an expression, followed by a for clause and then zero or more for or if cl...
Python Code: # Simple List Comprehension list = [x for x in range(5)] print(list) Explanation: List Comprehensions List comprehensions are quick and concise way to create lists. List comprehensions comprises of an expression, followed by a for clause and then zero or more for or if clauses. The result of the list compr...
8,932
Given the following text description, write Python code to implement the functionality described below step by step Description: Python for Bioinformatics This Jupyter notebook is intented to be used alongside the book Python for Bioinformatics Chapter 7 Step1: Listing 7.1 Step2: Listing 7.2 Step3: Listing 7.3 Step...
Python Code: !curl https://raw.githubusercontent.com/Serulab/Py4Bio/master/samples/samples.tar.bz2 -o samples.tar.bz2 !mkdir samples !tar xvfj samples.tar.bz2 -C samples Explanation: Python for Bioinformatics This Jupyter notebook is intented to be used alongside the book Python for Bioinformatics Chapter 7: Error Hand...
8,933
Given the following text description, write Python code to implement the functionality described below step by step Description: mosasaurus example This notebook shows how to run mosasaurus to extract spectra from a sample dataset. In this example, there's a small sample dataset of raw LDSS3C images stored in the dire...
Python Code: %matplotlib auto # create an instrument with the appropriate settings from mosasaurus.instruments import LDSS3C i = LDSS3C(grism='vph-all') # set up the basic directory structure, where `data/` should be found path = '/Users/zkbt/Cosmos/Data/mosaurusexample' i.setupDirectories(path) # set the extraction de...
8,934
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2019 The TensorFlow Authors. Step1: Post-training weight quantization <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https Step2: Train and...
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...
8,935
Given the following text description, write Python code to implement the functionality described below step by step Description: Function Approximation with a Multilayer Perceptron This code is provided as supplementary material of the lecture Machine Learning and Optimization in Communications (MLOC).<br> This code i...
Python Code: import numpy as np import matplotlib.pyplot as plt %matplotlib inline function_select = 4 def myfun(x): functions = { 1: np.power(x,2), # quadratic function 2: np.sin(x), # sinus 3: np.sign(x), # signum 4: np.exp(x), # exponential function 5: np.abs(x) } ...
8,936
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2020 Google LLC Step1: Adversarial Learning Step2: Main Objective — Building an Apparel Classifier & Performing Adversarial Learning We will keep things simple here with regard t...
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 # ...
8,937
Given the following text description, write Python code to implement the functionality described below step by step Description: Diffusion Boundary The simulation script described in this chapter is available at STEPS_Example repository. In some systems it may be a convenient simulation feature to be able to localize ...
Python Code: import steps.model as smodel import steps.geom as sgeom import steps.rng as srng import steps.solver as solvmod import steps.utilities.meshio as meshio import numpy import pylab Explanation: Diffusion Boundary The simulation script described in this chapter is available at STEPS_Example repository. In some...
8,938
Given the following text description, write Python code to implement the functionality described below step by step Description: About iPython Notebooks iPython Notebooks are interactive coding environments embedded in a webpage. After writing your code, you can run the cell by either pressing "SHIFT"+"ENTER" or by cl...
Python Code: test = "Hello World" print ("test: " + test) Explanation: About iPython Notebooks iPython Notebooks are interactive coding environments embedded in a webpage. After writing your code, you can run the cell by either pressing "SHIFT"+"ENTER" or by clicking on "Run Cell" (denoted by a play symbol) in the uppe...
8,939
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 Simon's algorithm. We start by declaring all necessary imports. Step1: Simon's algorithm can be used to find the mask $m$ of a 2-to-1 periodic ...
Python Code: from collections import defaultdict import numpy as np from mock import patch from grove.simon.simon import Simon, create_valid_2to1_bitmap Explanation: This notebook is a brief sketch of how to use Simon's algorithm. We start by declaring all necessary imports. End of explanation mask = '110' bm = create_...
8,940
Given the following text description, write Python code to implement the functionality described below step by step Description: Step2: Survival Curve, S(t) maps from a duration, t, to the probability of surviving longer than t. $$ S(t) = 1-\text{CDF}(t) $$ where CDF(t) is the probability of a lifetime less than or...
Python Code: preg = nsfg.ReadFemPreg() complete = preg.query('outcome in [1,3,4]').prglngth cdf = thinkstats2.Cdf(complete, label='cdf') ##note: property is a method that can be invoked as if ##it were a variable. class SurvivalFunction(object): def __init__(self, cdf, label=''): self.cdf = cdf ...
8,941
Given the following text description, write Python code to implement the functionality described below step by step Description: Keras model are serialzed in a JSON format. Step1: Getting the weights Weights can be retrieved either directly from the model or from each individual layer. Step2: Moreover the respespect...
Python Code: model.get_config() Explanation: Keras model are serialzed in a JSON format. End of explanation # Weights and biases of the entire model. model.get_weights() # Weights and bias for a single layer. conv_layer = model.get_layer('conv2d_1') conv_layer.get_weights() Explanation: Getting the weights Weights can ...
8,942
Given the following text description, write Python code to implement the functionality described below step by step Description: Manual Neural Network In this notebook we will manually build out a neural network that mimics the TensorFlow API. This will greatly help your understanding when working with the real Tensor...
Python Code: class SimpleClass(): def __init__(self, str_input): print("SIMPLE" + str_input) class ExtendedClass(SimpleClass): def __init__(self): print('EXTENDED') Explanation: Manual Neural Network In this notebook we will manually build out a neural network that mimics the TensorFlow API. Thi...
8,943
Given the following text description, write Python code to implement the functionality described below step by step Description: Справочник Токенизатор Токенизатор в Yargy реализован на регулярных выражениях. Для каждого типа токена есть правило с регуляркой Step1: Токенизатор инициализируется списком правил. По-умол...
Python Code: from yargy.tokenizer import RULES RULES Explanation: Справочник Токенизатор Токенизатор в Yargy реализован на регулярных выражениях. Для каждого типа токена есть правило с регуляркой: End of explanation from yargy.tokenizer import Tokenizer text = 'a@mail.ru' tokenizer = Tokenizer() list(tokenizer(text)) E...
8,944
Given the following text description, write Python code to implement the functionality described below step by step Description: Simulation of the METIS scenario with rooms in one floor This notebook simulates the scenario with one access point in each room of a given floor building. Some Initialization Code First we ...
Python Code: %matplotlib inline # xxxxxxxxxx Add the parent folder to the python path. xxxxxxxxxxxxxxxxxxxx import sys import os sys.path.append('../') # xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx from matplotlib import pyplot as plt import numpy as np from IPython.html.widgets import int...
8,945
Given the following text description, write Python code to implement the functionality described below step by step Description: Installation d'un distribution Python Il existe plusieurs distributions de Python à destination des scientifiques Step1: Scalaires Les types numériques int et float Step2: Nombres complex...
Python Code: print "Hello world" print '1', # la virgule empèche le saut de ligne après le print print '2' Explanation: Installation d'un distribution Python Il existe plusieurs distributions de Python à destination des scientifiques : Anaconda Canopy Python(x,y) Chacune de ces distributions est disponible pour un gra...
8,946
Given the following text description, write Python code to implement the functionality described below step by step Description: Read in the data Step1: Read in the surveys Step2: Add DBN columns Step3: Convert columns to numeric Step4: Condense datasets Step5: Convert AP scores to numeric Step6: Combine the dat...
Python Code: import pandas as pd import numpy as np import re data_files = ["ap_2010.csv", "class_size.csv", "demographics.csv", "graduation.csv", "hs_directory.csv", "sat_results.csv"] data = {} for f in data_files: d = pd.read_csv("../data/scho...
8,947
Given the following text description, write Python code to implement the functionality described below step by step Description: BigQuery query magic Jupyter magics are notebook-specific shortcuts that allow you to run commands with minimal syntax. Jupyter notebooks come with many built-in commands. The BigQuery clien...
Python Code: %%bigquery SELECT name, SUM(number) as count FROM `bigquery-public-data.usa_names.usa_1910_current` GROUP BY name ORDER BY count DESC LIMIT 10 Explanation: BigQuery query magic Jupyter magics are notebook-specific shortcuts that allow you to run commands with minimal syntax. Jupyter notebooks come with man...
8,948
Given the following text description, write Python code to implement the functionality described below step by step Description: \title{myHDL Implementation of a CIC Filter} \author{Steven K Armour} \maketitle <h1>Table of Contents<span class="tocSkip"></span></h1> <div class="toc"><ul class="toc-item"><li><span><a hr...
Python Code: import numpy as np np.seterr(divide='ignore', invalid='ignore') import pandas as pd import matplotlib.pyplot as plt from matplotlib import cm from mpl_toolkits.mplot3d import Axes3D #import plotly.plotly as py #import plotly.graph_objs as go from sympy import * from sympy import S; Zero=S.Zero init_printin...
8,949
Given the following text description, write Python code to implement the functionality described below step by step Description: Deque kolekcja zbliżona do listy optymalne operacje na brzegach, nieoptymalne indeksowanie implementacja bazuje na double linked liście Step1: Krotki immutable podobne do listy hashowalne, ...
Python Code: from collections import deque a = deque([1, 2, 3], maxlen=5) a.append(4) a.append(5) a.append(6) print(a) Explanation: Deque kolekcja zbliżona do listy optymalne operacje na brzegach, nieoptymalne indeksowanie implementacja bazuje na double linked liście End of explanation a = (1, 2, 3) b = (1, ) c = () pr...
8,950
Given the following text description, write Python code to implement the functionality described below step by step Description: Get the data 2MASS => J, H K, angular resolution ~4" WISE => 3.4, 4.6, 12, and 22 μm (W1, W2, W3, W4) with an angular resolution of 6.1", 6.4", 6.5", & 12.0" GALEX imaging => Five imaging s...
Python Code: #obj = ["3C 454.3", 343.49062, 16.14821, 1.0] obj = ["PKS J0006-0623", 1.55789, -6.39315, 1.0] #obj = ["M87", 187.705930, 12.391123, 1.0] #### name, ra, dec, radius of cone obj_name = obj[0] obj_ra = obj[1] obj_dec = obj[2] cone_radius = obj[3] obj_coord = coordinates.SkyCoord(ra=obj_ra, dec=obj_dec, u...
8,951
Given the following text description, write Python code to implement the functionality described below step by step Description: Phoenix BT-Settl Bolometric Corrections Figuring out the best method of handling Phoenix bolometric correction files. Step1: Change to directory containing bolometric correction files. Step...
Python Code: %matplotlib inline import matplotlib.pyplot as plt import numpy as np import scipy.interpolate as scint Explanation: Phoenix BT-Settl Bolometric Corrections Figuring out the best method of handling Phoenix bolometric correction files. End of explanation cd /Users/grefe950/Projects/starspot/starspot/color/t...
8,952
Given the following text description, write Python code to implement the functionality described below step by step Description: WikiData From here Step1: Add the 590 MetAtlas compounds that are missing from all these databases Step2: miBIG (using notebook and pubchem API) Step3: get names for ones that are missing...
Python Code: terms_to_keep = ['smiles','inchi','source_database','ROMol','common_name','Definition', 'synonyms','pubchem_compound_id','lipidmaps_id','metacyc_id','hmdb_id','img_abc_id','chebi_id','kegg_id'] import_compounds = reload(import_compounds) wikidata = import_compounds.get_wikidata(terms_to_keep) df = wikidata...
8,953
Given the following text description, write Python code to implement the functionality described below step by step Description: OpenCV Filters Webcam In this notebook, several filters will be applied to webcam images. Those input sources and applied filters will then be displayed either directly in the notebook or on...
Python Code: from pynq import Overlay Overlay("base.bit").download() Explanation: OpenCV Filters Webcam In this notebook, several filters will be applied to webcam images. Those input sources and applied filters will then be displayed either directly in the notebook or on HDMI output. To run all cells in this notebook ...
8,954
Given the following text description, write Python code to implement the functionality described below step by step Description: <span style='color Step1: Part A - Calculate features for an individual source To demonstrate how the FATS library works, we will begin by calculating features for the source with $\alpha_{...
Python Code: shelf_file = " " # complete the path to the appropriate shelf file here shelf = shelve.open(shelf_file) shelf.keys() Explanation: <span style='color:red'>An essential note in preparation for this exercise.</span> We will use scikit-learn to provide classifications of the PTF sources that we developed on th...
8,955
Given the following text description, write Python code to implement the functionality described below step by step Description: On-the-fly training using ASE Yu Xie (xiey@g.harvard.edu) This is a quick introduction of how to set up our ASE-OTF interface to train a force field. We will train a force field model for di...
Python Code: import numpy as np from ase import units from ase.spacegroup import crystal from ase.build import bulk np.random.seed(12345) a = 3.52678 super_cell = bulk('C', 'diamond', a=a, cubic=True) Explanation: On-the-fly training using ASE Yu Xie (xiey@g.harvard.edu) This is a quick introduction of how to set up o...
8,956
Given the following text description, write Python code to implement the functionality described below step by step Description: Head model and forward computation The aim of this tutorial is to be a getting started for forward computation. For more extensive details and presentation of the general concepts for forwar...
Python Code: import os.path as op import mne from mne.datasets import sample data_path = sample.data_path() # the raw file containing the channel location + types raw_fname = data_path + '/MEG/sample/sample_audvis_raw.fif' # The paths to Freesurfer reconstructions subjects_dir = data_path + '/subjects' subject = 'sampl...
8,957
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: <i class="fa fa-diamond"></i> Primero pimpea tu libreta! Step2: <i class="fa fa-book"></i> Primero librerias Step3: <i class="fa fa-database"></i> Vamos a crear datos de jugete Crea...
Python Code: from IPython.core.display import HTML import os def css_styling(): Load default custom.css file from ipython profile base = os.getcwd() styles = "<style>\n%s\n</style>" % (open(os.path.join(base,'files/custom.css'),'r').read()) return HTML(styles) css_styling() Explanation: <i class="fa fa-...
8,958
Given the following text description, write Python code to implement the functionality described below step by step Description: Now it's time for you to demonstrate your new skills with a project of your own! In this exercise, you will work with a dataset of your choosing. Once you've selected a dataset, you'll desi...
Python Code: import pandas as pd pd.plotting.register_matplotlib_converters() import matplotlib.pyplot as plt %matplotlib inline import seaborn as sns print("Setup Complete") Explanation: Now it's time for you to demonstrate your new skills with a project of your own! In this exercise, you will work with a dataset of y...
8,959
Given the following text description, write Python code to implement the functionality described. Description: Largest number in the Array having frequency same as value Function to find the largest number whose frequency is equal to itself . ; Adding 65536 to keep the count of the current number ; Right shifting by 16...
Python Code: def findLargestNumber(arr , n ) : for i in range(n ) : arr[i ] &= 0xFFFF ; if(arr[i ] <= n ) : arr[i ] += 0x10000 ;   for i in range(n - 1 , 0 , - 1 ) : if(( arr[i ] >> 16 ) == i ) : return i + 1 ;   return - 1 ;  if __name__== ' __main __' : arr =[3 , 2 , 5 , 5 , 2 , 4 , 5 ]...
8,960
Given the following text description, write Python code to implement the functionality described below step by step Description: Planar data classification with one hidden layer Welcome to your week 3 programming assignment. It's time to build your first neural network, which will have a hidden layer. You will see a b...
Python Code: # Package imports import numpy as np import matplotlib.pyplot as plt from testCases_v2 import * import sklearn import sklearn.datasets import sklearn.linear_model from planar_utils import plot_decision_boundary, sigmoid, load_planar_dataset, load_extra_datasets %matplotlib inline np.random.seed(1) # set a ...
8,961
Given the following text description, write Python code to implement the functionality described below step by step Description: <div style='background-image Step1: 1. Initialization of setup Step2: 2. Finite Differences setup Step3: 3. Finite Volumes setup Step4: 4. Initial condition Step5: 4. Solution for the i...
Python Code: # Import all necessary libraries, this is a configuration step for the exercise. # Please run it before the simulation code! import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation # Show the plots in the Notebook. plt.switch_backend("nbagg") Explanation: <div style='bac...
8,962
Given the following text description, write Python code to implement the functionality described below step by step Description: Science, Data, Tools or 'Tips and tricks for a your everyday workflow' Matteo Guzzo Prologue AKA My Research The cumulant expansion The struggle has been too long, but we are starting to see...
Python Code: import numpy as np import matplotlib.pyplot as plt %matplotlib inline with plt.xkcd(): plt.rcParams['figure.figsize'] = (6., 4.) x = np.linspace(-5, 5, 50) gauss = np.exp(-(x**2) / 2)/np.sqrt(2 * np.pi) ax = plt.subplot(111) ax.plot(x, gauss, label="Best curve ever") cdf = np.array(...
8,963
Given the following text description, write Python code to implement the functionality described below step by step Description: Machine Learning Engineer Nanodegree Unsupervised Learning Project Step1: Data Exploration In this section, you will begin exploring the data through visualizations and code to understand h...
Python Code: # Import libraries necessary for this project import numpy as np import pandas as pd from IPython.display import display # Allows the use of display() for DataFrames # Import supplementary visualizations code visuals.py import visuals as vs # Pretty display for notebooks %matplotlib inline # Load the whole...
8,964
Given the following text description, write Python code to implement the functionality described below step by step Description: Example of DenseCRF with non-RGB data This notebook goes through an example of how to use DenseCRFs on non-RGB data. At the same time, it will explain basic concepts and walk through an exam...
Python Code: #import sys #sys.path.insert(0,'/path/to/pydensecrf/') import pydensecrf.densecrf as dcrf from pydensecrf.utils import unary_from_softmax, create_pairwise_bilateral import numpy as np import matplotlib.pyplot as plt %matplotlib inline plt.rcParams['image.interpolation'] = 'nearest' plt.rcParams['image.cmap...
8,965
Given the following text description, write Python code to implement the functionality described below step by step Description: Goal If the DNA species distribution is truely Gaussian in a buoyant density gradient, then what sigma would be needed to reproduce the detection of all taxa > 0.1% in abundance throughout t...
Python Code: %load_ext rpy2.ipython workDir = '/home/nick/notebook/SIPSim/dev/fullCyc/frag_norm_9_2.5_n5/default_run/' %%R sigmas = seq(1, 50, 1) means = seq(25, 100, 1) # mean GC content of 30 to 70% ## max 13C shift max_13C_shift_in_BD = 0.036 ## min BD (that we care about) min_GC = 13.5 min_BD = min_GC/100.0 * 0....
8,966
Given the following text description, write Python code to implement the functionality described below step by step Description: Try tsfresh tsfresh rolling ts Step1: Generate features for rolling & expanding windows roll_time_series By default it's expanding window For rolling window, set max_timeshift value and mak...
Python Code: import pandas as pd # mock up ts data df = pd.DataFrame({ "group": ['a', 'a', 'a', 'a', 'a', 'a', 'a', 'b', 'b', 'b', 'b', 'b'], "time": [1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 4, 5], "x": [1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23], "y": [2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24], }) df Explanation: ...
8,967
Given the following text description, write Python code to implement the functionality described below step by step Description: A Network Tour of Data Science Michaël Defferrard, PhD student, Pierre Vandergheynst, Full Professor, EPFL LTS2. Exercise 5 Step1: 1 Graph Goal Step2: Step 2 Step3: Step 3 Step4: Step 4 ...
Python Code: import numpy as np import scipy.spatial import matplotlib.pyplot as plt %matplotlib inline Explanation: A Network Tour of Data Science Michaël Defferrard, PhD student, Pierre Vandergheynst, Full Professor, EPFL LTS2. Exercise 5: Graph Signals and Fourier Transform The goal of this exercise is to experiment...
8,968
Given the following text description, write Python code to implement the functionality described below step by step Description: Generate Two Networks with Different Spacing Step1: Position Networks Appropriately, then Stitch Together Step2: Quickly Visualize the Network Let's just make sure things are working as pl...
Python Code: spacing_lg = 0.00006 layer_lg = op.network.Cubic(shape=[10, 10, 1], spacing=spacing_lg) spacing_sm = 0.00002 layer_sm = op.network.Cubic(shape=[30, 5, 1], spacing=spacing_sm) Explanation: Generate Two Networks with Different Spacing End of explanation # Start by assigning labels to each network for identif...
8,969
Given the following text description, write Python code to implement the functionality described below step by step Description: Import the libraries Step1: Create an empty network Step2: Create a new species S0 S0 is a reference to access quickly to the newly created species latter in the code. Note that one can a...
Python Code: from phievo.Networks import mutation,deriv2 import random Explanation: Import the libraries End of explanation g = random.Random(20160225) # This define a new random number generator L = mutation.Mutable_Network(g) # Create an empty network Explanation: Create an empty network End of explanation parameters...
8,970
Given the following text description, write Python code to implement the functionality described below step by step Description: Podemos clasificar de dos formas, mediante discriminación o asignando probabilidades. Discriminando, asignamos a cada $x$ una de las $K$ clases $C_k$. Por contra, desde un punto de vista pro...
Python Code: from sklearn.linear_model import LogisticRegression from sklearn.datasets import make_classification %matplotlib inline import matplotlib.pyplot as plt import numpy as np Explanation: Podemos clasificar de dos formas, mediante discriminación o asignando probabilidades. Discriminando, asignamos a cada $x$ u...
8,971
Given the following text description, write Python code to implement the functionality described below step by step Description: Learn to Throw In this notebook, we will train a fully-connected neural network to solve an inverse ballistics problem. We will compare supervised training to differentiable physics training...
Python Code: # !pip install phiflow # from phi.tf.flow import * from phi.torch.flow import * # from phi.jax.stax.flow import * Explanation: Learn to Throw In this notebook, we will train a fully-connected neural network to solve an inverse ballistics problem. We will compare supervised training to differentiable physic...
8,972
Given the following text description, write Python code to implement the functionality described below step by step Description: Nodes and Edges Step1: Basic Network Statistics Let's first understand how many students and friendships are represented in the network. Step2: Exercise Can you write a single line of code...
Python Code: G = cf.load_seventh_grader_network() Explanation: Nodes and Edges: How do we represent relationships between individuals using NetworkX? As mentioned earlier, networks, also known as graphs, are comprised of individual entities and their representatives. The technical term for these are nodes and edges, an...
8,973
Given the following text description, write Python code to implement the functionality described below step by step Description: Forward Modeling the X-ray Image data In this notebook, we'll take a closer look at the X-ray image data products, and build a simple, generative, forward model for the observed data. Step1:...
Python Code: from __future__ import print_function import astropy.io.fits as pyfits import astropy.visualization as viz import matplotlib.pyplot as plt import numpy as np %matplotlib inline plt.rcParams['figure.figsize'] = (10.0, 10.0) Explanation: Forward Modeling the X-ray Image data In this notebook, we'll take a cl...
8,974
Given the following text description, write Python code to implement the functionality described below step by step Description: "Third" Light Setup Let's first make sure we have the latest version of PHOEBE 2.4 installed (uncomment this line if running in an online notebook session such as colab). Step1: As always, ...
Python Code: #!pip install -I "phoebe>=2.4,<2.5" Explanation: "Third" Light Setup Let's first make sure we have the latest version of PHOEBE 2.4 installed (uncomment this line if running in an online notebook session such as colab). End of explanation import phoebe from phoebe import u # units import numpy as np import...
8,975
Given the following text description, write Python code to implement the functionality described below step by step Description: Catapult Project - Australian Geoscience Datacube API Perform band maths and produce a Normalised Difference Vegetation Index (NDVI) file. Step1: Select the first time index and plot the fi...
Python Code: from pprint import pprint %matplotlib inline from matplotlib import pyplot as plt import xarray import datacube.api dc = datacube.api.API() alos2 = dc.get_dataset(product='gamma0', platform='ALOS_2', y=(-42.55,-42.57), x=(147.55,147.57), variables=['hh_gamma0',...
8,976
Given the following text description, write Python code to implement the functionality described below step by step Description: <a href="http Step1: After the import command, we now have access to a large number of pre-built classes and functions. This assumes the library is installed; in our lab environment all the...
Python Code: import pandas as pd Explanation: <a href="http://cocl.us/topNotebooksPython101Coursera"><img src = "https://ibm.box.com/shared/static/yfe6h4az47ktg2mm9h05wby2n7e8kei3.png" width = 750, align = "center"></a> <a href="https://www.bigdatauniversity.com"><img src = "https://ibm.box.com/shared/static/ugcqz6ohbv...
8,977
Given the following text description, write Python code to implement the functionality described below step by step Description: pyJHTDB are failed to compile on windows. One alternative way might be to use zeep package. More details can be found at http Step1: In GetData_Python, Function_name could be GetVelocity,...
Python Code: import zeep import numpy as np client = zeep.Client('http://turbulence.pha.jhu.edu/service/turbulence.asmx?WSDL') ArrayOfFloat = client.get_type('ns0:ArrayOfFloat') ArrayOfArrayOfFloat = client.get_type('ns0:ArrayOfArrayOfFloat') SpatialInterpolation = client.get_type('ns0:SpatialInterpolation') TemporalIn...
8,978
Given the following text description, write Python code to implement the functionality described below step by step Description: Material Science Tensile Tests In an engineering tensile stress test, a given specimen of cross-sectional area $A_{o}$ is subjected to a given load $P$ under tension. The stress $\sigma$ gen...
Python Code: import numpy as np # imports the numpy package and creates the alias np for broader control of vector arrays import pandas as pd # imports the pandas package and creates the alias pd to work with data tables and lists import matplotlib.pyplot as pl...
8,979
Given the following text description, write Python code to implement the functionality described below step by step Description: Tag Key Value Uploader A tool for bulk editing key value pairs for CM placements. License Copyright 2020 Google LLC, Licensed under the Apache License, Version 2.0 (the "License"); you may n...
Python Code: !pip install git+https://github.com/google/starthinker Explanation: Tag Key Value Uploader A tool for bulk editing key value pairs for CM placements. 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 Li...
8,980
Given the following text description, write Python code to implement the functionality described below step by step Description: Basic Data Analysis and Visualization Using Python by Yanal Kashou This is a free dataset of exoplanets from the RDatasets. The data was obtained from the URLs below of the .csv data file an...
Python Code: import pandas as pd porsche = pd.read_csv("PorschePrice.csv") Explanation: Basic Data Analysis and Visualization Using Python by Yanal Kashou This is a free dataset of exoplanets from the RDatasets. The data was obtained from the URLs below of the .csv data file and the .html documentation file, respective...
8,981
Given the following text description, write Python code to implement the functionality described below step by step Description: Part 2 Step1: Intermediate Level This exercise is designed for those who are already somewhat comfortable with python and want to learn more about exploiting its capabilities. It asks you t...
Python Code: # Put your code here pass # only run this cell after you finished writing your code %load beginner_soln.py Explanation: Part 2: Demonstration Exercises Here are some sample exercises to work through. They demonstrate many techniques that we use all the time. Beginner Level This exercise is designed for tho...
8,982
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('../sentiment_network/reviews.txt', 'r') as f: reviews = f.read() with open('../sentiment_network/labels.txt', 'r') as f: labels = f.read() reviews[:2000] Explanation: Sentiment Analysis with an RNN In this notebook, you'll implement a recurrent ...
8,983
Given the following text description, write Python code to implement the functionality described below step by step Description: Nearest Neighbors When exploring a large set of documents -- such as Wikipedia, news articles, StackOverflow, etc. -- it can be useful to get a list of related material. To find relevant doc...
Python Code: import graphlab import matplotlib.pyplot as plt import numpy as np %matplotlib inline Explanation: Nearest Neighbors When exploring a large set of documents -- such as Wikipedia, news articles, StackOverflow, etc. -- it can be useful to get a list of related material. To find relevant documents you typical...
8,984
Given the following text description, write Python code to implement the functionality described below step by step Description: The Step1: Step2: Now, we can create an Step3: Epochs behave similarly to Step4: You can select subsets of epochs by indexing the Step5: It is also possible to iterate through Ste...
Python Code: import mne import os.path as op import numpy as np from matplotlib import pyplot as plt Explanation: The :class:Epochs &lt;mne.Epochs&gt; data structure: epoched data :class:Epochs &lt;mne.Epochs&gt; objects are a way of representing continuous data as a collection of time-locked trials, stored in an array...
8,985
Given the following text description, write Python code to implement the functionality described below step by step Description: Exporting CSV data from the server This process is slightly cumbersome because of Unix permissions. Remember - nine times out of ten, on Unix, it's probably a permissions problem. In this c...
Python Code: !echo 'redspot' | sudo -S service postgresql restart %load_ext sql !createdb -U dbuser test %sql postgresql://dbuser@localhost:5432/test Explanation: Exporting CSV data from the server This process is slightly cumbersome because of Unix permissions. Remember - nine times out of ten, on Unix, it's probably...
8,986
Given the following text description, write Python code to implement the functionality described below step by step Description: Upload a gist via the GitHub API Our OAuthenticator config has passed GitHub information via environment variables. We can use these to publish gists to GitHub. Get the GitHub username and t...
Python Code: import os gh_user = os.environ['GITHUB_USER'] gh_token = os.environ['GITHUB_TOKEN'] Explanation: Upload a gist via the GitHub API Our OAuthenticator config has passed GitHub information via environment variables. We can use these to publish gists to GitHub. Get the GitHub username and token from environmen...
8,987
Given the following text description, write Python code to implement the functionality described below step by step Description: [PUBLIC] Analysis of CLBlast client multiple sizes <a id="overview"></a> Overview This Jupyter Notebook analyses the performance that CLBlast (single configuaration) achieves across a range...
Python Code: import os import sys import json import re Explanation: [PUBLIC] Analysis of CLBlast client multiple sizes <a id="overview"></a> Overview This Jupyter Notebook analyses the performance that CLBlast (single configuaration) achieves across a range of sizes. <a id="data"></a> Get the experimental data from D...
8,988
Given the following text description, write Python code to implement the functionality described below step by step Description: Mustererkennung in Funkmessdaten Aufgabe 1 Step1: Wir öffnen die Datenbank und lassen uns die Keys der einzelnen Tabellen ausgeben.  Step2: Aufgabe 2 Step3: Als nächstes Untersuchen wir...
Python Code: # imports import re import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt import pprint as pp Explanation: Mustererkennung in Funkmessdaten Aufgabe 1: Laden der Datenbank in Jupyter Notebook End of explanation hdf = pd.HDFStore('../../data/raw/TestMessungen_NEU.hdf') ...
8,989
Given the following text description, write Python code to implement the functionality described below step by step Description: Topology This caterogy of questions is intended to retrieve the network topology used by Batfish. This topology is a combination of information in the snapshot and inference logic (e.g., whi...
Python Code: bf.set_network('generate_questions') bf.set_snapshot('aristaevpn') Explanation: Topology This caterogy of questions is intended to retrieve the network topology used by Batfish. This topology is a combination of information in the snapshot and inference logic (e.g., which interfaces are layer3 neighbors). ...
8,990
Given the following text description, write Python code to implement the functionality described below step by step Description: Support Vector Machine - Basics Support Vector Machine (SVM) is one of the commonly used algorithm. It can be used for both classification and regression. Today we will walk through the ba...
Python Code: #import all the needed package import numpy as np import scipy as sp import pandas as pd import sklearn from sklearn.linear_model import LogisticRegression from sklearn.preprocessing import StandardScaler from sklearn.cross_validation import train_test_split,cross_val_score from sklearn import metrics from...
8,991
Given the following text description, write Python code to implement the functionality described below step by step Description: Determining the worst winter ever in Chicago The object of this exercise is to take weather observations from past winters in Chicago and determine which of them could be considered the wors...
Python Code: import pandas as pd # Read data, sort by year & month dateparse = lambda x: pd.datetime.strptime(x, '%Y%m%d') noaa_monthly = pd.read_csv('chicago-midway-noaa.csv', index_col=2, parse_dates=True, date_parser=dateparse, na_values=-9999) noaa_monthly = noaa_monthly.groupby([noaa_mon...
8,992
Given the following text description, write Python code to implement the functionality described below step by step Description: InfluxDB Logger Example This notebook is a small demo of how to use gpumon in Jupyter notebooks and some convenience methods for working with GPUs You will need to have PyTorch and Torchvisi...
Python Code: from gpumon import device_count, device_name device_count() # Returns the number of GPUs available device_name() # Returns the type of GPU available Explanation: InfluxDB Logger Example This notebook is a small demo of how to use gpumon in Jupyter notebooks and some convenience methods for working with GPU...
8,993
Given the following text description, write Python code to implement the functionality described below step by step Description: Histograms are a useful type of statistics plot for engineers. A histogram is a type of bar plot that shows the frequency or number of values compared to a set of value ranges. Histogram plo...
Python Code: import matplotlib.pyplot as plt import numpy as np # if using a Jupyter notebook, includue: %matplotlib inline Explanation: Histograms are a useful type of statistics plot for engineers. A histogram is a type of bar plot that shows the frequency or number of values compared to a set of value ranges. Histog...
8,994
Given the following text description, write Python code to implement the functionality described below step by step Description: Gradient Checking Welcome to the final assignment for this week! In this assignment you will learn to implement and use gradient checking. You are part of a team working to make mobile paym...
Python Code: # Packages import numpy as np from testCases import * from gc_utils import sigmoid, relu, dictionary_to_vector, vector_to_dictionary, gradients_to_vector Explanation: Gradient Checking Welcome to the final assignment for this week! In this assignment you will learn to implement and use gradient checking. ...
8,995
Given the following text description, write Python code to implement the functionality described below step by step Description: Trace Analysis Examples Kernel Functions Profiling Details on functions profiling are given in Plot Functions Profiling Data below. Step1: Import required modules Step2: Target Configurati...
Python Code: import logging from conf import LisaLogging LisaLogging.setup() Explanation: Trace Analysis Examples Kernel Functions Profiling Details on functions profiling are given in Plot Functions Profiling Data below. End of explanation # Generate plots inline %matplotlib inline import json import os # Support to a...
8,996
Given the following text description, write Python code to implement the functionality described below step by step Description: Lecture 2 – Lists, conditionals and loops Recap on Variables A variable named cell of memory storing a single value Assigned a value using the equals symbol Can be given any name you like E...
Python Code: exam_scores = [67,78,94,45,55,66] print("scores: " ,exam_scores) Explanation: Lecture 2 – Lists, conditionals and loops Recap on Variables A variable named cell of memory storing a single value Assigned a value using the equals symbol Can be given any name you like Except no spaces and cannot start with a...
8,997
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Scope 1. Representation - 2D, 3D plots 2. Provide idioms -- "Business graphics" line, bar, scatter plots -- "Statistics plots" whisker -- "Higher dimensioned data" - heatmap 3. In-cla...
Python Code: def mm(s_conc, vmax, km): :param np.array s_conc: substrate concentrations :param float vmax: maximum reaction rate :param float km: half substrate concentration :return np.array: reaction rates result = vmax*s_conc/(s_conc+km) return result s_conc = np.array([m+0.1 for m ...
8,998
Given the following text description, write Python code to implement the functionality described below step by step Description: The MIT License (MIT)<br> Copyright (c) 2018 Massachusetts Institute of Technology<br> Authors Step1: TESS End-to-End 6 Simulated Light Curve Time Series<br> Source Step2: Normalize flux S...
Python Code: %matplotlib inline import matplotlib.pyplot as plt plt.rcParams['figure.dpi'] = 150 Explanation: The MIT License (MIT)<br> Copyright (c) 2018 Massachusetts Institute of Technology<br> Authors: Cody Rude<br> This software has been created in projects supported by the US National<br> Science Foundation and N...
8,999
Given the following text description, write Python code to implement the functionality described below step by step Description: Implementing and comparing several pitch detection methods on sample files For simplicity I am using the Anaconda distribution on my Macbook Pro for this notebook. The purpose is to first e...
Python Code: import numpy as np import pandas as pd import matplotlib.pyplot as plt %matplotlib inline Explanation: Implementing and comparing several pitch detection methods on sample files For simplicity I am using the Anaconda distribution on my Macbook Pro for this notebook. The purpose is to first experiment here...