Unnamed: 0 int64 0 16k | text_prompt stringlengths 110 62.1k | code_prompt stringlengths 37 152k |
|---|---|---|
15,300 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Normal distribution
Standard normal distribution takes a bell curve. It is also called as gaussian distribution. Values in nature are believed to take a normal distribution. The equation for... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
vals = np.random.standard_normal(100000)
len(vals)
fig, ax = plt.subplots(1,1)
hist_vals = ax.hist(vals, bins=200, color='red', density=True)
Explanation: Normal distribution
Standard normal distribution takes a bell curve. It is also ca... |
15,301 |
Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
how to create dummy variables for dataframe df1
| Python Code::
import pandas as pd
pd.get_dummies(df1.town)
|
15,302 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Centrality
This evaluates the Eigenvector Centrality and PageRank implemented in Python against C++-native EVZ and PageRank. The Python implementation uses SciPy (and thus ARPACK) to compute... | Python Code:
cd ../../
import networkit
import pandas as pd
import random as rd
G = networkit.graphio.readGraph("input/celegans_metabolic.graph", networkit.Format.METIS)
Explanation: Centrality
This evaluates the Eigenvector Centrality and PageRank implemented in Python against C++-native EVZ and PageRank. The Python i... |
15,303 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
As explained in the Composing Data and Containers tutorials, HoloViews allows you to build up hierarchical containers that express the natural relationships between your data items, in whate... | Python Code:
import numpy as np
import holoviews as hv
hv.notebook_extension()
%opts Layout [fig_size=125] Points [size_index=None] (s=50) Scatter3D [size_index=None]
%opts Bounds (linewidth=2 color='k') {+axiswise} Text (fontsize=16 color='k') Image (cmap='Reds')
Explanation: As explained in the Composing Data and Con... |
15,304 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Optically pumped magnetometer (OPM) data
In this dataset, electrical median nerve stimulation was delivered to the
left wrist of the subject. Somatosensory evoked fields were measured using
... | Python Code:
import os.path as op
import numpy as np
import mne
data_path = mne.datasets.opm.data_path()
subject = 'OPM_sample'
subjects_dir = op.join(data_path, 'subjects')
raw_fname = op.join(data_path, 'MEG', 'OPM', 'OPM_SEF_raw.fif')
bem_fname = op.join(subjects_dir, subject, 'bem',
subject + '-... |
15,305 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2021 The TensorFlow Authors.
Step1: <table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https
Step2: Train a tf.keras model for MNIST to be prun... | 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... |
15,306 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Chapter 7 - Sets
This chapter will introduce a different kind of container
Step1: Curly brackets surround sets, and commas separate the elements in the set
A set can be empty (use set() to ... | Python Code:
a_set = {1, 2, 3}
a_set
empty_set = set() # you have to use set() to create an empty set! (we will see why later)
print(empty_set)
Explanation: Chapter 7 - Sets
This chapter will introduce a different kind of container: sets. Sets are unordered lists with no duplicate entries. You might wonder why we need ... |
15,307 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Project Euler
Step1: Now write a set of assert tests for your number_to_words function that verifies that it is working as expected.
Step2: Now define a count_letters(n) that returns the n... | Python Code:
def ones(one,count):
if one == 1 or one == 2 or one == 6:
count += 3
if one == 4 or one == 5 or one == 9:
count += 4
if one == 3 or one == 7 or one == 8:
count += 5
return count
def teens(teen,count):
if teen == 10:
count += 3
if teen == ... |
15,308 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Decision Trees in Practice
In this assignment we will explore various techniques for preventing overfitting in decision trees. We will extend the implementation of the binary decision trees ... | Python Code:
import graphlab
Explanation: Decision Trees in Practice
In this assignment we will explore various techniques for preventing overfitting in decision trees. We will extend the implementation of the binary decision trees that we implemented in the previous assignment. You will have to use your solutions from... |
15,309 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Objektorientiere Programmierung
Step1: Wie wir sehen, ist die Eigenschaft _val durchaus von außerhalb verfügbar. Allerdings signalisiert das Underline, dass vom Programmierer der Klasse nic... | Python Code:
class MyClass:
def __init__(self, val):
self.set_val(val)
def get_val(self):
return self._val
def set_val(self, val):
if val > 0:
self._val = val
else:
raise ValueError('val must be greater 0')
myclass = MyC... |
15,310 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Data Analysis
This is the main notebook performing all feature engineering, model selection, training, evaluation etc.
The different steps are
Step1: Step2
load the payloads into memory
Ste... | Python Code:
%matplotlib inline
import pandas as pd
import numpy as np
import pickle
import matplotlib.pyplot as plt
import seaborn
import string
from IPython.display import display
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.model... |
15,311 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Landice
MIP Era
Step1: Document Authors
Set document authors
Step2: Document Contributors
Specify document contributors
Step3: Document Publication
Specify... | Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'ncc', 'noresm2-lme', 'landice')
Explanation: ES-DOC CMIP6 Model Properties - Landice
MIP Era: CMIP6
Institute: NCC
Source ID: NORESM2-LME
Topic: Landice
Sub-Topics: Glaciers, Ice.
Pr... |
15,312 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introduction
This blog post is a three-part series. See part 1 for retrieving the dataset and part 2 for the calculation of similarity between test cases.
In the previous blog post, we've se... | Python Code:
import pandas as pd
distance_df = pd.read_excel(
"datasets/test_distance_matrix.xlsx",
index_col=[0,1],
header=[0,1])
# show only subset of data
distance_df.iloc[:5,:2]
Explanation: Introduction
This blog post is a three-part series. See part 1 for retrieving the dataset and part 2 for the calc... |
15,313 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Authorization & securitySchemes
OAS allows to specify authorization policies in the spec,
under components.securitySchemes.
Between supported security schemes we have
Step3: Add user... | Python Code:
# Test here the my_auth implementation.
def my_auth(username, password,required_scopes=None):
An dummy authentication function.
:params: username, the username
:params: password, the password
:params: scopes, the scope
:returns: `{"sub": username, "scope": ""}` on success,
... |
15,314 | 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: Train embeddings on TPU using Autoencoder
Overview
This colab explores how ... | 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... |
15,315 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
BI kurzus
Bővítőcsomagok importálása
Step1: Romániai lakosság letöltése INSSE-ról
Step2: Wikipédia táblázatok letöltése
Step3: Ha html5llib not found hibaüzenetet kapunk, akkor egy konzol... | Python Code:
import pandas as pd
import html5lib
import matplotlib.pyplot as plt
%matplotlib inline
Explanation: BI kurzus
Bővítőcsomagok importálása:
End of explanation
#https://www.csaladen.es/present/sapientia1/exportPivot_POP105A.csv
csv_path='exportPivot_POP105A.csv' #SAJAT HELY CSV FILE
df=pd.read_csv(csv_path)
... |
15,316 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<small><i>This notebook is based on the 2016 AAS Python Workshop tutorial on tables, available on GitHub, though it has been modified. Some of the pandas stuff was borrowed from a notebook p... | Python Code:
from astropy.table import Table
from numpy import *
import matplotlib
matplotlib.use('nbagg') # required for interactive plotting
import matplotlib.pyplot as plt
%matplotlib inline
Explanation: <small><i>This notebook is based on the 2016 AAS Python Workshop tutorial on tables, available on GitHub, thoug... |
15,317 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Extract facility generation and fuel use data
This notebook creates dataframes with monthly facility generation and fuel use data, merges them, and exports the results. The code assumes that... | Python Code:
import json
import pandas as pd
import os
from os.path import join
import numpy as np
from joblib import Parallel, delayed
import sys
cwd = os.getcwd()
data_path = join(cwd, '..', 'Data storage')
Explanation: Extract facility generation and fuel use data
This notebook creates dataframes with monthly facili... |
15,318 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Resultant
If $p$ and $q$ are two polynomials over a commutative ring with identity which can be factored into linear factors,
$$p(x)= a_0 (x - r_1) (x- r_2) \dots (x - r_m) $$
$$q(x)=b_0 (x ... | Python Code:
x = sym.symbols('x')
Explanation: Resultant
If $p$ and $q$ are two polynomials over a commutative ring with identity which can be factored into linear factors,
$$p(x)= a_0 (x - r_1) (x- r_2) \dots (x - r_m) $$
$$q(x)=b_0 (x - s_1)(x - s_2) \dots (x - s_n)$$
then the resultant $R(p,q)$ of $p$ and $q$ is def... |
15,319 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Measures of Central Tendency
By Evgenia "Jenny" Nitishinskaya, Maxwell Margenot, and Delaney Mackenzie.
Part of the Quantopian Lecture Series
Step1: We can also define a <i>weighted</i> ari... | Python Code:
# Two useful statistical libraries
import scipy.stats as stats
import numpy as np
# We'll use these two data sets as examples
x1 = [1, 2, 2, 3, 4, 5, 5, 7]
x2 = x1 + [100]
print 'Mean of x1:', sum(x1), '/', len(x1), '=', np.mean(x1)
print 'Mean of x2:', sum(x2), '/', len(x2), '=', np.mean(x2)
Explanation: ... |
15,320 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Getting the data
Please look at the information in the get_data.ipynb notebook. You have to end up with swift.dkrz.de folder located somwere in your system. All data used in this examples ar... | Python Code:
import sys
sys.path.append("../")
import pyfesom as pf
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap
from matplotlib.colors import LinearSegmentedColormap
import numpy as np
# %matplotlib notebook
%matplotlib inline
from matplotlib import cm
from netCDF4 import Dataset, MFDataset... |
15,321 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
SS82
Talking to Bruno about his project on stacking Swift observations and my project on Stripe82 SED we started to think about a collaboration to create a set of deep observations with Swif... | Python Code:
from IPython.display import HTML
HTML('''<script>
code_show=true;
function code_toggle() {
if (code_show){
$('div.input').hide();
} else {
$('div.input').show();
}
code_show = !code_show
}
$( document ).ready(code_toggle);
</script>
<form action="javascript:code_toggle()"><input type="submit" value... |
15,322 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Title
Step1: Create Matrix
Step2: Find Maximum Element
Step3: Find Minimum Element
Step4: Find Maximum Element By Column
Step5: Find Maximum Element By Row | Python Code:
# Load library
import numpy as np
Explanation: Title: Find The Maximum And Minimum
Slug: find_maximum_and_minimum
Summary: How to find the maximum, minimum, and average of the elements in an array.
Date: 2017-09-03 12:00
Category: Machine Learning
Tags: Vectors Matrices Arrays
Authors: Chris Albon
Prel... |
15,323 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Exercises
1. Logistic regression
The simple network we created is similar to a logistic regression model. Verify that the accuracy is close to that of sklearn.linear_model.LogisticRegression... | Python Code:
# Uncomment and execute this cell for an example solution
load spoilers/logreg.py
Explanation: Exercises
1. Logistic regression
The simple network we created is similar to a logistic regression model. Verify that the accuracy is close to that of sklearn.linear_model.LogisticRegression.
End of explanation
#... |
15,324 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
회귀 분석용 가상 데이터 생성 방법
Scikit-learn 의 datasets 서브 패키지에는 회귀 분석 시험용 가상 데이터를 생성하는 명령어인 make_regression() 이 있다.
http
Step1: 위 선형 모형은 다음과 같다.
$$
y = 100 + 79.1725 x
$$
noise 인수를 증가시키면 $\text{Var}... | Python Code:
from sklearn.datasets import make_regression
X, y, c = make_regression(n_samples=10, n_features=1, bias=0, noise=0, coef=True, random_state=0)
print("X\n", X)
print("y\n", y)
print("c\n", c)
plt.scatter(X, y, s=100)
plt.show()
Explanation: 회귀 분석용 가상 데이터 생성 방법
Scikit-learn 의 datasets 서브 패키지에는 회귀 분석 시험용 가상 데... |
15,325 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
PyBroMo - 2. Generate smFRET data, including mixtures
<small><i>
This notebook is part of <a href="http
Step1: Create smFRET data-files
Create a file for a single FRET efficiency
In this se... | Python Code:
%matplotlib inline
from pathlib import Path
import numpy as np
import tables
import matplotlib.pyplot as plt
import seaborn as sns
import pybromo as pbm
print('Numpy version:', np.__version__)
print('PyTables version:', tables.__version__)
print('PyBroMo version:', pbm.__version__)
Explanation: PyBroMo - 2... |
15,326 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Title
Step1: Create some text
Step2: Apply regex | Python Code:
# Load regex package
import re
Explanation: Title: Match Any Character
Slug: match_any_character
Summary: Match Any Character
Date: 2016-05-01 12:00
Category: Regex
Tags: Basics
Authors: Chris Albon
Based on: Regular Expressions Cookbook
Preliminaries
End of explanation
# Create a variable containing a t... |
15,327 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<div style='background-image
Step1: Calling the original FORTRAN code
Step2: Visualization of the Green's function
Step3: Convolution
Let $S(t)$ be a general source time function, then th... | Python Code:
# Import all necessary libraries, this is a configuration step for the exercise.
# Please run it before the simulation code!
import numpy as np
import matplotlib.pyplot as plt
import os
from ricker import ricker
# Show the plots in the Notebook.
plt.switch_backend("nbagg")
# Compile the source code (needs ... |
15,328 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Write a function
Step1: n = 10
Step2: n=100
Step3: converting binary to decimal
Step4: testing more binary to decimal conversions | Python Code:
n = 1
print n.bit_length()
a = n.bit_length()
print bin(n)
print '%0*d' % (a, int(bin(n)[2:]))
print '{0:08b}'.format(n)
Explanation: Write a function:
def solution(N)
that, given a positive integer N, returns the length of its longest binary gap. The function should return 0 if N doesn't contain a binary ... |
15,329 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<h1> Bour Equation </h1>
Bour equation (a.k.a sine-Gordon) takes the canonical form
\begin{equation}
u_{xt}-\frac{1}{\rho^2}\sin(u)=0,
\end{equation}
where $-1/\rho^2$ equals the Gaussian cu... | Python Code:
# ----------------------------------------/
%matplotlib inline
# ----------------------------------------/
import math
import numpy as np
import matplotlib.pyplot as plt
import scipy.sparse.linalg as la
from pylab import *
from scipy import *
from ipywidgets import *
from scipy.sparse import spdiags
from n... |
15,330 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Huntsman Telephoto Array specifications
Introduction
The Huntsman Telephoto Array is an astronomical imaging system consisting of 1-10 imaging units attached to a telescope mount. The conce... | Python Code:
import math
from astropy import units as u
pixel_pitch = 5.4 * u.micron / u.pixel # STF-8300M pixel pitch
focal_length = 400 * u.millimeter # Canon EF 400 mm f/2.8L IS II USM focal length
resolution = (3326, 2504) * u.pixel # STF-8300M resolution in pixels, (x, y)
sampling = (pixel_pitch / focal_length).... |
15,331 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Weighted Generalized Linear Models
Step1: Weighted GLM
Step2: Load the data into a pandas dataframe.
Step3: The dependent (endogenous) variable is affairs
Step4: In the following we will... | Python Code:
import numpy as np
import pandas as pd
import statsmodels.formula.api as smf
import statsmodels.api as sm
Explanation: Weighted Generalized Linear Models
End of explanation
print(sm.datasets.fair.NOTE)
Explanation: Weighted GLM: Poisson response data
Load data
In this example, we'll use the affair dataset ... |
15,332 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Python 知之深浅
Python 中的对象分为两种:可变对象(mutable)和不可变对象(immutable)。不可变对象包括int,float,long,str,tuple等,可变对象包括list,set,dict等。在 Python 中,赋值(assignment, =)的过程仅仅是:
创建一个(某个值的)对象;
将变量名指向(引用)这个对象。
这就像 C 语言中指针... | Python Code:
lst = [1, 2, 3]
s = lst
s.pop()
print(lst)
d = {'a': 0}
e = d
e['b'] = 1
print(d)
Explanation: Python 知之深浅
Python 中的对象分为两种:可变对象(mutable)和不可变对象(immutable)。不可变对象包括int,float,long,str,tuple等,可变对象包括list,set,dict等。在 Python 中,赋值(assignment, =)的过程仅仅是:
创建一个(某个值的)对象;
将变量名指向(引用)这个对象。
这就像 C 语言中指针的概念,只不过更灵活地是 Python 中的... |
15,333 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2020 The TensorFlow Authors.
Step1: TF Lattice Canned Estimator
<table class="tfo-notebook-buttons" align="left">
<td><a target="_blank" href="https
Step2: 필수 패키지 가져오기
Step3: ... | 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... |
15,334 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
The Combinatorial Explosion
"During the past century, science has developed a limited capability to design materials, but we are still too dependent on serendipity" - Eberhart and Clougherty... | Python Code:
from math import factorial as factorial
grid_points = 1000.0
atoms = 30.0
elements = 50.0
##########
# A. Show that assigning each of the 30 atoms as one of 50 elements is ~ 9e50 (permutations)
element_assignment = 0
print(f'Number of possible element assignments is: {element_assignment}')
# B. Show that t... |
15,335 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Poppy Web Service
Demarrage d'un web service poppy avec HTTPRobotServer
Step5: http
Step6: Lancement du serveur
Step7: Le script start_servers.py crée une instance de poppy, puis de lanc... | Python Code:
#imports and initilaize virutal poppy using vrep
from pypot.vrep import from_vrep
from poppy.creatures import PoppyHumanoid
robot = PoppyHumanoid(simulator='vrep')
#import and initialize physical poppy
from poppy.creatures import PoppyHumanoid
robot = PoppyHumanoid()
from pypot.server import HTTPRobotServe... |
15,336 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Benchmark NumPyro in large dataset
This notebook uses numpyro and replicates experiments in references [1] which evaluates the performance of NUTS on various frameworks. The benchmark is run... | Python Code:
!pip install -q numpyro@git+https://github.com/pyro-ppl/numpyro
import time
import numpy as np
import jax.numpy as jnp
from jax import random
import numpyro
import numpyro.distributions as dist
from numpyro.examples.datasets import COVTYPE, load_dataset
from numpyro.infer import HMC, MCMC, NUTS
assert nump... |
15,337 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
The Epochs data structure
Step1:
Step2: As we saw in the tut-events-vs-annotations tutorial, we can extract an
events array from
Step3: <div class="alert alert-info"><h4>Note</h4><p>We ... | Python Code:
import os
import mne
Explanation: The Epochs data structure: discontinuous data
This tutorial covers the basics of creating and working with :term:epoched
<epochs> data. It introduces the :class:~mne.Epochs data structure in
detail, including how to load, query, subselect, export, and plot data from ... |
15,338 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Set up rotation matrices representing a 3-1-3 $(\psi,\theta,\phi)$ Euler angle set.
Step1: $\tilde{\omega} = {}^\mathcal{B}C^{\mathcal{I}} {}^\mathcal{B}{\dot{C}}^{\mathcal{I}}$
Step2: $\... | Python Code:
aCi = rotMat(3,psi)
cCa = rotMat(1,th)
bCc = rotMat(3,ph)
aCi,cCa,bCc
bCi = bCc*cCa*aCi; bCi #3-1-3 rotation
bCi_dot = difftotalmat(bCi,t,{th:thd,psi:psid,ph:phd});
bCi_dot
Explanation: Set up rotation matrices representing a 3-1-3 $(\psi,\theta,\phi)$ Euler angle set.
End of explanation
omega_tilde = bCi*... |
15,339 | 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', 'messy-consortium', 'sandbox-2', 'atmoschem')
Explanation: ES-DOC CMIP6 Model Properties - Atmoschem
MIP Era: CMIP6
Institute: MESSY-CONSORTIUM
Source ID: SANDBOX-2
Topic: Atmoschem
Su... |
15,340 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Your First CAS Connection from Python
Let's start with a gentle introduction to the Python CAS client by doing some basic operations like creating a CAS connection and running a simple actio... | Python Code:
# Import the SWAT package which contains the CAS interface
import swat
# Create a CAS session on mycas1 port 12345
conn = swat.CAS('mycas1', 12345, 'username', 'password')
Explanation: Your First CAS Connection from Python
Let's start with a gentle introduction to the Python CAS client by doing some basic... |
15,341 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Azure Fune tuning example
In this example we'll try to go over all operations that can be done using the Azure endpoints and their differences with the openAi endpoints (if any).<br>
This ex... | Python Code:
import openai
from openai import cli
Explanation: Azure Fune tuning example
In this example we'll try to go over all operations that can be done using the Azure endpoints and their differences with the openAi endpoints (if any).<br>
This example focuses on finetuning but touches on the majority of operatio... |
15,342 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Parse a description into components
This notebook requires at least version 0.8.8.
Step1: We have some text
Step2: To read this with striplog, we need to define a Lexicon. This is a dictio... | Python Code:
import striplog
striplog.__version__
Explanation: Parse a description into components
This notebook requires at least version 0.8.8.
End of explanation
text = "wet silty fine sand with tr clay"
Explanation: We have some text:
End of explanation
from striplog import Lexicon
lex_dict = {
'lithology': ['s... |
15,343 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Repsly trial data
Step1: Let's see what the data looks like
Step2: As you can see above, each input vector X has 1+15*16=241 values, most of which are zeros. The first one is the trial sta... | Python Code:
from repsly_data import RepslyData
repsly_data = RepslyData()
print('Reading data (this might take a minute or so)...', end='')
repsly_data.read_data('data/trial_users_analysis.csv', mode='FC')
print('done.')
Explanation: Repsly trial data
End of explanation
read_batch = repsly_data.read_batch(batch_size=2... |
15,344 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Ordinary Differential Equations Exercise 3
Imports
Step1: Damped, driven nonlinear pendulum
The equations of motion for a simple pendulum of mass $m$, length $l$ are
Step4: Write a functio... | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
from scipy.integrate import odeint
from IPython.html.widgets import interact, fixed
Explanation: Ordinary Differential Equations Exercise 3
Imports
End of explanation
g = 9.81 # m/s^2
l = 0.5 # length of pendul... |
15,345 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Filtrage de Kalman
Loi conditionnelle gaussienne
Soit $Z=\left(\begin{matrix}X \ Y\end{matrix}\right)$ un vecteur aléatoire gaussien à valeurs dans $\mathbb R^{n+d}$ de moyenne $\bar Z$ et d... | Python Code:
%matplotlib inline
from ipywidgets import interact, fixed
import numpy as np
import matplotlib.pyplot as plt
import scipy.stats as stats
barZ = np.array([[1],[3]])
QZ = np.array([[3,1],[1,1]])
a = barZ[0]
b = QZ[0,0]
xx = np.linspace(-6, 10, 100)
R = QZ[0,0]-QZ[0,1]*QZ[0,1]/QZ[1,1]
def pltbayesgauss(obs):
... |
15,346 | 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 ... |
15,347 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Spatiotemporal permutation F-test on full sensor data
Tests for differential evoked responses in at least
one condition using a permutation clustering test.
The FieldTrip neighbor templates ... | Python Code:
# Authors: Denis Engemann <denis.engemann@gmail.com>
# Jona Sassenhagen <jona.sassenhagen@gmail.com>
#
# License: BSD (3-clause)
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
from mne.viz import plot_topomap
import mne
from mne.stats imp... |
15,348 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Feature extractor setup
This line constructs a "feature extractor" that uses Wikipedia's API to solve dependencies.
Step1: Using the extractor to extract features
The following line demonst... | Python Code:
extractor = APIExtractor(api.Session("https://en.wikipedia.org/w/api.php"))
Explanation: Feature extractor setup
This line constructs a "feature extractor" that uses Wikipedia's API to solve dependencies.
End of explanation
list(extractor.extract(123456789, [diff.chars_added]))
Explanation: Using the extra... |
15,349 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
W8 Lab Assignment
Step1: Ratio and logarithm
If you use linear scale to visualize ratios, it can be very misleading.
Let's first create some ratios.
Step2: Plot on the linear scale using t... | Python Code:
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
import numpy as np
import scipy.stats as ss
import warnings
warnings.filterwarnings("ignore")
sns.set_style('white')
%matplotlib inline
Explanation: W8 Lab Assignment
End of explanation
x = np.array([1, 1, 1,1, 10, 100, 1000])
y = np... |
15,350 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
How many user talk comments before first attacking comment?
Step1: Anons produce far fewer comments before their first attack than registered users. This could indicate that anons are more ... | Python Code:
t = 0.5
df_first_attack = df_diffs['2015'].query('pred_recipient_score>=%s' % t).sort('rev_timestamp')\
.assign(timestamp = lambda x: x.rev_timestamp)\
.groupby(['user_text'], as_index=False).first()[['user_text', 'timestamp']]
df_counts = df_diffs['2015'].merge... |
15,351 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Hacking into Evolutionary Dynamics!
This Jupyter notebook implements some of the ideas in following two books, specifically chapters 1-5 in Evolutionary Dynamics. For better undrestanding of... | Python Code:
%%html
<div >
<iframe type="text/html" width="336" height="550" frameborder="0" allowfullscreen style="max-width:100%;float: left" src="https://lesen.amazon.de/kp/card?asin=B003UV8TC2&preview=inline&linkCode=kpe&ref_=cm_sw_r_kb_dp_MamPyb1NWT7A8" ></iframe>
</div>
<div >
<iframe type="text/html" width="336"... |
15,352 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
用Python 3开发网络爬虫
By Terrill Yang (Github
Step1: 2. Python的集合
在爬虫程序中, 为了不重复爬那些已经爬过的网站, 我们需要把爬过的页面的url放进集合中, 在每一次要爬某一个url之前, 先看看集合里面是否已经存在. 如果已经存在, 我们就跳过这个url; 如果不存在, 我们先把url放入集合中, 然后再去爬这个页面.
... | Python Code:
from collections import deque
queue = deque(["Eric", "John", "Michael"])
queue.append("Terry") # Terry 入队
queue.append("Graham") # Graham 入队
queue.pop() # 队尾元素出队
queue.popleft() # 队首元素出队
queue # 队列中剩下的元素
Explanation: 用Python 3... |
15,353 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step 1
Step1: OK, the D3 area is set up
Now we'll focus on live updating. A manual test first.
Step2: Step 2 | Python Code:
from IPython.core.display import display, HTML
from string import Template
import pandas as pd
import json, random
HTML('<script src="lib/d3/d3.min.js"></script>')
html_template = Template('''
<svg id="graph-div"></div>
<script> $js_text </script>
''')
js_text_template = Template('''
var data = $data;
var ... |
15,354 | Given the following text description, write Python code to implement the functionality described.
Description:
Program for finding the Integral of a given function using Boole 's Rule
Function to return the value of f ( x ) for the given value of x ; Function to computes the integrand of y at the given intervals of x w... | Python Code:
def y(x ) :
return(1 /(1 + x ) )
def BooleRule(a , b ) :
n = 4
h =(( b - a ) / n )
sum = 0
bl =(7 * y(a ) + 32 * y(a + h ) + 12 * y(a + 2 * h ) + 32 * y(a + 3 * h ) + 7 * y(a + 4 * h ) ) * 2 * h / 45
sum = sum + bl
return sum
if __name__== ' __main __' :
lowlimit = 0
upplimit =... |
15,355 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<h1>Workcamp Maschinelles Lernen</h1>
<h2>Grundlagen - Arbeiten mit Panda Dataframes</h2>
<h3>EInlesen von Dateien in Dataframes</h3>
Lassen Sie uns jetzt unsere Kenntnisse erweitern. Wir wo... | Python Code:
import pandas as pd
dateipfad = 'SN_d_tot_V2.0.csv'
sunsets = pd.read_csv(dateipfad, sep=';', header=None)
sunsets.info()
sunsets.head(10)
Explanation: <h1>Workcamp Maschinelles Lernen</h1>
<h2>Grundlagen - Arbeiten mit Panda Dataframes</h2>
<h3>EInlesen von Dateien in Dataframes</h3>
Lassen Sie uns jetzt ... |
15,356 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<h1>Trying out the copulalib python package.</h1>
<p><h3>Frank, Clayton and Gumbel copulas from 2d data.</h3></p>
<h3>Pre-setup</h3>
<p>The package is in pip, so you can conveniently just "p... | Python Code:
#The first assert makes sure that you are getting a 1D in X and Y
#replace this code around line 58 in site-packages/copulalib/copulalib.py
try:
if X.shape[0] != Y.shape[0]:
raise ValueError('The size of both arrays should be same.')
except:
... |
15,357 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2020 The TensorFlow Hub Authors.
Licensed under the Apache License, Version 2.0 (the "License");
Step1: <table class="tfo-notebook-buttons" align="left">
<td>
<a target="_bl... | Python Code:
#@title Copyright 2020 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
#
# Unl... |
15,358 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a href="https
Step1: We want to create a network that has only one LSTM cell. The LSTM cell has 2 hidden nodes, so we need 2 state vector as well. Here, state is a tuple with 2 elements, ... | Python Code:
import numpy as np
import tensorflow as tf
tf.reset_default_graph()
sess = tf.InteractiveSession()
Explanation: <a href="https://www.bigdatauniversity.com"><img src = "https://ibm.box.com/shared/static/jvcqp2iy2jlx2b32rmzdt0tx8lvxgzkp.png" width = 300, align = "center"></a>
<h1 align=center><font size = 5>... |
15,359 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Title
Step1: Create some simulated geo data
Geo-data comes in a wide variety of forms, in this case we have a Python dictionary of five latitude and longitude strings, with each coordinate ... | Python Code:
# Load packages
from pygeocoder import Geocoder
import pandas as pd
import numpy as np
Explanation: Title: Geocoding And Reverse Geocoding
Slug: geocoding_and_reverse_geocoding
Summary: Geocoding And Reverse Geocoding
Date: 2016-05-01 12:00
Category: Python
Tags: Data Wrangling
Authors: Chris Albon
Geoco... |
15,360 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
admissionDrug
The following columns are available
Step2: Examine a single patient
Step4: Here we can see that these drugs were documented 2153 minutes (1.5 days) after ICU admission, but a... | Python Code:
# Import libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import psycopg2
import getpass
import pdvega
# for configuring connection
from configobj import ConfigObj
import os
%matplotlib inline
# Create a database connection using settings from config file
config='../db/conf... |
15,361 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Agile and Test-Driven Development
TDD Worked Example
Robert Haines, University of Manchester, UK
Adapted from "Test-Driven Development By Example", Kent Beck
Introduction
Very simple example... | Python Code:
import unittest
def run_tests():
suite = unittest.TestLoader().loadTestsFromTestCase(TestFibonacci)
unittest.TextTestRunner().run(suite)
Explanation: Agile and Test-Driven Development
TDD Worked Example
Robert Haines, University of Manchester, UK
Adapted from "Test-Driven Development By Example", K... |
15,362 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introduction
You are a Starbucks big data analyst (that’s a real job!) looking to find the next store into a Starbucks Reserve Roastery. These roasteries are much larger than a typical Star... | Python Code:
import math
import pandas as pd
import geopandas as gpd
#from geopy.geocoders import Nominatim # What you'd normally run
from learntools.geospatial.tools import Nominatim # Just for this exercise
import folium
from folium import Marker
from folium.plugins import MarkerCluster
from learntools.co... |
15,363 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
FASTQ format
The file is organized in 4 lines per read
Step1: Count the number of lines in the file (4 times the number of reads)
Step2: There are 40 M lines in the file, which means 10 M ... | Python Code:
for renz in ['HindIII', 'MboI']:
print renz
! head -n 4 /media/storage/FASTQs/K562_"$renz"_1.fastq
print ''
Explanation: FASTQ format
The file is organized in 4 lines per read:
1 - The header of the DNA sequence with the read id (the read length is optional)
2 - The DNA sequence
3 - The head... |
15,364 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Tight Binding program to compute the band structure of simple semiconductors.
Parameters taken from Vogl, Hjalmarson and Dow,
A Semiempirical Tight-Binding Theory of the Electronic Structure... | Python Code:
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
from numpy.linalg import eigvalsh
from collections import namedtuple
import TB
TB.band(TB.Si)
TB.band(TB.GaAs)
TB.band(TB.Ge)
Explanation: Tight Binding program to compute the band structure of simple semiconductors.
Parameters taken fro... |
15,365 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
initialize the Cosmological models
Step1: Define proxy modelling
Use a mass proxy, define the probability for observing a proxy given a mass and redhsift
$$
P(\log\lambda|M,z) = N(\mu(M,z),... | Python Code:
#CCL cosmology
cosmo_ccl = ccl.Cosmology(Omega_c = 0.30711 - 0.048254, Omega_b = 0.048254, h = 0.677, sigma8 = 0.8822714165197718, n_s=0.96, Omega_k = 0, transfer_function='eisenstein_hu')
#ccl_cosmo_set_high_prec (cosmo_ccl)
cosmo_numcosmo, dist, ps_lin, ps_nln, hmfunc = create_nc_obj (cosmo_ccl)
psf = hm... |
15,366 | 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... |
15,367 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Download Data
Step1: Process Data
Split data into train and test set and preview data
Step2: Convert to lists in preparation for modeling
Step3: Pre-Process Data For Deep Learning
See thi... | Python Code:
# Ensure that the github-issues-data volume is mounted in /mnt
!ls -la /mnt
# Set path for data dir
%env DATA_DIR=/mnt/github-issues-data
# Download the github-issues.zip training data to /mnt/github-issues-data
!wget --directory-prefix=${DATA_DIR} https://storage.googleapis.com/kubeflow-examples/github-is... |
15,368 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Visualize source time courses (stcs)
This tutorial focuses on visualization of
Step1: Then, we read the stc from file
Step2: This is a
Step3: The SourceEstimate object is in fact a surfa... | Python Code:
import os
import os.path as op
import numpy as np
import matplotlib.pyplot as plt
import mne
from mne.datasets import sample
from mne.minimum_norm import apply_inverse, read_inverse_operator
from mne import read_evokeds
data_path = sample.data_path()
sample_dir = os.path.join(data_path, 'MEG', 'sample')
su... |
15,369 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
The k-nearest neighbors (kNN) regression algorithm
Author
Step1: 1. The dataset
We describe next the regression task that we will use in the session. The dataset is an adaptation of the <a ... | Python Code:
# Import some libraries that will be necessary for working with data and displaying plots
# To visualize plots in the notebook
%matplotlib inline
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import pylab
# Packages used to read datasets
import scipy.io # To read matlab files
... |
15,370 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
CSAL4243
Step1: Plot data
Step2: Train model
Step3: Predict output using trained model
Step4: Plot results
Step5: Do it yourself
Step6: Predict labels using model and print it | Python Code:
import pandas as pd
from sklearn import linear_model
import matplotlib.pyplot as plt
# read data in pandas frame
dataframe = pd.read_csv('datasets/house_dataset1.csv')
# assign x and y
x_feature = dataframe[['Size']]
y_labels = dataframe[['Price']]
# check data by printing first few rows
dataframe.head()
E... |
15,371 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
CrowdTruth for Binary Choice Tasks
Step1: Declaring a pre-processing configuration
The pre-processing configuration defines how to interpret the raw crowdsourcing input. To do this, we need... | Python Code:
import pandas as pd
test_data = pd.read_csv("../data/person-video-binary-choice.csv")
test_data.head()
Explanation: CrowdTruth for Binary Choice Tasks: Person Identification in Video
In this tutorial, we will apply CrowdTruth metrics to a binary choice crowdsourcing task for Person Identification in video ... |
15,372 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Diamond Quality Analysis
Frame
If you want to buy one of the best diamonds in the world, what are the different aspects you want to look at? Let's find out how a stone is turned into a preci... | Python Code:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
plt.style.use('ggplot')
plt.rcParams['figure.figsize'] = (13,8)
Explanation: Diamond Quality Analysis
Frame
If you want to buy one of the best diamonds in the world, what are the different aspect... |
15,373 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Nested Statements and Scope
Now that we have gone over on writing our own functions, its important to understand how Python deals with the variable names you assign. When you create a variab... | Python Code:
x = 25
def printer():
x = 50
return x
print x
print printer()
Explanation: Nested Statements and Scope
Now that we have gone over on writing our own functions, its important to understand how Python deals with the variable names you assign. When you create a variable name in Python the name is stor... |
15,374 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Predicting World Series Winners
Fall 2016
Jack Limongelli (jal839@stern.nyu.edu)
Introduction
Baseball is America's pasttime. It began in 1846 when the Carwright Knickerbockers lost to th... | Python Code:
# Packages
import pandas as pd
import matplotlib.pyplot as plt
Explanation: Predicting World Series Winners
Fall 2016
Jack Limongelli (jal839@stern.nyu.edu)
Introduction
Baseball is America's pasttime. It began in 1846 when the Carwright Knickerbockers lost to the New York Baseball Club in Hoboken, New ... |
15,375 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Summary Statistics - Exercises
In these exercises you'll use a real life medical dataset to learn how to obtain basic statistics from the data. This dataset comes from Gluegrant, an A... | Python Code:
import pandas as pd
import numpy as np
from IPython.display import display, HTML
CSS =
.output {
flex-direction: row;
}
patient_data = pd.read_csv("../data/Exercises_Summary_Statistics_Data.csv")
patient_data.head()
Explanation: Summary Statistics - Exercises
In these exercises you'll use a real life ... |
15,376 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Part 4
Step1: Gradient estimators provide an interface to estimate gradients of some loss with respect to the parameters of some meta-learned system.
GradientEstimator are not specific to l... | Python Code:
import numpy as np
import jax.numpy as jnp
import jax
import functools
from matplotlib import pylab as plt
from typing import Optional, Tuple, Mapping
from learned_optimization.outer_trainers import full_es
from learned_optimization.outer_trainers import truncated_pes
from learned_optimization.outer_traine... |
15,377 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Comparison of two dataset
Here we compare two rainfall dataset with each other. The first is a satellite observation dataset, the so called HOAPS climatology and the second is a CMIP5 model ... | Python Code:
# read in the data
from pycmbs.data import Data
h_file = 'hoaps-g.t63.m01.rain.1987-2008_monmean.nc'
m_file = 'pr_Amon_MPI-ESM-LR_amip_r1i1p1_197901-200812_2000-01-01_2007-09-30_T63_monmean.nc'
hoaps = Data(h_file, 'rain', read=True)
model = Data(m_file, 'pr', read=True, scale_factor=86400.) # note the s... |
15,378 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
HoloViews is designed to be both highly customizable, allowing you to control how your visualizations appear, but also to enforce a strong separation between your data (with any semantically... | Python Code:
import numpy as np
import holoviews as hv
hv.notebook_extension()
x,y = np.mgrid[-50:51, -50:51] * 0.1
image = hv.Image(np.sin(x**2+y**2), group="Function", label="Sine")
coords = [(0.1*i, np.sin(0.1*i)) for i in range(100)]
curve = hv.Curve(coords)
curves = {phase: hv.Curve([(0.1*i, np.sin(phase+0.1*i)) ... |
15,379 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Arbeitsgrundlagen
Die Geschwindigkeit eines Objektes kann durch \ref{eq
Step1: Auswertung
Dieses Kapitel befasst sich mit den Möglichkeiten und Tricks der Fehlerrechnung. Normalerweise würd... | Python Code:
# Preparations
import math
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import numpy as np
from scipy import stats
from scipy.optimize import curve_fit
import seaborn as sns
from IPython.display import Latex
import warnings
from PrettyTable import PrettyTable
wa... |
15,380 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Watch Me Code 3
Step1: Map Pins
Step2: Choropleths
Choropleths are cartographic overlays based on boundries defined in a geo JSON file. | Python Code:
! pip install folium
import folium
import pandas as pd
import random
# we need to center the map in the middle of the US. I googled for the location.
CENTER_US = (39.8333333,-98.585522)
london = (51.5074, -0.1278)
map = folium.Map(location=CENTER_US, zoom_start=4)
map
Explanation: Watch Me Code 3: Mapping... |
15,381 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Supplemental Information
Step1: Data import
Length distribution of homozygosity tracts
Step2: Fluctuation assay
Luria-Delbrück fluctuation assay.
Step3: Figure 5 - Loss of heterozygosity | Python Code:
# Load external dependencies
from setup import *
# Load internal dependencies
import config,plot,utils
%load_ext autoreload
%autoreload 2
%matplotlib inline
Explanation: Supplemental Information:
"Clonal heterogeneity influences the fate of new adaptive mutations"
Ignacio Vázquez-García, Francisco Salinas,... |
15,382 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Data from <font color = "red"> the "IMDB5000"</font> database
Step1: Scrape data from <font color = "red"> DOUBAN.COM </font>
Step2: 1. Preliminary data visualization and analysis
Step3: ... | Python Code:
imdb_dat = pd.read_csv("movie_metadata.csv")
imdb_dat.info()
Explanation: Data from <font color = "red"> the "IMDB5000"</font> database
End of explanation
import requests
import re
from bs4 import BeautifulSoup
import time
import string
# return the douban movie rating that matches the movie name and year
... |
15,383 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Construyendo AutoEncoders sobre MNIST con Learninspy
<img style="display
Step1: Carga de datos
Step2: <h2><center>## Modelado con un AutoEncoder ##</center></h2>
Selección de parámetros pa... | Python Code:
from learninspy.core.model import NetworkParameters, NeuralNetwork
from learninspy.core.autoencoder import AutoEncoder, StackedAutoencoder
from learninspy.core.optimization import OptimizerParameters
from learninspy.core.stops import criterion
from learninspy.utils.data import StandardScaler, LocalLabeledD... |
15,384 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Demo for prox_elasticnet package
Below we import prox_elasticnet along with some other useful packages.
Step1: Diabetes dataset
Import the diabetes dataset which is included in sklearn.
It ... | Python Code:
from prox_elasticnet import ElasticNet, ElasticNetCV
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline
np.random.seed(319159)
Explanation: Demo for prox_elasticnet package
Below we import prox_elasticnet along with some other useful packages.
End of explanation
from sklearn.datasets imp... |
15,385 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Interpolation Exercise 1
Step1: 2D trajectory interpolation
The file trajectory.npz contains 3 Numpy arrays that describe a 2d trajectory of a particle as a function of time
Step2: Use the... | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
from scipy.interpolate import interp1d
Explanation: Interpolation Exercise 1
End of explanation
trajectory = np.load('trajectory.npz')
x = trajectory['x']
y = trajectory['y']
t = trajectory['t']
assert isinstance(x,... |
15,386 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2019 The TensorFlow Authors.
Step1: Use XLA with tf.function
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https
Step2: Then define some n... | 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... |
15,387 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Let's try to find the lag of asynchrony by looking at the cross-correlation.
Step1: Cross-correlation on the signals is a bad idea! Two many oscillations.
Instead, we should get the envelop... | Python Code:
# the cross-correlation function in statsmodels does not use FFT so it is really slow
# from statsmodels.tsa.stattools import ccf
# res = ccf(ts1[1][200000:400000,1],ts2[1][200000:400000,1])
Explanation: Let's try to find the lag of asynchrony by looking at the cross-correlation.
End of explanation
# Warni... |
15,388 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Anna KaRNNa
In this notebook, we'll build a character-wise RNN trained on Anna Karenina, one of my all-time favorite books. It'll be able to generate new text based on the text from the book... | Python Code:
import time
from collections import namedtuple
import numpy as np
import tensorflow as tf
Explanation: Anna KaRNNa
In this notebook, we'll build a character-wise RNN trained on Anna Karenina, one of my all-time favorite books. It'll be able to generate new text based on the text from the book.
This network... |
15,389 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Exercício 01
Step1: Exercício 02
Step2: Exercício 03
Step3: Exercício 04
Step4: Exercício 05
Step5: Exercício 06
Step6: Exercício 07
Step7: Exercício 08 | Python Code:
# Contador de palavras
import codecs
from collections import defaultdict
def ContaPalavras(texto):
for palavra, valor in ContaPalavras('exemplo.txt').iteritems():
print (palavra, valor)
Explanation: Exercício 01: Crie uma função ContaPalavras que receba como entrada o nome de um arquivo de texto e... |
15,390 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Load yesterday's data
Step1: Add class data
Continue scraping the web to add primary role
Step2: Visualizing high-dimensional data
Step3: t-distributed Stochastic Neighbor Embedding (TSNE... | Python Code:
# Load data
dat = pd.read_csv("lol_base_stats.tsv", sep="\t")
dat.head()
Explanation: Load yesterday's data
End of explanation
from bs4 import BeautifulSoup
import requests
primary_role = []
for url in dat.href:
html_data = requests.get(url).text
soup = BeautifulSoup(html_data, "html5lib")
... |
15,391 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Implementing a Neural Network
In this exercise we will develop a neural network with fully-connected layers to perform classification, and test it out on the CIFAR-10 dataset.
Step2: ... | Python Code:
# A bit of setup
import numpy as np
import matplotlib.pyplot as plt
from cs231n.classifiers.neural_net import TwoLayerNet
from __future__ import print_function
%matplotlib inline
plt.rcParams['figure.figsize'] = (10.0, 8.0) # set default size of plots
plt.rcParams['image.interpolation'] = 'nearest'
plt.rcP... |
15,392 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
The Dirichlet process mixture model is incredibly flexible in terms of the family of parametric component distributions {fθ | fθ∈Θ}{fθ | fθ∈Θ}. We illustrate this flexibility below by using ... | Python Code:
# pymc3.distributions.DensityDist?
import matplotlib.pyplot as plt
import matplotlib as mpl
from pymc3 import Model, Normal, Slice
from pymc3 import sample
from pymc3 import traceplot
from pymc3.distributions import Interpolated
from theano import as_op
import theano.tensor as tt
import numpy as np
from sc... |
15,393 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Matplotlib
Matplotlib is a plotting library. In this section give a brief introduction to the matplotlib.pyplot module, which provides a plotting system similar to that of MATLAB.
Step1: NO... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
##################
%matplotlib inline
Explanation: Matplotlib
Matplotlib is a plotting library. In this section give a brief introduction to the matplotlib.pyplot module, which provides a plotting system similar to that of MATLAB.
End of explanation
# Comp... |
15,394 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2020 The TensorFlow Authors.
Step1: Efficient serving
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https
Step2: We also need to install s... | 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... |
15,395 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Now fundamentally the data frame is just an abstraction but it provides a ton of useful tools that you’re going to get to see. This video is just going to go over the basic idea of the data ... | Python Code:
import string
upcase = [x for x in string.ascii_uppercase]
lcase = [x for x in string.ascii_lowercase]
print(upcase[:5], lcase[:5])
Explanation: Now fundamentally the data frame is just an abstraction but it provides a ton of useful tools that you’re going to get to see. This video is just going to go over... |
15,396 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Assess Huntington's disease progression from PET/MR images
Step1: Inflammation assesment using PBR scans
Participants information
Step2: We also set some colors for the groups.
Step3: Pri... | Python Code:
import itertools
import glob
import os
%matplotlib inline
import matplotlib.pyplot as plt
from matplotlib import gridspec
import nibabel as nib
import numpy as np
import pandas as pd
import seaborn as sns
import hd_classifier
Explanation: Assess Huntington's disease progression from PET/MR images
End of ex... |
15,397 | 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... |
15,398 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Logistic Regression with L2 regularization
The goal of this second notebook is to implement your own logistic regression classifier with L2 regularization. You will do the following
Step1: ... | Python Code:
from __future__ import division
import graphlab
Explanation: Logistic Regression with L2 regularization
The goal of this second notebook is to implement your own logistic regression classifier with L2 regularization. You will do the following:
Extract features from Amazon product reviews.
Convert an SFrame... |
15,399 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Load Data for PyLadies and their local Python User Groups
Step1: Get date for when the PyLadies group was started
Step2: Create some dataframes in Pandas
WARNING I do not know how to prope... | Python Code:
DATA_DIR = "meetup_data"
MEMBER_JSON = "pug_members.json"
GROUP_DIRS = [d for d in os.listdir(DATA_DIR)]
PYLADIES_GROUPS = []
for group in GROUP_DIRS:
if os.path.isdir(os.path.join(DATA_DIR, group)):
PYLADIES_GROUPS.append(group)
def load_group_data(pyladies_group):
pyladies_dir = os.path.j... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.