Unnamed: 0 int64 0 16k | text_prompt stringlengths 110 62.1k | code_prompt stringlengths 37 152k |
|---|---|---|
4,600 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
What is a distribution?
An object-oriented exploration of one of the most useful concepts in statistics.
Copyright 2016 Allen Downey
MIT License
Step14: Playing dice with the universe
One o... | Python Code:
from __future__ import print_function, division
%matplotlib inline
%precision 6
import matplotlib.pyplot as plt
import numpy as np
from numpy.fft import fft, ifft
from inspect import getsourcelines
def show_code(func):
lines, _ = getsourcelines(func)
for line in lines:
print(line, end='')
E... |
4,601 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2019 The TensorFlow Authors.
Step1: Transfer learning and fine-tuning
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https
Step2: Data prep... | Python Code:
#@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# dist... |
4,602 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
First, we need to connect to NewsroomDB and download all shootings and homicides.
Step1: Right now, we're interested in all shootings and homicides for the current month. So filter the list... | Python Code:
import os
import requests
def get_table_data(table_name):
url = '%stable/json/%s' % (os.environ['NEWSROOMDB_URL'], table_name)
try:
r = requests.get(url)
return r.json()
except:
print 'doh'
return get_table_data(table_name)
homicides = get_table_data('homicides')... |
4,603 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
感知器
感知机(Perceptron)是一种二元线性分类器,是最简单的前向人工神经网络.1957由Rosenblatt在康奈尔航空研究室提出,受到心理学家McCulloch和数理逻辑学家Watt Pitts关于人工神经元数学模型的启发,开发出的模仿人类具有感知能力的试错,调整的机器学习方法.
算法
感知机有多种算法,比如最基本的感知机算法,感知机边界算法和多层感知机.我们这里介... | Python Code:
import requests
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelEncoder,StandardScaler
from sklearn.neural_network import MLPClassifier
from sklearn.metrics import classification_report
Explanation: 感知器
感知机(Perceptron)是一种二元线性分类器,是最简单的前向人工神经网络.... |
4,604 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Turbulence example
In this notebook we show how to perform a simulation using a soundspeed field based on a Gaussian turbulence spectrum.
Step1: Configuration
The following are the paramete... | Python Code:
import numpy as np
from pstd import PSTD, PML, Medium, Position2D, PointSource
from pstd import PSTD
from acoustics import Signal
from turbulence import Field2D, Gaussian2DTemp
#import seaborn as sns
%matplotlib inline
Explanation: Turbulence example
In this notebook we show how to perform a simulation usi... |
4,605 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Datasets
Step1: The data is from two colour spotted cDNA arrays. It has been widely studied in computational biology. There are four different time series in the data as well as induction e... | Python Code:
import pods
import pylab as plt
%matplotlib inline
data = pods.datasets.spellman_yeast()
Explanation: Datasets: The Spellman Yeast Data
Open Data Science Initiative
29th May 2014 Neil D. Lawrence
This data set collection is from an classic early microarray paper on the yeast cell cycle, Spellman et al (199... |
4,606 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Source of the materials
Step1: The <span>PERMISSIVE</span> flag indicates that a number of common
problems (see [problem structures]) associated with PDB files will be
ignored (but note tha... | Python Code:
from Bio.PDB.PDBParser import PDBParser
p = PDBParser(PERMISSIVE=1)
Explanation: Source of the materials: Biopython cookbook (adapted)
<font color='red'>Status: Draft</font>
Going 3D: The PDB module
Bio.PDB is a Biopython module that focuses on working with crystal
structures of biological macromolecules. ... |
4,607 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Data Set Information
1593 handwritten digits from around 80 persons were scanned, stretched
in a rectangular box 16x16 in a gray scale of 256 values.Then each pixel
of each image was scale... | Python Code:
data = pd.read_csv('data/semeion.csv', sep=",", header=None)
data.head()
data_train = data.sample(frac=0.9, random_state=42)
data_val = data.drop(data_train.index)
df_x_train = data_train.iloc[:,:256]
df_y_train = data_train.iloc[:,256:]
df_x_val = data_val.iloc[:,:256]
df_y_val = data_val.iloc[:,256]
x_tr... |
4,608 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Figure
Step1: 1. What is the voxelwise threshold?
Step2: 2. Definition of alternative
Detect 1 region
We define a 'success' as a situation in which the maximum in the active field exceeds
... | Python Code:
% matplotlib inline
from __future__ import division
import os
import nibabel as nib
import numpy as np
from neuropower import peakdistribution
import scipy.integrate as integrate
import pandas as pd
import matplotlib.pyplot as plt
import palettable.colorbrewer as cb
if not 'FSLDIR' in os.environ.keys():
... |
4,609 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
2A.data - Classification, régression, anomalies - correction
Le jeu de données Wine Quality Data Set contient 5000 vins décrits par leurs caractéristiques chimiques et évalués par un expert.... | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
from jyquickhelper import add_notebook_menu
add_notebook_menu()
Explanation: 2A.data - Classification, régression, anomalies - correction
Le jeu de données Wine Quality Data Set contient 5000 vins décrits par leurs caractéristiques chimiques et évalués par... |
4,610 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Supervised Descent Method - Basics
The aim of this notebook is to showcase how one can build and fit SDMs to images using Menpo.
Note that this notebook assumes that the user has previously ... | Python Code:
%matplotlib inline
from pathlib import Path
path_to_lfpw = Path('/vol/atlas/databases/lfpw')
path_to_lfpw = Path('/home/nontas/Dropbox/lfpw/')
import menpo.io as mio
training_images = []
# load landmarked images
for i in mio.import_images(path_to_lfpw / 'trainset', verbose=True):
# crop image
i = i... |
4,611 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Convolutional Autoencoder
Sticking with the MNIST dataset, let's improve our autoencoder's performance using convolutional layers. Again, loading modules and the data.
Step1: Network Archit... | Python Code:
%matplotlib inline
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('MNIST_data', validation_size=0)
img = mnist.train.images[2]
plt.imshow(img.reshape((28, 28)), cmap='Greys_r')
Explanati... |
4,612 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Custom training and batch prediction
<table align="left">
<td>
<a href="https
Step1: Install the latest GA version of google-cloud-storage library as well.
Step2: Install the pillow ... | Python Code:
import os
# The Google Cloud Notebook product has specific requirements
IS_GOOGLE_CLOUD_NOTEBOOK = os.path.exists("/opt/deeplearning/metadata/env_version")
# Google Cloud Notebook requires dependencies to be installed with '--user'
USER_FLAG = ""
if IS_GOOGLE_CLOUD_NOTEBOOK:
USER_FLAG = "--user"
! pip ... |
4,613 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a href="http
Step1: 1. Create and run the synthetic example of NST
First, we need to create an implementation of the Landlab NetworkModelGrid to plot. This example creates a synthetic grid... | Python Code:
import warnings
warnings.filterwarnings("ignore")
import os
import pathlib
import matplotlib.pyplot as plt
import matplotlib.colors as colors
import numpy as np
from landlab import ExampleData
from landlab.components import FlowDirectorSteepest, NetworkSedimentTransporter
from landlab.data_record import Da... |
4,614 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Join the data for preprocessing
Step1: Create additional features
Step2: Convert "PubDate" into two columns
Step3: More features and gap filling
Below are the results of one day of search... | Python Code:
print('Max train ID: %d. Max test ID: %d' % (np.max(NYT_train_raw['UniqueID']), np.max(NYT_test_raw['UniqueID'])))
joined = NYT_train_raw.merge(NYT_test_raw, how = 'outer')
Explanation: Join the data for preprocessing
End of explanation
joined['QorE'] = joined['Headline'].str.contains(r'\!|\?').astype(int)... |
4,615 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Learning Linear Classifiers
Question 1
<img src="images/lec2_pic01.png">
Screenshot taken from Coursera
<!--TEASER_END-->
Question 2
<img src="images/lec2_pic02.png">
Screenshot taken from C... | Python Code:
import numpy as np
dummy_feature_matrix = np.array([[1.,2.5], [1.,0.3], [1.,2.8], [1.,0.5]])
dummy_coefficients = np.array([0., 1.])
sentiment = np.array([1., -1., 1., 1.])
def predict_probability(feature_matrix, coefficients):
# Take dot product of feature_matrix and coefficients
# YOUR CODE HER... |
4,616 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a href="https
Step1: Assignment Resit - Part B
Deadline
Step2: Tip 0
Step3: Tip 1
Step4: Tip 2
Step5: Tip 3
Step6: 3. Building python modules to process files in a directory
In this e... | Python Code:
%%capture
!wget https://github.com/cltl/python-for-text-analysis/raw/master/zips/Data.zip
!wget https://github.com/cltl/python-for-text-analysis/raw/master/zips/images.zip
!wget https://github.com/cltl/python-for-text-analysis/raw/master/zips/Extra_Material.zip
!unzip Data.zip -d ../
!unzip images.zip -d .... |
4,617 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Indicators of Future Success in Men's Professional Tennis
May 2016
Written by John Ockay at NYU's Stern School of Business
Contact
Step1: Data (Part I)
To complete this project, I used dat... | Python Code:
%matplotlib inline
import pandas as pd
import matplotlib.pyplot as plt
import xlrd
Explanation: Indicators of Future Success in Men's Professional Tennis
May 2016
Written by John Ockay at NYU's Stern School of Business
Contact: jfo262@... |
4,618 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Before beginning this exercise you must download some data files, which can be retrieved from here
Step1: We have provided three images containing stars, taken with 3 different CCDs, in "st... | Python Code:
from IPython.core.display import display, HTML
display(HTML("<style>.container { width:95% !important; }</style>"))
import os
import numpy as np
import matplotlib.pyplot as plt
from rhlUtils import BBox, CCD, Image, imshow
%matplotlib inline
%config InlineBackend.figure_format = 'retina'
#%matplotlib qt
#... |
4,619 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Dogs vs Cats using VGG16
Author
Step1: Custom Packages
Step2: Declaring paths & global parameters
The path to the dataset is defined here. It will point to the sample folder which contain... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
Explanation: Dogs vs Cats using VGG16
Author : Aman Hussain
Email : aman@amandavinci.me
Description : Classifying images of dogs and cats by finetuning the VGG16 model
Import Libraries
Scientific Computing Stack
End of explanation
import... |
4,620 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: pomegranate and parallelization
pomegranate supports parallelization through a set of built in functions based off of joblib. All computationally intensive functions in pomegranate ar... | Python Code:
%pylab inline
from sklearn.mixture import GaussianMixture
from pomegranate import *
import seaborn, time
seaborn.set_style('whitegrid')
def create_dataset(n_samples, n_dim, n_classes, alpha=1):
Create a random dataset with n_samples in each class.
X = numpy.concatenate([numpy.random.normal(i*a... |
4,621 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
확률 분포, 확률 변수, 확률 모형의 의미
분포
확률 분포
확률 변수
확률 모형
샘플링
모집단
확률 분포
자료의 분포(distribution)란 자료가 어떤 수치적인 값을 가지는지를 그 전반적인 특징을 서술한 것을 말한다.
어떤 경우에 자료의 분포가 필요할까? 다음의 세 가지 경우를 생각해보자.
우선 복수의 자료 즉, 자료의 집합이 존재... | Python Code:
sp.random.seed(0)
x = sp.random.normal(size=1000)
x
ns, bins, ps = plt.hist(x, bins=10)
ns
bins
ps
pd.DataFrame([bins, ns/1000])
Explanation: 확률 분포, 확률 변수, 확률 모형의 의미
분포
확률 분포
확률 변수
확률 모형
샘플링
모집단
확률 분포
자료의 분포(distribution)란 자료가 어떤 수치적인 값을 가지는지를 그 전반적인 특징을 서술한 것을 말한다.
어떤 경우에 자료의 분포가 필요할까? 다음의 세 가지 경우를 생각해보자... |
4,622 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
What's the fuzz all about?
Randomized data generation for robust testing
Moritz Gronbach, Blue Yonder
EuroPython 2015, Bilbao, Spain
About me and why I want to talk about this
Predictive Ana... | Python Code:
import secret_algorithms
def create_pipeline():
pipeline = []
pipeline.append(TimeSeriesProcessor())
pipeline.append(WeatherData())
pipeline.append(secret_algorithms.SuperModel())
return Pipeline(pipeline)
Explanation: What's the fuzz all about?
Randomized data generation for robust tes... |
4,623 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Notebook to TreatGeoSelf with gridded climate data set coordinates
Case study
Step1: Establish a secure connection with HydroShare by instantiating the hydroshare class that is defined with... | Python Code:
# data processing
import os
import ogh
import tarfile
# data migration library
from utilities import hydroshare
# silencing warning
# import warnings
# warnings.filterwarnings("ignore")
Explanation: Notebook to TreatGeoSelf with gridded climate data set coordinates
Case study: the Sauk-Suiattle river water... |
4,624 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Filtro dos 10 crimes com mais ocorrências em março
Step1: Todas as ocorrências criminais de março
Step2: Quantidade de crimes por região
Step3: As 5 regiões com mais ocorrências
Step4: A... | Python Code:
all_crime_tipos.head(10)
all_crime_tipos_top10 = all_crime_tipos.head(10)
all_crime_tipos_top10.plot(kind='barh', figsize=(12,6), color='#3f3fff')
plt.title('Top 10 crimes por tipo (Mar 2017)')
plt.xlabel('Número de crimes')
plt.ylabel('Crime')
plt.tight_layout()
ax = plt.gca()
ax.xaxis.set_major_formatter... |
4,625 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a href="http
Step1: We will create a grid with 41 rows and 5 columns, and dx is 5 m (a long, narrow, hillslope). The initial elevation is 0 at all nodes.
We set-up boundary conditions so t... | Python Code:
# below is to make plots show up in the notebook
%matplotlib inline
# Code Block 1
import numpy as np
from matplotlib.pyplot import figure, legend, plot, show, title, xlabel, ylabel, ylim
from landlab.plot.imshow import imshow_grid
Explanation: <a href="http://landlab.github.io"><img style="float: left" sr... |
4,626 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Ejercicio de visualizacion de informacion con Pandas - Soluciones
Este es un pequenio ejercicio para revisar las diferentes graficas que nos permite generar Pandas.
* NOTA
Step1: Recrea la... | Python Code:
import pandas as pd
import matplotlib.pyplot as plt
df3 = pd.read_csv('../data/df3')
%matplotlib inline
df3.plot.scatter(x='a',y='b',c='red',s=50
df3.info()
df3.head()
Explanation: Ejercicio de visualizacion de informacion con Pandas - Soluciones
Este es un pequenio ejercicio para revisar las diferentes gr... |
4,627 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
I. Setting up the Problem
Step1: 1) Peeking into the Data
Step2: II. Preparing data
1) Keep only players that have a Rater Image
Step3: 2) Getting rif of referees and grouping data by soc... | Python Code:
import pandas as pd
import numpy as np
from IPython.display import Image
import matplotlib.pyplot as plt
# Import the random forest package
from sklearn.ensemble import RandomForestClassifier
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score
filename ="CrowdstormingDataJuly1s... |
4,628 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Self-Driving Car Engineer Nanodegree
Deep Learning
Project
Step1: some unexpected errors are present
Step2: executing the same codes again removes the errors, not sure why!!
Loading pickle... | Python Code:
# Imports all libraries required
import os
import cv2
import csv
import time
import pickle
import numpy as np
import pandas as pd
import seaborn as sns
import tensorflow as tf
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
from PIL import Image
from pylab import rcParams
from skimage impo... |
4,629 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
NLTK experiments
based on NLTK with Python 3 for Natural Language Processing by Sentdex
Step1: Tokenizing
based on
- https
Step2: Stop words
sources
video
Step3: Stemming
source
video
St... | Python Code:
import nltk
from nltk import tokenize
# TODO: we don't relly want to download packages each time when we lauch this script
# so it'll better to check somehow whether we have packages or not - or Download on demand
# nltk.download()
Explanation: NLTK experiments
based on NLTK with Python 3 for Natural Langu... |
4,630 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
PUMP IT UP
Introduction
Step2: Data Analysis
Step3: cols_values_counts_dataframe
As we can see in above describe output, we seem to have lots of categorical values so let start exploring t... | Python Code:
import pickle
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from scripts.tools import game
%matplotlib inline
# %load_ext writeandexecute
plt.style.use('ggplot')
sns.set(color_codes=True)
# seed
np.random.seed(69572)
# import sys
# sys.path = sys.path + ['/Use... |
4,631 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Youtube Videos
Step1: Class Methods
Step2: Class Methods can be used to create alternate constructors
Step3: Static Methods
Instance methods take self as the first argument
Class methods ... | Python Code:
class Employee:
emp_count = 0 # Class Variable
company = 'Google' # Class Variable
def __init__(self, fname, lname):
self.fname = fname
self.lname = lname
self.email = self.fname + '.' + self.lname + '@' + self.company + '.com'
Employee.emp_count += 1
... |
4,632 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
AlientVault OTX <> Graphistry
Step1: Start
Step2: Continue | Python Code:
#!pip install graphistry -q
#!pip install OTXv2 -q
import graphistry
import pandas as pd
from OTXv2 import OTXv2, IndicatorTypes
from gotx import G_OTX
# To specify Graphistry account & server, use:
# graphistry.register(api=3, username='...', password='...', protocol='https', server='hub.graphistry.com')... |
4,633 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Comparision of Machine Learning Methods vs Rule Based
Traditionally, Educational Institutions use rule based models to generate risk score which then informs resource allocation. For example... | Python Code:
## Imports
import pandas as pd
import seaborn as sns
sns.set(color_codes=True)
import matplotlib.pyplot as plt
Explanation: Comparision of Machine Learning Methods vs Rule Based
Traditionally, Educational Institutions use rule based models to generate risk score which then informs resource allocation. For... |
4,634 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Analysis of Unicode Character Names
Character data from Python unicodedata module
Step1: Character data from UnicodeData.txt
Step2: Difference between names from unicodedata module and Uni... | Python Code:
import sys
import unicodedata
sys.maxunicode
unicodedata.unidata_version
def python_named_chars():
for code in range(sys.maxunicode):
char = chr(code)
try:
yield char, unicodedata.name(char)
except ValueError: # no such name
continue
l_py = list(python_na... |
4,635 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Pynamical
Step1: First, let's see the population values the logistic map produces for a range of growth rate parameters
Step2: Now let's visualize the system attractors for a large range o... | Python Code:
import IPython.display as IPdisplay
import matplotlib.cm as cm
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import pynamical
from pynamical import simulate, bifurcation_plot, save_fig
%matplotlib inline
title_font = pynamical.get_title_font()
label_font = pynamical.get_label_font(... |
4,636 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Serial Numbers, How I love thee...
No one really like serial numbers, but keeping track of them is one of the "brushing your teeth" activities that everyone needs to take care of. It's like... | Python Code:
from pyhpeimc.auth import *
from pyhpeimc.plat.netassets import *
import csv
auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin")
ciscorouter = get_dev_asset_details('10.101.0.1', auth.creds, auth.url)
Explanation: Serial Numbers, How I love thee...
No one really like serial numbers, but kee... |
4,637 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Title
Step1: Create Two Lists
Step2: Iterate Over Both Lists As A Single Sequence | Python Code:
from itertools import chain
Explanation: Title: Chain Together Lists
Slug: chain_together_lists
Summary: Chain Together Lists Using Python.
Date: 2017-02-02 12:00
Category: Python
Tags: Basics
Authors: Chris Albon
Preliminaries
End of explanation
# Create a list of allies
allies = ['Spain', 'Germany', 'N... |
4,638 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
NEB using ASE
1. Setting up an EAM calculator.
Suppose we want to calculate the minimum energy path of adatom diffusion on a (100) surface. We first need to choose an energy model, and in AS... | Python Code:
from ase.calculators.eam import EAM
Explanation: NEB using ASE
1. Setting up an EAM calculator.
Suppose we want to calculate the minimum energy path of adatom diffusion on a (100) surface. We first need to choose an energy model, and in ASE, this is done by defining a "calculator". Let's choose our calcula... |
4,639 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Plotting $\sin(x^2+y^2)$ for a regular grid with a total of 40,000 points or 20,000 points and on 20,000 random points
We create (x,y) points first and plot a scatter plot on them with gray ... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
Explanation: Plotting $\sin(x^2+y^2)$ for a regular grid with a total of 40,000 points or 20,000 points and on 20,000 random points
We create (x,y) points first and plot a scatter plot on them with gray level given by $\sin(x^2+y^2)$
Imp... |
4,640 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Wayne H Nixalo - 09 Aug 2017
This JNB is an attempt to do the neural artistic style transfer and super-resolution examples done in class, on a GPU using PyTorch for speed.
Lesson NB
Step1: ... | Python Code:
%matplotlib inline
import importlib
import os, sys; sys.path.insert(1, os.path.join('../utils'))
from utils2 import *
import torch, torch.nn as nn, torch.nn.functional as F, torch.optim as optim
from torch.autograd import Variable
from torch.utils.serialization import load_lua
from torch.utils.data import ... |
4,641 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Tutorial Part 21
Step1: With our setup in place, let's do a few standard imports to get the ball rolling.
Step2: The ntext step we want to do is load our dataset. We're using a small datas... | Python Code:
!curl -Lo conda_installer.py https://raw.githubusercontent.com/deepchem/deepchem/master/scripts/colab_install.py
import conda_installer
conda_installer.install()
!/root/miniconda/bin/conda info -e
!pip install --pre deepchem
import deepchem
deepchem.__version__
Explanation: Tutorial Part 21: Exploring Quan... |
4,642 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
La Magia de la television
Capitulo 1
Step2: En psicologia probablemente se harian un festin analizando estas canciones, la protagonista se nombra a si misma tantas veces que no deja lugar a... | Python Code:
Image(filename='./clase-09-04_images/i1.jpg')
Explanation: La Magia de la television
Capitulo 1: La television argentina es un template gigante
Parte 0: Repaso general de secuencias
| |Cadenas|Tuplas|Listas|
|:---|:---|:---|:---|
|Acceso por indice|Si|Si|Si|
|Recorrer por indices|Si|Si|Si|
|Recorrer por el... |
4,643 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Chapter 13 - Hydrogen functions
Start with some imports fro Symbolic Python library
Step1: Define some variables, radial, polar, azimuthal, time, and two frequencies
Step2: Look at a few o... | Python Code:
from sympy.physics.hydrogen import R_nl
from sympy.functions.special.spherical_harmonics import Ynm
from sympy import *
Explanation: Chapter 13 - Hydrogen functions
Start with some imports fro Symbolic Python library:
End of explanation
var("r theta phi t w1 w2")
Explanation: Define some variables, radial,... |
4,644 | Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
look at my code below: | Problem:
import pandas as pd
from sklearn.ensemble import ExtraTreesClassifier
from sklearn.feature_selection import SelectFromModel
import numpy as np
X, y = load_data()
clf = ExtraTreesClassifier(random_state=42)
clf = clf.fit(X, y)
model = SelectFromModel(clf, prefit=True)
column_names = X.columns[model.get_support(... |
4,645 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Fast Fourier Transform snippets
Documentation
Numpy implementation
Step1: Make data
Step2: Fourier transform with Numpy
Do the fourier transform
Step3: Filter
Step4: Do the reverse trans... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
Explanation: Fast Fourier Transform snippets
Documentation
Numpy implementation: http://docs.scipy.org/doc/numpy/reference/routines.fft.html
Scipy implementation: http://docs.scipy.org/doc/scipy/reference/fftpack.html
Import direc... |
4,646 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Neural Network Classifier
Neural networks can learn
Step1: Load Iris Data
Step2: Targets 0, 1, 2 correspond to three species
Step3: Split into Training and Testing
Step4: Let's test out ... | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
import pandas as pd
from sklearn.cross_validation import train_test_split
from sklearn.linear_model import LogisticRegressionCV
from sklearn import datasets
from keras.models import Sequential
from keras.layers.core... |
4,647 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Thermochemistry Validation Test
Han, Kehang (hkh12@mit.edu)
This notebook is designed to use a big set of tricyclics for testing the performance of new polycyclics thermo estimator. Currentl... | Python Code:
from rmgpy.data.rmg import RMGDatabase
from rmgpy import settings
from rmgpy.species import Species
from rmgpy.molecule import Molecule
from rmgpy.molecule import Group
from rmgpy.rmg.main import RMG
from rmgpy.cnn_framework.predictor import Predictor
from IPython.display import display
import numpy as np
... |
4,648 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Deep Convolutional GANs
In this notebook, you'll build a GAN using convolutional layers in the generator and discriminator. This is called a Deep Convolutional GAN, or DCGAN for short. The D... | Python Code:
%matplotlib inline
import pickle as pkl
import matplotlib.pyplot as plt
import numpy as np
from scipy.io import loadmat
import tensorflow as tf
!mkdir data
Explanation: Deep Convolutional GANs
In this notebook, you'll build a GAN using convolutional layers in the generator and discriminator. This is called... |
4,649 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<h1>Table of Contents<span class="tocSkip"></span></h1>
<div class="toc"><ul class="toc-item"><li><span><a href="#PageRank" data-toc-modified-id="PageRank-1"><span class="toc-item-num">1&nbs... | Python Code:
# code for loading the format for the notebook
import os
# path : store the current path to convert back to it later
path = os.getcwd()
os.chdir(os.path.join('..', 'notebook_format'))
from formats import load_style
load_style(plot_style=False)
os.chdir(path)
# 1. magic for inline plot
# 2. magic to print v... |
4,650 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Art Style Transfer
This notebook is an implementation of the algorithm described in "A Neural Algorithm of Artistic Style" (http
Step1: Load the pretrained weights into the network
Step2: ... | Python Code:
import theano
import theano.tensor as T
import lasagne
from lasagne.utils import floatX
import numpy as np
import scipy
import matplotlib.pyplot as plt
%matplotlib inline
import os # for directory listings
import pickle
import time
AS_PATH='./images/art-style'
from model import googlenet
net = googlenet.bu... |
4,651 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Image Gradients
In this notebook we'll introduce the TinyImageNet dataset and a deep CNN that has been pretrained on this dataset. You will use this pretrained model to compute gradients wit... | Python Code:
# As usual, a bit of setup
import time, os, json
import numpy as np
import skimage.io
import matplotlib.pyplot as plt
from cs231n.classifiers.pretrained_cnn import PretrainedCNN
from cs231n.data_utils import load_tiny_imagenet
from cs231n.image_utils import blur_image, deprocess_image
%matplotlib inline
pl... |
4,652 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Guided Project 3
Learning Objective
Step1: Step 1. Environment setup
Envirnonment Variables
Setup the your Kubeflow pipelines endopoint below the same way you did in guided project 1 & 2.
S... | Python Code:
import os
Explanation: Guided Project 3
Learning Objective:
Learn how to customize the tfx template to your own dataset
Learn how to modify the Keras model scaffold provided by tfx template
In this guided project, we will use the tfx template tool to create a TFX pipeline for the covertype project, but thi... |
4,653 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Decoding sensor space data with generalization across time and conditions
This example runs the analysis described in [1]_. It illustrates how one can
fit a linear classifier to identify a d... | Python Code:
# Authors: Jean-Remi King <jeanremi.king@gmail.com>
# Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr>
# Denis Engemann <denis.engemann@gmail.com>
#
# License: BSD (3-clause)
import matplotlib.pyplot as plt
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing ... |
4,654 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
This notebook gives a Nengo implementation of the Spiking Elementary Motion Detector (sEMD) from doi
Step1: Now let's re-create Figure 2
Step2: Now let's see what the performance is as we ... | Python Code:
# the facilitation spikes
def stim_1_func(t):
index = int(t/0.001)
if index in [100, 1100, 2100]:
return 1000
else:
return 0
# the trigger spikes
def stim_2_func(t):
index = int(t/0.001)
if index in [90, 1500, 2150]:
return 1000
else:
return 0
# ... |
4,655 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
NumPy를 활용한 선형대수 입문
선형대수(linear algebra)는 데이터 분석에 필요한 각종 계산을 위한 기본적인 학문이다.
데이터 분석을 하기 위해서는 실제로 수많은 숫자의 계산이 필요하다. 하나의 데이터 레코드(record)가 수십개에서 수천개의 숫자로 이루어져 있을 수도 있고 수십개에서 수백만개의 이러한 데이터 레코드를 조합... | Python Code:
x = np.array([1, 2, 3, 4])
x
x = np.array([[1], [2], [3], [4]])
x
Explanation: NumPy를 활용한 선형대수 입문
선형대수(linear algebra)는 데이터 분석에 필요한 각종 계산을 위한 기본적인 학문이다.
데이터 분석을 하기 위해서는 실제로 수많은 숫자의 계산이 필요하다. 하나의 데이터 레코드(record)가 수십개에서 수천개의 숫자로 이루어져 있을 수도 있고 수십개에서 수백만개의 이러한 데이터 레코드를 조합하여 계산하는 과정이 필요할 수 있다.
선형대수를 사용하는 첫번째 ... |
4,656 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2019 The TensorFlow Hub Authors.
Licensed under the Apache License, Version 2.0 (the "License");
Step1: SSGAN Demo
This notebook is a demo of Generative Adversarial Networks (GANs... | Python Code:
# Copyright 2019 The TensorFlow Hub Authors. All Rights Reserved.
#
# 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 re... |
4,657 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Import data
Step1: Data exploration
Shape, types, distribution, modalities and potential missing values
Step3: Data processing
Step4: Feature engineering
Step5: Modelling
This model aims... | Python Code:
raw_dataset = pd.read_csv(source_path + "Speed_Dating_Data.csv")
Explanation: Import data
End of explanation
raw_dataset.head(3)
raw_dataset_copy = raw_dataset
#merged_datasets = raw_dataset.merge(raw_dataset_copy, left_on="pid", right_on="iid")
#merged_datasets[["iid_x","gender_x","pid_y","gender_y"]].hea... |
4,658 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step 1 - Subject selection
written by R.A.I. Bethlehem, D. Margulies and M. Falkiewicz for the Autism Gradients project at Brainhack Cambridge 2017
Subjects are selected based on
Step1: Ch... | Python Code:
# imports
from __future__ import print_function
import numpy as np
import os
import nibabel as nib
from os import listdir
from os.path import isfile, join
import os.path
# little helper function to return the proper filelist with the full path but that skips hidden files
def listdir_nohidden(path):
for... |
4,659 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Curvature Matrix error estimation
Please cite
Step1: Read in the network and set up coordinates
Step2: Set up the grid of source points
Step3: Set source power and run the curvature matri... | Python Code:
%pylab inline
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import simulation_functions as sf
from mpl_toolkits.basemap import Basemap
from coordinateSystems import TangentPlaneCartesianSystem, GeographicSystem
c0 = 3.0e8 # m/s
dt_rms = 23.e-9 # seconds
Explanation: Curvature Matri... |
4,660 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Detecting Forest Change using Landsat 8 imagery
In this notebook forest change is detected by observing two contiguous acquisitions from landsat_8 imagery. The comparisons between a before a... | Python Code:
def ndvi(dataset):
return ((dataset.nir - dataset.red)/(dataset.nir + dataset.red)).rename("NDVI")
Explanation: Detecting Forest Change using Landsat 8 imagery
In this notebook forest change is detected by observing two contiguous acquisitions from landsat_8 imagery. The comparisons between a before ... |
4,661 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Language Translation
In this project, you’re going to take a peek into the realm of neural network machine translation. You’ll be training a sequence to sequence model on a dataset o... | Python Code:
DON'T MODIFY ANYTHING IN THIS CELL
import helper
import problem_unittests as tests
source_path = 'data/small_vocab_en'
target_path = 'data/small_vocab_fr'
source_text = helper.load_data(source_path)
target_text = helper.load_data(target_path)
Explanation: Language Translation
In this project, you’re going ... |
4,662 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Encontro 07
Step1: Configurando a biblioteca
Step2: Carregando o grafo
Step3: Vamos fazer uma simulação de $k$ iterações do algoritmo Hub/Authority
Step4: Considere as seguintes definiçõ... | Python Code:
import sys
sys.path.append('..')
import numpy as np
import socnet as sn
Explanation: Encontro 07: Simulação e Demonstração de Hub/Authority
Importando as bibliotecas:
End of explanation
sn.graph_width = 225
sn.graph_height = 225
Explanation: Configurando a biblioteca:
End of explanation
g = sn.load_graph('... |
4,663 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
В данном ноутбуке вам предлагается написать различные обработчики для команд с компьютера.Также можно реализовать свой дополнительный набор команд под свои задачи.
Подключение всех библиотек... | Python Code:
import serial
import pyaudio
import numpy as np
import wave
import scipy.signal as signal
import warnings
warnings.filterwarnings('ignore')
Explanation: В данном ноутбуке вам предлагается написать различные обработчики для команд с компьютера.Также можно реализовать свой дополнительный набор команд под сво... |
4,664 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
We start with a fasta file for our RNA
Step1: Folding using RNAfold from Vienna suite
RNAfold perfomrs MFE folding at the given temperature (-T option) and outputs top three structures in t... | Python Code:
ls -lah ../data/
!head ../data/rose.fa
Explanation: We start with a fasta file for our RNA
End of explanation
%%bash
cd ../data/
RNAfold -p -d2 --noPS --noLP -T 37 < rose.fa
cd -
ls -lah ../data/
Explanation: Folding using RNAfold from Vienna suite
RNAfold perfomrs MFE folding at the given temperature (-T ... |
4,665 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Classes and Object Oriented Programming
In an earlier section we discussed classes as a way of representing an abstract object, such as a polynomial. The resulting code
Step2: allowe... | Python Code:
class Polynomial(object):
Representing a polynomial.
explanation = "I am a polynomial"
def __init__(self, roots, leading_term):
self.roots = roots
self.leading_term = leading_term
self.order = len(roots)
def display(self):
string = str(self.lead... |
4,666 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Lab
Step1: TensorFlow 付属のモジュールを使って MNIST データセットをダウンロードします。
Step2: ニューラルネットの入力となる Tensor を tf.placeholder で用意します。
学習の際にランダムサンプリングしたデータを使って weight の更新を行うので、後から使うデータを変更できるように tf.placeholder を... | Python Code:
import numpy as np
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
print(tf.__version__)
Explanation: Lab: tf.layers
tf.layers を使うと行列演算や Variable の存在を隠蔽しつつ、柔軟にニューラルネットを記述することができます。
TensorFlow v1.0 で contrib から外れて、変更が加わりにくい安定したモジュールになりました。
楽さと柔軟さのバランスも取れており、おすすめの書き方です。
End... |
4,667 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
LAB 1a
Step2: The source dataset
Our dataset is hosted in BigQuery. The CDC's Natality data has details on US births from 1969 to 2008 and is a publically available dataset, meaning anyone ... | Python Code:
%%bash
sudo pip freeze | grep google-cloud-bigquery==1.6.1 || \
sudo pip install google-cloud-bigquery==1.6.1
from google.cloud import bigquery
Explanation: LAB 1a: Exploring natality dataset.
Learning Objectives
Use BigQuery to explore natality dataset
Use Cloud AI Platform Notebooks to plot data explora... |
4,668 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Ejercicio
Step1: Empecemos echando un ojo a la función del rotor, para ver qué vamos a necesitar y con qué parámetros vamos a trabajar.
Step2: Podemos trazar unas cuantas curvas para obser... | Python Code:
%matplotlib inline
import numpy as np # Trabajaremos con arrays
import matplotlib.pyplot as plt # Y vamos a pintar gráficos
from optrot.rotor import calcular_rotor # Esta función es la que vamos a usar para calcular el rotor
import random as random # Necesitaremos números aleatorios
Explanation: Ejercicio:... |
4,669 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Algoritmo de Optimización por Colonia de Hormigas (ACO)
Como vimos en la parte de teoría, el problema del viajante es un problema clásico
Step1: Lo primero que vamos a hacer es crear un map... | Python Code:
#Comencemos importando los paquetes necesarios:
%matplotlib inline
import numpy as np # Usaremos arrays
import matplotlib.pyplot as plt # Para pintar resultados
import ants as ants # Aquí están los objetos del algoritmo
Explanation: Algoritmo de Optimización por Colonia de Hormigas (ACO)
Como vimos en la... |
4,670 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Lab 2 - Spark SQL
This Lab will show you how to work with Spark SQL
Step 1
<h3>Getting started
Step1: Step 2
<h3>Dowload a JSON Recordset to work with</h3>
Let's download the data, we can r... | Python Code:
#Create the SQLContext
Explanation: Lab 2 - Spark SQL
This Lab will show you how to work with Spark SQL
Step 1
<h3>Getting started: Create a SQL Context</h3>
<b>Type:</b>
from pyspark.sql import SQLContext<br>
sqlContext = SQLContext(sc)
End of explanation
#enter the commands to remove and download file he... |
4,671 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
OT for domain adaptation
This example introduces a domain adaptation in a 2D setting and the 4 OTDA
approaches currently supported in POT.
Step1: Generate data
Step2: Instantiate the diffe... | Python Code:
# Authors: Remi Flamary <remi.flamary@unice.fr>
# Stanislas Chambon <stan.chambon@gmail.com>
#
# License: MIT License
import matplotlib.pylab as pl
import ot
Explanation: OT for domain adaptation
This example introduces a domain adaptation in a 2D setting and the 4 OTDA
approaches currently suppor... |
4,672 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
word2vec
This notebook is equivalent to demo-word.sh, demo-analogy.sh, demo-phrases.sh and demo-classes.sh from Google.
Training
Download some data, for example
Step1: Run word2phrase to gr... | Python Code:
import word2vec
Explanation: word2vec
This notebook is equivalent to demo-word.sh, demo-analogy.sh, demo-phrases.sh and demo-classes.sh from Google.
Training
Download some data, for example: http://mattmahoney.net/dc/text8.zip
End of explanation
word2vec.word2phrase('./text8', './text8-phrases', verbose=Tr... |
4,673 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
This notebook is to test several models for measuring the drop in $f_{features}$ in the FERENGI-fied galaxies. Refer to the link below for the final version, where zeta is calculated with th... | Python Code:
%matplotlib inline
from matplotlib import pyplot as plt
from astropy.table import Table,Column
from astropy.io import fits
from scipy import optimize
from scipy.optimize import minimize
from scipy import stats
from scipy.stats import distributions as dist
import numpy as np
import os
import requests
import... |
4,674 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
RiiDataFrame
Here, a little bit more detail about RiiDataFrame class will be given.
Step1: RiiDataFrame has an attribute named catalog that is a Pandas DataFrame provinding the catalog of e... | Python Code:
import riip
ri = riip.RiiDataFrame()
Explanation: RiiDataFrame
Here, a little bit more detail about RiiDataFrame class will be given.
End of explanation
ri.catalog.head(3)
Explanation: RiiDataFrame has an attribute named catalog that is a Pandas DataFrame provinding the catalog of experimental data as show... |
4,675 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a href="http
Step1: The docstring describes the component and provides some simple examples
Step2: The __init__ docstring lists the parameters
Step3: Example 1
Step4: To use DrainageDen... | Python Code:
import copy
import numpy as np
import matplotlib as mpl
from landlab import RasterModelGrid, imshow_grid
from landlab.io import read_esri_ascii
from landlab.components import FlowAccumulator, DrainageDensity
Explanation: <a href="http://landlab.github.io"><img style="float: left" src="../../../landlab_head... |
4,676 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Simple model of epidemic dynamics
Step1: Setup a python function that specifies the dynamics
Step2: The function SIR above takes three arguments, $U$, $t$, and $p$ that represent the state... | Python Code:
#Import the necessary modules and perform the necessary tests
import scipy as sc
import pylab as gr
sc.test("all",verbose=0)
%matplotlib inline
Explanation: Simple model of epidemic dynamics: SIR
Prof. Marco Arieli Herrera-Valdez,
Facultad de Ciencias, Universidad Nacional Autónoma de México
Created March ... |
4,677 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Python for Bioinformatics
This Jupyter notebook is intented to be used alongside the book Python for Bioinformatics
Note
Step1: Chapter 9
Step2: Test Installation
Step3: Tip
Step4: Seq O... | Python Code:
!curl https://raw.githubusercontent.com/Serulab/Py4Bio/master/samples/samples.tar.bz2 -o samples.tar.bz2
!mkdir samples
!tar xvfj samples.tar.bz2 -C samples
Explanation: Python for Bioinformatics
This Jupyter notebook is intented to be used alongside the book Python for Bioinformatics
Note: Before opening ... |
4,678 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
An information filter is used to combine a noisy measurement and a noisy predicition about the state of a system into a better estimate of the real state of said system
Step1: On of the mos... | Python Code:
# Lets define some constants so we can play with the simulations later
# I used 81 time steps so at each time step the speed will increase by 1
TIME_STEPS = 81
V_0 = 40
V_F = 120
# Create the true speeds from V_0 to V_F
real_speeds = np.linspace(start=V_0, stop=V_F, num=TIME_STEPS)
# Define a generator tha... |
4,679 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Tutorial 1
Step1: Overview of a simulation script
Typically, a simulation script consists of the following parts
Step2: The next step would be to create an instance of the System class and... | Python Code:
import espressomd
print(espressomd.features())
required_features = ["LENNARD_JONES"]
espressomd.assert_features(required_features)
Explanation: Tutorial 1: Lennard-Jones Liquid
Table of Contents
Introduction
Background
The Lennard-Jones Potential
Units
First steps
Overview of a simulation script
System set... |
4,680 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Ndmg Tutorial
Step1: Check for dependencies, Set Directories
The below code is a simple check that makes sure AFNI and FSL are installed. <br>
We also set the input, data, and atlas paths.
... | Python Code:
import os
import os.path as op
import glob
import shutil
import warnings
import subprocess
from pathlib import Path
from ndmg.scripts import ndmg_dwi_pipeline
from ndmg.scripts.ndmg_bids import get_atlas
from ndmg.utils import cloud_utils
Explanation: Ndmg Tutorial: Running Inside Python
This tutorial prov... |
4,681 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
The Contextual Bandits
We'll look into a policy-gradient based agent.
Step1: The Contextual Bandits
Here we define our contextual bandits. In this example, we are using three four-armed ban... | Python Code:
import tensorflow as tf
import numpy as np
import tensorflow.contrib.slim as slim
Explanation: The Contextual Bandits
We'll look into a policy-gradient based agent.
End of explanation
class contextual_bandit():
def __init__(self):
self.state = 0
#List out our bandits. Currently arms 4, ... |
4,682 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Markov switching autoregression models
This notebook provides an example of the use of Markov switching models in Statsmodels to replicate a number of results presented in Kim and Nelson (19... | Python Code:
%matplotlib inline
import numpy as np
import pandas as pd
import statsmodels.api as sm
import matplotlib.pyplot as plt
import requests
from io import BytesIO
# NBER recessions
from pandas_datareader.data import DataReader
from datetime import datetime
usrec = DataReader('USREC', 'fred', start=datetime(1947... |
4,683 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ModelSelection.ipynb
Choosing the number of states and a suitable timescale for hidden Markov models
One of the challenges associated with using hidden Markov models is specifying the correc... | Python Code:
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
import sys
from IPython.display import display, clear_output
sys.path.insert(0, 'helpers')
from efunctions import * # load my helper function(s) to save pdf figures, etc.
from hc3 import load_data, get_sessions
fro... |
4,684 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Numpy Exercise 1
Imports
Step2: Checkerboard
Write a Python function that creates a square (size,size) 2d Numpy array with the values 0.0 and 1.0
Step3: Use vizarray to visualize a checker... | 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 1
Imports
End of explanation
def checkerboard(size):
Return a 2d checkboard of 0.0 and 1.0 as a NumPy array
board = ... |
4,685 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Linear Algebra Review
From xkcd
Step2: Linear Algebra and Linear Systems
A lot of problems in statistical computing can be described mathematically using linear algebra. This lectur... | Python Code:
import os
import sys
import glob
import matplotlib.pyplot as plt
import matplotlib.patches as patch
import numpy as np
import pandas as pd
%matplotlib inline
%precision 4
plt.style.use('ggplot')
from scipy import linalg
np.set_printoptions(suppress=True)
# Students may (probably should) ignore this code. I... |
4,686 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Static & Transient DataFrames in PyNastran
The iPython notebook for this demo can be found in
Step1: Solid Bending
Let's show off combine=True/False. We'll talk about the keys soon.
Step2:... | Python Code:
import os
import pandas as pd
import pyNastran
from pyNastran.op2.op2 import read_op2
pkg_path = pyNastran.__path__[0]
model_path = os.path.join(pkg_path, '..', 'models')
Explanation: Static & Transient DataFrames in PyNastran
The iPython notebook for this demo can be found in:
- docs\quick_start\demo\o... |
4,687 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Behavior of the median filter with noised sine waves
DW 2015.11.12
Step1: 1. Create all needed arrays and data.
Step2: Figure 1. Behavior of the median filter with given window length and ... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
from scipy.signal import medfilt
import gitInformation
%matplotlib inline
gitInformation.printInformation()
Explanation: Behavior of the median filter with noised sine waves
DW 2015.11.12
End of explanation
# Sine wave, 16 wave numbers, 16*128 samples.
x... |
4,688 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a href="https
Step1: Setup
Loading auxiliary files and importing the necessary libraries.
Step2: Grading
We will create a grader instance below and use it to collect your answers. Note th... | Python Code:
%tensorflow_version 1.x
Explanation: <a href="https://colab.research.google.com/github/saketkc/notebooks/blob/master/coursera-BayesianML/05_Vae_assignment.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
First things first
Click File -> ... |
4,689 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Exact DKL (Deep Kernel Learning) Regression w/ KISS-GP
Overview
In this notebook, we'll give a brief tutorial on how to use deep kernel learning for regression on a medium scale dataset usin... | Python Code:
import math
import tqdm
import torch
import gpytorch
from matplotlib import pyplot as plt
# Make plots inline
%matplotlib inline
Explanation: Exact DKL (Deep Kernel Learning) Regression w/ KISS-GP
Overview
In this notebook, we'll give a brief tutorial on how to use deep kernel learning for regression on a ... |
4,690 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Robust Process Scheduling (with Python)
Nominal Model
Necessary imports
Step1: We instantiate the nominal model and solve it using the default solver (Gurobi).
The data of the nominal mode... | Python Code:
%matplotlib inline
from robust_STN import *
Explanation: Robust Process Scheduling (with Python)
Nominal Model
Necessary imports:
End of explanation
stn = STN()
stn.solve()
Explanation: We instantiate the nominal model and solve it using the default solver (Gurobi).
The data of the nominal model can be ch... |
4,691 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Crear el "engine" pasando la dirección de la db
Step1: Hacer la query especificando el "engine" que se desea usar
Step2: Link a Pandas NB para ver join, merge, append, etc
Agregando un nue... | Python Code:
engine = create_engine('postgresql://celia@localhost:5432/mytestdb')
engine
df_customer.to_json('/tmp/test.json')
json_df = pd.read_json('/home/celia/Downloads/MOCK_DATA.json')
json_df
json_df.to_sql('Customer', engine, index=None)
Explanation: Crear el "engine" pasando la dirección de la db
End of explan... |
4,692 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
可视化线性关系¶
许多数据集包含多个定量变量,分析的目标通常是将这些变量相互关联
Step1: regplot()和lmplot()绘制两个变量的散点图,x和y,然后拟合回归模型并绘制得到的回归直线和该回归一个95%置信区间:y ~ x
Step2: You should note that the resulting plots are identical, except... | Python Code:
import numpy as np
import pandas as pd
import matplotlib as mpl
import matplotlib.pyplot as plt
import seaborn as sns
sns.set(style="whitegrid", color_codes=True)
np.random.seed(sum(map(ord, "regression")))
tips = sns.load_dataset("tips")
Explanation: 可视化线性关系¶
许多数据集包含多个定量变量,分析的目标通常是将这些变量相互关联
End of explana... |
4,693 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Uncertainty analysis for drillholes in Gippsland Basin Model
We here evaluate how to analyse and visualise uncertainties in a kinematic model. The basic idea is that we have a set of drillho... | Python Code:
from IPython.core.display import HTML
css_file = 'pynoddy.css'
HTML(open(css_file, "r").read())
%matplotlib inline
# here the usual imports. If any of the imports fails, make sure that pynoddy is installed
# properly, ideally with 'python setup.py develop' or 'python setup.py install'
import sys, os
import... |
4,694 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Requirements
Step1: PyTorch deployment requires using an unstable version of PyTorch (1.0.0+).
In order to install this version, use "Preview" option when choosing PyTorch version.
https | Python Code:
torch.__version__
Explanation: Requirements
End of explanation
# Let's create an example model using ResNet-18
model = torchvision.models.resnet18()
model
# Creating a sample of the input
# It will be used to pass it to the network to build the dimensions
sample = torch.rand(size=(1, 3, 224, 224))
# Creati... |
4,695 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
+
Word Count Lab
Step1: Part 1
Step3: (1b) Pluralize and test
Let's use a map() transformation to add the letter 's' to each string in the base RDD we just created. We'll define a Python... | Python Code:
labVersion = 'cs190_week2_word_count_v_1_0'
Explanation: +
Word Count Lab: Building a word count application
This lab will build on the techniques covered in the Spark tutorial to develop a simple word count application. The volume of unstructured text in existence is growing dramatically, and Spark is a... |
4,696 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
1. Contexto
O Instituto Nacional de Estudos e Pesquisas Educacionais Anísio Teixeira (Inep) divulgou no dia 21 de Junho de 2017 sobre remuneração média dos professores em exercício na educaç... | Python Code:
# Começamos importando as bibliotecas a serem utilizadas:
import numpy as np
import pandas as pd
import seaborn as sns; sns.set()
%matplotlib inline
# Importando os microdados do arquivo .zip:
rs = pd.read_table('/mnt/part/Data/RAIS/2014/RS2014.zip', sep = ';', encoding = 'cp860', decimal = ',')
rs.head() ... |
4,697 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Experimental
Step1: 1. Write Eager code that is fast and scalable
TF.Eager gives you more flexibility while coding, but at the cost of losing the benefits of TensorFlow graphs. For example,... | Python Code:
# Install TensorFlow; note that Colab notebooks run remotely, on virtual
# instances provided by Google.
!pip install -U -q tf-nightly
import os
import time
import tensorflow as tf
from tensorflow.contrib import autograph
import matplotlib.pyplot as plt
import numpy as np
import six
from google.colab impor... |
4,698 | 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... |
4,699 | Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
I may be missing something obvious, but I can't find a way to compute this. | Problem:
import numpy as np
import pandas as pd
import torch
x, y = load_data()
maxs = torch.max(torch.abs(x), torch.abs(y))
xSigns = (maxs == torch.abs(x)) * torch.sign(x)
ySigns = (maxs == torch.abs(y)) * torch.sign(y)
finalSigns = xSigns.int() | ySigns.int()
signed_max = maxs * finalSigns |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.