Unnamed: 0
int64
0
16k
text_prompt
stringlengths
110
62.1k
code_prompt
stringlengths
37
152k
7,100
Given the following text description, write Python code to implement the functionality described below step by step Description: Quality Measures Step1: <a id='pain'></a> Pain Step2: <a id='dyspnea'></a> Dyspnea Step3: <a id='constipation'></a> Constipation Screening Step4: <a id='opiod'></a> Opiod bowel regimen C...
Python Code: import pandas as pd import pickle import numpy as np import matplotlib.pyplot as plt from textwrap import wrap #from matplotlib import rcParams #rcParams.update({'figure.autolayout': True}) %matplotlib inline dd = pickle.load(open("./python_scripts/02_data_dictionary_dict.p", "rb" )) voi = ['ESASPain','ES...
7,101
Given the following text description, write Python code to implement the functionality described below step by step Description: Generative Adversarial Network In this notebook, we'll be building a generative adversarial network (GAN) trained on the MNIST dataset. From this, we'll be able to generate new handwritten d...
Python Code: %matplotlib inline import pickle as pkl import numpy as np import tensorflow as tf import matplotlib.pyplot as plt from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets('MNIST_data') Explanation: Generative Adversarial Network In this notebook, we'll be building a gen...
7,102
Given the following text description, write Python code to implement the functionality described below step by step Description: Deputado Histogramado expressao.xyz/deputado/ Como processar as sessões do parlamento Português Índice Reunír o dataset Contando as palavras mais comuns Fazendo histogramas Representações ge...
Python Code: %matplotlib inline import pylab import matplotlib import pandas import numpy dateparse = lambda x: pandas.datetime.strptime(x, '%Y-%m-%d') sessoes = pandas.read_csv('sessoes_democratica_org.csv',index_col=0,parse_dates=['data'], date_parser=dateparse) Explanation: Deputado Histogramado expressao.xyz/deputa...
7,103
Given the following text description, write Python code to implement the functionality described below step by step Description: Exercise 8 – Fit an Hubble Diagram The SN Ia Science in short The Type Ia Supernova event is the thermonuclear runaway of a white dwarf. This bright event is extremely stable and the maximum...
Python Code: import warnings # No annoying warnings warnings.filterwarnings('ignore') # Because we always need that # plot within the notebook %matplotlib inline import numpy as np import matplotlib.pyplot as mpl Explanation: Exercise 8 – Fit an Hubble Diagram The SN Ia Science in short The Type Ia Supernova event is t...
7,104
Given the following text description, write Python code to implement the functionality described below step by step Description: The network directory in this share (which is still uploading, btw) contains a pickle (data.pkl) and the code used to generate it (network.py). The lfdr_pcor object in the pickle has the par...
Python Code: ! ls -lh ../waffle_network_dir/*.tsv ! wc -l ../waffle_network_dir/network.py.tsv ! head -n 5 ../waffle_network_dir/network.py.tsv | csvlook -t ! ls -lh ../waffle_network_dir/network.py.tsv Explanation: The network directory in this share (which is still uploading, btw) contains a pickle (data.pkl) and th...
7,105
Given the following text description, write Python code to implement the functionality described below step by step Description: Example Usage Step1: pandas-learn has an identical module structure to scikit-learn, so you already know where to find all the models you already use Step2: You can use pandas to manipulat...
Python Code: import pandas as pd %matplotlib inline Explanation: Example Usage: Titanic Dataset An example of training a model on the titanic dataset. The name of the package is pandas-learn, a mixing pandas into scikit-learn. Therefore, you should always use pandas to handle your data if you are using the package(!):...
7,106
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2020 The TensorFlow Authors. Step1: Keras での重みクラスタリングの例 <table class="tfo-notebook-buttons" align="left"> <td><a target="_blank" href="https Step2: クラスタを使用せずに、MNIST の tf.keras ...
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...
7,107
Given the following text description, write Python code to implement the functionality described below step by step Description: Gravity Brightening/Darkening (gravb_bol) Setup Let's first make sure we have the latest version of PHOEBE 2.0 installed. (You can comment out this line if you don't use pip for your install...
Python Code: !pip install -I "phoebe>=2.0,<2.1" Explanation: Gravity Brightening/Darkening (gravb_bol) Setup Let's first make sure we have the latest version of PHOEBE 2.0 installed. (You can comment out this line if you don't use pip for your installation or don't want to update to the latest release). End of explanat...
7,108
Given the following text description, write Python code to implement the functionality described below step by step Description: Object-Oriented Programming We've talked about how everyting in Python is an object. In addition, we've come to use many objects. However, we have not created any objects. In this lecture, w...
Python Code: # Creating a class called Bike class Bike: pass Explanation: Object-Oriented Programming We've talked about how everyting in Python is an object. In addition, we've come to use many objects. However, we have not created any objects. In this lecture, we will discuss object-oriented programming, and what...
7,109
Given the following text description, write Python code to implement the functionality described below step by step Description: Como usar com o Pandas Os catálogos de dados abertos podem ser consultados facilmente com a ferramenta Pandas, com ou sem Jupyter Notebook. Esse tutorial inspirado na demonstração do Open Kn...
Python Code: import pandas as pd # Para trabalhar com Frictionless Data – frictionlessdata.io from tableschema import Storage from datapackage import Package # Para visualização import plotly_express as px import plotly as py, plotly.graph_objects as go Explanation: Como usar com o Pandas Os catálogos de dados abertos ...
7,110
Given the following text description, write Python code to implement the functionality described below step by step Description: build a neural network to predict the magnitude of an Earthquake given the date, time, Latitude, and Longitude as features. This is the dataset. Optimize at least 1 hyperparameter using Rand...
Python Code: %matplotlib inline import matplotlib.pyplot as plt import pandas as pd import numpy as np df = pd.read_csv("data/earthquake-database.csv") print(df.shape) df.head() Explanation: build a neural network to predict the magnitude of an Earthquake given the date, time, Latitude, and Longitude as features. This ...
7,111
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction to the TensorFlow computation graph When I started with deep learning, one of the concepts that took me quite a while to wrap my head around was the use of a computation graph w...
Python Code: import tensorflow as tf assert tf.__version__=="1.2.0" # we want that version Explanation: Introduction to the TensorFlow computation graph When I started with deep learning, one of the concepts that took me quite a while to wrap my head around was the use of a computation graph within code. Furthermore, ...
7,112
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2020 The TensorFlow Authors. Step1: Masking and padding with Keras <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https Step2: Introduction...
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...
7,113
Given the following text description, write Python code to implement the functionality described below step by step Description: This is the notebook for the python pandas dataframe course The idea of this notebook is to show the power of working with pandas dataframes Motivation We usually work with tabular data We s...
Python Code: # Import libraries import pandas as pd import numpy as np Explanation: This is the notebook for the python pandas dataframe course The idea of this notebook is to show the power of working with pandas dataframes Motivation We usually work with tabular data We should not handle them with bash commands like:...
7,114
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 MNE, dSPM, sLORETA, and eLORETA. Step1: Fixed orientation First let's...
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 fname_evoked = data_path ...
7,115
Given the following text description, write Python code to implement the functionality described below step by step Description: Getting started in scikit-learn with the famous iris dataset From the video series Step1: Machine learning on the iris dataset Framed as a supervised learning problem Step2: Machine learni...
Python Code: from IPython.display import IFrame IFrame('http://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data', width=300, height=200) Explanation: Getting started in scikit-learn with the famous iris dataset From the video series: Introduction to machine learning with scikit-learn Agenda What is the ...
7,116
Given the following text description, write Python code to implement the functionality described below step by step Description: Numpy Exercise 3 Imports Step2: Geometric Brownian motion Here is a function that produces standard Brownian motion using NumPy. This is also known as a Wiener Process. Step3: Call the bro...
Python Code: import numpy as np %matplotlib inline import matplotlib.pyplot as plt import seaborn as sns import antipackage import github.ellisonbg.misc.vizarray as va Explanation: Numpy Exercise 3 Imports End of explanation def brownian(maxt, n): Return one realization of a Brownian (Wiener) process with n steps a...
7,117
Given the following text description, write Python code to implement the functionality described below step by step Description: Hydropy-package Step1: We have a Dataframe with river discharge at different locations in the Maarkebeek basin (Belgium) Step2: Data downloaded from http Step3: Converting the dataframe t...
Python Code: #Loading the hydropy package import hydropy as hp Explanation: Hydropy-package End of explanation HTML('<iframe src=http://biomath.ugent.be/~stvhoey/maarkebeek_data/ width=700 height=350></iframe>') Explanation: We have a Dataframe with river discharge at different locations in the Maarkebeek basin (Belgiu...
7,118
Given the following text description, write Python code to implement the functionality described below step by step Description: In this exercise, you will use your new knowledge to propose a solution to a real-world scenario. To succeed, you will need to import data into Python, answer questions using the data, and ...
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: In this exercise, you will use your new knowledge to propose a solution to a real-world scenario. To succeed, you will need to impo...
7,119
Given the following text description, write Python code to implement the functionality described below step by step Description: Transliteration Transliteration is the conversion of a text from one script to another. For instance, a Latin transliteration of the Greek phrase "Ελληνική Δημοκρατία", usually translated as...
Python Code: from polyglot.transliteration import Transliterator Explanation: Transliteration Transliteration is the conversion of a text from one script to another. For instance, a Latin transliteration of the Greek phrase "Ελληνική Δημοκρατία", usually translated as 'Hellenic Republic', is "Ellēnikḗ Dēmokratía". End ...
7,120
Given the following text description, write Python code to implement the functionality described below step by step Description: 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 model for the observed data. Step1: A closer look at...
Python Code: 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: Modeling the X-ray image data In this notebook, we'll take a closer look at the X-ray image data products, an...
7,121
Given the following text description, write Python code to implement the functionality described below step by step Description: Basic reading and visualization of radar data with Py-ART Introduction to Jupyter What you are looking at is a Jupyter Notebook, a web-based interactive computation enviroment well suited fo...
Python Code: # This is a Python comment # the next line is a line of Python code print("Hello World!") Explanation: Basic reading and visualization of radar data with Py-ART Introduction to Jupyter What you are looking at is a Jupyter Notebook, a web-based interactive computation enviroment well suited for creating and...
7,122
Given the following text description, write Python code to implement the functionality described below step by step Description: Classifying Images using Dropout and Batchnorm Layer Introduction In this notebook, you learn how to build a neural network to classify the tf-flowers dataset using dropout and batchnorm lay...
Python Code: import tensorflow as tf print(tf.version.VERSION) Explanation: Classifying Images using Dropout and Batchnorm Layer Introduction In this notebook, you learn how to build a neural network to classify the tf-flowers dataset using dropout and batchnorm layer. Learning objectives Define Helper Functions. Apply...
7,123
Given the following text description, write Python code to implement the functionality described below step by step Description: Prediction For investors it's interesting to know which characteristics of a loan are predictive of a loan ending in charged off. Lending club has its own algorithms beforehand that they use...
Python Code: loans = pd.read_csv('../data/loan.csv') closed_loans = loans[loans['loan_status'].isin(['Fully Paid', 'Charged Off'])] print(closed_loans.shape) round(sum(closed_loans['loan_status']=='Charged Off')/len(closed_loans['loan_status'])*100) Explanation: Prediction For investors it's interesting to know which c...
7,124
Given the following text description, write Python code to implement the functionality described below step by step Description: The basic imports and the variables we'll be using Step1: Examples and tests Step2: Sympy can be a little tricky because it caches things, which means that the first implementation of this...
Python Code: from __future__ import division import sympy from sympy import * from sympy import Rational as frac import simpletensors from simpletensors import Vector, TensorProduct, SymmetricTensorProduct, Tensor init_printing() var('vartheta, varphi') var('nu, m, delta, c, t') # These are related scalar functions of ...
7,125
Given the following text description, write Python code to implement the functionality described below step by step Description: Resumen de NLTK Step2: Gramáticas Independientes del Contexto (CFG) Noam Chmosky definió una jerarquía de lenguajes y gramáticas que se utiliza habitualmente en Lingüística e Informática pa...
Python Code: from __future__ import print_function from __future__ import division import nltk Explanation: Resumen de NLTK: Análisis sintáctico Este resumen se corresponde con el capítulo 8 del NLTK Book Analyzing Sentence Structure. La lectura del capítulo es muy recomendable. En este resumen vamos a repasar cómo cre...
7,126
Given the following text description, write Python code to implement the functionality described below step by step Description: Compute ICA on MEG data and remove artifacts ICA is fit to MEG raw data. The sources matching the ECG and EOG are automatically found and displayed. Subsequently, artifact detection and reje...
Python Code: # Authors: Denis Engemann <denis.engemann@gmail.com> # Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr> # # License: BSD (3-clause) import numpy as np import mne from mne.preprocessing import ICA from mne.preprocessing import create_ecg_epochs, create_eog_epochs from mne.datasets impor...
7,127
Given the following text description, write Python code to implement the functionality described below step by step Description: CUSTOMER CHURN Credits Step1: We'll be keeping the statistical model pretty simple for this example so the feature space is almost unchanged from what you see above. The following code simp...
Python Code: from __future__ import division import pandas as pd import numpy as np import matplotlib.pyplot as plt import json from sklearn.cross_validation import KFold from sklearn.preprocessing import StandardScaler from sklearn.cross_validation import train_test_split from sklearn.svm import SVC from sklearn.ensem...
7,128
Given the following text description, write Python code to implement the functionality described below step by step Description: Example jupyter_spark notebook This is an example notebook to demonstrate the jupyter_spark notebook plugin. It is based on the approximating pi example in the pyspark documentation. This w...
Python Code: import sys from random import random from operator import add from pyspark.sql import SparkSession Explanation: Example jupyter_spark notebook This is an example notebook to demonstrate the jupyter_spark notebook plugin. It is based on the approximating pi example in the pyspark documentation. This works ...
7,129
Given the following text description, write Python code to implement the functionality described. Description: Everyone knows Fibonacci sequence, it was studied deeply by mathematicians in the last couple centuries. However, what people don't know is Tribonacci sequence. Tribonacci sequence is defined by the r...
Python Code: def tri(n): if n == 0: return [1] my_tri = [1, 3] for i in range(2, n + 1): if i % 2 == 0: my_tri.append(i / 2 + 1) else: my_tri.append(my_tri[i - 1] + my_tri[i - 2] + (i + 3) / 2) return my_tri
7,130
Given the following text description, write Python code to implement the functionality described below step by step Description: RCM modeling with varying reactor volume This example is available as an ipynb (Jupyter Notebook) file in the main GitHub repository at https Step1: Next, we have to load the ChemKED file a...
Python Code: import cantera as ct import numpy as np from pyked import ChemKED Explanation: RCM modeling with varying reactor volume This example is available as an ipynb (Jupyter Notebook) file in the main GitHub repository at https://github.com/pr-omethe-us/PyKED/blob/master/docs/rcm-example.ipynb The ChemKED file th...
7,131
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction au Streaming adaptatif Luc Trudeau Au menu Step1: Llama Drama Low (1920x1080) 256 kbits/secondes Step2: Llama Drama Medium (1920x1080) 512 kbits/secondes Step3: Llama Drama H...
Python Code: !ffmpeg -i LlamaDrama.mp4 -movflags faststart -b:v 256000 -maxrate 256000 -x264opts "fps=24:keyint=48:min-keyint=48:no-scenecut" -hls_list_size 0 -hls_time 4 -hls_base_url http://192.168.3.14:8000/low/ low/LlamaDrama.m3u8 Explanation: Introduction au Streaming adaptatif Luc Trudeau Au menu: Implémentation ...
7,132
Given the following text description, write Python code to implement the functionality described below step by step Description: Image classification with Convolutional Neural Networks Welcome to the first week of the second deep learning certificate! We're going to use convolutional neural networks (CNNs) to allow ou...
Python Code: # Put these at the top of every notebook, to get automatic reloading and inline plotting %reload_ext autoreload %autoreload 2 %matplotlib inline Explanation: Image classification with Convolutional Neural Networks Welcome to the first week of the second deep learning certificate! We're going to use convolu...
7,133
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...
7,134
Given the following text description, write Python code to implement the functionality described below step by step Description: DAT210x - Programming with Python for DS Module3 - Lab1 Step1: Load up the wheat seeds dataset into a dataframe. We've stored a copy in the Datasets directory. Step2: Create a slice from y...
Python Code: import pandas as pd import matplotlib.pyplot as plt import matplotlib # Look pretty... # matplotlib.style.use('ggplot') plt.style.use('ggplot') Explanation: DAT210x - Programming with Python for DS Module3 - Lab1 End of explanation # .. your code here .. Explanation: Load up the wheat seeds dataset into a ...
7,135
Given the following text description, write Python code to implement the functionality described below step by step Description: Exercise 1.1 Trim sequence to multiples of three characters Write a function trim(s) that trims the sequence s (which is a Seq object) to a multiple of three characters so that its translati...
Python Code: def trim(s): # implement this function pass # test case import Bio.Seq as BS s = BS.Seq("ACGCGGCGTG") print(s, "has length", len(s)) # write a piece of code here which will # print the translated sequence 'TRR' # without any errors Explanation: Exercise 1.1 Trim sequence to multiples of three chara...
7,136
Given the following text description, write Python code to implement the functionality described below step by step Description: Since the annotation channel of this data is somewhat suspect, I decided to load some alternate annoation files to compare Interestingly, the labels are exactly 3 times the z span of the p1 ...
Python Code: def otsuVox(argVox): probVox = np.nan_to_num(argVox) bianVox = np.zeros_like(probVox) for zIndex, curSlice in enumerate(probVox): #if the array contains all the same values if np.max(curSlice) == np.min(curSlice): #otsu thresh will fail here, leave bianVox as all 0's...
7,137
Given the following text description, write Python code to implement the functionality described below step by step Description: Libraries Step1: NOTE Step2: Analysis RASLseqAnalysis_STAR Step3: Demultiplexing and Aligning FASTQ Reads Step4: SUMMARY REPORT
Python Code: import pandas as pd import os, sys, time, random import numpy as np from scipy import stats sys.path.append('../') from RASLseqTools import * sys.path.append('../RASLseqTools') import RASLseqAnalysis_STAR import seaborn %pylab inline %matplotlib inline %config InlineBackend.figure_format = 'retina' Explana...
7,138
Given the following text problem statement, write Python code to implement the functionality described below in problem statement Problem: So in numpy arrays there is the built in function for getting the diagonal indices, but I can't seem to figure out how to get the diagonal ending at bottom left rather than botton r...
Problem: import numpy as np a = np.array([[ 0, 1, 2, 3, 4, 5], [ 5, 6, 7, 8, 9, 10], [10, 11, 12, 13, 14, 15], [15, 16, 17, 18, 19, 20], [20, 21, 22, 23, 24, 25]]) dim = min(a.shape) b = a[:dim,:dim] result = np.vstack((np.diag(b), np.diag(np.fliplr(b))))
7,139
Given the following text description, write Python code to implement the functionality described below step by step Description: Sigma to Pressure Interpolation By using metpy.calc.log_interp, data with sigma as the vertical coordinate can be interpolated to isobaric coordinates. Step1: Data The data for this example...
Python Code: import cartopy.crs as ccrs import cartopy.feature as cfeature import matplotlib.pyplot as plt from netCDF4 import Dataset, num2date from metpy.cbook import get_test_data from metpy.interpolate import log_interpolate_1d from metpy.plots import add_metpy_logo, add_timestamp from metpy.units import units Expl...
7,140
Given the following text description, write Python code to implement the functionality described below step by step Description: Simple charts in pandas In this session, we're gonna revisit our MLB data to rock a quick chart in pandas. Our goal Step1: Let Jupyter know that you're gonna be charting inline (Don't worry...
Python Code: # import a ticker formatting class from matplotlib Explanation: Simple charts in pandas In this session, we're gonna revisit our MLB data to rock a quick chart in pandas. Our goal: A horizontal bar chart of the top 10 teams by payroll. Import pandas and a some chart formatting help End of explanation # cre...
7,141
Given the following text description, write Python code to implement the functionality described below step by step Description: Function definitions and some other parameters Step1: Load a mean pulse profile for B1957+20, and fit a gaussian to the main pulse Step2: Isolate the main pulse, sqrt it, and center Step3:...
Python Code: res = 10000 # 1 sample is 1/res*1.6ms, 1e7 to resolve 311Mhz n = 40 * res # grid size, total time n = n-1 # To get the wave periodicity edge effects to work out #freq = 311.25 # MHz, observed band freq = 0.5 # Test, easier on computation p_spin = 1.6 # ms, spin period freq *= 1e6 #MHz to Hz p_spin *= 1e-3 ...
7,142
Given the following text description, write Python code to implement the functionality described below step by step Description: Example implementation of the ESU subgraph enumeration algorithm in python Load the packages that we will need Step1: Set the random number seed to 1337 Step2: Define the extend_subgraph f...
Python Code: import igraph import random import collections Explanation: Example implementation of the ESU subgraph enumeration algorithm in python Load the packages that we will need End of explanation def exclusive_neighborhood(graph, v, Vp): assert type(graph)==igraph.Graph assert type(v)==int assert typ...
7,143
Given the following text description, write Python code to implement the functionality described below step by step Description: 1. Giới thiệu Trong notebook này, mình sẽ trình bày cách giải quyết đề tài tuyển dụng của VinID. Mô hình CNN được sử dụng để phân loại 10 số viết tay trong bộ MNIST. Trong notebook này,bao g...
Python Code: !pip install hyperas # Basic compuational libaries import pandas as pd import numpy as np import matplotlib.pyplot as plt import matplotlib.image as mpimg import seaborn as sns %matplotlib inline np.random.seed(2) from sklearn.model_selection import train_test_split from sklearn.metrics import confusion_ma...
7,144
Given the following text description, write Python code to implement the functionality described. Description: Program to find the smallest element among three elements Python implementation to find the smallest of three elements
Python Code: a , b , c = 5 , 7 , 10 if(a <= b and a <= c ) : print(a , "is ▁ the ▁ smallest ")  elif(b <= a and b <= c ) : print(b , "is ▁ the ▁ smallest ")  else : print(c , "is ▁ the ▁ smallest ") 
7,145
Given the following text description, write Python code to implement the functionality described below step by step Description: Step3: Testing the Numerial Gradient This notebook explores the assess the differences and validity in calculating the spectral slope using finite differences or np.gradient(). In Figueira e...
Python Code: import matplotlib matplotlib.rcParams["text.usetex"] = False matplotlib.rcParams["text.latex.unicode"] = True import matplotlib.pyplot as plt import numpy as np %matplotlib inline from eniric.utilities import load_aces_spectrum # from eniric.precision import slope, slope_grad def slope(wavelength, flux): ...
7,146
Given the following text description, write Python code to implement the functionality described below step by step Description: Ensemble of Decision Trees By Parijat Mazumdar (GitHub ID Step1: Next, we decide the parameters of our Random Forest. Step2: In the above code snippet, we decided to create a forest using ...
Python Code: import os SHOGUN_DATA_DIR=os.getenv('SHOGUN_DATA_DIR', '../../../../data') import shogun as sg import numpy as np import matplotlib.pyplot as plt %matplotlib inline def load_file(feat_file,label_file): feats=sg.create_features(sg.read_csv(feat_file)) labels=sg.create_labels(sg.read_csv(label_file))...
7,147
Given the following text description, write Python code to implement the functionality described below step by step Description: <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https Step1: We define the model, adapted from the Keras CIFAR-10 example Step2: We train the model us...
Python Code: import tensorflow as tf # Check that GPU is available: cf. https://colab.research.google.com/notebooks/gpu.ipynb assert(tf.test.is_gpu_available()) tf.keras.backend.clear_session() tf.config.optimizer.set_jit(False) # Start with XLA disabled. def load_data(): (x_train, y_train), (x_test, y_test) = tf.ker...
7,148
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2018 The TensorFlow Authors. Step1: tf.data を使ったテキストの読み込み <table class="tfo-notebook-buttons" align="left"> <td><a target="_blank" href="https Step2: 例 1 Step3: train/csharp、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 # dist...
7,149
Given the following text description, write Python code to implement the functionality described below step by step Description: Φ<sub>Flow</sub> Math The phi.math module provides abstract access to tensor operations. It internally uses NumPy/SciPy, TensorFlow or PyTorch to execute the actual operations, depending on ...
Python Code: from phi import math Explanation: Φ<sub>Flow</sub> Math The phi.math module provides abstract access to tensor operations. It internally uses NumPy/SciPy, TensorFlow or PyTorch to execute the actual operations, depending on which backend is selected (see below). This ensures that code written against phi.m...
7,150
Given the following text description, write Python code to implement the functionality described below step by step Description: Number of papers over time data source We load the data from the Competence Centre for Bibliometrics Step1: set parameter Step24: load data from SQL database Step25: merging data Step26: ...
Python Code: import cx_Oracle #ensure that OS, InstantClient (Basic, ODBC, SDK) and cx_Oracle are all 64 bit. Install with "pip install cx_Oracle". Add link to InstantClient in Path variable! import pandas as pd import re import plotly.plotly as py import plotly.graph_objs as go Explanation: Number of papers over time ...
7,151
Given the following text description, write Python code to implement the functionality described below step by step Description: syncID Step1: First we will define the extents of the rectangular array containing the section from each BRDF flightline. Step2: Next we will define the coordinates of the target of intere...
Python Code: import h5py import csv import numpy as np import os import gdal import matplotlib.pyplot as plt import sys from math import floor import time import warnings warnings.filterwarnings('ignore') def h5refl2array(h5_filename): hdf5_file = h5py.File(h5_filename,'r') #Get the site name file_attrs_str...
7,152
Given the following text description, write Python code to implement the functionality described below step by step Description: Index - Back - Next Widget List Step1: Numeric widgets There are many widgets distributed with IPython that are designed to display numeric values. Widgets exist for displaying integers an...
Python Code: import ipywidgets as widgets Explanation: Index - Back - Next Widget List End of explanation widgets.IntSlider( value=7, min=0, max=10, step=1, description='Test:', disabled=False, continuous_update=False, orientation='horizontal', readout=True, readout_format='d' ) ...
7,153
Given the following text description, write Python code to implement the functionality described below step by step Description: A Decision Tree of Observable Operators Part 3 Step1: ...by emitting all of the items emitted by corresponding Observables flat_map(flat_map) Step2: flat_map_latest(select_switch) Step3: ...
Python Code: reset_start_time(O.map, title='map') # alias is "select" # warming up: d = subs(O.from_((1, 2 , 3)).map(lambda x: x * 2)) rst(O.pluck, title='pluck') d = subs(O.from_([{'x': 1, 'y': 2}, {'x': 3, 'y': 4}]).pluck('y')) class Coord: def __init__(self, x, y): self.x = x self.y = y rst(titl...
7,154
Given the following text description, write Python code to implement the functionality described below step by step Description: Solving the HJB The HJB equation, is used in dynamic programming to solve optimisation problem. Optimisation problems occur in all walks of life and some can even be solved. And some of thos...
Python Code: import numpy as np import time import matplotlib.pyplot as plt Explanation: Solving the HJB The HJB equation, is used in dynamic programming to solve optimisation problem. Optimisation problems occur in all walks of life and some can even be solved. And some of those that can be solved are best solved with...
7,155
Given the following text description, write Python code to implement the functionality described below step by step Description: Working with Graphs using Networkx Intro When creating a graph object, it can either be empty (default) or you can pass data as an argument. The data can take multiple forms Step1: Notice t...
Python Code: # isntantiate a graph object G = nx.Graph() # add a single node G.add_node(1) # add multiple nodes from a list G.add_nodes_from([2,3,5]) # return lists of nodes and edges in the graph G.nodes(), G.edges() Explanation: Working with Graphs using Networkx Intro When creating a graph object, it can either be e...
7,156
Given the following text description, write Python code to implement the functionality described below step by step Description: ATM 623 Step1: Contents The ice ages Introducing the astronomical theory of the ice ages Ellipses and orbits Past orbital variations Using climlab to calculate insolation for arbitrary orbi...
Python Code: # Ensure compatibility with Python 2 and 3 from __future__ import print_function, division Explanation: ATM 623: Climate Modeling Brian E. J. Rose, University at Albany Lecture 16: Orbital variations, insolation, and the ice ages Warning: content out of date and not maintained You really should be looking...
7,157
Given the following text description, write Python code to implement the functionality described below step by step Description: Random forest regression example As an experiment, we'll look at a dataset uniquely well suited to modeling with random forest regression. Step1: Generate fake data Step2: The target varia...
Python Code: import numpy as np import pandas as pd from sklearn.ensemble import RandomForestRegressor from sklearn.metrics import r2_score import matplotlib.pyplot as plt Explanation: Random forest regression example As an experiment, we'll look at a dataset uniquely well suited to modeling with random forest regressi...
7,158
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_orig = f.read() reviews[:2000] Explanation: Sentiment Analysis with an RNN In this notebook, you'll implement a recur...
7,159
Given the following text description, write Python code to implement the functionality described below step by step Description: Logistic Regression cf. sklearn.linear_model.LogisticRegression documentation Let's take a look at the examples in the LogisticRegression documentation of sklearn. The Logistic Regression ...
Python Code: import numpy as np import matplotlib.pyplot as plt from sklearn import linear_model, datasets # import some data to play with iris = datasets.load_iris() X = iris.data[:, :2] # take the first two features. # EY : 20160503 type(X) is numpy.ndarray Y = iris.target # EY : 20160503 type(Y) is numpy.ndarray h ...
7,160
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...
7,161
Given the following text description, write Python code to implement the functionality described below step by step Description: Filter Design Using the Helper Modules The Scipy package signal assists with the design of many digital filter types. As an alternative, here we explore the use of the filter design modules ...
Python Code: Image('300ppi/FIR_Lowpass_Highpass_Bandpass_Bandstop@300ppi.png',width='90%') Explanation: Filter Design Using the Helper Modules The Scipy package signal assists with the design of many digital filter types. As an alternative, here we explore the use of the filter design modules found in scikit-dsp-comm (...
7,162
Given the following text description, write Python code to implement the functionality described below step by step Description: When we cannot afford to sample the quantity of interest many times at every design within an optimization, we can use surrogate models instead. Here we will show you how to use third party ...
Python Code: from horsetailmatching import HorsetailMatching, UniformParameter from horsetailmatching.demoproblems import TP2 from horsetailmatching.surrogates import PolySurrogate import numpy as np uparams = [UniformParameter(), UniformParameter()] Explanation: When we cannot afford to sample the quantity of interest...
7,163
Given the following text description, write Python code to implement the functionality described below step by step Description: Note that job 2 has not executed because it is waiting for job 4, which has not run yet Step3: Here is how to make a dependency queue with pool We have to sleep a lot in this script to allo...
Python Code: queue.put([jon, 'done', None]) myjobs = update_jobs(myjobs, outqueue) myjobs runner.is_alive() outqueue.empty() myjobs = update_jobs(myjobs, outqueue) myjobs Explanation: Note that job 2 has not executed because it is waiting for job 4, which has not run yet End of explanation def job_runner(cores, jobqueu...
7,164
Given the following text description, write Python code to implement the functionality described below step by step Description: Программирование на Python Дзен Python Step1: Красивое лучше, чем уродливое.<br> Явное лучше, чем неявное.<br> Простое лучше, чем сложное.<br> Сложное лучше, чем запутанное.<br> Плоское луч...
Python Code: %pylab inline import this Explanation: Программирование на Python Дзен Python End of explanation import numpy as np np.array([1,2,3]) a = np.array([[1,2,3], [4,5,6]]) a = np.array([1,2,3]) b = np.array([4,5,6]) a+b a*b a/b a**b Explanation: Красивое лучше, чем уродливое.<br> Явное лучше, чем неявное.<br> П...
7,165
Given the following text description, write Python code to implement the functionality described below step by step Description: Text Analysis with NLTK Author Step1: 1. Corpus acquisition. In these notebooks we will explore some tools for text analysis and two topic modeling algorithms available from Python toolboxe...
Python Code: # %matplotlib inline import numpy as np import matplotlib.pyplot as plt # import pylab # Required imports from wikitools import wiki from wikitools import category import nltk from nltk.tokenize import word_tokenize from nltk.corpus import stopwords from nltk.stem import WordNetLemmatizer from time import ...
7,166
Given the following text description, write Python code to implement the functionality described below step by step Description: Review from the previous lecture In yesterday's Lecture 2, you learned how to use the numpy module, how to make your own functions, and how to import and export data. Below is a quick review...
Python Code: import numpy as np Explanation: Review from the previous lecture In yesterday's Lecture 2, you learned how to use the numpy module, how to make your own functions, and how to import and export data. Below is a quick review before we move on to Lecture 3. Remember, to use the numpy module, first it must be ...
7,167
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2020 Google LLC Licensed under the Apache License, Version 2.0 (the "License") Step1: Retrain a classification model for Edge TPU using post-training quantization (with TF2) In th...
Python Code: # 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 # distribute...
7,168
Given the following text description, write Python code to implement the functionality described below step by step Description: 1. Python basics This chapter only gives a short introduction to Python to make the explanations in the following chapters more understandable. A detailed description would be too extensive ...
Python Code: print('Hello World') Explanation: 1. Python basics This chapter only gives a short introduction to Python to make the explanations in the following chapters more understandable. A detailed description would be too extensive and would go beyond the scope of this tutorial. Take a look at https://docs.python....
7,169
Given the following text description, write Python code to implement the functionality described below step by step Description: ===================================================================== Spectro-temporal receptive field (STRF) estimation on continuous data ==================================================...
Python Code: # Authors: Chris Holdgraf <choldgraf@gmail.com> # Eric Larson <larson.eric.d@gmail.com> # # License: BSD (3-clause) import numpy as np import matplotlib.pyplot as plt import mne from mne.decoding import ReceptiveField, TimeDelayingRidge from scipy.stats import multivariate_normal from scipy.io imp...
7,170
Given the following text description, write Python code to implement the functionality described below step by step Description: <h1>CAR Classic predictor - Regressor</h1> <hr style="border Step1: <span> Build a processor. </span> <br> <span> This is required by the regressor in order to parse the input raw data.<br>...
Python Code: import sys #sys.path.insert(0, 'I:/git/att/src/python/') sys.path.insert(0, 'i:/dev/workspaces/python/att-workspace/att/src/python/') Explanation: <h1>CAR Classic predictor - Regressor</h1> <hr style="border: 1px solid #000;"> <span> <h2>ATT hit predictor.</h2> </span> <br> <span> This notebook shows how t...
7,171
Given the following text description, write Python code to implement the functionality described below step by step Description: Vision data Helper functions to get data in a DataLoaders in the vision application and higher class ImageDataLoaders The main classes defined in this module are ImageDataLoaders and Segment...
Python Code: #|export @delegates(subplots) def get_grid( n:int, # Number of axes in the returned grid nrows:int=None, # Number of rows in the returned grid, defaulting to `int(math.sqrt(n))` ncols:int=None, # Number of columns in the returned grid, defaulting to `ceil(n/rows)` figsize:tuple=None, # Wid...
7,172
Given the following text description, write Python code to implement the functionality described below step by step Description: Chapter 8 Step1: Why was an a returned instead of b? Computer scientists (and much of Europe) count starting with 0 These sequence are referred to as zero-based The bracket notation only ac...
Python Code: fruit = 'banana' letter = fruit[1] print( letter ) Explanation: Chapter 8: Strings Contents - A string is a sequence - The len operator - Traversal with a for loop - String slices - Strings are immutable - Searching - String methods - The in operator - String comparison - Debugging - Exercises This noteboo...
7,173
Given the following text description, write Python code to implement the functionality described below step by step Description: Using lambdify for plotting expressions The syntethic isotope Technetium-99m is used in medical diagnostics (scintigraphy) Step1: now we need to determine the integration constants from the...
Python Code: import sympy as sym sym.init_printing() symbs = t, l1, l2, x0, y0, z0 = sym.symbols('t lambda_1 lambda_2 x0 y0 z0', real=True, nonnegative=True) funcs = x, y, z = [sym.Function(s)(t) for s in 'xyz'] inits = [f.subs(t, 0) for f in funcs] diffs = [f.diff(t) for f in funcs] exprs = -l1*x, l1*x - l2*y, l2*y eq...
7,174
Given the following text description, write Python code to implement the functionality described below step by step Description: Following the tutorial at Step1: Accessing Data You can access DataFrame data using familiar Python dict/list operations Step2: Manipulating Data You may apply Python's basic arithmetic op...
Python Code: import pandas as pd # There are two data structures in pandas, Series and DataFrames city_names = pd.Series(['San Francisco', 'San Jose', 'Sacramento']) population = pd.Series([852469, 1015785, 485199]) pd.DataFrame({"City Name": city_names, "Population": population}) # importing an existing csv file into ...
7,175
Given the following text description, write Python code to implement the functionality described below step by step Description: Google form analysis tests Table of Contents 'Google form analysis' functions checks Google form loading Selection of a question Selection of a user's answers checking answers comparison of ...
Python Code: %run "../Functions/1. Google form analysis.ipynb" # Localplayerguids of users who answered the questionnaire (see below). # French #localplayerguid = 'a4d4b030-9117-4331-ba48-90dc05a7e65a' #localplayerguid = 'd6826fd9-a6fc-4046-b974-68e50576183f' #localplayerguid = 'deb089c0-9be3-4b75-9b27-28963c77b10c' #l...
7,176
Given the following text description, write Python code to implement the functionality described below step by step Description: Predicting sentiment from product reviews Fire up GraphLab Create Step1: Read some product review data Loading reviews for a set of baby products. Step2: Let's explore this data together D...
Python Code: import graphlab Explanation: Predicting sentiment from product reviews Fire up GraphLab Create End of explanation products = graphlab.SFrame('amazon_baby.gl/') Explanation: Read some product review data Loading reviews for a set of baby products. End of explanation products.head() Explanation: Let's explor...
7,177
Given the following text description, write Python code to implement the functionality described below step by step Description: <h1>Training Keras model on Cloud AI Platform</h1> This notebook illustrates distributed training and hyperparameter tuning on Cloud AI Platform (formerly known as Cloud ML Engine). This use...
Python Code: # change these to try this notebook out BUCKET = 'cloud-training-demos-ml' PROJECT = 'cloud-training-demos' REGION = 'us-central1' import os os.environ['BUCKET'] = BUCKET os.environ['PROJECT'] = PROJECT os.environ['REGION'] = REGION os.environ['TFVERSION'] = '2.0' # not used in this notebook %%bash gcloud...
7,178
Given the following text description, write Python code to implement the functionality described below step by step Description: k-Nearest Neighbor (kNN) exercise Complete and hand in this completed worksheet (including its outputs and any supporting code outside of the worksheet) with your assignment submission. For ...
Python Code: import sys print(sys.version) # Run some setup code for this notebook. import random import numpy as np from cs231n.data_utils import load_CIFAR10 import matplotlib.pyplot as plt # This is a bit of magic to make matplotlib figures appear inline in the notebook # rather than in a new window. %matplotlib inl...
7,179
Given the following text description, write Python code to implement the functionality described below step by step Description: Particle Swarm Optimization Algorithm (in Python!) [SPOILER] We will be using the Particle Swarm Optimization algorithm to obtain the minumum of a customed objective function First of all, l...
Python Code: import numpy as np import matplotlib.pyplot as plt # import scipy as sp # import time %matplotlib inline plt.style.use('bmh') Explanation: Particle Swarm Optimization Algorithm (in Python!) [SPOILER] We will be using the Particle Swarm Optimization algorithm to obtain the minumum of a customed objective fu...
7,180
Given the following text description, write Python code to implement the functionality described below step by step Description: The Quantum Approximate Optimization Algorithm for MAX-CUT The following is a step-by-step guide to running QAOA on the MaxCut problem. In the debue paper on QAOA (arXiv Step1: The cost Ha...
Python Code: import pyquil.forest as qvm_module import numpy as np from grove.pyqaoa.maxcut_qaoa import maxcut_qaoa barbell = [(0, 1)] # graph is a defined by a list of edges. Edge weights are assumed to be 1.0 steps = 1 # evolution path length between the ref hamiltonian and cost hamiltonian inst = maxcut_qaoa(barb...
7,181
Given the following text description, write Python code to implement the functionality described below step by step Description: Distributed Deep Learning with Apache Spark and Keras Joeri Hermans (Technical Student, IT-DB-SAS, CERN) Departement of Knowledge Engineering Maastricht University, The Net...
Python Code: !(date +%d\ %B\ %G) Explanation: Distributed Deep Learning with Apache Spark and Keras Joeri Hermans (Technical Student, IT-DB-SAS, CERN) Departement of Knowledge Engineering Maastricht University, The Netherlands End of explanation import numpy as np import time import requests from kera...
7,182
Given the following text description, write Python code to implement the functionality described below step by step Description: Question 1 Step1: Motivations The problem we try to solve in the question 1 is evaluating the average causal effect of the "treatment" represented by the job training program. A naive anal...
Python Code: import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import numpy as np from scipy import optimize from scipy import spatial %matplotlib inline import warnings warnings.filterwarnings('ignore') sns.set(rc={"figure.figsize": (15, 6)}) sns.set_palette(sns.color_palette("Set2", 10)) lalon...
7,183
Given the following text description, write Python code to implement the functionality described below step by step Description: This notebook is intended to show how to use pandas, and sql alchemy to upload data into DB2-switch and create geospatial coordinate and indexes. Install using pip or any other package manag...
Python Code: import pandas as pd from sqlalchemy import create_engine Explanation: This notebook is intended to show how to use pandas, and sql alchemy to upload data into DB2-switch and create geospatial coordinate and indexes. Install using pip or any other package manager pandas, sqlalchemy and pg8000. The later one...
7,184
Given the following text description, write Python code to implement the functionality described below step by step Description: Funciones y expresiones booleanas El paquete sympy tiene un módulo de lógica. Con él podemos hacer algunas simplificaciones Step1: Definimos los símbolos que vamos a utilizar. Supremo e ínf...
Python Code: from sympy import * Explanation: Funciones y expresiones booleanas El paquete sympy tiene un módulo de lógica. Con él podemos hacer algunas simplificaciones End of explanation x, y, z = symbols("x,y,z") p = (x | y) & ~ z pprint(p) Explanation: Definimos los símbolos que vamos a utilizar. Supremo e ínfimo s...
7,185
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction to Lea Step1: Summary Random variables are abstract objects. Transparent method for drawing random samples variable.random(times). Standard statistical metrics of the probabil...
Python Code: from lea import * # mandatory die example - initilize a die object die = Lea.fromVals(1, 2, 3, 4, 5, 6) # throw the die a few times die.random(20) # mandatory coin toss example - states can be strings! coin = Lea.fromVals('Head', 'Tail') # toss the coin a few times coin.random(10) # how about a Boolean var...
7,186
Given the following text description, write Python code to implement the functionality described below step by step Description: ES-DOC CMIP6 Model Properties - Ocnbgchem MIP Era Step1: Document Authors Set document authors Step2: Document Contributors Specify document contributors Step3: Document Publication Speci...
Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'mpi-m', 'mpi-esm-1-2-lr', 'ocnbgchem') Explanation: ES-DOC CMIP6 Model Properties - Ocnbgchem MIP Era: CMIP6 Institute: MPI-M Source ID: MPI-ESM-1-2-LR Topic: Ocnbgchem Sub-Topics: Tr...
7,187
Given the following text problem statement, write Python code to implement the functionality described below in problem statement Problem: I am trying to find duplicates rows in a pandas dataframe.
Problem: import pandas as pd df=pd.DataFrame(data=[[1,2],[3,4],[1,2],[1,4],[1,2]],columns=['col1','col2']) def g(df): df['index_original'] = df.groupby(['col1', 'col2']).col1.transform('idxmin') return df[df.duplicated(subset=['col1', 'col2'], keep='first')] result = g(df.copy())
7,188
Given the following text description, write Python code to implement the functionality described below step by step Description: Wilson-Devinney Style Meshing NOTE Step1: As always, let's do imports and initialize a logger and a new bundle. See Building a System for more details. Step2: Changing Meshing Options Nex...
Python Code: !pip install -I "phoebe>=2.1,<2.2" %matplotlib inline Explanation: Wilson-Devinney Style Meshing NOTE: Wilson-Devinney Style meshing requires developer mode in PHOEBE and is meant to be used for testing, not used for science. Setup Let's first make sure we have the latest version of PHOEBE 2.1 installed. (...
7,189
Given the following text description, write Python code to implement the functionality described below step by step Description: We're going to simulate data discretely sampled in time. We need to set a sample rate in Hz. The highest resolvable frequency, the Nyquist frequency, is half the sample rate. We also need to...
Python Code: sample_rate = 4096 nyquist = sample_rate/2 time_length_seconds = 512 Explanation: We're going to simulate data discretely sampled in time. We need to set a sample rate in Hz. The highest resolvable frequency, the Nyquist frequency, is half the sample rate. We also need to decide how long the simulated data...
7,190
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Statistics of Stable Step2: Property Occurence Step3: Success Ratio of Properties (Normalized) Step4: Success Ratio by unit Step5: Failure Ratio does not depend on #props Step6: ...
Python Code: import json, re, pprint, os, datetime import pandas as pd import numpy as np import matplotlib pltsettings = { "figure.figsize" : (5.0, 4.0), "pgf.texsystem" : "pdflatex", "font.family": "sans", "font.serif": [], # use latex default serif font #"font.sans-serif": ["Dej...
7,191
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction to Earth Engine and TensorFlow in Cloud Datalab This notebook walks you through a simple example of using Earth Engine and TensorFlow together in Cloud Datalab. Specifically, we...
Python Code: import ee from IPython import display import math from matplotlib import pyplot import numpy from osgeo import gdal import tempfile import tensorflow as tf import urllib import zipfile Explanation: Introduction to Earth Engine and TensorFlow in Cloud Datalab This notebook walks you through a simple example...
7,192
Given the following text description, write Python code to implement the functionality described below step by step Description: Benchmarking Python Clustering Algorithms on 2D Data Other notebooks perform a more genenral analysis of clustering algorithms; this notebook is looking at the special case of two dimensiona...
Python Code: import hdbscan import debacl import fastcluster import sklearn.cluster import scipy.cluster import sklearn.datasets import numpy as np import pandas as pd import time import matplotlib.pyplot as plt import seaborn as sns %matplotlib inline sns.set_context('poster') sns.set_palette('Paired', 10) sns.set_col...
7,193
Given the following text description, write Python code to implement the functionality described below step by step Description: PyBroom Example - Multiple Datasets - Minimize This notebook is part of pybroom. This notebook demonstrate using pybroom when performing Maximum-Likelihood fitting (scalar minimization as op...
Python Code: %matplotlib inline %config InlineBackend.figure_format='retina' # for hi-dpi displays import numpy as np import pandas as pd import matplotlib.pyplot as plt from matplotlib.pylab import normpdf import seaborn as sns from lmfit import Model import lmfit print('lmfit: %s' % lmfit.__version__) sns.set_style(...
7,194
Given the following text description, write Python code to implement the functionality described below step by step Description: Exogenous Variables with PyAF PyAF allows using some external sources to improve its forecasts. In addition to the training dataset, the user can provide an external table with exogenous va...
Python Code: import numpy as np import pandas as pd import datetime csvfile_link = "https://raw.githubusercontent.com/antoinecarme/pyaf/master/data/ozone-la-exogenous-2.csv" exog_dataframe = pd.read_csv(csvfile_link); exog_dataframe['Date'] = exog_dataframe['Date'].astype(np.datetime64); print(exog_dataframe.info()) ex...
7,195
Given the following text description, write Python code to implement the functionality described below step by step Description: Continuing from the previous blog post, this notebook will explain how to deploy a Bokeh server on Heroku, allowing the world to access the brilliant data visualizations that you've develope...
Python Code: python-3.6.1 Explanation: Continuing from the previous blog post, this notebook will explain how to deploy a Bokeh server on Heroku, allowing the world to access the brilliant data visualizations that you've developed using Bokeh. Note- this tutorial was written in May 2017. If you're reading at a much lat...
7,196
Given the following text description, write Python code to implement the functionality described below step by step Description: Examining racial discrimination in the US job market Background Racial discrimination continues to be pervasive in cultures throughout the world. Researchers examined the level of racial dis...
Python Code: %matplotlib inline import pandas as pd import numpy as np import scipy.stats as stats import matplotlib.pyplot as plt import seaborn as sns sns.set(color_codes=True) from IPython.core.display import HTML css = open('style-table.css').read() + open('style-notebook.css').read() HTML('<style>{}</style>'.forma...
7,197
Given the following text description, write Python code to implement the functionality described below step by step Description: Load up some example data. This is a little 28 residue peptide Step1: md.baker_hubbard idenfies hydrogen bonds baced on cutoffs for the Donor-H...Acceptor distance and angle. The criterion ...
Python Code: t = md.load_pdb('http://www.rcsb.org/pdb/files/2EQQ.pdb') print(t) Explanation: Load up some example data. This is a little 28 residue peptide End of explanation hbonds = md.baker_hubbard(t, periodic=False) label = lambda hbond : '%s -- %s' % (t.topology.atom(hbond[0]), t.topology.atom(hbond[2])) for hbond...
7,198
Given the following text description, write Python code to implement the functionality described below step by step Description: Summarizing Images Images are high dimensional objects Step1: How Many Photons Came From the Cluster? Let's estimate the total counts due to the cluster. That means we need to somehow ignor...
Python Code: import astropy.io.fits as pyfits import numpy as np import astropy.visualization as viz import matplotlib.pyplot as plt %matplotlib inline plt.rcParams['figure.figsize'] = (10.0, 10.0) targdir = 'a1835_xmm/' imagefile = targdir+'P0098010101M2U009IMAGE_3000.FTZ' expmapfile = targdir+'P0098010101M2U009EXPMA...
7,199
Given the following text description, write Python code to implement the functionality described below step by step Description: Detecting Twitter Bots Step1: Exploratory Data Analysis Identifying Missingness in the data Step2: Identifying Imbalance in the data Step3: Feature Independence using Spearman correlation...
Python Code: import pandas as pd import numpy as np import matplotlib.pyplot as plt import matplotlib as mpl mpl.rcParams['patch.force_edgecolor'] = True import seaborn as sns import warnings warnings.filterwarnings("ignore") %matplotlib inline filepath = 'https://raw.githubusercontent.com/jubins/ML-TwitterBotDetection...