Unnamed: 0 int64 0 16k | text_prompt stringlengths 110 62.1k | code_prompt stringlengths 37 152k |
|---|---|---|
8,800 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Experiment
Step1: Load and check data
Step2: ## Analysis
Experiment Details
Step3: Plot accuracy over epochs | Python Code:
%load_ext autoreload
%autoreload 2
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import glob
import tabulate
import pprint
import click
import numpy as np
import pandas as pd
from ray.tune.commands import *
from nupic.research.framewo... |
8,801 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
FireEye Health Insurance 2016 Analysis
Individual Plans (Employee only)
Assumptions and Notes
Step1: Helper functions
Step2: Plan cost functions
Step3: Sanity Tests
Zero costs
Step4: Cos... | Python Code:
%matplotlib inline
import matplotlib
import numpy as np
import matplotlib.pyplot as plt
class Plan: pass
# Plan 1 = Cigna HDHP/HSA
p1 = Plan()
p1.family_deductible = 2000.00 # Same deductible for both family and individual for the HDHP
p1.individual_deductible = 2000.00
p1.family_oopmax = 3000.00 ... |
8,802 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Heteroscedastic Regression
Updated on 27th November 2015
by Ricardo Andrade
In this Ipython Notebook we will look at how to implement a GP regression with different noise terms using GPy.
$\... | Python Code:
import numpy as np
import pylab as pb
import GPy
%pylab inline
Explanation: Heteroscedastic Regression
Updated on 27th November 2015
by Ricardo Andrade
In this Ipython Notebook we will look at how to implement a GP regression with different noise terms using GPy.
$\bf N.B.:$ There is currently no implemen... |
8,803 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2018 The TensorFlow Probability Authors.
Licensed under the Apache License, Version 2.0 (the "License");
Step1: Linear Mixed-Effect Regression in {TF Probability, R, Stan}
<table ... | Python Code:
#@title Licensed under the Apache License, Version 2.0 (the "License"); { display-mode: "form" }
# 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... |
8,804 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Deep Learning activation functions examined below
Step2: 1. ReLU
A great default choice for hidden layers. It is frequently used in industry and is almost always adequete to solve a ... | Python Code:
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline
#Create array of possible z values
z = np.linspace(-5,5,num=1000)
def draw_activation_plot(a,quadrants=2,y_ticks=[0],two_quad_y_lim=[0,5], four_quad_y_lim=[-1,1]):
Draws plot of activation function
Parameters
------... |
8,805 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
The code on the left is a hack to make this notebook two-column. I found it here
Step1: Extending built-in types
Note that multi-inheritence is constrained to one built-in type only. You ca... | Python Code:
class classA():
pass
a = classA()
print type(a)
class classA(object):
pass
a = classA()
print type(a)
Explanation: The code on the left is a hack to make this notebook two-column. I found it here:
http://stackoverflow.com/questions/23370670/ipython-notebook-put-code-cells-into-columns
Object Orient... |
8,806 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<h1> Preprocessing using Dataflow </h1>
This notebook illustrates
Step1: Run the command again if you are getting oauth2client error.
Note
Step2: You may receive a UserWarning about the Ap... | Python Code:
pip install --user apache-beam[gcp]
Explanation: <h1> Preprocessing using Dataflow </h1>
This notebook illustrates:
<ol>
<li> Creating datasets for Machine Learning using Dataflow
</ol>
<p>
While Pandas is fine for experimenting, for operationalization of your workflow, it is better to do preprocessing in ... |
8,807 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
2A.ML101.6
Step1: PCA is performed using linear combinations of the original features
using a truncated Singular Value Decomposition of the matrix X so
as to project the data onto a base of... | Python Code:
from sklearn.datasets import load_iris
iris = load_iris()
X = iris.data
y = iris.target
Explanation: 2A.ML101.6: Unsupervised Learning: Dimensionality Reduction and Visualization
Unsupervised learning is interested in situations in which X is available, but not y: data without labels. A typical use case is... |
8,808 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<center> Introduction to Spark In-memmory Computing via Python PySpark </center>
Step1: Airlines Data
Spark SQL
- Spark module for structured data processing
- provide more information abou... | Python Code:
import sys
import os
sys.path.insert(0, '/usr/hdp/2.6.0.3-8/spark2/python')
sys.path.insert(0, '/usr/hdp/2.6.0.3-8/spark2/python/lib/py4j-0.10.4-src.zip')
os.environ['SPARK_HOME'] = '/usr/hdp/2.6.0.3-8/spark2/'
os.environ['SPARK_CONF_DIR'] = '/etc/hadoop/synced_conf/spark2/'
os.environ['PYSPARK_PYTHON'] = ... |
8,809 | 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
2018/6/6
Step1: The cost and driver Hamiltonians corresponding to the barbell graph are stored in QAOA object fields in the form o... | Python Code:
import numpy as np
from grove.pyqaoa.maxcut_qaoa import maxcut_qaoa
from functools import reduce
barbell = [(0,1)] # graph is defined by a list of edges. Edge weights are assumed to be 1.0
steps = 1 # evolution path length ebtween the ref and cost hamiltonians
inst = maxcut_qaoa(barbell, steps=steps) ... |
8,810 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
LEARNING APPLICATIONS
In this notebook we will take a look at some indicative applications of machine learning techniques. We will cover content from learning.py, for chapter 18 from Stuart ... | Python Code:
from learning import *
from notebook import *
Explanation: LEARNING APPLICATIONS
In this notebook we will take a look at some indicative applications of machine learning techniques. We will cover content from learning.py, for chapter 18 from Stuart Russel's and Peter Norvig's book Artificial Intelligence: ... |
8,811 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Environment Loading Examples
In this notebook, we walk through a few examples of how to load and interact with the Construction environments, both using discrete relative actions with graph ... | Python Code:
# Copyright 2020 DeepMind Technologies Limited
#
# 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicab... |
8,812 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step2: Making Python faster
This homework provides practice in making Python code faster. Note that we start with functions that already use idiomatic numpy (which are about two orders of ma... | Python Code:
def logistic(x):
Logistic function.
return np.exp(x)/(1 + np.exp(x))
def gd(X, y, beta, alpha, niter):
Gradient descent algorihtm.
n, p = X.shape
Xt = X.T
for i in range(niter):
y_pred = logistic(X @ beta)
epsilon = y - y_pred
grad = Xt @ epsilon / n
... |
8,813 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Look at encounter durations to check how long patients are in hospital, for both RRT & non-RRT encounters.
When this was first done, we did not use the checkin time from the checkin table, w... | Python Code:
import pandas as pd
import numpy as np
from impala.util import as_pandas
# connect to impala
from impala.dbapi import connect
conn = connect(host="mycluster.domain.com", port=my_impala_port_number)
# Make sure we're pulling from the right location
cur = conn.cursor()
cur.execute('use my_db')
import matplot... |
8,814 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Análisis de los datos obtenidos
Uso de ipython para el análsis y muestra de los datos obtenidos durante la producción. La regulación del diámetro se hace mediante el control del filawinder. ... | Python Code:
#Importamos las librerías utilizadas
import numpy as np
import pandas as pd
import seaborn as sns
#Mostramos las versiones usadas de cada librerías
print ("Numpy v{}".format(np.__version__))
print ("Pandas v{}".format(pd.__version__))
print ("Seaborn v{}".format(sns.__version__))
#Abrimos el fichero csv co... |
8,815 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Cloud SQL basics
Cloud SQL is a fully-managed database service that makes it easy to set up, maintain, manage, and administer your relational databases on Google Cloud Platform.
Install and ... | Python Code:
!wget https://dl.google.com/cloudsql/cloud_sql_proxy.linux.amd64 -O cloud_sql_proxy
!chmod +x cloud_sql_proxy
Explanation: Cloud SQL basics
Cloud SQL is a fully-managed database service that makes it easy to set up, maintain, manage, and administer your relational databases on Google Cloud Platform.
Instal... |
8,816 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Lecture 21
Step1: We define our functional. Note that the functional is only a function of the derivative of $y$ rather than $y$ alone.
Step2: You may be tempted to do this
Step3: You wo... | Python Code:
%matplotlib notebook
import sympy as sp
sp.init_printing()
f = sp.symbols('f', cls=sp.Function)
x, y = sp.symbols('x, y', real=True)
Explanation: Lecture 21: The Calculus of Variations
What to Learn?
The concept of a "function of functions" and the definition of a functional
The concept of finding a func... |
8,817 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Facies classification - Sequential Feature Selection
<a rel="license" href="http
Step1: Make performance scorers
Step2: Sequential Feature Selection with mlextend
http
Step3: The next cel... | Python Code:
%matplotlib inline
import numpy as np
import pandas as pd
import matplotlib as mpl
import matplotlib.pyplot as plt
from sklearn import preprocessing
from sklearn.metrics import f1_score, accuracy_score, make_scorer
filename = 'engineered_features.csv'
training_data = pd.read_csv(filename)
training_data.des... |
8,818 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Lesson 37
Step1: This code produces an incorrent response. The debugger can be used to go through the program line by line and find the errors.
Step2: The problem with the program was that... | Python Code:
def simpleAdd():
print('Enter the first nuber to add:')
first = input()
print('Enter the second number to add:')
second = input()
print('Enter the third number to add:')
third = input()
print('The sum is ' + first + second + third +'.')
simpleAdd()
Explanation: Lesson 37:
Using... |
8,819 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Exercises about Numpy and MLLib Data Types
Notebook version
Step1: 1. Objectives
This notebook reviews some of the Python modules that make it possible to work with data structures in an ea... | Python Code:
# Import some libraries that will be necessary for working with data and displaying plots
# To visualize plots in the notebook
%matplotlib inline
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import scipy.io # To read matlab files
import pylab
from test_helper import Test
Expl... |
8,820 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Lecture 2
Step1: Problem 2
Step2: C
Step3: D
Step5: <a id='prob1ans'></a>
E | Python Code:
# To begin, define the prior as the probability of the car being behind door i (i=1,2,3), call this "pi".
# Note that pi is uniformly distributed.
p1 = 1/3.
p2 = 1/3.
p3 = 1/3.
# Next, to define the class conditional, we need three pieces of information. Supposing Monty reveals door 3,
# we must find:
# ... |
8,821 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Project 2
Step1: Now, can you find out the following facts about the dataset?
- Total number of students
- Number of students who passed
- Number of students who failed
- Graduation rate of... | Python Code:
# Import libraries
import numpy as np
import pandas as pd
# Read student data
student_data = pd.read_csv("student-data.csv")
print "Student data read successfully!"
# Note: The last column 'passed' is the target/label, all other are feature columns
Explanation: Project 2: Supervised Learning
Building a Stu... |
8,822 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Python Word Sense Disambiguation
(C) 2017-2019 by Damir Cavar
Version
Step1: For a word that we want to disambiguate, we need to get all its synsets
Step2: For each synset we need to get i... | Python Code:
from nltk.corpus import wordnet
Explanation: Python Word Sense Disambiguation
(C) 2017-2019 by Damir Cavar
Version: 1.2, November 2019
License: Creative Commons Attribution-ShareAlike 4.0 International License (CA BY-SA 4.0)
This is a tutorial related to the discussion of a WordSense disambiguation and var... |
8,823 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Reinforcement Learning
This IPy notebook acts as supporting material for Chapter 21 Reinforcement Learning of the book Artificial Intelligence
Step1: CONTENTS
Overview
Passive Reinforcement... | Python Code:
from rl import *
Explanation: Reinforcement Learning
This IPy notebook acts as supporting material for Chapter 21 Reinforcement Learning of the book Artificial Intelligence: A Modern Approach. This notebook makes use of the implementations in rl.py module. We also make use of implementation of MDPs in the ... |
8,824 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
WikiNetworking Stallion Demo
Introduction
This notebook creates both interactive and high resolution graphs of social networks from Wikipedia articles. Several demonstration data sets are in... | Python Code:
!pip install git+https://github.com/jchuahtacc/WikiNetworking.git
# Just in case we don't want to re-run the crawl, we will load the data directly
import wikinetworking as wn
import networkx as nx
import matplotlib.pyplot as plt
import urllib2
import json
%matplotlib inline
bet_hiphop_directed = "http... |
8,825 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Music Recommender System using Apache Spark and Python
Estimated time
Step1: Loading data
Load the three datasets into RDDs and name them artistData, artistAlias, and userArtistData. View t... | Python Code:
from pyspark.mllib.recommendation import *
import random
from operator import *
Explanation: Music Recommender System using Apache Spark and Python
Estimated time: 8hrs
Description
For this project, you are to create a recommender system that will recommend new musical artists to a user based on their list... |
8,826 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Convolutional Neural Networks
Step2: 2 - Outline of the Assignment
You will be implementing the building blocks of a convolutional neural network! Each function you will implement will have... | Python Code:
import numpy as np
import h5py
import matplotlib.pyplot as plt
%matplotlib inline
plt.rcParams['figure.figsize'] = (5.0, 4.0) # set default size of plots
plt.rcParams['image.interpolation'] = 'nearest'
plt.rcParams['image.cmap'] = 'gray'
%load_ext autoreload
%autoreload 2
np.random.seed(1)
Explanation: Con... |
8,827 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: <img src="images/utfsm.png" alt="" width="200px" align="right"/>
USM Numérica
Algoritmos y Funciones
Objetivos
Conocer los conceptos de algoritmo, código y pseudo-código.
Conectar los... | Python Code:
IPython Notebook v4.0 para python 3.0
Librerías adicionales:
Contenido bajo licencia CC-BY 4.0. Código bajo licencia MIT.
(c) Sebastian Flores, Christopher Cooper, Alberto Rubio, Pablo Bunout.
# Configuración para recargar módulos y librerías dinámicamente
%reload_ext autoreload
%autoreload 2
# Configura... |
8,828 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
What's New in Marvin 2.1
Marvin is Python 3.5+ compliant!
Step1: Web
Interactive NASA-Sloan Atlas (NSA) Parameter Visualization
http
Step2: Map Plotting
Completely redesigned map plotting
... | Python Code:
import matplotlib
%matplotlib inline
# only necessary if you have a local DB
from marvin import config
config.forceDbOff()
Explanation: What's New in Marvin 2.1
Marvin is Python 3.5+ compliant!
End of explanation
from marvin.tools.cube import Cube
cube = Cube(plateifu='7957-12702')
print(cube)
list(cube.ns... |
8,829 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Probabilities are a way of quantifying the possibility of the occurrence of a specific event or events given the set of all possible events.
Notationally, $P(E)$ means "the probability of ev... | Python Code:
def uniform_pdf(x):
return 1 if x >= 0 and x < 1 else 0
xs = np.arange(-1, 2, .001)
ys = [uniform_pdf(x) for x in xs]
plt.plot(xs, ys);
uniform_pdf(-0.01)
Explanation: Probabilities are a way of quantifying the possibility of the occurrence of a specific event or events given the set of all possible ev... |
8,830 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: The Rise and Fall of the US Employment-Population Ratio
A research project at NYU's Stern School of Business.
Written by David Cai (txc202@nyu.edu) under the direction of David Backus... | Python Code:
Creates a figure using FRED data
Uses pandas Remote Data Access API
Documentation can be found at http://pandas.pydata.org/pandas-docs/stable/remote_data.html
%matplotlib inline
import pandas as pd
import pandas.io.data as web
import matplotlib.pyplot as plt
import numpy as np
import datetime as dt
from da... |
8,831 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Electric Field of a Moving Charge
PROGRAM
Step1: 2 - Define Constants
To see what happens when the speed $\beta$ of the charge changes, modify the value of beta below.
Step2: 3 - Calculate... | Python Code:
import numpy as np
import matplotlib.pylab as plt
#Import 3-dimensional plotting package.
from mpl_toolkits.mplot3d import axes3d
Explanation: Electric Field of a Moving Charge
PROGRAM: Electric field of a moving charge
CREATED: 5/30/2018
In this problem, I plot the electric field of a moving charge for di... |
8,832 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
(📗) ipyrad Cookbook
Step1: Connect to cluster
The code can be easily parallelized across cores on your machine, or many nodes of an HPC cluster using the ipyparallel library (see ou... | Python Code:
import ipyrad.analysis as ipa
import ipyparallel as ipp
import toytree
Explanation: (📗) ipyrad Cookbook: abba-baba admixture tests
The ipyrad.analysis Python module includes functions to calculate abba-baba admixture statistics (including several variants of these measures), to perform signifance t... |
8,833 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Downloading Continuous Data
This notebook demonstrates the use of EQTransformer for downloading continuous data from seismic networks.
Step1: You can use help() to learn about input paramet... | Python Code:
from EQTransformer.utils.downloader import makeStationList, downloadMseeds
Explanation: Downloading Continuous Data
This notebook demonstrates the use of EQTransformer for downloading continuous data from seismic networks.
End of explanation
help(makeStationList)
Explanation: You can use help() to learn ab... |
8,834 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Importar datos de entreno
Step1: Importar datos para predecir
Step2: Mapear los valores verdadero y falso a 1 y 0
hayErrPalabra, falloCaracter, palabraCorrecta
Step3: Quitarle los espacio... | Python Code:
data = pd.read_csv('train.csv', header=None ,delimiter=";")
feature_names = ['usuario', 'palabra', 'palabraLeida', 'tiempoCaracter',
'hayErrPalabra', 'tiempoErrPalabra', 'numPalabra','tiempoPalabra', 'tamPalabra', 'caracter',
'falloCaracter', 'palabraCorrecta']
data.columns = feature_names
Ex... |
8,835 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<p><font size="4"> MOOC
Step1: 2) Run the following code that computes recursively the state probability vectors $\pi(t)$ at times $t=0,\ldots,100$. The state probability vectors can be co... | Python Code:
%matplotlib inline
from pylab import *
P = array([[.7, .3, 0], [.3, .5, .2], [.1, .4, .5]])
def X(x0,P=P,T=100):
# Function X supplies a trajectory of the discrete Markov chain
# with initial state x0 and transition matrix P, till time T
x = [x0]
for _ in ... |
8,836 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
"Detection of anomalous tweets using supervising outlier techniques"
Importing the Dependencies and Loading the Data
Step1: Data Preparation
Data prepration with the available data. I made ... | Python Code:
import nltk
import pandas as pd
import numpy as np
data = pd.read_csv("original_train_data.csv", header = None,delimiter = "\t", quoting=3,names = ["Polarity","TextFeed"])
#Data Visualization
data.head()
Explanation: "Detection of anomalous tweets using supervising outlier techniques"
Importing the Depende... |
8,837 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Unity ML Agents
Proximal Policy Optimization (PPO)
Contains an implementation of PPO as described here.
Step1: Hyperparameters
Step2: Load the environment
Step3: Train the Agent(s)
Step4:... | Python Code:
import numpy as np
import os
import tensorflow as tf
from ppo.history import *
from ppo.models import *
from ppo.trainer import Trainer
from unityagents import *
Explanation: Unity ML Agents
Proximal Policy Optimization (PPO)
Contains an implementation of PPO as described here.
End of explanation
### Gener... |
8,838 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Split oxygen-vacancy defects in Co
We want to work out the symmetry analysis for our split oxygen-vacancy (V-O-V) defects $\alpha$-Co (HCP) and $\beta$-Co (FCC).
The split defects can be rep... | Python Code:
import sys
sys.path.extend(['../'])
import numpy as np
import matplotlib.pyplot as plt
plt.style.use('seaborn-whitegrid')
%matplotlib inline
import onsager.crystal as crystal
import onsager.OnsagerCalc as onsager
from scipy.constants import physical_constants
kB = physical_constants['Boltzmann constant in ... |
8,839 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Are categorical variables getting lost in your random forests?
Step1: TL;DR Decision tree models can handle categorical variables without one-hot encoding them. However, popular implementat... | Python Code:
__author__ = 'Nick Dingwall, Chris Potts'
Explanation: Are categorical variables getting lost in your random forests?
End of explanation
from tree_categorical_variables import *
Explanation: TL;DR Decision tree models can handle categorical variables without one-hot encoding them. However, popular implemen... |
8,840 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Check two SMIRNOFFs have the same typing
This notebook was created to check that a change to a SMIRNOFF force field doesn't change the way it types
molecules. This concern came from switchin... | Python Code:
# Imports
from __future__ import print_function
from convert_frcmod import *
import openeye.oechem as oechem
import openeye.oeiupac as oeiupac
import openeye.oeomega as oeomega
import openeye.oedepict as oedepict
from IPython.display import display
from openff.toolkit.typing.engines.smirnoff.forcefield imp... |
8,841 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
IA369Z - Reprodutibilidade em Pesquisa Computacional.
Descrição de códigos para devices e coletas
Code Client Device
ESP8266 Runing program language LUA.
Step1: Server Local
Step2: Export... | Python Code:
-- Campainha IoT - LHC - v1.1
-- ESP Inicializa pinos, Configura e Conecta no Wifi, Cria conexão TCP
-- e na resposta de um "Tocou" coloca o ESP em modo DeepSleep para economizar bateria.
-- Se nenhuma resposta for recebida em 15 segundos coloca o ESP em DeepSleep.
led_pin = 3
status_led = gpio.LOW
ip_serv... |
8,842 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
2A.i - Données non structurées, programmation fonctionnelle
Une table dans une base de données est déjà le résultat d'une réflexion sur la façon de les représenter.
Step1: Avant-propos
Ste... | Python Code:
from jyquickhelper import add_notebook_menu
add_notebook_menu()
Explanation: 2A.i - Données non structurées, programmation fonctionnelle
Une table dans une base de données est déjà le résultat d'une réflexion sur la façon de les représenter.
End of explanation
import pyensae.datasource
pyensae.datasource.d... |
8,843 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
We covered a lot of information today and I'd like you to practice developing classification trees on your own. For each exercise, work through the problem, determine the result, and provide... | Python Code:
from sklearn import datasets
from sklearn import tree
from sklearn.cross_validation import train_test_split
from sklearn import metrics
import numpy as np
def measure_performance(X,y,clf, show_accuracy=True, show_classification_report=True, show_confussion_matrix=True):
y_pred=clf.predict(X)
if sho... |
8,844 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
CHAPTER 3
Logging
As you are exploring and, later, using bestPy you might want to keep track (in a discrete way) of what happens under the hood. For that purpose, a convenient logging faciĺi... | Python Code:
import sys
sys.path.append('../..')
Explanation: CHAPTER 3
Logging
As you are exploring and, later, using bestPy you might want to keep track (in a discrete way) of what happens under the hood. For that purpose, a convenient logging faciĺity is built into bestPy that keeps you up to date.
Preliminaries
We ... |
8,845 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
EECS 445
Step1: Python Basics
Data Types
Containers
Functions
Classes
Basic data types
Numbers
Integers and floats work as you would expect from other languages
Step2: Note that unlike man... | Python Code:
print ('Hello Python!')
Explanation: EECS 445: Python Tutorial
Presented by: Zhao Fu
September 12, 2016
References:
1. https://docs.python.org/3/tutorial/
2. https://docs.python.org/3/library/
3. http://cs231n.github.io/python-numpy-tutorial/
4. https://github.com/donnemartin/data-science-ipython-notebooks... |
8,846 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Apache Spark Streaming
http
Step1: Python Example
Step2: 2
You need this
Step3: Python Example | Python Code:
import org.apache.spark._
import org.apache.spark.streaming._
val conf = new SparkConf().setMaster("local[*]").setAppName("Example")
val ssc = new StreamingContext(conf, Seconds(1))
Explanation: Apache Spark Streaming
http://spark.apache.org/streaming/
Documentation URL:
http://spark.apache.org/docs/latest... |
8,847 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
A brief note about pseudo-random numbers
When carrying out simulations, it is typical to use random number generators. Most computers can not generate true random numbers -- instead we use ... | Python Code:
# set the seed for the pseudo-random number generator
# the seed is any 32 bit integer
# different seeds will generate different results for the
# simulations that follow
np.random.seed(20160208)
Explanation: A brief note about pseudo-random numbers
When carrying out simulations, it is typical to use ran... |
8,848 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2021 The TensorFlow Authors.
Step1: Sparsity preserving clustering Keras example
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https
Step2:... | 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,849 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Example of DOV search methods for interpretations (informele stratigrafie)
Use cases explained below
Get 'informele stratigrafie' in a bounding box
Get 'informele stratigrafie' with specific... | Python Code:
%matplotlib inline
import inspect, sys
# check pydov path
import pydov
Explanation: Example of DOV search methods for interpretations (informele stratigrafie)
Use cases explained below
Get 'informele stratigrafie' in a bounding box
Get 'informele stratigrafie' with specific properties
Get 'informele strati... |
8,850 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Goal
Step1: T2 relaxation
Step2: Fit CEST for each slices and mouse | Python Code:
# Import Python Modules
import numpy as np
#import seaborn as sn
import matplotlib.pyplot as plt
%matplotlib inline
from pylab import *
import pandas as pd
# Import LOCAL functions written by me
from mylocal_functions import *
Explanation: Goal: Differentiate Infections, sterile inflammation, and healthy ... |
8,851 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Anscombe's quartet
Step1: Load the Anscombe's quartet dataset
Step2: And df is... a pandas dataframe
Step3: that we can print, plot, ...
Step4: Print just first dataset
Step5: Basic sta... | Python Code:
#!conda install -y numpy pandas matplotlib seaborn statsmodels
%matplotlib inline
import seaborn as sns
import pandas as pd
sns.set(style="ticks")
Explanation: Anscombe's quartet
End of explanation
df = sns.load_dataset("anscombe")
Explanation: Load the Anscombe's quartet dataset
End of explanation
type(df... |
8,852 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Land
MIP Era
Step1: Document Authors
Set document authors
Step2: Document Contributors
Specify document contributors
Step3: Document Publication
Specify do... | Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'bnu', 'bnu-esm-1-1', 'land')
Explanation: ES-DOC CMIP6 Model Properties - Land
MIP Era: CMIP6
Institute: BNU
Source ID: BNU-ESM-1-1
Topic: Land
Sub-Topics: Soil, Snow, Vegetation, Ene... |
8,853 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
decision trees
Step1: Decision trees are directed graphs beginning with one node and branching to many. They are a hierarchical data structure that represent data by implementing a divide-a... | Python Code:
import graphviz
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import sklearn.datasets
import sklearn.tree
plt.rcParams["figure.figsize"] = [17, 10]
Explanation: decision trees
End of explanation
# features
X = [
[0, 0],
[1, 1]
]
# targets
Y = [
0,
... |
8,854 | 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.
Assignment 4
Step1: Design a technique to construct smooth scalar signals $x... | Python Code:
import numpy as np
import scipy.io
import matplotlib.pyplot as plt
%matplotlib inline
import os.path
X = scipy.io.mmread(os.path.join('datasets', 'graph_inpainting', 'embedding.mtx'))
W = scipy.io.mmread(os.path.join('datasets', 'graph_inpainting', 'graph.mtx'))
N = W.shape[0]
print('N = |V| = {}, k|V| < |... |
8,855 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
GeosPy
Step1: Basic Example
The standard use case of GeosPy is trying to find a user's location given various data.
To use GeosPy, the first thing we need to do is see what models are avai... | Python Code:
from GeosPy import Geos
geosPy = Geos()
Explanation: GeosPy: Geolocation Inference Made Easy
GeosPy is a python 3 library written to make geolocation inference easy. Geolocation inference is the identification of the real-world geographic location of an object on Earth based off of available data. GeosPy c... |
8,856 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Validation and Model Selection
Credits
Step1: Validating Models
One of the most important pieces of machine learning is model validation
Step2: Let's fit a K-neighbors classifier
Step3: N... | Python Code:
from __future__ import print_function, division
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
# Use seaborn for plotting defaults
import seaborn as sns; sns.set()
Explanation: Validation and Model Selection
Credits: Forked from PyCon 2015 Scikit-learn Tutorial by Jake VanderPlas
In ... |
8,857 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Integration Exercise 2
Imports
Step1: Indefinite integrals
Here is a table of definite integrals. Many of these integrals has a number of parameters $a$, $b$, etc.
Find five of these integr... | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
from scipy import integrate
Explanation: Integration Exercise 2
Imports
End of explanation
def integrand(x, a):
return 1.0/(x**2 + a**2)
def integral_approx(a):
# Use the args keyword argument to feed extra ... |
8,858 | 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', 'ipsl', 'sandbox-1', 'ocnbgchem')
Explanation: ES-DOC CMIP6 Model Properties - Ocnbgchem
MIP Era: CMIP6
Institute: IPSL
Source ID: SANDBOX-1
Topic: Ocnbgchem
Sub-Topics: Tracers.
Prop... |
8,859 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Topic Networks
In this notebook, we will learn how to visualize topic model using network graphs. Networks can be a great way to explore topic models. We can use it to navigate that how topi... | Python Code:
!pip install plotly>=2.0.16 # 2.0.16 need for support 'hovertext' argument from create_dendrogram function
from gensim.models.ldamodel import LdaModel
from gensim.corpora import Dictionary
import pandas as pd
import re
from gensim.parsing.preprocessing import remove_stopwords, strip_punctuation
import nump... |
8,860 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
← Back to Index
Symbolic Representations
Symbolic music representations comprise any kind of score representation with an explicit encoding of notes or other musical events. These inclu... | Python Code:
ipd.display( ipd.YouTubeVideo("2A6ZXZwl3nA", start=106) )
Explanation: ← Back to Index
Symbolic Representations
Symbolic music representations comprise any kind of score representation with an explicit encoding of notes or other musical events. These include machine-readable data formats such as MIDI.... |
8,861 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Téléchargement des données et premier traitement
Step1: Météo Darksky
J'utilise l'API de DarkSky (https
Step2: Ce sont des données heure par heure. Pour avoir une meillieur précision avec ... | Python Code:
coords_grenoble = (45.1973288, 5.7139923)
startday = pd.to_datetime('12/07/2017', format='%d/%m/%Y').tz_localize('Europe/Paris')
lastday = pd.to_datetime('now').tz_localize('Europe/Paris')
Explanation: Téléchargement des données et premier traitement
End of explanation
# routine pour construire automatique... |
8,862 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Data Wrangling - Adding Latitudes and Longitudes using Google Maps Geocoding API, to create some neat visualisations
Most Data Scientists will tell you that they spend most of their time Dat... | Python Code:
__author__ = 'shivam_gaur'
import requests
from bs4 import BeautifulSoup
import re
from pymongo import MongoClient
Explanation: Data Wrangling - Adding Latitudes and Longitudes using Google Maps Geocoding API, to create some neat visualisations
Most Data Scientists will tell you that they spend most of the... |
8,863 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Example 2 - Plot PSDs for a station
The intent of this series of Jupyter Notebooks is to demonstrate how metrics can be retrieved from an ISPAQ sqlite database and provide some ideas on how ... | Python Code:
import sqlite3
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.dates import DateFormatter
import matplotlib.dates as mdates
import datetime
Explanation: Example 2 - Plot PSDs for a station
The intent of this series of Jupyter Notebooks is to demonstrate how metrics can be retrieved from... |
8,864 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Spark + Python = PySpark
Esse notebook introduz os conceitos básicos do Spark através de sua interface com a linguagem Python. Como aplicação inicial faremos o clássico examplo de contador d... | Python Code:
ListaPalavras = ['gato', 'elefante', 'rato', 'rato', 'gato']
palavrasRDD = sc.parallelize(ListaPalavras, 4)
print type(palavrasRDD)
print palavrasRDD.collect()
Explanation: Spark + Python = PySpark
Esse notebook introduz os conceitos básicos do Spark através de sua interface com a linguagem Python. Como ap... |
8,865 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Probability tutorial
Problems by Peter Komar
18 Jul 2016
Sample problems from Peter Komar; after trying to analytically solve everything, Monte Carlo and see if I'm right.
Step1: Forward pr... | Python Code:
def compare(analytic,N,f):
errval = err(f,N)
successes = sum(f)
print "Analytic prediction: {:.0f}%.".format(analytic*100.)
print "Monte Carlo: {:.0f} +- {:.0f}%.".format(successes/float(N)*100.,errval*100.)
def err(fx,N):
# http://www.northeastern.edu/afeiguin/phys5870/phys5870/node71.... |
8,866 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Keras Tutorial
http
Step1: 2. Construindo DFNs com Keras
Reshaping MNIST data
Step2: 3. Construindo CNNs com Keras
Reshaping MNIST data
Step3: Compilando e ajustando CNN
Step4: Comparamo... | Python Code:
import util
import numpy as np
import keras
from keras.utils import np_utils
X_train, y_train, X_test, y_test = util.load_mnist_dataset()
y_train_labels = np.array(util.get_label_names(y_train))
# Converte em one-hot para treino
y_train = np_utils.to_categorical(y_train, 10)
y_test = np_utils.to_categorica... |
8,867 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Regression simulation
Step 1
Step1: Step 4/5/6 part A
Step2: Now graphing this data
Step3: Step 4/5/6 part b
Step4: Now graphing it
Step5: Step 7
Step6: Tune parameters for RF and KNN
... | Python Code:
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
import urllib2
from __future__ import division
np.random.seed(1)
url = ('https://raw.githubusercontent.com/Upward-Spiral-Science'
'/data/master/syn-density/output.csv')
data = urllib2.urlopen(url)
csv = np.genfromtxt(data, delimit... |
8,868 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Tutorial for using structure factor data as the structure factor used in the structural-color package
This tutorial describes how to add your own structor factor data to Monte Carlo calculat... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
import structcol as sc
import structcol.refractive_index as ri
from structcol import montecarlo as mc
from structcol import detector as det
from structcol import model
from structcol import structure
%matplotlib inline
Explanation: Tutorial for using struc... |
8,869 | 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,870 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Time Series Filters
Step1: Hodrick-Prescott Filter
The Hodrick-Prescott filter separates a time-series $y_t$ into a trend $\tau_t$ and a cyclical component $\zeta_t$
$$y_t = \tau_t + \zeta... | Python Code:
%matplotlib inline
from __future__ import print_function
import pandas as pd
import matplotlib.pyplot as plt
import statsmodels.api as sm
dta = sm.datasets.macrodata.load_pandas().data
index = pd.Index(sm.tsa.datetools.dates_from_range('1959Q1', '2009Q3'))
print(index)
dta.index = index
del dta['year']
del... |
8,871 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Conway's Game of Life
Authors
Step1: Import necessary libraries
Step8: Conway Game of Life Grid Class
Step15: Conway Game of Life Cell Class
Step16: Test Text Grid
Step17: Test Animatio... | Python Code:
from IPython.display import IFrame
IFrame('https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life',
width = 800, height = 500)
Explanation: Conway's Game of Life
Authors: Edwin Weill & Brad Green
Due Date: November 29th
This iPython notebook serves as the project code for the final project in MATH 8... |
8,872 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright © 2019 The TensorFlow Authors.
Step1: TensorFlow Extended (TFX) Workshop
Run this notebook in Colab
Running a simple pipeline manually in a Colab Notebook
This notebook demon... | 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,873 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Data Source
Step1: Load Data
Step2: Convert Spark Dataframe to Pandas Dataframe
Step3: Verctorize the features
Step4: Fit Linear Regression Model
Step5: View model summary
Step6: Predi... | Python Code:
!ls -ltr /data
spark
Explanation: Data Source: https://archive.ics.uci.edu/ml/datasets/Combined+Cycle+Power+Plant
Features consist of hourly average ambient variables
Temperature (T) in the range 1.81°C and 37.11°C,
Ambient Pressure (AP) in the range 992.89-1033.30 milibar,
Relative Humidity (RH) in the ra... |
8,874 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2020 The TensorFlow Authors.
Step1: TensorFlow Recommenders
Step2: Read the data
Step3: Build vocabularies to convert user ids and movie titles into integer indices for embeddin... | 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,875 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Control Structures
A control statement is a statement that determines the control flow of a set of instructions.
Sequence control is an implicit form of control in which instructions are exe... | Python Code:
num = 10 # Assignment Operator
num == 12 # Comparison operator
Explanation: Control Structures
A control statement is a statement that determines the control flow of a set of instructions.
Sequence control is an implicit form of control in which instructions are executed in the order that they are written.... |
8,876 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Forecasting Growth
By default, Prophet uses a linear model for its forecast. When forecasting growth, there is usually some maximum achievable point
Step1: We must specify the carrying capa... | Python Code:
%%R
df <- read.csv('../examples/example_wp_log_R.csv')
df = pd.read_csv('../examples/example_wp_log_R.csv')
Explanation: Forecasting Growth
By default, Prophet uses a linear model for its forecast. When forecasting growth, there is usually some maximum achievable point: total market size, total population ... |
8,877 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Class 6
Step1: Creating a new DataFrame
Now we'll use our cross-country income per capita data to create a new DataFrame containing growth data.
Step2: Let $y_t$ denotes income per capita ... | Python Code:
# Use the requests module to download cross country GDP per capita
url = ''
filename=''
r = requests.get(url,verify=True)
with open(filename,'wb') as newFile:
newFile.write(r.content)
# Import the cross-country GDP data into a DataFrame called incomeDf with index_col=0
# Print the first five rows ... |
8,878 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Repeated measures ANOVA on source data with spatio-temporal clustering
This example illustrates how to make use of the clustering functions
for arbitrary, self-defined contrasts beyond stand... | Python Code:
# Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr>
# Eric Larson <larson.eric.d@gmail.com>
# Denis Engemannn <denis.engemann@gmail.com>
#
# License: BSD-3-Clause
import os.path as op
import numpy as np
from numpy.random import randn
import matplotlib.pyplot as plt
import mne
from... |
8,879 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2020 The TensorFlow Authors.
Licensed under the Apache License, Version 2.0 (the "License");
Step1: Chapter 3 - Sampling the Imaginary
<table class="tfo-notebook-buttons" align="l... | Python Code:
#@title Licensed under the Apache License, Version 2.0 (the "License"); { display-mode: "form" }
# 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... |
8,880 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Aula 9 - Interpolação Domínio da Frequência
Correção exercícios
isccsym
Solução não é trivial. Precisamos também verificar se a função funciona com entrada de imagem complexa.
Vamos refazer ... | Python Code:
# import cv2
Explanation: Aula 9 - Interpolação Domínio da Frequência
Correção exercícios
isccsym
Solução não é trivial. Precisamos também verificar se a função funciona com entrada de imagem complexa.
Vamos refazer este exercício, fornecendo um conjunto de imagens de teste para todos verificarem se sua im... |
8,881 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
网络科学理论简介
天涯论坛的回帖网络分析
王成军
wangchengjun@nju.edu.cn
计算传播网 http
Step1: Extract @
Step2: @贾也2012-10-297 | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
dtt = []
with open('/Users/chengjun/github/cjc2016/data/tianya_bbs_threads_network.txt', 'r') as f:
for line in f:
pnum, link, time, author_id, author, content = line.replace('\n', '').split('\t')
dtt.append([pnum, link, time, author_id... |
8,882 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Intro
Data comes in many different forms
Step1: With the model loaded, you can process text like this
Step2: There's a lot you can do with the doc object you just created.
Tokenizing
This ... | Python Code:
import spacy
nlp = spacy.load('en_core_web_sm')
Explanation: Intro
Data comes in many different forms: time stamps, sensor readings, images, categorical labels, and so much more. But text is still some of the most valuable data out there for those who know how to use it.
In this course about Natural Lang... |
8,883 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<h1>Natural Language Preprocessing</h1>
<br>
<em><b>Gregory Antell & Emily Halket</b></em>
<br>
<em><b>December, 2016</b></em>
This notebook provides a brief overview of common steps taken n... | Python Code:
# import requirements
import pandas as pd
import nltk
import gensim
import spacy
Explanation: <h1>Natural Language Preprocessing</h1>
<br>
<em><b>Gregory Antell & Emily Halket</b></em>
<br>
<em><b>December, 2016</b></em>
This notebook provides a brief overview of common steps taken natural language preproc... |
8,884 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Fitting Models Exercise 1
Imports
Step1: Fitting a quadratic curve
For this problem we are going to work with the following model
Step2: First, generate a dataset using this model using th... | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
import scipy.optimize as opt
Explanation: Fitting Models Exercise 1
Imports
End of explanation
a_true = 0.5
b_true = 2.0
c_true = -4.0
Explanation: Fitting a quadratic curve
For this problem we are going to work with the following model:... |
8,885 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Mineral NER using Data Programming
Project
Step1: Labelling functions
Step2: Distant supervision
Get list of known minerals for distant supervision
Step3: Fitting the generative models
St... | Python Code:
%load_ext autoreload
%autoreload 2
%matplotlib inline
from snorkel import SnorkelSession
import os
import numpy as np
import re
import codecs
os.environ['SNORKELDB'] = 'sqlite:///snorkel-mte.db'
# Open Session
session = SnorkelSession()
# Read input
base_dir = '/Users/thammegr/work/mte/data/newcorpus/MTE-c... |
8,886 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
How-To
Step1: If you have any installation issue, please check our forum or the github issue tracker.
Instantiating a Poppy Humanoid
In this section, we will see how a Poppy Humanoid can be... | Python Code:
from pypot.vrep import from_vrep
from poppy.creatures import PoppyHumanoid
Explanation: How-To: Control a Poppy Humanoid in a Simulator using a Python lib: pypot
<img src="image/vrep-header.png" alt="V-REP header" style="height: 400px;"/>
Introduction
In this notebook, we will present how a simulated Poppy... |
8,887 | Given the following text description, write Python code to implement the functionality described.
Description:
Minimum LCM of all subarrays of length at least 2
Python3 program for the above approach ; Function to find LCM pf two numbers ; Initialise lcm value ; Check for divisibility of a and b by the lcm ; Function t... | Python Code:
import sys
def LCM(a , b ) :
lcm = a if a > b else b
while(True ) :
if(lcm % a == 0 and lcm % b == 0 ) :
break
else :
lcm += 1
return lcm
def findMinLCM(arr , n ) :
minLCM = sys . maxsize
for i in range(n - 1 ) :
val = LCM(arr[i ] , arr[i + 1 ] )
if(val < minLCM ) : ... |
8,888 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Van der Pol oscillator
We will look at the second order differentual equation (see https
Step1: One way to reduce the order of our second order differential equation is to formulate a syste... | Python Code:
from __future__ import division, print_function
import itertools
import numpy as np
import sympy as sp
import matplotlib.pyplot as plt
from pyodesys.symbolic import SymbolicSys
sp.init_printing()
%matplotlib inline
print(sp.__version__)
Explanation: Van der Pol oscillator
We will look at the second order d... |
8,889 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
A USA Today article from 2006 includes this sentence
Step1: Average amount of debt is approximately 35,868 dollars but this will take around 10 years to pay off given that interest in compo... | Python Code:
abc = Table.read_table("debt_amt_distribution2014.csv")
abc
def replace(x):
return int(x.replace(",", ""))
bcd = abc.apply(replace, 1)
bcd
#Upper bound is arbitrarily defined based on scale from 100000 to 150000 and 150000 to 200000
new_table_debt = Table().with_columns("Balance 2014 (under $ given)", ... |
8,890 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Title
Step1: Create A Priority Queue Object
Step2: Add Items To Queue
Step3: Retrieve Items From Queue By Priority | Python Code:
import heapq
Explanation: Title: Priority Queues
Slug: priority_queues
Summary: Priority Queues Using Python.
Date: 2017-02-02 12:00
Category: Python
Tags: Basics
Authors: Chris Albon
Preliminaries
End of explanation
# Create a priority queue abstract base class
class priority_queue:
# Initialize the... |
8,891 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Boosting a decision stump
The goal of this notebook is to implement your own boosting module.
Brace yourselves! This is going to be a fun and challenging assignment.
Use SFrames to do some f... | Python Code:
import graphlab
import matplotlib.pyplot as plt
%matplotlib inline
Explanation: Boosting a decision stump
The goal of this notebook is to implement your own boosting module.
Brace yourselves! This is going to be a fun and challenging assignment.
Use SFrames to do some feature engineering.
Modify the decisi... |
8,892 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
WMI Eventing
Metadata
| Metadata | Value |
|
Step1: Download & Process Security Dataset
Step2: Analytic I
Look for WMI event filters registered
| Data source | Event Provider | ... | Python Code:
from openhunt.mordorutils import *
spark = get_spark()
Explanation: WMI Eventing
Metadata
| Metadata | Value |
|:------------------|:---|
| collaborators | ['@Cyb3rWard0g', '@Cyb3rPandaH'] |
| creation date | 2019/08/10 |
| modification date | 2020/09/20 |
| playbook related | [] |
Hypo... |
8,893 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Always start by import everything in a separate code block. That way if you forgot stuff, it's easy to just add and re-run without it actually doing anything.
Step1: Linear Regression
In th... | Python Code:
from __future__ import division
import numpy as np
import matplotlib.pyplot as plt
import mltools as ml
np.random.seed(0)
%matplotlib inline
Explanation: Always start by import everything in a separate code block. That way if you forgot stuff, it's easy to just add and re-run without it actually doing anyt... |
8,894 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step12: Module is an abstract class which defines fundamental methods necessary for a training a neural network. You do not need to change anything here, just read the comments.
Step19: Seq... | Python Code:
class Module(object):
def __init__ (self):
self.output = None
self.gradInput = None
self.training = True
Basically, you can think of a module as of a something (black box)
which can process `input` data and produce `ouput` data.
This is like applying a function... |
8,895 | Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
Was trying to generate a pivot table with multiple "values" columns. I know I can use aggfunc to aggregate values the way I want to, but what if I don't want to sum or avg both colu... | Problem:
import pandas as pd
import numpy as np
np.random.seed(1)
df = pd.DataFrame({
'A' : ['abc', 'def', 'xyz', 'abc'] * 3,
'B' : ['A', 'B', 'C'] * 4,
'D' : np.random.randn(12),
'E' : np.random.randn(12)
})
def g(df):
return pd.pivot_table(df, values=['D','E'], index=['B'], aggfunc={'D':np.sum, 'E':np.mean})
resu... |
8,896 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Testing tutor-student matching with spiking simulations
Step1: Define target motor programs
Step2: Choose target
Step6: General definitions
Step7: Create default parameters file
Step10: ... | Python Code:
%matplotlib inline
import matplotlib as mpl
import matplotlib.ticker as mtick
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_style('white')
plt.rc('text', usetex=True)
plt.rc('font', family='serif', serif='cm')
plt.rcParams['figure.titlesize'] = 10
plt.rcParams['axes.labelsize'] = 8
plt.rcPa... |
8,897 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2021 DeepMind Technologies Limited.
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 ... | Python Code:
import bandit
import multiarm_model
import arm_model
import agents as agent_classes
import kernel as kernel_classes
import random
from typing import List, Dict
import pickle as pkl
from scipy import spatial
import numpy as np
import copy
import matplotlib.pyplot as plt
%matplotlib inline
Explanation: Copyr... |
8,898 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Make figures more publication ready
In this example, we show several use cases to take MNE plots and
customize them for a more publication-ready look.
Step1:
Step2: Evoked plot with brain... | Python Code:
# Authors: Eric Larson <larson.eric.d@gmail.com>
# Daniel McCloy <dan.mccloy@gmail.com>
# Stefan Appelhoff <stefan.appelhoff@mailbox.org>
#
# License: BSD (3-clause)
Explanation: Make figures more publication ready
In this example, we show several use cases to take MNE plots and
customize... |
8,899 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step2: Network Traffic Forecasting with AutoTS
In telco, accurate forecast of KPIs (e.g. network traffic, utilizations, user experience, etc.) for communication networks ( 2G/3G/4G/5G/wired)... | Python Code:
def get_drop_dates_and_len(df, allow_missing_num=3):
Find missing values and get records to drop
missing_num = df.total.isnull().astype(int).groupby(df.total.notnull().astype(int).cumsum()).sum()
drop_missing_num = missing_num[missing_num > allow_missing_num]
drop_datetimes = df.i... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.