Unnamed: 0 int64 0 16k | text_prompt stringlengths 110 62.1k | code_prompt stringlengths 37 152k |
|---|---|---|
1,500 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
seaborn的绘图函数练习
处理一组数据时,首先要做的第一件事是了解变量是如何分布的
Step1: 核密度KDE的估计是对每个rug进行估计,然后把所有的KDE曲线加起来,之后进行归一化,得到所有的数据的平均KDE曲线
Step2: 还可以使用distplot()拟合参数分布到数据集,并直观地评估它与观察数据的对应关系
Step3: 可视化数据集中的成对关系¶
要在数据... | Python Code:
import numpy as np
import pandas as pd
from scipy import stats, integrate
import matplotlib.pyplot as plt
import seaborn as sns
sns.set(color_codes=True)
np.random.seed(sum(map(ord, "distributions")))
x = np.random.normal(size=100) # 单变量分布将绘制 直方图,并绘制 KDE (核心密度函数)
sns.distplot(x) # 分布绘制
plt.show()
sns.distp... |
1,501 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Pythonic Syntactic Sugar <a href="https
Step1: Let us begin by developing a convenient method for displaying images in our notebooks.
Step2: Multi-dimension slice indexing
If you are famil... | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import matplotlib as mpl
mpl.rc("image", aspect="equal")
import SimpleITK as sitk
# Download data to work on
%run update_path_to_download_script
from downloaddata import fetch_data as fdata
Explanation: Pythonic Syntactic Sugar <a href="https://mybinder.or... |
1,502 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2017 Google LLC.
Step1: # Travail préalable | 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... |
1,503 | 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 ... |
1,504 | Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
I would like to delete selected columns in a numpy.array . This is what I do: | Problem:
import numpy as np
a = np.array([[np.nan, 2., 3., np.nan],
[1., 2., 3., 9]])
z = np.any(np.isnan(a), axis = 0)
a = a[:, ~z] |
1,505 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Изрази
Изразите в Python са като изразите в математиката.
Всеки изразе е изграден от сотйности (като напр. числата 1, 2, 3, ...) и оператори (+, -, ...).
Типове
Всяка стойност се характеризи... | Python Code:
2 * 3 + 2
2 * (3 + 2)
Explanation: Изрази
Изразите в Python са като изразите в математиката.
Всеки изразе е изграден от сотйности (като напр. числата 1, 2, 3, ...) и оператори (+, -, ...).
Типове
Всяка стойност се характеризира с определн тип.
А типът е:
- Множеството от стойности
- Множество от операции, ... |
1,506 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2018 The TensorFlow Authors.
Licensed under the Apache License, Version 2.0 (the "License").
Neural Machine Translation with Attention
<table class="tfo-notebook-buttons" align="le... | Python Code:
from __future__ import absolute_import, division, print_function
# Import TensorFlow >= 1.10 and enable eager execution
import tensorflow as tf
tf.enable_eager_execution()
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
import unicodedata
import re
import numpy as np
im... |
1,507 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Selecting source and uid based on some criteria
Step1: Select calibrator with Flux > 0.1 Jy
Calibrator list here is downloaded (2017-06-23) from ALMA calibrator source catalogue (https
Step... | Python Code:
import sys
sys.path.append('../src/')
from ALMAQueryCal import *
q = queryCal()
Explanation: Selecting source and uid based on some criteria
End of explanation
fileCal = "alma_sourcecat_searchresults.csv"
listCal = q.readCal(fileCal, fluxrange=[0.1, 9999999999])
print "Number of selected sources: ", len(li... |
1,508 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Keras 利用資料擴增法訓練貓狗分類器
先從 Kaggle 下載資料集,這裡需要註冊 Kaggle 的帳號,並且取得 API Key,記得置換為自己的 API Token 才能下載資料。
Step1: 看看資料的基本結構,貓與狗訓練資料夾各有 4000 張,測試資料夾各有 1000 張影像
Step2: 資料處理
我們上面從 Kaggle 下載的檔案全部都是圖片,由於我們... | Python Code:
#!pip install kaggle
api_token = {"username":"your_username","key":"your_token"}
import json
import zipfile
import os
if not os.path.exists("/root/.kaggle"):
os.makedirs("/root/.kaggle")
with open('/root/.kaggle/kaggle.json', 'w') as file:
json.dump(api_token, file)
!chmod 600 /root/.kaggle/kaggle.... |
1,509 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
The typical problem we have to solve
Step1: Create the distribution and visualize it
Step2: Fit a function to the distribution and obtain its properties
Step3: Now do the fit | Python Code:
#Necessary imports
# lib for numeric calculations
import numpy as np
# standard lib for python plotting
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
# seaborn lib for more option in DS
import seaborn as sns
# so to obtain pseudo-random numbers
import random
... |
1,510 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Misdemeanor Amounts New York City
Data Bootcamp Final Project (Fall 2016)
by Zak Kukoff (kukoff@nyu.edu)
About this project
There's been much discussion in New York about the city's fluctuat... | Python Code:
# import packages
import pandas as pd
import matplotlib.pyplot as plt
import sys
from itertools import cycle, islice
import math
import numpy as np
%matplotlib inline
Explanation: Misdemeanor Amounts New York City
Data Bootcamp Final Project (Fall 2016)
by Zak Kukoff (kukoff@nyu... |
1,511 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2019 The TensorFlow Neural Structured Learning Authors
Step1: Graph regularization for document classification using natural graphs
<table class="tfo-notebook-buttons" align="left... | 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
# ... |
1,512 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Content
Glossary
1. Somename
Previous
Step1: Import section specific modules | Python Code:
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
from IPython.display import HTML
HTML('../style/course.css') #apply general CSS
Explanation: Content
Glossary
1. Somename
Previous: 1.1 Somename 2
Next: 1. Somename: References and further reading
Import standard modules:
End of expla... |
1,513 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Visu3d - Transform (go/v3d-transform)
If you're new to v3d, please look at the intro first.
Installation
We use same installation/imports as in the intro.
Step1: Transformations
v3d makes i... | Python Code:
!pip install visu3d etils[ecolab] jax[cpu] tf-nightly tfds-nightly sunds
from __future__ import annotations
from etils.ecolab.lazy_imports import *
Explanation: Visu3d - Transform (go/v3d-transform)
If you're new to v3d, please look at the intro first.
Installation
We use same installation/imports as in th... |
1,514 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Lesson 6
This lesson will review the Pythagorean theorem, how to find the distance between two points, and an interesting method for finding square roots.
Pythagorean Theorem
A triangle is a... | Python Code:
#Write your code here
#Solution
def isValidTriangle(arg_1, arg_2, arg_3):
if(arg_1 + arg_2 + arg_3 == 180):
print "YES"
else:
print "NO"
Explanation: Lesson 6
This lesson will review the Pythagorean theorem, how to find the distance between two points, and an interesting method for ... |
1,515 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
The Knuth-Bendix Completion Algorithm
This notebook presents the Knuth-Bendix completion algorithm for transforming a set of equations into a confluent term rewriting system. This notebook ... | Python Code:
%run Parser.ipynb
!cat Examples/quasigroups.eqn || type Examples\quasigroups.eqn
def test():
t = parse_term('x * y * z')
print(t)
print(to_str(t))
eq = parse_equation('i(x) * x = 1')
print(eq)
print(to_str(parse_file('Examples/quasigroups.eqn')))
test()
Explanation: The Knuth-B... |
1,516 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Title
Step1: Create Table
Step2: View Table
Step3: Create New Empty Table
Step4: Copy Contents Of First Table Into Empty Table
Step5: View Previously Empty Table | Python Code:
# Ignore
%load_ext sql
%sql sqlite://
%config SqlMagic.feedback = False
Explanation: Title: Copy Data From One Table To Another
Slug: copy_data_between_tables
Summary: Copy Data From One Table To Another in SQL.
Date: 2016-05-01 12:00
Category: SQL
Tags: Basics
Authors: Chris Albon
Note: This tutorial ... |
1,517 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Examples of Making Sky Plots from BOSS Meta Data
Examples of using the Basemap and healpy packages to make all sky maps of meta data accessed with the bossdata package. We use data from the... | Python Code:
%pylab inline
from mpl_toolkits.basemap import Basemap
from matplotlib.collections import PolyCollection
import astropy.units as u
from astropy.coordinates import SkyCoord
import healpy as hp
print(hp.version.__version__)
import bossdata.meta
print(bossdata.__version__)
Explanation: Examples of Making Sky ... |
1,518 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Defining a Custom Preprocessor and Extrapolator
Here you will be creating trivial preprocessor and and exztrqapolatoirs
following the API.
You start by importing the necessary modules.
Step1... | Python Code:
# General imports
import sunpy.map as mp
import numpy as np
from mayavi import mlab # Necessary for visulisation
# Module imports
from solarbextrapolation.preprocessors import Preprocessors
from solarbextrapolation.extrapolators import Extrapolators
from solarbextrapolation.map3dclasses import Map3D
from s... |
1,519 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Week 4 Assessment
Step1: Now, let's plot a digit from the dataset
Step5: Before we implement PCA, we will need to do some data preprocessing. In this assessment, some of them
will be impl... | Python Code:
# PACKAGE: DO NOT EDIT
import numpy as np
import timeit
# PACKAGE: DO NOT EDIT
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
plt.style.use('fivethirtyeight')
Explanation: Week 4 Assessment: Principal Component Analysis (PCA)
Learning Objective
In this notebook, we will implement P... |
1,520 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Quakebot
PART ONE
Step1: What we want
Step2: PART TWO
Step3: PART THREE
Step4: PART FOUR | Python Code:
earthquake = {
'rms': '1.85',
'updated': '2014-06-11T05:22:21.596Z',
'type': 'earthquake',
'magType': 'mwp',
'longitude': '-136.6561',
'gap': '48',
'depth': '10',
'dmin': '0.811',
'mag': '5.7',
'time': '2014-06-04T11:58:58.200Z',
'latitude':... |
1,521 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Explore U.S. Births
In this project, I am working with the dataset, compiled by FiveThirtyEight [https
Step1: Converting Data Into A List Of Lists
to convert the dataset into a list of li... | Python Code:
f = open('US_births_1994-2003_CDC_NCHS.csv', 'r')
data = f.read()
data
data_spl = data.split("\n")
data_spl
data_spl[0:10]
Explanation: Explore U.S. Births
In this project, I am working with the dataset, compiled by FiveThirtyEight [https://raw.githubusercontent.com/fivethirtyeight/data/master/births/US_... |
1,522 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Categorical Variables in Snorkel
This is a short tutorial on how to use categorical variables (i.e. more values than binary) in Snorkel. We'll use a completely toy scenario with three sente... | Python Code:
%load_ext autoreload
%autoreload 2
%matplotlib inline
import os
import numpy as np
from snorkel import SnorkelSession
session = SnorkelSession()
Explanation: Categorical Variables in Snorkel
This is a short tutorial on how to use categorical variables (i.e. more values than binary) in Snorkel. We'll use a... |
1,523 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Gender Distinguished Analysis of ADHD v.s. Bipolar - by Yating Jing
Build models for female patients and male patients separately.
Step1: Machine Learning Utilities
K-Means Clustering
Step2... | Python Code:
import pandas as pd
import numpy as np
df_adhd = pd.read_csv('ADHD_Gender_rCBF.csv')
df_bipolar = pd.read_csv('Bipolar_Gender_rCBF.csv')
n1, n2 = df_adhd.shape[0], df_bipolar.shape[0]
print 'Number of ADHD patients (without Bipolar) is', n1
print 'Number of Bipolar patients (without ADHD) is', n2
print 'Ch... |
1,524 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
All the work you do with pycomlink will be based on the Comlink object, which represents one CML between two sites and with an arbitrary number of channels, i.e. the different connections be... | Python Code:
df = pd.read_csv('example_data/gap0_gap4_2012.csv', parse_dates=True, index_col=0)
df.head()
Explanation: All the work you do with pycomlink will be based on the Comlink object, which represents one CML between two sites and with an arbitrary number of channels, i.e. the different connections between the t... |
1,525 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Generazione data set sintetico
Step2: Esercizio 1
Step3: Esercizio 2 | Python Code:
# Vari import da usare
import numpy as np
import matplotlib.pyplot as plt
# Supporto per operazioni tra matrici e vettori
from numpy import matmul
from numpy import transpose
from numpy.linalg import inv
from numpy.linalg import pinv
def MakeSyntethicData(n=100, ifplot=False):
Restituisce una matrice ... |
1,526 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Post processing
Step1: Read the smoothed files
The following files are filtered and smoothed motion parameter regressed
I got the file name using the command
Step2: Check which subjects ha... | Python Code:
from bids.grabbids import BIDSLayout
from nipype.interfaces.fsl import (BET, ExtractROI, FAST, FLIRT, ImageMaths,
MCFLIRT, SliceTimer, Threshold,Info, ConvertXFM,MotionOutliers)
from nipype.interfaces.afni import Resample
from nipype.interfaces.io import DataSink
from nip... |
1,527 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Iteration
One of the most basic operations in programming is iterating over a list of elements to perform some kind of operation.
In python we use the for statement to iterate. It is easier ... | Python Code:
a = [4,5,6,8,10]
for i in a:
print(i)
# A fragment of `One Hundred Years of Solitude`
GGM = 'Many years later, as he faced the firing squad, \
Colonel Aureliano Buendía was to remember that dist \
ant afternoon when his father took him to discover ice. \
At that time Macondo was a village of twenty ado... |
1,528 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<h3>Current School Panda</h3>
Working with directory school data
Creative Commons in all schools
This script uses a csv file from Creative Commons New Zealand and csv file from Ministry of E... | Python Code:
crcom = pd.read_csv('/home/wcmckee/Downloads/List of CC schools - Sheet1.csv', skiprows=5, index_col=0, usecols=[0,1,2])
Explanation: <h3>Current School Panda</h3>
Working with directory school data
Creative Commons in all schools
This script uses a csv file from Creative Commons New Zealand and csv file f... |
1,529 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Download the list of occultation periods from the MOC at Berkeley.
Note that the occultation periods typically only are stored at Berkeley for the future and not for the past. So this is onl... | Python Code:
fname = io.download_occultation_times(outdir='./data/')
print(fname)
Explanation: Download the list of occultation periods from the MOC at Berkeley.
Note that the occultation periods typically only are stored at Berkeley for the future and not for the past. So this is only really useful for observation pla... |
1,530 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Dénes Csala
MCC, 2022
Based on Elements of Data Science (Allen B. Downey, 2021) and Python Data Science Handbook (Jake VanderPlas, 2018)
License
Step1: Validating Models
One of the most i... | Python Code:
from __future__ import print_function, division
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
plt.style.use('seaborn')
Explanation: Dénes Csala
MCC, 2022
Based on Elements of Data Science (Allen B. Downey, 2021) and Python Data Science Handbook (Jake VanderPlas, 2018)
License: MIT... |
1,531 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Exploring precision and recall
The goal of this second notebook is to understand precision-recall in the context of classifiers.
Use Amazon review data in its entirety.
Train a logistic regr... | Python Code:
import graphlab
from __future__ import division
import numpy as np
graphlab.canvas.set_target('ipynb')
Explanation: Exploring precision and recall
The goal of this second notebook is to understand precision-recall in the context of classifiers.
Use Amazon review data in its entirety.
Train a logistic regre... |
1,532 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Using ChoiceRank to understand network traffic
This notebook provides a quick example on how to use ChoiceRank to estimate transitions along the edges of a network based only on the marginal... | Python Code:
import choix
import networkx as nx
import numpy as np
%matplotlib inline
Explanation: Using ChoiceRank to understand network traffic
This notebook provides a quick example on how to use ChoiceRank to estimate transitions along the edges of a network based only on the marginal traffic at the nodes.
End of e... |
1,533 |
Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
Feature Engineering para XGBoost
| Python Code::
important_values = values.merge(labels, on="building_id")
important_values.drop(columns=["building_id"], inplace = True)
important_values["geo_level_1_id"] = important_values["geo_level_1_id"].astype("category")
important_values
X_train, X_test, y_train, y_test = train_test_split(important_values.drop(col... |
1,534 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Vertex client library
Step1: Install the latest GA version of google-cloud-storage library as well.
Step2: Restart the kernel
Once you've installed the Vertex client library and Google clo... | Python Code:
import os
import sys
# Google Cloud Notebook
if os.path.exists("/opt/deeplearning/metadata/env_version"):
USER_FLAG = "--user"
else:
USER_FLAG = ""
! pip3 install -U google-cloud-aiplatform $USER_FLAG
Explanation: Vertex client library: AutoML text sentiment analysis model for online prediction
<ta... |
1,535 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Notes
Development and evaluation of imaginet and related models.
Step1: Image retrieval evaluation
Models
Step2: Models | Python Code:
%pylab inline
from ggplot import *
import pandas as pd
data = pd.DataFrame(
dict(epoch=range(1,11)+range(1,11)+range(1,11)+range(1,8)+range(1,11)+range(1,11),
model=hstack([repeat("char-3-grow", 10),
repeat("char-1", 10),
repeat("char-3", 10),
... |
1,536 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Collapsed Gibbs sampler for Generalized Relational Topic Models with Data Augmentation
<div style="display
Step1: Generate topics
We assume a vocabulary of 25 terms, and create ten "topics"... | Python Code:
%matplotlib inline
from modules.helpers import plot_images
from functools import partial
from sklearn.metrics import (roc_auc_score, roc_curve)
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
imshow = partial(plt.imshow, cmap='gray', interpolation='nearest', asp... |
1,537 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
This demo shows how to use the Bayesian Representational Similarity Analysis method in brainiak with a simulated dataset.
The brainik.reprsimil.brsa module has two estimators named BRSA and ... | Python Code:
%matplotlib inline
import scipy.stats
import scipy.spatial.distance as spdist
import numpy as np
from brainiak.reprsimil.brsa import BRSA, prior_GP_var_inv_gamma, prior_GP_var_half_cauchy
from brainiak.reprsimil.brsa import GBRSA
import brainiak.utils.utils as utils
import matplotlib.pyplot as plt
import l... |
1,538 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Tech - carte
Faire une carte, c'est toujours compliqué. C'est simple jusqu'à ce qu'on s'aperçoive qu'on doit récupérer la description des zones administratives d'un pays, fournies parfois da... | Python Code:
from jyquickhelper import add_notebook_menu
add_notebook_menu()
%matplotlib inline
Explanation: Tech - carte
Faire une carte, c'est toujours compliqué. C'est simple jusqu'à ce qu'on s'aperçoive qu'on doit récupérer la description des zones administratives d'un pays, fournies parfois dans des coordonnées au... |
1,539 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Layout viewport
Use the Layout class to create a variety of map views for comparison.
For more information, run help(Layout).
The first example sets a common viewport for all maps while the ... | Python Code:
from cartoframes.auth import set_default_credentials
set_default_credentials('cartoframes')
Explanation: Layout viewport
Use the Layout class to create a variety of map views for comparison.
For more information, run help(Layout).
The first example sets a common viewport for all maps while the second sets ... |
1,540 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Light 2 Numerical and Data Analysis Answers
Step1: 1. Identify Balmer absorption lines in a star
Author
Step2: 2. Identify Balmer emission lines in a galaxy
Author
Step3: Balmer Series
Th... | Python Code:
import numpy as np
import scipy.interpolate as interpolate
import astropy.io.fits as fits
import matplotlib.pyplot as plt
import requests
Explanation: Light 2 Numerical and Data Analysis Answers
End of explanation
def find_nearest(array, value):
index = (np.abs(array - value)).argmin()
return index... |
1,541 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Repairing artifacts with ICA
This tutorial covers the basics of independent components analysis (ICA) and
shows how ICA can be used for artifact repair; an extended example illustrates
repai... | Python Code:
import os
import mne
from mne.preprocessing import (ICA, create_eog_epochs, create_ecg_epochs,
corrmap)
sample_data_folder = mne.datasets.sample.data_path()
sample_data_raw_file = os.path.join(sample_data_folder, 'MEG', 'sample',
'sample_au... |
1,542 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Classification of Organisms
Using a Digital Dichotomous Key
Step 1 - Creating a Checkpoint
Create a checkpoint by clicking <b>File</b> ==> <b>Save and Checkpoint</b>. If you make a major mis... | Python Code:
# Import modules that contain functions we need
import pandas as pd
import numpy as np
%matplotlib inline
import matplotlib.pyplot as plt
# Our data is the dichotomous key table and is defined as the word 'key'.
# key is set equal to the .csv file that is read by pandas.
# The .csv file must be in the same... |
1,543 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Single Replica TIS
This notebook shows how to run single replica TIS move scheme. This assumes you can load engine, network, and initial sample from a previous calculation.
Step2: Op... | Python Code:
%matplotlib inline
import openpathsampling as paths
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from openpathsampling.visualize import PathTreeBuilder, PathTreeBuilder
from IPython.display import SVG, HTML
def ipynb_visualize(movevis):
Default settings to show a movevis in an... |
1,544 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
NumPy
Why NumPy ?
NumPy is an acronym for "Numeric Python" or "Numerical Python"
NumPy is the fundamental package for scientific computing with Python. It contains among other things
Step1: ... | Python Code:
# import NumPy library
# This library is bundled along with anaconda distribution
# np alias is the standard convention
import numpy as np
Explanation: NumPy
Why NumPy ?
NumPy is an acronym for "Numeric Python" or "Numerical Python"
NumPy is the fundamental package for scientific computing with Python. It ... |
1,545 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Here is the library of functions
Step1: Everything after here is the script that runs the simulation
Step2: Regression
Step3: HMC
Step4: HMC - Unscaled
nsample = 1000
m = 20
eps = .008
t... | Python Code:
def logistic(x):
'''
'''
return 1/(1+np.exp(-x))
def U_logistic(theta, Y, X, phi):
'''
'''
return - (Y.T @ X @ theta - np.sum(np.log(1+np.exp(X @ theta))) - 0.5 * phi * np.sum(theta**2))
def gradU_logistic(theta, Y, X, phi):
'''
'''
n = X.shape[0]
Y_pred = logis... |
1,546 | Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
I have fitted a k-means algorithm on more than 400 samples using the python scikit-learn library. I want to have the 100 samples closest (data, not just index) to a cluster center "... | Problem:
import numpy as np
import pandas as pd
from sklearn.cluster import KMeans
p, X = load_data()
assert type(X) == np.ndarray
km = KMeans()
km.fit(X)
d = km.transform(X)[:, p]
indexes = np.argsort(d)[::][:100]
closest_100_samples = X[indexes] |
1,547 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Tutorial
Step1: Transient Model
In this example the transient model is create from an ASCII file. Alternatively you could use the built-in SN models of sncosmo or the Blackbody model provid... | Python Code:
import os
home_dir = os.environ.get('HOME')
# Please enter the filename of the ztf_sim output file you would like to use. The example first determines
# your home directory and then uses a relative path (useful if working on several machines with different usernames)
survey_file = os.path.join(home_dir, 'd... |
1,548 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
LFC Data Analysis
Step1: Notebook Change Log
| Date | Change Description |
|
Step2: Print version numbers.
Step3: Data Load
Data description
The data files are located in the da... | Python Code:
%%html
<! left align the change log table in next cell >
<style>
table {float:left}
</style>
Explanation: LFC Data Analysis: From Rafa to Rodgers
Lies, Damn Lies and Statistics
See Terry's blog LFC: From Rafa To Rodgers for a discussion of of the data generated by this analysis.
This notebook analyses Live... |
1,549 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Binning in physt
Step1: Ideal number of bins
Step2: Binning schemes
Exponential binning
Uses numpy.logscale to create bins.
Step3: Integer binning
Useful for integer values (or something ... | Python Code:
# Necessary import evil
from physt import histogram, binnings
import numpy as np
import matplotlib.pyplot as plt
# Some data
np.random.seed(42)
heights1 = np.random.normal(169, 10, 100000)
heights2 = np.random.normal(180, 6, 100000)
numbers = np.random.rand(100000)
Explanation: Binning in physt
End of expl... |
1,550 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Plotting
There are many Python plotting libraries depending on your purpose. However, the standard general-purpose library is matplotlib. This is often used through its pyplot interface.
Ste... | Python Code:
from matplotlib import pyplot
%matplotlib inline
from matplotlib import rcParams
rcParams['figure.figsize']=(12,9)
from math import sin, pi
x = []
y = []
for i in range(201):
x_point = 0.01*i
x.append(x_point)
y.append(sin(pi*x_point)**2)
pyplot.plot(x, y)
pyplot.show()
Explanation: Plotting
Th... |
1,551 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Example xml file
Step1: Traversing the parsed tree
To visit all the children in order, user iter() to create a generator that iterates over the ElementTree instance.
Step2: To print only t... | Python Code:
from xml.etree import ElementTree
with open('podcasts.opml', 'rt') as f:
tree = ElementTree.parse(f)
print(tree)
Explanation: Example xml file:
```
<?xml version="1.0" encoding="UTF-8"?>
<opml version="1.0">
<head>
<title>My Podcasts</title>
<dateCreated>Sat, 06 Aug 2016 15:53:26 GMT</date... |
1,552 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
This is the program for a student Bayesian network
Step1: Add nodes and edges
Step2: In a Bayesian network, each node has an associated CPD (conditional probability distribution).
Step3: ... | Python Code:
from pgmpy.models import BayesianModel
student_model = BayesianModel()
Explanation: This is the program for a student Bayesian network
End of explanation
student_model.add_nodes_from(['difficulty', 'intelligence', 'grade', 'sat', 'letter'])
student_model.nodes()
student_model.add_edges_from([('difficulty',... |
1,553 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Off-Specular simulation
Off-specular simulation is a technique developed to study roughness or micromagnetism at micrometric scale [1]. For the moment BornAgain has only the limited support ... | Python Code:
%matplotlib inline
# %load offspec_ex.py
import numpy as np
import bornagain as ba
from bornagain import deg, angstrom, nm, kvector_t
def get_sample():
# Defining Materials
material_1 = ba.HomogeneousMaterial("Air", 0.0, 0.0)
material_2 = ba.HomogeneousMaterial("Si", 7.6e-06, 1.7e-07)
mater... |
1,554 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step2: Did the Hall of Fame voter purge make a difference?
In a recent Jayson Stark article and about lessons in hall of fame voting, he mentions the following three assumptions about the Ba... | Python Code:
#read in the data
def read_votes(infile):
Read in the number of votes in each file
lines = open(infile).readlines()
hof_votes = {}
for l in lines:
player={}
l = l.split(',')
name = l[1].replace('X-', '').replace(' HOF', '').strip()
player['year'] = l[2]
... |
1,555 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Data Bootcamp Final Project
Step1: II. Contestants' Age
We began by looking at the average age of contestants at different stages of the competition
Step2: The chart above shows the averag... | Python Code:
#We will begin by importing several packages to use for our analysis:
import sys
import pandas as pd
import matplotlib as mpl
import matplotlib.pyplot as plt
import datetime as dt
import numpy as np
%matplotlib inline
# Check versions
print('Python version: ', sys.version)
print('Pandas version: ', pd.__ve... |
1,556 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
LORIS API Tour 2/2
This tutorial contains basic examples in Python to demonstrate how to interact with the API.
To run this tutorial, click on Runtime -> Run allThis tutorial is also avai... | Python Code:
import getpass # For input prompt hide what is entered
import json # Provides convenient functions to handle json objects
import re # For regular expression
import requests # To handle http requests
import warnings # To ignore warnings
# Because the ssl certificates are unverified, warning... |
1,557 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Installating Julia/IJulia
1 - Downloading and Installing the right Julia binary in the right place
Step1: overwrite links, since v1.5.3 installation does not work properly due to
https
Step... | Python Code:
import os
import sys
import io
import re
import urllib.request as request # Python 3
# get latest stable release info, download link and hashes
g = request.urlopen("https://julialang.org/downloads/")
s = g.read().decode()
g.close;
r = r'<a href=".current_stable_release">([^<]+)</a></h2> ' + \
r'<p>Che... |
1,558 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Functions and exceptions
Functions
Write a function that converts from Celsius to Kelvin.
To convert from Celsius to Kelvin you add 273.15 from the value.
Try your solution for a few values.... | Python Code:
def celsius_to_kelvin(c):
# implementation here
pass
celsius_to_kelvin(0)
Explanation: Functions and exceptions
Functions
Write a function that converts from Celsius to Kelvin.
To convert from Celsius to Kelvin you add 273.15 from the value.
Try your solution for a few values.
End of explanation
de... |
1,559 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
# Interpret results through aggregation
Since I'm working with long documents, I'm not really concerned with BERT's raw predictions about individual text chunks. Instead I need to know how g... | Python Code:
# modules needed
import pandas as pd
from scipy.stats import pearsonr
import numpy as np
Explanation: # Interpret results through aggregation
Since I'm working with long documents, I'm not really concerned with BERT's raw predictions about individual text chunks. Instead I need to know how good the predict... |
1,560 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
.загружаем файлы .json
Step1: Смотрим, где именно в файле интересующие нас данные
Step2: Считываем нужные нам данные как датафреймы
Step3: Создаем в датафреймах отдельные столбцы с данным... | Python Code:
path = 'task_data/Sessions_Page.json'
path2 = 'task_data/Goal1CompletionLocation_Goal1Completions.json'
with open(path, 'r') as f:
sessions_page = json.loads(f.read())
with open(path2, 'r') as f:
goals_page = json.loads(f.read())
Explanation: .загружаем файлы .json
End of explanation
type (sessions... |
1,561 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Aim
Motive of the notebook is to give a brief overview as to how to use the evolutionary sampling powered ensemble models as part of the EvoML research project.
Will make the notebook more ... | Python Code:
from evoml.subsampling import BasicSegmenter_FEMPO, BasicSegmenter_FEGT, BasicSegmenter_FEMPT
df = pd.read_csv('datasets/ozone.csv')
df.head(2)
X, y = df.iloc[:,:-1], df['output']
print(BasicSegmenter_FEGT.__doc__)
from sklearn.tree import DecisionTreeRegressor
clf_dt = DecisionTreeRegressor(max_depth=3)
c... |
1,562 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: TV Script Generation
In this project, you'll generate your own Simpsons TV scripts using RNNs. You'll be using part of the Simpsons dataset of scripts from 27 seasons. The Neural Ne... | Python Code:
DON'T MODIFY ANYTHING IN THIS CELL
import helper
data_dir = './data/simpsons/moes_tavern_lines.txt'
text = helper.load_data(data_dir)
# Ignore notice, since we don't use it for analysing the data
text = text[81:]
Explanation: TV Script Generation
In this project, you'll generate your own Simpsons TV script... |
1,563 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<img src="http
Step1: Create a Dakota instance to perform a centered parameter study with HydroTrend.
Step2: Define the HydroTrend input variables to be used in the parameter study, as wel... | Python Code:
from dakotathon import Dakota
Explanation: <img src="http://csdms.colorado.edu/mediawiki/images/CSDMS_high_res_weblogo.jpg">
Centered Parameter Study with HydroTrend
HydroTrend is a numerical model that creates synthetic river discharge and sediment load time series as a function of climate trends and basi... |
1,564 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Sine Wave Generator
Step1: To implement our sine wave generator, we'll use a counter to index into a ROM that is programmed to output the value of discrete points in the sine wave.
Step2: ... | Python Code:
import math
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
def sine(x):
return np.sin(2 * math.pi * x)
x = np.linspace(0., 1., num=256, endpoint=False)
plt.plot(x, sine(x))
import magma as m
m.set_mantle_target("ice40")
import mantle
from loam.boards.icestick import IceStick
N = ... |
1,565 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
GroupBy examples
Allen Downey
MIT License
Step1: Let's load the GSS dataset.
Step2: The GSS interviews a few thousand respondents each year.
Step3: One of the questions they ask is "Do yo... | Python Code:
%matplotlib inline
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
sns.set(style='white')
from thinkstats2 import Pmf, Cdf
import thinkstats2
import thinkplot
decorate = thinkplot.config
Explanation: GroupBy examples
Allen Downey
MIT License
End of explanation
%... |
1,566 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a id="top"></a>
Db2 Compatibility Features
Moving from one database vendor to another can sometimes be difficult due to syntax differences between data types, functions, and language elemen... | Python Code:
%run db2.ipynb
Explanation: <a id="top"></a>
Db2 Compatibility Features
Moving from one database vendor to another can sometimes be difficult due to syntax differences between data types, functions, and language elements. Db2 already has a high degree of compatibility with Oracle PLSQL along with some of t... |
1,567 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Hospital readmissions data analysis and recommendations for reduction
Background
In October 2012, the US government's Center for Medicare and Medicaid Services (CMS) began reducing Medicare ... | Python Code:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import bokeh.plotting as bkp
from mpl_toolkits.axes_grid1 import make_axes_locatable
%matplotlib inline
# read in readmissions data provided
hospital_read_df = pd.read_csv('data/cms_hospital_readmissions.csv')
Explanation: Hospital read... |
1,568 | Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
Is it possible to delete or insert a step in a sklearn.pipeline.Pipeline object? | Problem:
import numpy as np
import pandas as pd
from sklearn.pipeline import Pipeline
from sklearn.svm import SVC
from sklearn.decomposition import PCA
from sklearn.preprocessing import PolynomialFeatures
estimators = [('reduce_poly', PolynomialFeatures()), ('dim_svm', PCA()), ('sVm_233', SVC())]
clf = Pipeline(estimat... |
1,569 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Self-Driving Car Engineer Nanodegree
Project
Step1: Read in an Image
Step9: Ideas for Lane Detection Pipeline
Some OpenCV functions (beyond those introduced in the lesson) that might be us... | Python Code:
#importing some useful packages
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
import cv2
%matplotlib inline
Explanation: Self-Driving Car Engineer Nanodegree
Project: Finding Lane Lines on the Road
In this project, you will use the tools you learned about in the lesson... |
1,570 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Title
Step1: Generate Features And Target Data
Step2: Create Logistic Regression
Step3: Cross-Validate Model Using Accuracy | Python Code:
# Load libraries
from sklearn.model_selection import cross_val_score
from sklearn.linear_model import LogisticRegression
from sklearn.datasets import make_classification
Explanation: Title: Accuracy
Slug: accuracy
Summary: How to evaluate a Python machine learning using accuracy.
Date: 2017-09-15 12:00
C... |
1,571 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Literate programming using IPython notebooks
Literate programming is a concept promoted by Donald Knuth, the famous computer scientist (and the author of the Art of Computer Programming.) Ac... | Python Code:
from m8r import view
Explanation: Literate programming using IPython notebooks
Literate programming is a concept promoted by Donald Knuth, the famous computer scientist (and the author of the Art of Computer Programming.) According to this concept, computer programs should be written in a combination of th... |
1,572 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
The MIT License (MIT)<br>
Copyright (c) 2016, 2017, 2018 Massachusetts Institute of Technology<br>
Authors
Step1: Get scale factor
Step2: Plot EWD $\times$ scale factor | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
plt.rcParams['figure.dpi']=150
# Gravity Recovery and Climate Experiment (GRACE) Data
# Source: http://grace.jpl.nasa.gov/
# Current surface mass change data, measuring equivalent water thickness in cm, versus time
# This data fetcher uses results from the... |
1,573 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Iris introduction course
2. Loading and Saving
Learning Outcome
Step1: 2.1 Iris Load Functions<a id='iris_load_functions'></a>
There are three main load functions in Iris
Step2: If we give... | Python Code:
import iris
Explanation: Iris introduction course
2. Loading and Saving
Learning Outcome: by the end of this section, you will be able to use Iris to load datasets from disk as Iris cubes and save Iris cubes back to disk.
Duration: 30 minutes.
Overview:<br>
2.1 Iris Load Functions<br>
2.2 Saving Cubes<br>
... |
1,574 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Face Generation
In this project, you'll use generative adversarial networks to generate new images of faces.
Get the Data
You'll be using two datasets in this project
Step3: Explore ... | Python Code:
data_dir = './data'
# FloydHub - Use with data ID "R5KrjnANiKVhLWAkpXhNBe"
#data_dir = '/input'
DON'T MODIFY ANYTHING IN THIS CELL
import helper
helper.download_extract('mnist', data_dir)
helper.download_extract('celeba', data_dir)
Explanation: Face Generation
In this project, you'll use generative adversa... |
1,575 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a href="https
Step1: a) We see from the above histogram that the distribution is approximately normal when we draw a sample of 1000 values from a standard normal distribution.
b) We also s... | Python Code:
#codes here for a)
import math
import pandas as pd
import numpy as np
from scipy import stats
import matplotlib.pyplot as plt
def demo1():
mu, sigma = 0, 0.1
sampleNo = 1000
s = np.random.normal(mu, sigma, sampleNo)
plt.hist(s, bins=100, density=True)
plt.show()
demo1()
Explanation: <a ... |
1,576 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
CS229 Machine Learning Exercise Homework 1 Problem 5b
Step1: Part i
The linear regression function below implements linear regression using the normal equations. We could also use some form... | Python Code:
import numpy as np
import numpy.linalg as linalg
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.colors as clrs
Explanation: CS229 Machine Learning Exercise Homework 1 Problem 5b
End of explanation
def linear_regression(X, y):
return linalg.inv(X.T.dot(X)).dot(X.T).dot(y)
Explanat... |
1,577 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Control Structures
Control Structures construct a fundamental part of language along with syntax,semantics and core libraries. It is the Control Structures which makes the program more livel... | Python Code:
response = input("Enter an integer : ")
num = int(response)
if num % 2 == 0:
print("{} is an even number".format(num))
Explanation: Control Structures
Control Structures construct a fundamental part of language along with syntax,semantics and core libraries. It is the Control Structures which makes the... |
1,578 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Density of States Analysis Example
Given sample and empty-can data, compute phonon DOS
To use this notebook, first click jupyter menu File->Make a copy
Click the title of the copied jupyter ... | Python Code:
# where am I now?
!pwd
# create a new working directory and change into it
workdir = '~/reduction/ARCS/getdos-multiple-Ei-demo'
!mkdir -p {workdir}
%cd {workdir}
# Data to reduce. Change the IPTS number and run numbers to suit your need
samplenxs = "/SNS/ARCS/IPTS-15398/shared/mantid_reduce/non-radC/non-ra... |
1,579 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Causal Effect for Logistic Regression
Import and settings
In this example, we need to import numpy, pandas, and graphviz in addition to lingam.
Step1: Utility function
We define a utility f... | Python Code:
import numpy as np
import pandas as pd
import graphviz
import lingam
from lingam.utils import make_prior_knowledge
print([np.__version__, pd.__version__, graphviz.__version__, lingam.__version__])
np.set_printoptions(precision=3, suppress=True)
np.random.seed(0)
Explanation: Causal Effect for Logistic Regr... |
1,580 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Data Wrangling with Pandas
The are two datasets in CSV format, both are from weather station 'USC00116760' in Petersburg, IL
Data ranges from 2015-01-01 to 2015-06-29
'Temp_116760.csv' store... | Python Code:
# How to read the 'Temp_116760.csv' file?
df_temp.tail()
# How to read the 'Prcp_116760.csv' file and make its index datetime dtype?
df_prcp.head()
# and I want the index to be of date-time, rather than just strings
df_prcp.index.dtype
Explanation: Data Wrangling with Pandas
The are two datasets in CSV for... |
1,581 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Generative Adversarial Network
In this notebook, we'll be building a generative adversarial network (GAN) trained on the MNIST dataset. From this, we'll be able to generate new handwritten d... | Python Code:
%matplotlib inline
import pickle as pkl
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
print(tf.__version__)
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('MNIST_data')
Explanation: Generative Adversarial Network
In this notebook, w... |
1,582 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Using the sampler
spvcm is a generic gibbs sampling framework for spatially-correlated variance components models. The current supported models are
Step1: Depending on the structure of the ... | Python Code:
import spvcm.api as spvcm #package API
spvcm.both.Generic # abstract customizable class, ignores rho/lambda, equivalent to MVCM
spvcm.both.MVCM # no spatial effect
spvcm.both.SESE # both spatial error (SE)
spvcm.both.SESMA # response-level SE, region-level spatial moving average
spvcm.both.SMASE # respons... |
1,583 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
xarray with MetPy Tutorial
xarray <http
Step1: Getting Data
While xarray can handle a wide variety of n-dimensional data (essentially anything that can
be stored in a netCDF file), a com... | Python Code:
import cartopy.crs as ccrs
import cartopy.feature as cfeature
import matplotlib.pyplot as plt
import xarray as xr
# Any import of metpy will activate the accessors
import metpy.calc as mpcalc
from metpy.testing import get_test_data
Explanation: xarray with MetPy Tutorial
xarray <http://xarray.pydata.org... |
1,584 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Renaming files based on EXIF info
Digital cameras generally name their files DSC00001.JPG or something silly like that. I prefer that have them named according to the shooting data first, an... | Python Code:
#!wget https://www.dropbox.com/s/-/DSC00005.JPG
#!cp DSC00005.JPG IMAGE.jpg
!cp IMAGE.jpg DSC00005.JPG
!ls -l *.JPG
Explanation: Renaming files based on EXIF info
Digital cameras generally name their files DSC00001.JPG or something silly like that. I prefer that have them named according to the shooting da... |
1,585 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Run the following
Step1: From official website ( http | Python Code:
#Run this from command line
!python -c "import this"
#Inside a python console
import this
Explanation: Run the following:
End of explanation
# execution semantics
for i in range(10):
print i**2
print "Outside for loop"
# dynamic binding
my_str = "hola"
type(my_str)
# dynamic binding
my_str = 90
type(my... |
1,586 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
The follow code is same as before, but you can send the commands all in one go.
However, there are implicit wait for the driver so it can do AJAX request and render the page for elements
al... | Python Code:
# browser = webdriver.Firefox() #I only tested in firefox
# browser.get('http://costcotravel.com/Rental-Cars')
# browser.implicitly_wait(5)#wait for webpage download
# browser.find_element_by_id('pickupLocationTextWidget').send_keys("PHX");
# browser.implicitly_wait(5) #wait for the airport suggestion box ... |
1,587 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Routing Protocol Sessions and Policies
This category of questions reveals information regarding which routing
protocol sessions are compatibly configured and which ones are
established. It ... | Python Code:
bf.set_network('generate_questions')
bf.set_snapshot('generate_questions')
Explanation: Routing Protocol Sessions and Policies
This category of questions reveals information regarding which routing
protocol sessions are compatibly configured and which ones are
established. It also allows to you analyze BG... |
1,588 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Intro to NumPy
This notebook demonstrates the limitations of Python's built-in data types in executing some scientific analyses.
Source
Step1: If we assume body mass index (BMI) = weight / ... | Python Code:
#Create a list of heights and weights
height = [1.73, 1.68, 1.17, 1.89, 1.79]
weight = [65.4, 59.2, 63.6, 88.4, 68.7]
print height
print weight
Explanation: Intro to NumPy
This notebook demonstrates the limitations of Python's built-in data types in executing some scientific analyses.
Source: https://campu... |
1,589 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Gassuain Processes Regression (GPR)
Step1: Single point prediction with GPR
We wont use optimized kernel hyperparameters here and only guess some values and predict the target for a single ... | Python Code:
def get_kernel(X1,X2,sigmaf,l,sigman):
k = lambda x1,x2,sigmaf,l,sigman:(sigmaf**2)*np.exp(-(1/float(2*(l**2)))*np.dot((x1-x2),(x1-x2).T)) + (sigman**2);
K = np.zeros((X1.shape[0],X2.shape[0]))
for i in range(0,X1.shape[0]):
for j in range(0,X2.shape[0]):
if i==j:
... |
1,590 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
A New Hope (for integrating functions)
Names of group members
// put your names here!
Goals of this assignment
The main goal of this assignment is to use https
Step1: Part 2
A torus that is... | Python Code:
# Put your code here!
Explanation: A New Hope (for integrating functions)
Names of group members
// put your names here!
Goals of this assignment
The main goal of this assignment is to use https://en.wikipedia.org/wiki/Monte_Carlo_integration - a technique for numerical integration that uses random number... |
1,591 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Most people find target leakage very tricky until they've thought about it for a long time.
So, before trying to think about leakage in the housing price example, we'll go through a few exam... | Python Code:
# Set up code checking
from learntools.core import binder
binder.bind(globals())
from learntools.ml_intermediate.ex7 import *
print("Setup Complete")
Explanation: Most people find target leakage very tricky until they've thought about it for a long time.
So, before trying to think about leakage in the hous... |
1,592 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: TV Script Generation - Using Tensorboard
In this project, you'll generate your own Simpsons TV scripts using RNNs. You'll be using part of the Simpsons dataset of scripts from 27 sea... | Python Code:
DON'T MODIFY ANYTHING IN THIS CELL
import helper
data_dir = './data/simpsons/moes_tavern_lines.txt'
text = helper.load_data(data_dir)
# Ignore notice, since we don't use it for analysing the data
text = text[81:]
Explanation: TV Script Generation - Using Tensorboard
In this project, you'll generate your ow... |
1,593 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Sveučilište u Zagrebu
Fakultet elektrotehnike i računarstva
Strojno učenje 2018/2019
http
Step1: 1. Probabilistički grafički modeli -- Bayesove mreže
Ovaj zadatak bavit će se Bayesovim mr... | Python Code:
# Učitaj osnovne biblioteke...
import sklearn
import codecs
import mlutils
import matplotlib.pyplot as plt
import pgmpy as pgm
%pylab inline
Explanation: Sveučilište u Zagrebu
Fakultet elektrotehnike i računarstva
Strojno učenje 2018/2019
http://www.fer.unizg.hr/predmet/su
Laboratorijska vježba 5: Probab... |
1,594 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Week 8 - Implementing a model in numpy and a survey of machine learning packages for python
This week we will be looking in detail at how to implement a supervised regression model using the... | Python Code:
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline
n = 20
x = np.random.random((n,1))
y = 5 + 6 * x ** 2 + np.random.normal(0,0.5, size=(n,1))
plt.plot(x, y, 'b.')
plt.show()
Explanation: Week 8 - Implementing a model in numpy and a survey of machine learning packages for python
This wee... |
1,595 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
The data from Kaggle is already here in the "data" folder. Let's take a look at it.
Step1: Naive manual analysis
Obviously a not-so-good algorithm, used primaraly for illustrating IPython
F... | Python Code:
hits_train = pd.read_csv("data/train.csv", index_col='global_id')
hits_train.head()
hits_test = pd.read_csv("data/test.csv", index_col='global_id')
hits_test.head()
Explanation: The data from Kaggle is already here in the "data" folder. Let's take a look at it.
End of explanation
set(hits_train.loc[(hits_t... |
1,596 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Statistics
Step1: Provide one or two visualizations that show the distribution of the sample data. Write one or two sentences noting what you observe about the plot or plots.
Step2: R | Python Code:
%matplotlib inline
import pandas
import matplotlib.pyplot as plt
plt.rcParams['figure.figsize'] = (16.0, 8.0)
df = pandas.read_csv('./stroopdata.csv')
df.describe()
Explanation: Statistics: The Science of Decisions Project Instructions
Background Information
In a Stroop task, participants are presented wit... |
1,597 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Deep Learning
Assignment 1
The objective of this assignment is to learn about simple data curation practices, and familiarize you with some of the data we'll be reusing later.
This notebook ... | 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 imageio
import matplotlib.pyplot as plt
import numpy as np
import os
import sys
import tarfile
from IPython.display import display, Image
from sklearn.li... |
1,598 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Detecting Credit Card Fraud
In this notebook we will use GraphLab Create to identify a large majority of fraud cases in real-world data from an online retailer. Starting by a simple fraud cl... | Python Code:
import graphlab as gl
data = gl.SFrame('fraud_detection.sf')
data.head(3)
len(data)
data.show()
Explanation: Detecting Credit Card Fraud
In this notebook we will use GraphLab Create to identify a large majority of fraud cases in real-world data from an online retailer. Starting by a simple fraud classifier... |
1,599 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Python for Bioinformatics
This Jupyter notebook is intented to be used alongside the book Python for Bioinformatics
Note
Step1: Chapter 12
Step2: Listing 12.1
Step3: Listing 12.2
Step4: ... | Python Code:
!curl https://raw.githubusercontent.com/Serulab/Py4Bio/master/samples/samples.tar.bz2 -o samples.tar.bz2
!mkdir samples
!tar xvfj samples.tar.bz2 -C samples
!wget https://raw.githubusercontent.com/Serulab/Py4Bio/master/code/ch12/PythonU.sql
!apt-get -y install mysql-server
!/etc/init.d/mysql start
!mysql -... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.