Unnamed: 0 int64 0 16k | text_prompt stringlengths 110 62.1k | code_prompt stringlengths 37 152k |
|---|---|---|
200 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Building an Apache log analyzer with Pandas
Apache access logs are text files that record the activity of a web site. The analysis of log files provides useful insights for web masters and s... | Python Code:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from dateutil.parser import *
Explanation: Building an Apache log analyzer with Pandas
Apache access logs are text files that record the activity of a web site. The analysis of log files provides useful insights for web masters and site... |
201 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Queuing Simulation
We present in this notebook a simple bank customer arrival model.
We use a Poisson distribution to model the arrival and departure times.
Step1: Next we initialize two a... | Python Code:
import random
#define and initialize the parameters of the Poisson distributions
lambd_in = 0.5
lambd_out = 0.4
#bank variables
closing_time = 100 #initialize the bank closing time
overtime = 0 #overtime the employees need to be paid for
#queue variables
num_arrivals = 0 #number ... |
202 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
欲抓的網頁列表
Step1: 下載網頁並且組成一個檔案
Step2: 我們來看一下實際檔案的內容
請點即此鏈結
載入頁面,並進行 json parsing
Step3: RDD 常用的 Function 如下
map(funct) - 對 RDD 的裡頭的元素進行處理動作
mapValues (func) - 排除 Key,只對 RDD 的裡頭的元素進行處理動作
redu... | Python Code:
urllist = ['http://chahabi77.pixnet.net/blog/post/436715527',
'http://chahabi77.pixnet.net/blog/post/403682269',
'http://chahabi77.pixnet.net/blog/post/354943724',
'http://chahabi77.pixnet.net/blog/post/386442944',
'http://chahabi77.pixnet.net/blog/post/235296791... |
203 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Tutorial
The Basics
We begin by importing selfies.
Step1: First, let's try translating between SMILES and SELFIES - as an example, we will use benzaldehyde. To translate from SMILES to SELF... | Python Code:
import selfies as sf
Explanation: Tutorial
The Basics
We begin by importing selfies.
End of explanation
original_smiles = "O=Cc1ccccc1" # benzaldehyde
try:
encoded_selfies = sf.encoder(original_smiles) # SMILES -> SELFIES
decoded_smiles = sf.decoder(encoded_selfies) # SELFIES -> SMILES
... |
204 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Vertex SDK
Step1: Install the Google cloud-storage library as well.
Step2: Restart the Kernel
Once you've installed the Vertex SDK and Google cloud-storage, you need to restart the noteboo... | Python Code:
! pip3 install -U google-cloud-aiplatform --user
Explanation: Vertex SDK: Train & deploy a TensorFlow model with hosted runtimes (aka pre-built containers)
Installation
Install the latest (preview) version of Vertex SDK.
End of explanation
! pip3 install google-cloud-storage
Explanation: Install the Google... |
205 | 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" style="margin-top
Step1: Dataset Description
| Variable Name | Definition ... | Python Code:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
sns.set_style(style="darkgrid")
# plt.rcParams['figure.figsize'] = [12.0, 8.0] # make plots size, double of the notebook normal
plt.rcParams['figure.figsize'] = [9.0, 6.0] # make plots size, ... |
206 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
27/10
Ordenamientos y búsquedas
Funciones anónimas.
Excepciones.
Ordenamiento de listas
Las listas se pueden ordenar fácilmente usando la función sorted
Step1: Pero, ¿y cómo hacemos para o... | Python Code:
lista_de_numeros = [1, 6, 3, 9, 5, 2]
lista_ordenada = sorted(lista_de_numeros)
print lista_ordenada
Explanation: 27/10
Ordenamientos y búsquedas
Funciones anónimas.
Excepciones.
Ordenamiento de listas
Las listas se pueden ordenar fácilmente usando la función sorted:
End of explanation
lista_de_numeros = ... |
207 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Mediation Analysis
Written by Jin Cheong & Luke Chang
A mediation analysis is conducted when a researcher is interested in the mechanism underlying how variable X has an effect on variable Y... | Python Code:
%matplotlib inline
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import statsmodels.formula.api as smf
import statsmodels.api as sm
from scipy import stats
def sobel_test(a, b, se_a, se_b):
'''
Sobel test for significance of mediation
Args:
a: coefficient ... |
208 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright © 2019 The TensorFlow Authors.
Step1: TFX – Introduction to Apache Beam
TFX is designed to be scalable to very large datasets which require substantial resources. Distribute... | 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... |
209 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
This notebooks aims at visualizing the content of the MNIST dataset
As a fist step, we use keras to download the dataset.
Then we print the shape of it.
Step1: In case it needs disambiguati... | Python Code:
import keras
from keras.datasets import mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
print "input of training set has shape {} and output has shape {}".format(x_train.shape, y_train.shape)
print "input of testing set has shape {} and output has shape {}".format(x_test.shape, y_test.shape)... |
210 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Numerical Evaluation of Integrals
Integration problems are common in statistics whenever we are dealing with continuous distributions. For example the expectation of a function is an integra... | Python Code:
from scipy.integrate import quad
def f(x):
return x * np.cos(71*x) + np.sin(13*x)
x = np.linspace(0, 1, 100)
plt.plot(x, f(x))
pass
Explanation: Numerical Evaluation of Integrals
Integration problems are common in statistics whenever we are dealing with continuous distributions. For example the expecta... |
211 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Treating Trees
Although any expression in Joy can be considered to describe a tree with the quotes as compound nodes and the non-quote values as leaf nodes, in this page I want to talk about... | Python Code:
from notebook_preamble import J, V, define
define('BTree-iter == [not] [pop] roll< [dupdip rest rest] cons [step] genrec')
J('[] [23] BTree-iter') # It doesn't matter what F is as it won't be used.
J('["tommy" 23 [] []] [first] BTree-iter')
J('["tommy" 23 ["richard" 48 [] []] ["jenny" 18 [] []]] [first] ... |
212 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Original Voce-Chaboche Model Fitting Using Only Tension Test Example 1
An example of fitting the original Voce-Chaboche model to only a tension test is presented in this notebook.
Documentat... | Python Code:
import RESSPyLab as rpl
import numpy as np
Explanation: Original Voce-Chaboche Model Fitting Using Only Tension Test Example 1
An example of fitting the original Voce-Chaboche model to only a tension test is presented in this notebook.
Documentation for all the functions used in this example can be found b... |
213 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Arbeitsgrundlagen
Im Versuch M1 geht es darum die Geschwindigkeit einer Pistolenkugel auf verschiedene Arten zu bestimmen. Dabei gibt es noch verschiedene Arten von Geschwindigkeiten.
Die ge... | Python Code:
# define base values and measurements
v1_s = 0.500
v1_sb1 = 1.800
v1_sb2 = 1.640
v1_m = np.mean([0.47, 0.46, 0.46, 0.46, 0.46, 0.47, 0.46, 0.46, 0.46, 0.46, 4.65 / 10]) * 1e-3
v1_T = np.mean([28.68 / 10, 28.91 / 10])
v1_cw = 0.75
v1_cw_u = 0.08
v1_A = 4*1e-6
v1_pl = 1.2041
def air_resistance(s, v):
k =... |
214 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Representing an Artificial Neural Network as a Cartesian Genetic Program
(a.k.a dCGPANN)
Neural networks (deep, shallow, convolutional or not) are, after all, computer programs and as such c... | Python Code:
# Initial import
import dcgpy
import matplotlib.pyplot as plt
import numpy as np
from tqdm import tqdm
%matplotlib inline
Explanation: Representing an Artificial Neural Network as a Cartesian Genetic Program
(a.k.a dCGPANN)
Neural networks (deep, shallow, convolutional or not) are, after all, computer prog... |
215 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
.. _tut_stats_cluster_source_1samp
Step1: Set parameters
Step2: Read epochs for all channels, removing a bad one
Step3: Transform to source space
Step4: Transform to common cortical spac... | Python Code:
# Authors: Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr>
# Eric Larson <larson.eric.d@gmail.com>
# License: BSD (3-clause)
import os.path as op
import numpy as np
from numpy.random import randn
from scipy import stats as stats
import mne
from mne import (io, spatial_tris_connectivit... |
216 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a href="https
Step1: Visualizations
Visualizations play an important role in the field of machine learning and data science. Often we need to distill key information found in large quantit... | Python Code:
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distribute... |
217 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Sky coordinate DSLR aperture photometry yielding untransformed magnitudes
Uses Python 3, astropy, matplotlib, PythonPhot, PhotUtils
Assumes a plate-solved image for RA/Dec determination
Defi... | Python Code:
import os
from random import random
# TODO: shouldn't need ordered dictionary now either
from collections import OrderedDict
import numpy as np
import pandas as pd
from astropy.io import fits
from astropy.visualization import astropy_mpl_style
import matplotlib.pyplot as plt
from matplotlib.colors import L... |
218 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Basic objects
A striplog depends on a hierarchy of objects. This notebook shows the objects and their basic functionality.
Lexicon
Step1: <hr />
Lexicon
Step2: Most of the lexicon works 'b... | Python Code:
import striplog
striplog.__version__
Explanation: Basic objects
A striplog depends on a hierarchy of objects. This notebook shows the objects and their basic functionality.
Lexicon: A dictionary containing the words and word categories to use for rock descriptions.
Component: A set of attributes.
Interval... |
219 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Analysis Ready Data Tutorial Part 2
Step1: Step 1
Step2: Step 2
Step3: Step 3
Step4: Step 4
Step5: Step 4.2
Step6: Step 5
Step7: Step 5.2
Step8: Step 6 | Python Code:
from copy import copy
import datetime
import os
from pathlib import Path
from pprint import pprint
import shutil
import time
from zipfile import ZipFile
import numpy as np
from planet import api
from planet.api import downloader, filters
Explanation: Analysis Ready Data Tutorial Part 2: Use Case 1
Time-ser... |
220 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Development of a Reader for Siemens Trend CSV files
This notebook was used for development of the final Siemens reader. The code was then exported out
out of here and put into the ddc_reade... | Python Code:
import csv
import string
import datetime
import pandas as pd
import numpy as np
# import matplotlib pyplot commands
from matplotlib.pyplot import *
# Show Plots in the Notebook
%matplotlib inline
rcParams['figure.figsize']= (10, 8) # set Chart Size
rcParams['font.size'] = 14 # set Font siz... |
221 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Simplex.py
En el siguiente tutorial, se van a ver todos los métodos con los que cuenta la librería Simplex.py. Por supuesto, una aplicación de muchos de ellos, siguiendo una secuencia, corre... | Python Code:
from PySimplex import Simplex
from PySimplex import rational
import numpy as np
number="2"
print(Simplex.convertStringToRational(number))
number="2/5"
print(Simplex.convertStringToRational(number))
# Si recibe algo que no es un string, devuelve None
number=2
print(Simplex.convertStringToRational(number))
E... |
222 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step2: Multimodale Versuche der Alignierung historischer Texte
Andreas Wagner und Manuela Bragagnolo, Max-Planck-Institut für europäische Rechtsgeschichte, Frankfurt/M.
<wag... | Python Code:
from typing import Dict
import lxml
from lxml import etree
document=etree.fromstring(
<TEI xmlns="http://www.tei-c.org/ns/1.0">
<text>
<body>
<div n="1">
<p>
... <milestone unit="number" n="9"/>aun que el amor de Dios ha de ser
grandissimo ..., como despues de. S. Tho.
<ref ta... |
223 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Think Bayes
Copyright 2018 Allen B. Downey
MIT License
Step3: The Geiger counter problem
I got the idea for the following problem from Tom Campbell-Ricketts, author of the Maximum Entropy b... | Python Code:
# Configure Jupyter so figures appear in the notebook
%matplotlib inline
# Configure Jupyter to display the assigned value after an assignment
%config InteractiveShell.ast_node_interactivity='last_expr_or_assign'
import numpy as np
import pandas as pd
# import classes from thinkbayes2
from thinkbayes2 impo... |
224 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a href="https
Step1: Loading and exploring our data set
This is a database of customers of an insurance company. Each data point is one customer. The group represents the number of acciden... | Python Code:
import tensorflow as tf
tf.logging.set_verbosity(tf.logging.ERROR)
print(tf.__version__)
Explanation: <a href="https://colab.research.google.com/github/DJCordhose/ai/blob/master/notebooks/2019_tf/autoencoders_tabular.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg... |
225 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Reinforcement Learning
This Jupyter notebook acts as supporting material for Chapter 21 Reinforcement Learning of the book Artificial Intelligence
Step1: CONTENTS
Overview
Passive Reinforce... | Python Code:
from rl import *
Explanation: Reinforcement Learning
This Jupyter 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 ... |
226 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Chinmai Raman
Homework 3
A.4 Solving a system of difference equations
Computes the development of a loan over time.
The below function calculates the amount paid per month (the first array) ... | Python Code:
p1.loan(6, 10000, 12)
Explanation: Chinmai Raman
Homework 3
A.4 Solving a system of difference equations
Computes the development of a loan over time.
The below function calculates the amount paid per month (the first array) and the amount left to be paid (the second array) at each month of the year at a p... |
227 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Problemas
Defina una función que obtenga la cinemática inversa de un pendulo doble.
Step1: Obtenga las posiciones en el espacio articular, $q_1$ y $q_2$, necesarias para que el punto final ... | Python Code:
def ci_pendulo_doble(x, y):
# tome en cuenta que las longitudes de los eslabones son 2 y 2
l1, l2 = 2, 2
from numpy import arccos, arctan2, sqrt
# YOUR CODE HERE
raise NotImplementedError()
return q1, q2
from numpy.testing import assert_allclose
assert_allclose(ci_pendulo_doble(4, 0... |
228 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Compute spatial resolution metrics in source space
Compute peak localisation error and spatial deviation for the point-spread
functions of dSPM and MNE. Plot their distributions and differen... | Python Code:
# Author: Olaf Hauk <olaf.hauk@mrc-cbu.cam.ac.uk>
#
# License: BSD-3-Clause
import mne
from mne.datasets import sample
from mne.minimum_norm import make_inverse_resolution_matrix
from mne.minimum_norm import resolution_metrics
print(__doc__)
data_path = sample.data_path()
subjects_dir = data_path / 'subjec... |
229 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Create Better Graphs with Bokeh
This guide walks through the process of creating better graphs with bokeh. The coolest thing about bokeh is that it lets you create interactive plots. We will... | Python Code:
import numpy as np
from scipy.integrate import odeint
from bokeh.plotting import figure, show
from bokeh.io import output_notebook
Explanation: Create Better Graphs with Bokeh
This guide walks through the process of creating better graphs with bokeh. The coolest thing about bokeh is that it lets you create... |
230 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2018 The TensorFlow Authors.
Step1: Automatically rewrite TF 1.x and compat.v1 API symbols
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="ht... | 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... |
231 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Прогнозирование уровня средней заработной платы в России
Известны данные о заработной плате за каждый месяц с января 1993 по август 2016. Необходимо проанализировать данные, подобрать для ни... | Python Code:
%pylab inline
import pandas as pd
from scipy import stats
import statsmodels.api as sm
import matplotlib.pyplot as plt
import warnings
from itertools import product
def invboxcox(y,lmbda):
if lmbda == 0:
return(np.exp(y))
else:
return(np.exp(np.log(lmbda*y+1)/lmbda))
Explanation: Прогнози... |
232 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Multidimentional data - Matrices and Images
Step1: Let us work with the matrix
Step2: numpy matrix multiply uses the dot() function
Step3: Caution the * will just multiply the matricies o... | Python Code:
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
from scipy import linalg
plt.style.use('ggplot')
plt.rc('axes', grid=False) # turn off the background grid for images
Explanation: Multidimentional data - Matrices and Images
End of explanation
my_matrix = np.array([[1,2],[1,1]])
print... |
233 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Behaviour suite
This is the official results page for bsuite. You can use this to
Step1: Overall bsuite scores
Load your experiments below. We recommend a maximum of 5 result sets, for clar... | Python Code:
#@title Imports
! pip install --quiet git+git://github.com/deepmind/bsuite
import warnings
from bsuite.experiments import summary_analysis
from bsuite.logging import csv_load
from bsuite.logging import sqlite_load
import numpy as np
import pandas as pd
import plotnine as gg
pd.options.mode.chained_assignme... |
234 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
BigQuery Essentials for Teradata Users
In this lab you will take an existing 2TB+ TPC-DS benchmark dataset and learn common day-to-day activities you'll perform in BigQuery.
What you'll do
... | Python Code:
%%bash
gcloud config list
Explanation: BigQuery Essentials for Teradata Users
In this lab you will take an existing 2TB+ TPC-DS benchmark dataset and learn common day-to-day activities you'll perform in BigQuery.
What you'll do
In this lab, you will learn how to:
Use BigQuery to access and query the TPC-D... |
235 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Spatial Gaussian Process inference in PyMC3
This is the first step in modelling Species occurrence.
The good news is that MCMC works,
The bad one is that it's computationally intense.
Step1... | Python Code:
# Load Biospytial modules and etc.
%matplotlib inline
import sys
sys.path.append('/apps/external_plugins/spystats/')
#import django
#django.setup()
import pandas as pd
import matplotlib.pyplot as plt
## Use the ggplot style
plt.style.use('ggplot')
import numpy as np
## Model Specification
import pymc3 as p... |
236 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Input pipeline into Keras
In this notebook, we will look at how to read large datasets, datasets that may not fit into memory, using TensorFlow. We can use the tf.data pipeline to feed data ... | Python Code:
%%bash
export PROJECT=$(gcloud config list project --format "value(core.project)")
echo "Your current GCP Project Name is: "$PROJECT
!pip install tensorflow==2.1.0 --user
Explanation: Input pipeline into Keras
In this notebook, we will look at how to read large datasets, datasets that may not fit into memo... |
237 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Time Series Analysis with Pastas
Developed by Mark Bakker, TU Delft
Required files to run this notebook (all available from the data subdirectory)
Step1: Load the head observations
The firs... | Python Code:
import pandas as pd
import pastas as ps
import matplotlib.pyplot as plt
ps.set_log_level("ERROR")
ps.show_versions()
Explanation: Time Series Analysis with Pastas
Developed by Mark Bakker, TU Delft
Required files to run this notebook (all available from the data subdirectory):
Head files: head_nb1.csv, B58... |
238 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Building an ARIMA Model for a Financial Dataset
In this notebook, you will build an ARIMA model for AAPL stock closing prices. The lab objectives are
Step1: Import data from Google Clod Sto... | Python Code:
!pip install --user statsmodels
%matplotlib inline
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import datetime
%config InlineBackend.figure_format = 'retina'
Explanation: Building an ARIMA Model for a Financial Dataset
In this notebook, you will build an ARIMA model for AAPL stoc... |
239 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Lesson18 Individual Assignment
Individual means that you do it yourself. You won't learn to code if you don't struggle for yourself and write your own code. Remember that while you can disc... | Python Code:
## import libraries we need
import numpy as np
import matplotlib.pyplot as plt
## makes our population of 10,000 numbers from 1-100
## you might get a warning that this function is deprecated, but it still works
population = np.random.random_integers(1, high=100, size=10000)
## look at 1st 25 (don't print... |
240 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Goals for today's pre-class assignment
Write a Python program to make simple calculations
Work with number and string data types
Work with the list data type
Assignment instructions
Watch th... | Python Code:
# Imports the functionality that we need to display YouTube videos in a Jupyter Notebook.
# You need to run this cell before you run ANY of the YouTube videos.
from IPython.display import YouTubeVideo
# Display a specific YouTube video, with a given width and height.
# WE STRONGLY RECOMMEND that you ... |
241 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Errors, or bugs, in your software
Today we'll cover dealing with errors in your Python code, an important aspect of writing software.
What is a software bug?
According to Wikipedia (accessed... | Python Code:
import numpy as np
Explanation: Errors, or bugs, in your software
Today we'll cover dealing with errors in your Python code, an important aspect of writing software.
What is a software bug?
According to Wikipedia (accessed 16 Oct 2018), a software bug is an error, flaw, failure, or fault in a computer prog... |
242 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Study of Exploration Algorithms in developmental robotics with Explauto
This tutorial explains and implements some exploration algorithms used in developmental robotics.
The goal is to get u... | Python Code:
import matplotlib
matplotlib.use('TkAgg')
from utils import *
Explanation: Study of Exploration Algorithms in developmental robotics with Explauto
This tutorial explains and implements some exploration algorithms used in developmental robotics.
The goal is to get used to the concepts of Goal Babbling [Oude... |
243 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
pyplearnr demo
Here I demonstrate pyplearnr, a wrapper for building/training/validating scikit learn pipelines using GridSearchCV or RandomizedSearchCV.
Quick keyword arguments give access t... | Python Code:
import pandas as pd
df = pd.read_pickle('trimmed_titanic_data.pkl')
df.info()
Explanation: pyplearnr demo
Here I demonstrate pyplearnr, a wrapper for building/training/validating scikit learn pipelines using GridSearchCV or RandomizedSearchCV.
Quick keyword arguments give access to optional feature selecti... |
244 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Modeling and Simulation in Python
Case Study
Step2: One queue or two?
This notebook presents a solution to an exercise from Modeling and Simulation in Python. It uses features from the fir... | Python Code:
# Configure Jupyter so figures appear in the notebook
%matplotlib inline
# Configure Jupyter to display the assigned value after an assignment
%config InteractiveShell.ast_node_interactivity='last_expr_or_assign'
# import functions from the modsim.py module
from modsim import *
# set the random number gene... |
245 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Summary
Use Tensorboard to build and train a neural net for recognizing
Conclusion
The Neural net has mediocre overall performance, likely because I didn't spend that much time optimizing i... | Python Code:
# imports
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
import string
import math
import tabulate
import os
Explanation: Summary
Use Tensorboard to build and train a neural net for recognizing
Conclusion
The Neural net has mediocre overall performance, likely because I didn't ... |
246 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Regression Week 3
Step1: Next we're going to write a polynomial function that takes an SArray and a maximal degree and returns an SFrame with columns containing the SArray to all the powers... | Python Code:
import graphlab
Explanation: Regression Week 3: Assessing Fit (polynomial regression)
In this notebook you will compare different regression models in order to assess which model fits best. We will be using polynomial regression as a means to examine this topic. In particular you will:
* Write a function t... |
247 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
First example
Step1: The step method (Sampling method)
Step2: If we wanted to use the slice sampling algorithm to sigma instead of NUTS (which was assigned automatically), we could have sp... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
# Initialize random number generator
np.random.seed(123)
# True parameter values
alpha, sigma = 1, 1
beta = [1, 2.5]
# Size of dataset
size = 100
# Predictor variable
X1 = np.random.randn(size)
X2 = np.random.randn(size) * 0.2
# Simulate outcome variable
Y... |
248 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Kittens
Modeling and Simulation in Python
Copyright 2021 Allen Downey
License
Step1: If you have used the Internet, you have probably seen videos of kittens unrolling toilet paper.
And you ... | Python Code:
# download modsim.py if necessary
from os.path import basename, exists
def download(url):
filename = basename(url)
if not exists(filename):
from urllib.request import urlretrieve
local, _ = urlretrieve(url, filename)
print('Downloaded ' + local)
download('https://github... |
249 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
阅读笔记
作者:方跃文
Email
Step1: 基础知识
语言语义
python语言的设计特点是重视可读性、简洁性和明确性。
缩进,而不是大括号
python是通过空白符(制表符或者空格)来阻止代码的,不像R、C++等用的是大括号。该书原作者建议使用4空格作为缩进量。
万物皆对象
python语言的一个重要特点就是其对象模型的一致性。任何数值、字符串等都待在自己的“盒... | Python Code:
%run appendix-A/simple01.py
Explanation: 阅读笔记
作者:方跃文
Email: fyuewen@gmail.com
时间:始于2017年9月12日, 结束写作于
附录 A
附录A在原书最后,不过我自己为了复习python的一些命令,所以特意将这一部分提前到此。
python 解释器
python解释器通过“一次执行一条语句”的方式运行程序。多加利用Ipython。
通过使用 %run 命令,IPython 会在同个进程中执行指定文件中的代码。例如我在当年目录的下级目录appendix-A中创建了一个simple01.py的程序,它的内容是
```
a = ... |
250 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
$$V(X) = -w (X) + \frac{w L}{2}$$
Where
Step1: $$\Delta(x) = x^{3} \left(- \frac{L w}{12 E I} - \frac{w x_{0}}{6 E I}\right) + x^{2} \left(\frac{L w x_{0}}{4 E I} + \frac{w x_{0}^{2}}{4 E I... | Python Code:
from sympy import symbols, collect, expand, latex, simplify
D, x, x_0, E, I, w, y_0, L, y, t = symbols('Delta x x_0 E I w y_0 L y t')
from sympy import init_printing
init_printing(use_unicode=True)
D = w/(2*E*I)*((x-x_0)**4/12-L*(x-x_0)**3/6+L**3/12*(x-x_0)+2*y_0*E*I/w)
D
E = expand(D)
E
F = collect(E,x)
... |
251 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Numpy
for some reason, python is pretty slow at matrix math, so numpy was invented to fix it up. Matrix math and vectors is the backbone of neural nets and much else, so learning numpy is im... | Python Code:
import numpy as np
# the below line outputs all variables, not just the last one
from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"
Explanation: Numpy
for some reason, python is pretty slow at matrix math, so numpy was invented to fix it up. Matrix ma... |
252 | Given the following text description, write Python code to implement the functionality described.
Description:
Check if three straight lines are concurrent or not
Return true if three line are concurrent , else false . ; Driven Program
| Python Code:
def checkConcurrent(a1 , b1 , c1 , a2 , b2 , c2 , a3 , b3 , c3 ) :
return(a3 *(b1 * c2 - b2 * c1 ) + b3 *(c1 * a2 - c2 * a1 ) + c3 *(a1 * b2 - a2 * b1 ) == 0 )
a1 = 2
b1 = - 3
c1 = 5
a2 = 3
b2 = 4
c2 = - 7
a3 = 9
b3 = - 5
c3 = 8
if(checkConcurrent(a1 , b1 , c1 , a2 , b2 , c2 , a3 ,... |
253 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
pyOpenCGA basic alignment and coverage usage
[NOTE] The server methods used by pyopencga client are defined in the following swagger URL
Step1: Setting credentials for LogIn
Credentials
Pl... | Python Code:
# Initialize PYTHONPATH for pyopencga
import sys
import os
from pprint import pprint
cwd = os.getcwd()
print("current_dir: ...."+cwd[-10:])
base_modules_dir = os.path.dirname(cwd)
print("base_modules_dir: ...."+base_modules_dir[-10:])
sys.path.append(base_modules_dir)
from pyopencga.opencga_config import C... |
254 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Intermediate Topics in Python
Author
Step1: The eagle-eyed amongst you may notice the quotes around each number - but we'll address that in a bit.
Methods and Attributes
Step2: Our txt fil... | Python Code:
# let's make sure of our working directory
import os
os.chdir('/Users/Ahmed/Desktop')
with open('scores.txt', 'r') as file:
scores = file.read().split(',')
print(scores)
Explanation: Intermediate Topics in Python
Author: Ahmed Hasan
Made for U of T Coders, to be delivered on 05/04/2017
Contents
Read... |
255 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Atmoschem
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', 'ncc', 'noresm2-lmec', 'atmoschem')
Explanation: ES-DOC CMIP6 Model Properties - Atmoschem
MIP Era: CMIP6
Institute: NCC
Source ID: NORESM2-LMEC
Topic: Atmoschem
Sub-Topics: Transport,... |
256 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Find frequencies that make only $(\hat{a}^2\hat{b}^2+\hat{a}\hat{b}\hat{d}^2+\hat{d}^4)\hat{c}^\dagger +h.c.$ resonant in the 5th order expansion of $\sin(\hat{a}+\hat{b}+\hat{c}+\hat{d}+h.c... | Python Code:
import hamnonlineng as hnle
Explanation: Find frequencies that make only $(\hat{a}^2\hat{b}^2+\hat{a}\hat{b}\hat{d}^2+\hat{d}^4)\hat{c}^\dagger +h.c.$ resonant in the 5th order expansion of $\sin(\hat{a}+\hat{b}+\hat{c}+\hat{d}+h.c.)$
Import the "Hamiltonian-through-Nonlinearities Engineering" module (it c... |
257 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
First, import relevant modules and configure matplotlib to generate plots inline. The submodule scipy.integrate contains a number of routines to compute integrals numerically.
Step1: Quadra... | Python Code:
import numpy as np
import matplotlib.pylab as mpl
%matplotlib inline
Explanation: First, import relevant modules and configure matplotlib to generate plots inline. The submodule scipy.integrate contains a number of routines to compute integrals numerically.
End of explanation
fun = lambda x: np.cos(np.exp(... |
258 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Excercises Electric Machinery Fundamentals
Chapter 4
Problem 4-7
Step1: Description
A 100-MVA, 14.4-kV, 0.8-PF-lagging, 50-Hz, two-pole, Y-connected synchronous generator has a per-unit syn... | Python Code:
%pylab notebook
%precision 1
Explanation: Excercises Electric Machinery Fundamentals
Chapter 4
Problem 4-7
End of explanation
Vl = 14.4e3 # [V]
S = 100e6 # [VA]
ra = 0.011 # [pu]
xs = 1.1 # [pu]
PF = 0.8
p = 2
fse = 50 # [Hz]
Explanation: Description
A 100-MVA, 14.4-kV, 0.8-PF-lagging, 50-Hz, ... |
259 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Conv2D
[convolutional.Conv2D.0] 4 3x3 filters on 5x5x2 input, strides=(1,1), padding='valid', data_format='channels_last', dilation_rate=(1,1), activation='linear', use_bias=True
Step1: [co... | Python Code:
data_in_shape = (5, 5, 2)
conv = Conv2D(4, (3,3), strides=(1,1), padding='valid',
data_format='channels_last', dilation_rate=(1,1),
activation='linear', use_bias=True)
layer_0 = Input(shape=data_in_shape)
layer_1 = conv(layer_0)
model = Model(inputs=layer_0, outputs=layer_1)
# s... |
260 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Matplotlib Exercise 1
Imports
Step1: Line plot of sunspot data
Download the .txt data for the "Yearly mean total sunspot number [1700 - now]" from the SILSO website. Upload the file to the ... | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
Explanation: Matplotlib Exercise 1
Imports
End of explanation
import os
assert os.path.isfile('yearssn.dat')
Explanation: Line plot of sunspot data
Download the .txt data for the "Yearly mean total sunspot number [1700 - now]" from the S... |
261 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Problem Set 01
1. COUNTING VOWELS
Step1: 2. COUNTING BOBS | Python Code:
s= 'wordsmith'
vowels = {'a','e','i','o','u'}
count = 0
for char in s:
if char in vowels:
count+=1
print "Number of vowels: " + str(count)
Explanation: Problem Set 01
1. COUNTING VOWELS
End of explanation
s = 'azcbobobegghakl'
pattern = 'bob'
count =0
for position in range(0,len(s)):
if s[p... |
262 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Use of the wflow OpenStreams framework API to connect a reservoir model
http
Step1: Set model run-time parameters
Set the
Step2: Here we make a pit in the middle of the main river. This wi... | Python Code:
# First import the model. Here we use the HBV version
from wflow.wflow_sbm import *
import IPython
from IPython.display import display, clear_output
%pylab inline
#clear_output = IPython.core.display.clear_output
# Here we define a simple fictious reservoir
reservoirstorage = 15000
def simplereservoir(inpu... |
263 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Feature
Step1: Config
Automatically discover the paths to various data folders and compose the project structure.
Step2: Identifier for storing these features on disk and referring to them... | Python Code:
from pygoose import *
Explanation: Feature: Simple Summary Statistics
Extract rudimentary statistical features, such as question lengths (in words and characters), differences and ratios of these lengths.
Imports
This utility package imports numpy, pandas, matplotlib and a helper kg module into the root na... |
264 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Deep Learning
Assignment 2
Previously in 1_notmnist.ipynb, we created a pickle with formatted datasets for training, development and testing on the notMNIST dataset.
The goal of this assignm... | Python Code:
# These are all the modules we'll be using later. Make sure you can import them
# before proceeding further.
from __future__ import print_function
import numpy as np
import tensorflow as tf
from six.moves import cPickle as pickle
from six.moves import range
Explanation: Deep Learning
Assignment 2
Previousl... |
265 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Evaluate mock community classification accuracy for nb-extra
The purpose of this notebook is to evaluate taxonomic classification accuracy of mock communities using different classification ... | Python Code:
%matplotlib inline
from os.path import join, exists, expandvars
import pandas as pd
from IPython.display import display, Markdown
import seaborn.xkcd_rgb as colors
from tax_credit.plotting_functions import (pointplot_from_data_frame,
boxplot_from_data_frame,
... |
266 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Ferrofluid - Part 3
Table of Contents
Susceptibility with fluctuation formulas
Derivation of the fluctuation formula
Simulation
Magnetization curve of a 3D system
Remark
Step1: Now we set u... | Python Code:
import espressomd
import espressomd.magnetostatics
espressomd.assert_features(['DIPOLES', 'DP3M', 'LENNARD_JONES'])
%matplotlib inline
import matplotlib.pyplot as plt
plt.rcParams.update({'font.size': 18})
import numpy as np
import tqdm
Explanation: Ferrofluid - Part 3
Table of Contents
Susceptibility with... |
267 |
Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
Drop a specific row in pandas
| Python Code::
dataFrame = dataFrame.drop(row)
|
268 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
'lc' Datasets and Options
Setup
Let's first make sure we have the latest version of PHOEBE 2.4 installed (uncomment this line if running in an online notebook session such as colab).
Step1: ... | Python Code:
#!pip install -I "phoebe>=2.4,<2.5"
Explanation: 'lc' Datasets and Options
Setup
Let's first make sure we have the latest version of PHOEBE 2.4 installed (uncomment this line if running in an online notebook session such as colab).
End of explanation
import phoebe
from phoebe import u # units
logger = phoe... |
269 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
基于FM-index的序列比对算法
1. 什么是序列比对?
为确定两个或多个序列之间的相似性以至于同源性,而将它们按照一定的规律排列。
用个例子来看一下吧!
先看看数据是个啥。
读取Reads.fq文件,这是一个fastq格式的文件,存放了2条Read。read1, read2表示两条read的名字,名字下面是两条read对应的序列信息。
Step1: 现在对这两个Read比... | Python Code:
from Bio import SeqIO, pairwise2
handle = open("../data/Reads.fa", "r")
records = list(SeqIO.parse(handle, "fasta"))
handle.close()
for record in records:
print record.id
print record.seq
Explanation: 基于FM-index的序列比对算法
1. 什么是序列比对?
为确定两个或多个序列之间的相似性以至于同源性,而将它们按照一定的规律排列。
用个例子来看一下吧!
先看看数据是个啥。
读取Reads.f... |
270 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Clustering
Step1: Fit a simple KMeans cluster model in iris dataset
Step2: Q
Step3: Q
Step4: Always interpret results with caution!
Clustering as Data Compression
Step5: Overview of clu... | Python Code:
import numpy as np
from sklearn.datasets import load_iris, load_digits
from sklearn.metrics import f1_score
from sklearn.cluster import KMeans
from sklearn.decomposition import PCA
import matplotlib.pyplot as plt
plt.style.use('ggplot')
%matplotlib inline
iris = load_iris()
X = iris.data
y = iris.target
pr... |
271 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Operations on word vectors
Welcome to your first assignment of this week!
Because word embeddings are very computionally expensive to train, most ML practitioners will load a pre-trained se... | Python Code:
import numpy as np
from w2v_utils import *
Explanation: Operations on word vectors
Welcome to your first assignment of this week!
Because word embeddings are very computionally expensive to train, most ML practitioners will load a pre-trained set of embeddings.
After this assignment you will be able to:
... |
272 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Interactive Image Processing with Numba and Bokeh
This demo shows off how interactive image processing can be done in the notebook, using Numba for numerics, Bokeh for plotting, and Ipython ... | Python Code:
from timeit import default_timer as timer
from bokeh.plotting import figure, show, output_notebook
from bokeh.models import GlyphRenderer, LinearColorMapper
from bokeh.io import push_notebook
from numba import jit, njit
from ipywidgets import interact
import numpy as np
import scipy.misc
output_notebook()
... |
273 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Exporting a BigQuery ML Model for Online Prediction
Learning Objectives
Train and deploy a logistic regression model - also applies to DNN classifier, DNN regressor, k-means, linear regressi... | Python Code:
!sudo chown -R jupyter:jupyter /home/jupyter/training-data-analyst
Explanation: Exporting a BigQuery ML Model for Online Prediction
Learning Objectives
Train and deploy a logistic regression model - also applies to DNN classifier, DNN regressor, k-means, linear regression, and matrix factorization models.
... |
274 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2021 Google LLC
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 Licens... | Python Code:
#@title Install arviz and update pymc3
!pip install arviz -q
!pip install pymc3 -U -q
Explanation: Copyright 2021 Google LLC
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.a... |
275 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<h2>Analisi comparativa dei metodi di dosaggio degli anticorpi anti recettore del TSH</h2>
<h3>Metodo Routine
Step1: <h4>Importazione del file con i dati </h4>
Step2: Varibili d'ambiete in... | Python Code:
%matplotlib inline
#importo le librerie
import pandas as pd
import os
from __future__ import print_function,division
import numpy as np
import seaborn as sns
os.environ["NLS_LANG"] = "ITALIAN_ITALY.UTF8"
Explanation: <h2>Analisi comparativa dei metodi di dosaggio degli anticorpi anti recettore del TSH</h2>... |
276 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
FloPy
Simple water-table solution with recharge
This problem is an unconfined system with a uniform recharge rate, a horizontal bottom, and flow between constant-head boundaries in column 1 ... | Python Code:
%matplotlib inline
from __future__ import print_function
import sys
import os
import platform
import numpy as np
import matplotlib.pyplot as plt
import flopy
import flopy.utils as fputl
#Set name of MODFLOW exe
# assumes executable is in users path statement
exe_name = 'mfnwt'
if platform.system() == 'Win... |
277 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Binomial and negative binomial distributions
Today's post is prompted by this question from Reddit
Step1: Solution
There are two ways to solve this problem. One is to relate the desired di... | Python Code:
from __future__ import print_function, division
import thinkplot
from thinkstats2 import Pmf, Cdf
from scipy import stats
from scipy import special
%matplotlib inline
Explanation: Binomial and negative binomial distributions
Today's post is prompted by this question from Reddit:
How do I calculate the dist... |
278 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Image Classification
In this project, we'll classify images from the CIFAR-10 dataset. The dataset consists of airplanes, dogs, cats, and other objects. We'll preprocess the images, then tr... | Python Code:
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_cifar10_location = '/input/cifar-10/python.tar.gz'
if isfile(fl... |
279 | 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
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 dta['quarter']
print(sm.datasets.macr... |
280 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Analýza časových řad 1 - manipulace s daty v Pandas
Popis základních funkcí pomocí pro analýzu dat v Pandas.
Info o verzi a notebooku
Step1: Informace o použitých python modulech
Step2: Se... | Python Code:
import datetime
MY_VERSION = 1,0
print('Verze notebooku:', '.'.join(map(str, MY_VERSION)))
print('Poslední aktualizace:', datetime.datetime.now())
Explanation: Analýza časových řad 1 - manipulace s daty v Pandas
Popis základních funkcí pomocí pro analýzu dat v Pandas.
Info o verzi a notebooku
End of explan... |
281 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Neural Networks
This is an jupyter notebook.
Lectures about Python, useful both for beginners and experts, can be found at http
Step1: Now we plot the two classes as a scatter plot!
Step2: ... | Python Code:
%matplotlib inline
import numpy as np
import scipy as sp
import matplotlib.pyplot as plt
# now we genrate the data
N = 30
x = np.zeros(N, dtype=np.float64)
y = np.zeros(N, dtype=np.float64)
for k in range(N):
x[k], y[k] = [np.random.uniform(-1,1) for i in range(2)]
a = np.random.uniform(-1,1)
b = ... |
282 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Reinforcement Learning (DQN) tutorial
http
Step2: Experience Replay
DQNは観測を蓄積しておいてあとでシャッフルしてサンプリングして使う
Transition - a named tuple representing a single transition in our environment
ReplayM... | Python Code:
import gym
import math
import random
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from collections import namedtuple
from itertools import count
from copy import deepcopy
from PIL import Image
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional ... |
283 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Intro into IPython notebooks
Step1: Fitting Lines to Data
We'll cover very basic line fitting, largely ignoring the subtleties of the statistics in favor of showing you how to perform simpl... | Python Code:
%pylab inline
from IPython.display import YouTubeVideo
YouTubeVideo("qb7FT68tcA8", width=600, height=400, theme="light", color="blue")
# You can ignore this, it's just for aesthetic purposes
matplotlib.rcParams['figure.figsize'] = (8,5)
rcParams['savefig.dpi'] = 100
Explanation: Intro into IPython notebook... |
284 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Model Building Part 2
Code for building the models
Author
Step1: Training and Testing Split
Step2: Text
Step3: Classification Models
Step4: Although tuning is not necessary for Naive Bay... | Python Code:
import os
import pandas as pd
import numpy as np
import scipy as sp
import seaborn as sns
import matplotlib.pyplot as plt
import json
from IPython.display import Image
from IPython.core.display import HTML
retval=os.chdir("..")
clean_data=pd.read_pickle('./clean_data/clean_data.pkl')
clean_data.head()
kept... |
285 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Regression with Random Forest
Random Forest is also a popular algorithm in machine learning, it is very flexible and based on the decision tree.
Generate data
Let's first generate a toy dat... | Python Code:
np.random.seed(0)
x = 10 * np.random.rand(100)
def model(x, sigma=0.3):
fast_oscillation = np.sin(5 * x)
slow_oscillation = np.sin(0.5 * x)
noise = sigma * np.random.rand(len(x))
return slow_oscillation + fast_oscillation + noise
plt.figure(figsize = (12,10))
y = model(x)
plt.errorbar(x, y,... |
286 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Guided Project 1
Learning Objectives
Step1: Step 1. Environment setup
skaffold tool setup
Step2: Modify the PATH environment variable so that skaffold is available
Step3: Environment vari... | Python Code:
import os
Explanation: Guided Project 1
Learning Objectives:
Learn how to generate a standard TFX template pipeline using tfx template
Learn how to modify and run a templated TFX pipeline
Note: This guided project is adapted from Create a TFX pipeline using templates).
End of explanation
PATH = %env PATH
... |
287 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Link Prediction
Definition of Link Prediction
Perform link prediction on dataset
Jaccard coefficient
Preferential Attachment
Step1: Link Prediction
The idea of link prediction was first pro... | Python Code:
import networkx as nx
import matplotlib.pyplot as plt # for plotting graphs
%matplotlib inline
GA = nx.read_gexf('../data/ga_graph.gexf')
Explanation: Link Prediction
Definition of Link Prediction
Perform link prediction on dataset
Jaccard coefficient
Preferential Attachment
End of explanation
preds_jc = n... |
288 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Window functions
Stingray now has a bunch of window functions that can be used for various applications in signal processing.
Windows available include
Step1: create_window function in stin... | Python Code:
from stingray.utils import create_window
from scipy.fftpack import fft, fftshift, fftfreq
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
Explanation: Window functions
Stingray now has a bunch of window functions that can be used for various applications in signal processing.
Windows ... |
289 | Given the following text description, write Python code to implement the functionality described.
Description:
Minimize the maximum difference of any pair by doubling odd elements and reducing even elements by half
Function to minimize the maximum difference between any pair of elements of the array by the given operat... | Python Code:
def minimumMaxDiff(nums ) :
s = { }
for i in range(len(nums ) ) :
if(nums[i ] % 2 == 0 ) :
s[nums[i ] ] = 1
else :
s[nums[i ] * 2 ] = 1
sr = list(s . keys() )
res = sr[- 1 ] - sr[0 ]
while(list(s . keys() )[- 1 ] % 2 == 0 ) :
r = list(s . keys() )
x = r[- 1 ]
del s[x ]
... |
290 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Minimal Example to Produce a Synthetic Light Curve
Setup
Let's first make sure we have the latest version of PHOEBE 2.4 installed (uncomment this line if running in an online notebook sessio... | Python Code:
#!pip install -I "phoebe>=2.4,<2.5"
Explanation: Minimal Example to Produce a Synthetic Light Curve
Setup
Let's first make sure we have the latest version of PHOEBE 2.4 installed (uncomment this line if running in an online notebook session such as colab).
End of explanation
import phoebe
from phoebe impor... |
291 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Rand 2011 Cooperation Study
This notebook outlines how to recreate the analysis of the Rand et al. 2011 study "Dynamic social networks promote cooperation in experiments with humans" Link to... | Python Code:
from bedrock.client.client import BedrockAPI
import requests
import pandas
import pprint
SERVER = "http://localhost:81/"
api = BedrockAPI(SERVER)
Explanation: Rand 2011 Cooperation Study
This notebook outlines how to recreate the analysis of the Rand et al. 2011 study "Dynamic social networks promote coope... |
292 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Practical Deep Learning for Coders, v3
Lesson3_imdb
IMDB影评数据
Step1: Preparing the data 准备数据
First let's download the dataset we are going to study. The dataset has been curated by Andrew Ma... | Python Code:
%reload_ext autoreload
%autoreload 2
%matplotlib inline
from fastai.text import *
Explanation: Practical Deep Learning for Coders, v3
Lesson3_imdb
IMDB影评数据
End of explanation
path = untar_data(URLs.IMDB_SAMPLE)
path.ls()
Explanation: Preparing the data 准备数据
First let's download the dataset we are going to ... |
293 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Import Packages, Load Data
Step1: Look at the data
Patterns differ from state to state
Step2: What do we learn?
Variation over provinces
If we ignore space
Step3: What do we learn?
Autoco... | Python Code:
import pandas as pd
import statsmodels.api as sm
import numpy as np
import scipy as sp
import matplotlib.pyplot as plt
%matplotlib inline
import datetime
import time
migration_df = pd.read_csv('migration_dums.csv')
migration_df.set_index(['date_stamp','Province'],inplace=True)
Explanation: Import Packages,... |
294 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Baysian Classification and Naive Bayes for genre classification using lyrics
In this notebook we look at the problem of classifying songs to three genres (rap, rock and country) based on a s... | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import pickle
import numpy as np
# load some lyrics bag of words data, binarize, separate matrix rows by genre
data = np.load('data/data.npz')
a = data['arr_0']
a[a > 0] = 1
labels = np.load('data/labels.npz')
labels = labels['arr_0']
dictionary = pickl... |
295 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Data exploration
Step1: age, education_num, hours_per_week, fnlwgt seem like good candidates as features. Not much information in capital_gain, capital_loss.
Some routine stuff
Convert obje... | Python Code:
def read_data(path):
return pd.read_csv(path,
index_col=False,
skipinitialspace=True,
names=['age', 'workclass', 'fnlwgt', 'education', 'education_num',
'marital_status', 'occupation', 'relationship', 'rac... |
296 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2019 The TensorFlow Authors.
Step1: Dogs vs Cats Image Classification With Image Augmentation
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href=... | 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... |
297 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Problem 1
Test whether the series is convergent or divergent
Step1: Let $a_n = \sum_{n=1}^{\infty} \frac{1}{n + 7^n}$.
Could $a_n$ be a Combination of Series (i.e. the sum of two series)? | Python Code:
import sympy as sp
from matplotlib import pyplot as plt
%matplotlib inline
# Customize figure size
plt.rcParams['figure.figsize'] = 25, 15
#plt.rcParams['lines.linewidth'] = 1
#plt.rcParams['lines.color'] = 'g'
plt.rcParams['font.family'] = 'monospace'
plt.rcParams['font.size'] = '16.0'
plt.rcParams['text.... |
298 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Jump_to opening comments and overview of lesson 10
Callbacks
Callbacks as GUI events
Jump_to lesson 10 video
Step1: From the ipywidget docs
Step2: NB
Step3: Lambdas and partials
Jump_to l... | Python Code:
import ipywidgets as widgets
def f(o): print('hi')
Explanation: Jump_to opening comments and overview of lesson 10
Callbacks
Callbacks as GUI events
Jump_to lesson 10 video
End of explanation
w = widgets.Button(description='Click me')
w
w.on_click(f)
Explanation: From the ipywidget docs:
the button widget ... |
299 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2021 The TensorFlow Authors.
Step1: Simple TFX Pipeline for Vertex Pipelines
<div class="devsite-table-wrapper"><table class="tfo-notebook-buttons" align="left">
<td><a target="_b... | 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... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.