Unnamed: 0 int64 0 16k | text_prompt stringlengths 110 62.1k | code_prompt stringlengths 37 152k |
|---|---|---|
2,100 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
US Births dataset - Guided Project <a class="tocSkip">
Guided project from dataquest.io Data Scientist path.
Data provided by fivethirtyeight.
Import data
Step1: Cleanup
Step2: Next steps | Python Code:
from pathlib import Path
my_file = Path('US_births_1994-2003_CDC_NCHS.csv')
if my_file.is_file():
print('File exists.')
data = open('US_births_1994-2003_CDC_NCHS.csv', 'r').read()
data_lst = data.split('\n')
else:
print("File doesn't exist, will be downloaded.")
import urllib.request
... |
2,101 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2018 Google LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the Licens... | Python Code:
import matplotlib.pyplot as plt
import numpy as np
from __future__ import division
from __future__ import print_function
import math
import gym
import pandas as pd
from gym import spaces
from sklearn import neural_network, model_selection
from sklearn.neural_network import MLPClassifier
from third_party im... |
2,102 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Examples and Exercises from Think Stats, 2nd Edition
http
Step1: Again, I'll load the NSFG pregnancy file and select live births
Step2: Here's the histogram of birth weights
Step3: To nor... | Python Code:
from __future__ import print_function, division
%matplotlib inline
import numpy as np
import nsfg
import first
import thinkstats2
import thinkplot
Explanation: Examples and Exercises from Think Stats, 2nd Edition
http://thinkstats2.com
Copyright 2016 Allen B. Downey
MIT License: https://opensource.org/lice... |
2,103 |
Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
Sklearn Classification Metrics
| Python Code::
from sklearn.metrics import classification_report, log_loss, roc_auc_score
print('Classification Report:',classification_report(y_test, y_pred))
print('Log Loss:',log_loss(y_test, y_pred))
print('ROC AUC:',roc_auc_score(y_test, y_pred))
|
2,104 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Este sistema lineal
Step1: Eigenvalores y Eigenvectores
Step2: La matriz b por el vector [y1 y2] es igual a cualquier eigenvalor (e.g. $ -1 + 2i $) por [y1 y2].
$$ \left[\begin{array}{cc}
... | Python Code:
b = symbols('b')
b = Matrix([[1, -4],
[2, -3]])
b
Explanation: Este sistema lineal
End of explanation
b.eigenvects()
Explanation: Eigenvalores y Eigenvectores
End of explanation
y1, y2 = symbols("y1 y2")
solve(((-1 + 2j) * y1) - (y1 - 4 * y2),
y1)
solve(((-1 + 2j) * y2) - (2 * y1 - 3 * y... |
2,105 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Slip on a planar fault in a halfspace
This is the first and simplest example of Tectosaur. Here, we'll solve for the halfspace surface displacement caused by a Gaussian slip field on a plana... | Python Code:
import logging
import numpy as np
import matplotlib.pyplot as plt
import scipy.sparse.linalg as spsla
import okada_wrapper
import tectosaur as tct
tct.logger.setLevel(logging.INFO)
Explanation: Slip on a planar fault in a halfspace
This is the first and simplest example of Tectosaur. Here, we'll solve for ... |
2,106 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Similarity Measures in Multimodal Retrieval
This tutorial assumes an Anaconda 3.x installation with Python 3.6.x. Missing libraries can be installed with conda or pip.
To start with prepared... | Python Code:
%matplotlib inline
import os
import tarfile as TAR
import sys
from datetime import datetime
from PIL import Image
import warnings
import json
import pickle
import zipfile
from math import *
import numpy as np
import pandas as pd
from sklearn.cluster import MiniBatchKMeans
import matplotlib.pyplot as plt
im... |
2,107 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Purpose
The purpose of this notebook is to work out the data structure for saving the computed results for a single session. Here we are using the xarray package to structure the data, becau... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import xarray as xr
from src.data_processing import (get_LFP_dataframe, make_tetrode_dataframe,
make_tetrode_pair_info, reshape_to_segments)
from src.parameters import (ANIMALS, SAM... |
2,108 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Chapter 7 – Ensemble Learning and Random Forests
This notebook contains all the sample code and solutions to the exercises in chapter 7.
Setup
First, let's make sure this notebook works well... | Python Code:
# To support both python 2 and python 3
from __future__ import division, print_function, unicode_literals
# Common imports
import numpy as np
import os
# to make this notebook's output stable across runs
np.random.seed(42)
# To plot pretty figures
%matplotlib inline
import matplotlib
import matplotlib.pypl... |
2,109 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
AGDCv2 Landsat analytics example using USGS Surface Reflectance
Import the required libraries
Step2: Include some helpful functions
Step3: Plot the spatial extent of our data for each prod... | Python Code:
%matplotlib inline
from matplotlib import pyplot as plt
import datacube
from datacube.model import Range
from datetime import datetime
dc = datacube.Datacube(app='dc-example')
from datacube.storage import masking
from datacube.storage.masking import mask_valid_data as mask_invalid_data
import pandas
import... |
2,110 | Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
I am having a problem with minimization procedure. Actually, I could not create a correct objective function for my problem. | Problem:
import scipy.optimize
import numpy as np
np.random.seed(42)
a = np.random.rand(3,5)
x_true = np.array([10, 13, 5, 8, 40])
y = a.dot(x_true ** 2)
x0 = np.array([2, 3, 1, 4, 20])
x_lower_bounds = x_true / 2
def residual_ans(x, a, y):
s = ((y - a.dot(x**2))**2).sum()
return s
bounds = [[x, None] for x in ... |
2,111 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Logistic Regression Classification
Step1: Utility function to create the appropriate data frame for classification algorithms in MLlib
Step2: create the dataframe from a csv
Step3: Classi... | Python Code:
from pyspark.ml.classification import LogisticRegression
from pyspark.ml.evaluation import RegressionEvaluator
from pyspark.ml import Pipeline
from pyspark.mllib.regression import LabeledPoint
from pyspark.ml.linalg import Vectors
from pyspark.ml.feature import StringIndexer
from pyspark.mllib.evaluation i... |
2,112 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Subject Selection Experiments disorder data - Srinivas (handle
Step1: Extracting the samples we are interested in
Step2: Dimensionality reduction
Manifold Techniques
ISOMAP
Step3: Cluster... | Python Code:
# Standard
import pandas as pd
import numpy as np
%matplotlib inline
import matplotlib.pyplot as plt
# Dimensionality reduction and Clustering
from sklearn.decomposition import PCA
from sklearn.cluster import KMeans
from sklearn.cluster import MeanShift, estimate_bandwidth
from sklearn import manifold, dat... |
2,113 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Author
Step1: First let's check if there are new or deleted files (only matching by file names).
Step2: So we have the same set of files in both versions
Step3: Let's make sure the struct... | Python Code:
import collections
import glob
import os
from os import path
import matplotlib_venn
import pandas as pd
rome_path = path.join(os.getenv('DATA_FOLDER'), 'rome/csv')
OLD_VERSION = '338'
NEW_VERSION = '339'
old_version_files = frozenset(glob.glob(rome_path + '/*{}*'.format(OLD_VERSION)))
new_version_files = f... |
2,114 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
"What just happened???"
Here we take an existing modflow model and setup a very complex parameterization system for arrays and boundary conditions. All parameters are setup as multpliers
St... | Python Code:
%matplotlib inline
import os
import platform
import shutil
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import flopy
import pyemu
nam_file = "freyberg.nam"
org_model_ws = "freyberg_sfr_update"
temp_model_ws = "temp"
new_model_ws = "template"
# load the model, change dir and run on... |
2,115 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
SMOGN (0.1.0)
Step1: Dependencies
Next, we load the required dependencies. Here we import smogn to later apply Synthetic Minority Over-Sampling Technique for Regression with Gaussian Noise.... | Python Code:
## suppress install output
%%capture
## install pypi release
# !pip install smogn
## install developer version
!pip install git+https://github.com/nickkunz/smogn.git
Explanation: SMOGN (0.1.0): Usage
Example 2: Intermediate
Installation
First, we install SMOGN from the Github repository. Alternatively, we ... |
2,116 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
DiscreteDP Example
Step1: Setup
Step2: Continuous-state benchmark
Let us compute the value function of the continuous-state version
as described in equations (2.22) and (2.23) in Section 2... | Python Code:
%matplotlib inline
import numpy as np
import itertools
import scipy.optimize
import matplotlib.pyplot as plt
import pandas as pd
from quantecon.markov import DiscreteDP
# matplotlib settings
plt.rcParams['axes.autolimit_mode'] = 'round_numbers'
plt.rcParams['axes.xmargin'] = 0
plt.rcParams['axes.ymargin'] ... |
2,117 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Lecture 20
Step1: L is the LENGTH of our box. You can set this to any value you choose however, appropriate scaling of the problem would admit 1 as the length of choice.
nx is the number o... | Python Code:
%matplotlib osx
from fipy import *
%matplotlib
from fipy import *
Explanation: Lecture 20: Introduction to FiPy - Getting to Know the Diffusion Equation
Objectives:
Understand how to create the diffusion equation in FiPy.
Be able to change variables in the equation and observe the effects in the diffusion ... |
2,118 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Building Histograms with Bayesian Priors
An Introduction to Bayesian Blocks
========
Version 0.1
By LM Walkowicz 2019 June 14
This notebook makes heavy use of Bayesian block implementations ... | Python Code:
# execute this cell
np.random.seed(0)
x = np.concatenate([stats.cauchy(-5, 1.8).rvs(500),
stats.cauchy(-4, 0.8).rvs(2000),
stats.cauchy(-1, 0.3).rvs(500),
stats.cauchy(2, 0.8).rvs(1000),
stats.cauchy(4, 1.5).rvs(500)])
# trunca... |
2,119 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
States
A Riemann Problem is specified by the state of the material to the left and right of the interface. In this hydrodynamic problem, the state is fully determined by an equation of state... | Python Code:
from r3d2 import eos_defns, State
eos = eos_defns.eos_gamma_law(5.0/3.0)
U = State(1.0, 0.1, 0.0, 2.0, eos)
Explanation: States
A Riemann Problem is specified by the state of the material to the left and right of the interface. In this hydrodynamic problem, the state is fully determined by an equation of s... |
2,120 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Outline
Glossary
1. Radio Science using Interferometric Arrays
Previous
Step1: Import section specific modules
Step2: 1.6.1 Synchrotron Emission
Step3: Figure 1.6.1 Example path of a cha... | 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: Outline
Glossary
1. Radio Science using Interferometric Arrays
Previous: 1.5 Black body radiation
Next: 1.7 Line emission
Section status: <span... |
2,121 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Executed
Step1: Load software and filenames definitions
Step2: Data folder
Step3: List of data files
Step4: Data load
Initial loading of the data
Step5: Laser alternation selection
At t... | Python Code:
ph_sel_name = "Dex"
data_id = "22d"
# ph_sel_name = "all-ph"
# data_id = "7d"
Explanation: Executed: Mon Mar 27 11:36:04 2017
Duration: 8 seconds.
usALEX-5samples - Template
This notebook is executed through 8-spots paper analysis.
For a direct execution, uncomment the cell below.
End of explanation
from f... |
2,122 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Benchmarking Performance and Scaling of Python Clustering Algorithms
There are a host of different clustering algorithms and implementations thereof for Python. The performance and scaling c... | Python Code:
import hdbscan
import debacl
import fastcluster
import sklearn.cluster
import scipy.cluster
import sklearn.datasets
import numpy as np
import pandas as pd
import time
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
sns.set_context('poster')
sns.set_palette('Paired', 10)
sns.set_col... |
2,123 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Calculates and plots the NIWA SOI
The NIWA SOI is calculated using the Troup method, where the climatological period is taken to be 1941-2010
Step1: imports
Step2: defines a function to ge... | Python Code:
%matplotlib inline
Explanation: Calculates and plots the NIWA SOI
The NIWA SOI is calculated using the Troup method, where the climatological period is taken to be 1941-2010:
Thus, if T and D are the monthly pressures at Tahiti and Darwin, respectively, and Tc and Dc the climatological monthly pressures, t... |
2,124 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a href="https
Step1: Import packages
Importing the necessary packages, including the standard TFX component classes
Step2: Palmer Penguins example pipeline
Download Example Data
We downlo... | Python Code:
!pip install -U tfx
# getting the code directly from the repo
x = !pwd
if 'feature_selection' not in str(x):
!git clone -b main https://github.com/tensorflow/tfx-addons.git
%cd tfx-addons/tfx_addons/feature_selection
Explanation: <a href="https://colab.research.google.com/github/deutranium/tfx-addons/... |
2,125 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
There are many talks tomorrow at the CSV Conf. I want to cluster the talks
Step1: Document representation
Step2: Preprocess text
Step3: Cluster the talks
I refer to Jörn Hees (2015) to ge... | Python Code:
from bs4 import BeautifulSoup
import requests
import pandas as pd
website_to_parse = "https://csvconf.com/speakers/"
# Save HTML to soup
html_data = requests.get(website_to_parse).text
soup = BeautifulSoup(html_data, "html5lib")
doc = soup.find_all("table", attrs={"class", "speakers"})[1]
names = doc.find_... |
2,126 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Chapter 33. Nonparametric permutation testing
Step1: Figure 33.1
Step2: 33.3
Using the same fig/data as 33.1
Step3: 33.5/6
These are generated in chap 34.
33.8
Step5: 33.9
Rather than do... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
import scipy as sp
from scipy.stats import norm
from scipy.signal import convolve2d
import skimage.measure
Explanation: Chapter 33. Nonparametric permutation testing
End of explanation
x = np.arange(-5,5, .01)
pdf = norm.pdf(x)
data = np.random.randn(1000)... |
2,127 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Reading file
Step1: Syntax
python
str.split(str=" ", num=string.count(str)).
Parameters
str -- This is any delimeter, by default it is space.
num -- this is number of lines to b... | Python Code:
filename='LittleRedRidingHood.txt'
with open(filename) as f:
print f.read()
filename='LittleRedRidingHood.txt'
with open(filename) as f:
for line in f:
print line
Explanation: Reading file
End of explanation
line
line.split(" ")
Explanation: Syntax
python
str.split(str=" ", num=... |
2,128 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Convolutions in JAX
JAX provides a number of interfaces to compute convolutions across data, including
Step1: The mode parameter controls how boundary conditions are treated; here we use mo... | Python Code:
import matplotlib.pyplot as plt
from jax import random
import jax.numpy as jnp
import numpy as np
key = random.PRNGKey(1701)
x = jnp.linspace(0, 10, 500)
y = jnp.sin(x) + 0.2 * random.normal(key, shape=(500,))
window = jnp.ones(10) / 10
y_smooth = jnp.convolve(y, window, mode='same')
plt.plot(x, y, 'lightg... |
2,129 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Gene tree estimation error in sliding windows
What size window is too big such that concatenation washes away the differences among genealogies for MSC-based analyses (i.e., ASTRAL, SNAQ).
S... | Python Code:
import toytree
import ipcoal
import numpy as np
import ipyrad.analysis as ipa
Explanation: Gene tree estimation error in sliding windows
What size window is too big such that concatenation washes away the differences among genealogies for MSC-based analyses (i.e., ASTRAL, SNAQ).
End of explanation
tree = t... |
2,130 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Table of Contents
<p><div class="lev1 toc-item"><a href="#Python-für-Fortgeschrittene-2" data-toc-modified-id="Python-für-Fortgeschrittene-2-1"><span class="toc-item-num">1 </span... | Python Code:
#beispiel
a = [1, 2, 3,]
my_iterator = iter(a)
my_iterator.__next__()
my_iterator.__next__()
Explanation: Table of Contents
<p><div class="lev1 toc-item"><a href="#Python-für-Fortgeschrittene-2" data-toc-modified-id="Python-für-Fortgeschrittene-2-1"><span class="toc-item-num">1 </span>Python für... |
2,131 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
机器学习纳米学位
监督学习
项目2
Step1: 准备数据
在数据能够被作为输入提供给机器学习算法之前,它经常需要被清洗,格式化,和重新组织 - 这通常被叫做预处理。幸运的是,对于这个数据集,没有我们必须处理的无效或丢失的条目,然而,由于某一些特征存在的特性我们必须进行一定的调整。这个预处理都可以极大地帮助我们提升几乎所有的学习算法的结果和预测能力。
获得特征和标签
inco... | Python Code:
# TODO:总的记录数
n_records = len(data)
# # TODO:被调查者 的收入大于$50,000的人数
n_greater_50k = len(data[data.income.str.contains('>50K')])
# # TODO:被调查者的收入最多为$50,000的人数
n_at_most_50k = len(data[data.income.str.contains('<=50K')])
# # TODO:被调查者收入大于$50,000所占的比例
greater_percent = (n_greater_50k / n_records) * 100
# 打印结果
p... |
2,132 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
DefinedAEpTandZ0 media example
Step1: Measurement of two CPWG lines with different lengths
The measurement where performed the 21th March 2017 on a Anritsu MS46524B 20GHz Vector Network Ana... | Python Code:
%load_ext autoreload
%autoreload 2
import skrf as rf
import skrf.mathFunctions as mf
import numpy as np
from numpy import real, log, log10, sum, absolute, pi, sqrt
import matplotlib.pyplot as plt
from matplotlib.ticker import AutoMinorLocator
from scipy.optimize import minimize
rf.stylely()
Explanation: De... |
2,133 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
BigO, Complexity, Time Complexity, Space Complexity, Algorithm Analysis
cf. pp. 40 McDowell, 6th Ed. VI BigO
cf. 2.2. What Is Algorithm Analysis?
Step1: A good basic unit of computation for... | Python Code:
def sumOfN(n):
theSum = 0
for i in range(1,n+1):
theSum = theSum + i
return theSum
print(sumOfN(10))
def foo(tom):
fred = 0
for bill in range(1,tom+1):
barney = bill
fred = fred + barney
return fred
print(foo(10))
import time
def sumOfN2(... |
2,134 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Problem Set 12
First the exercises
Step1: Let us load up a sample dataset.
Step6: Now construct a KNN classifier
Step7: Calculate accuracy on this very small subset.
Step8: Let's time th... | Python Code:
import numpy as np
import pandas as pd
import keras
from keras.datasets import mnist
Explanation: Problem Set 12
First the exercises:
* Let $\mu=\frac{1}{|S|}\sum_{x_i\in S} x_i$ let us expand
\begin{align}
\sum_{x_i\in S} ||x_i-\mu||^2 &=\sum_{x_i\in S}(x_i-\mu)^T(x_i-\mu)\
&= |S|\mu^T\mu+\sum_{x_i\i... |
2,135 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Simulation Runs 3 – 16 based on experiment fits
<div id="toc-wrapper"><h3> Table of Contents </h3><div id="toc" style="max-height
Step1: Run 4
Step2: Run 5
Step3: Run 14
Step4: Run 15
St... | Python Code:
%%writefile simulation_run_3.py
#!/usr/bin/env python
#SBATCH --mem=8000
import subprocess as sp
import os
import sys
jobindex = int(sys.argv[1])
currentindex = -1
mrnafiles = filter(lambda x: x.startswith('yfp'), os.listdir('../annotations/simulations/run3/'))
mrnafiles = ['../annotations/simulations/run3... |
2,136 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
The python Language Reference
CPython -> Python implmentation in C<br>
Python program is read by a parser, input to the parser is a stream of tokens, generated by lexical analyzer.<br>
<ol>
... | Python Code:
def \
quicksort():
pass
Explanation: The python Language Reference
CPython -> Python implmentation in C<br>
Python program is read by a parser, input to the parser is a stream of tokens, generated by lexical analyzer.<br>
<ol>
<li>Logical Lines -> The end of a logical line is represented by NEWLINE</li... |
2,137 |
Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
Using Sklearn RFE to Select Features
| Python Code::
from sklearn.ensemble import RandomForestRegressor
from sklearn.feature_selection import RFE
rf = RandomForestRegressor(random_state=101)
rfe = RFE(rf, n_features_to_select=8)
rfe = rfe.fit(X_train, y_train)
predictions = rfe.predict(X_test)
#Print feature rankings
feature_rankings = pd.DataFrame({'featur... |
2,138 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Evaluation des modèles pour l'extraction supercritique
L'extraction supercritique est de plus en plus utilisée afin de retirer des matières organiques de différents liquides ou matrices soli... | Python Code:
import numpy as np
from scipy import integrate
from matplotlib.pylab import *
Explanation: Evaluation des modèles pour l'extraction supercritique
L'extraction supercritique est de plus en plus utilisée afin de retirer des matières organiques de différents liquides ou matrices solides. Cela est dû au fait q... |
2,139 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Title
Step1: Load Iris Data
Step2: Create Random Forest Classifier
Step3: Train Random Forest Classifier
Step4: Predict Previously Unseen Observation | Python Code:
# Load libraries
from sklearn.ensemble import RandomForestClassifier
from sklearn import datasets
Explanation: Title: Random Forest Classifier
Slug: random_forest_classifier
Summary: Training a random forest classifier in scikit-learn.
Date: 2017-09-21 12:00
Category: Machine Learning
Tags: Trees And Fores... |
2,140 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Working with Multidimensional Coordinates
Author
Step1: As an example, consider this dataset from the xarray-data repository.
Step2: In this example, the logical coordinates are x and y, w... | Python Code:
%matplotlib inline
import numpy as np
import pandas as pd
import xarray as xr
import cartopy.crs as ccrs
from matplotlib import pyplot as plt
Explanation: Working with Multidimensional Coordinates
Author: Ryan Abernathey
Many datasets have physical coordinates which differ from their logical coordinates. X... |
2,141 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Network Traffic Forecasting (using time series data)
In telco, accurately forecasting KPIs (e.g. network traffic, utilizations, user experience, etc.) for communication networks ( 2G/... | Python Code:
import warnings
warnings.filterwarnings('ignore')
import matplotlib.pyplot as plt
%matplotlib inline
def plot_predict_actual_values(date, y_pred, y_test, ylabel):
plot the predicted values and actual values (for the test data)
fig, axs = plt.subplots(figsize=(12,5))
axs.plot(date, y_p... |
2,142 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Harvesting WMS into CKAN
This notebook illustrates harvesting of a WMS endpoint into a CKAN instance.
Context
The harvested WMS endpoint belongs to Landgate's Spatial Land Information Progra... | Python Code:
import ckanapi
from harvest_helpers import *
from secret import CKAN, SOURCES
## enable one of:
#ckan = ckanapi.RemoteCKAN(CKAN["ct"]["url"], apikey=CKAN["ct"]["key"])
#ckan = ckanapi.RemoteCKAN(CKAN["ca"]["url"], apikey=CKAN["ca"]["key"])
ckan = ckanapi.RemoteCKAN(CKAN["cb"]["url"], apikey=CKAN["cb"]["key... |
2,143 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Sentiment Analysis with an RNN
In this notebook, you'll implement a recurrent neural network that performs sentiment analysis. Using an RNN rather than a feedfoward network is more accurate ... | Python Code:
import numpy as np
import tensorflow as tf
with open('../sentiment-network/reviews.txt', 'r') as f:
reviews = f.read()
with open('../sentiment-network/labels.txt', 'r') as f:
labels = f.read()
reviews[:2000]
Explanation: Sentiment Analysis with an RNN
In this notebook, you'll implement a recurrent ... |
2,144 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Homework assignment #3
These problem sets focus on using the Beautiful Soup library to scrape web pages.
Problem Set #1
Step1: Now, in the cell below, use Beautiful Soup to write an express... | Python Code:
!pip3 install bs4
from bs4 import BeautifulSoup
from urllib.request import urlopen
html_str = urlopen("http://static.decontextualize.com/widgets2016.html").read()
document = BeautifulSoup(html_str, "html.parser")
Explanation: Homework assignment #3
These problem sets focus on using the Beautiful Soup libra... |
2,145 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Pandana demo
Sam Maurer, July 2020
This notebook demonstrates the main features of the Pandana library, a Python package for network analysis that uses contraction hierarchies to calculate s... | Python Code:
import numpy as np
import pandas as pd
import pandana
print(pandana.__version__)
Explanation: Pandana demo
Sam Maurer, July 2020
This notebook demonstrates the main features of the Pandana library, a Python package for network analysis that uses contraction hierarchies to calculate super-fast travel access... |
2,146 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Chapter 7 – Ensemble Learning and Random Forests
This notebook contains all the sample code and solutions to the exercises in chapter 7.
<table align="left">
<td>
<a target="_blank" hr... | Python Code:
# To support both python 2 and python 3
from __future__ import division, print_function, unicode_literals
# Common imports
import numpy as np
import os
# to make this notebook's output stable across runs
np.random.seed(42)
# To plot pretty figures
%matplotlib inline
import matplotlib as mpl
import matplotl... |
2,147 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Post-processing Examples
This notebook provides some examples for using the post-processing features in RESSPyLab.
Automatic table generation and calculation of the consistency metric $\xi_2... | Python Code:
# First load RESSPyLab and necessary packages
import numpy as np
import RESSPyLab as rpl
Explanation: Post-processing Examples
This notebook provides some examples for using the post-processing features in RESSPyLab.
Automatic table generation and calculation of the consistency metric $\xi_2$ are shown for... |
2,148 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Define and Preview Sets
Step1: Define Metric
Also, show values
Step2: Clip and compare
We are going to create a comparison object which contains sets that are proper subsets of the origina... | Python Code:
num_samples_left = 50
num_samples_right = 50
delta = 0.5 # width of measure's support per dimension
L = unit_center_set(2, num_samples_left, delta)
R = unit_center_set(2, num_samples_right, delta)
plt.scatter(L._values[:,0], L._values[:,1], c=L._probabilities)
plt.xlim([0,1])
plt.ylim([0,1])
plt.show()
plt... |
2,149 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Using Sylbreak in Jupyter Notebook
ဒီ Jupyter Notebook က GitHub မှာ ကျွန်တော်တင်ပေးထားတဲ့ Sylbreak Python ပရိုဂရမ် https
Step2: စိတ်ထဲမှာ ပေါ်လာတာကို ကောက်ရေးပြီးတော့ syllable segmentation ... | Python Code:
# Regular Expression Python Library ကို သုံးလို့ရအောင် import လုပ်တာ
import re
# စာလုံးတွေကို အုပ်စုဖွဲ့တာ (သို့) variable declaration လုပ်တာ
# တကယ်လို့ syllable break လုပ်တဲ့ အခါမှာ မြန်မာစာလုံးချည်းပဲ သပ်သပ် လုပ်ချင်တာဆိုရင် enChar က မလိုပါဘူး
myConsonant = "က-အ"
enChar = "a-zA-Z0-9"
otherChar = "ဣဤဥဦဧဩဪ... |
2,150 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Misc Advance Topics
copy — Duplicate Objects
Shallow Copies
The shallow copy created by copy() is a new container populated with references to the contents of the original object. When makin... | Python Code:
import copy
class MyTry:
def __init__(self):
self.lst = [1,2,3,4,5]
a = MyTry()
dup = copy.copy(a)
a.lst.append(6)
print(a.lst, dup.lst)
print(id(a), id(dup))
import copy
class MyTry:
def __init__(self):
self.lst = [1,2,3,4,5]
a = MyTry()
dup = copy.copy(a)
a.lst.append(6)
print(a... |
2,151 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
LAB 4c
Step1: Verify CSV files exist
In the seventh lab of this series 4a_sample_babyweight, we sampled from BigQuery our train, eval, and test CSV files. Verify that they exist, otherwise ... | Python Code:
import datetime
import os
import shutil
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
print(tf.__version__)
Explanation: LAB 4c: Create Keras Wide and Deep model.
Learning Objectives
Set CSV Columns, label column, and column defaults
Make dataset of features and label from CSV... |
2,152 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
The Schilling distribution in CorMap
András Wacha
27th Oct. 2016.
Initialization
Step6: Definition of the algorithms
Algorithms according Schilling's paper
I have implemented these in Cytho... | Python Code:
%pylab inline
%load_ext cython
import time
import ipy_table
import numpy as np
import matplotlib.pyplot as plt
Explanation: The Schilling distribution in CorMap
András Wacha
27th Oct. 2016.
Initialization
End of explanation
%%cython
cimport numpy as np
import numpy as np
np.import_array()
cdef Py_ssize_t A... |
2,153 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Iteradores
Una de las cosas más maravillosas de las compus es que podemos repetir un mismo cálculo para muchos valores de forma automática. Ya hemos visto al menos un iterator (iterador), qu... | Python Code:
for i in range(10):
print(i, end=' ')
Explanation: Iteradores
Una de las cosas más maravillosas de las compus es que podemos repetir un mismo cálculo para muchos valores de forma automática. Ya hemos visto al menos un iterator (iterador), que no es una lista... es otro objeto.
End of explanation
for va... |
2,154 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
신경망 성능 개선
신경망의 예측 성능 및 수렴 성능을 개선하기 위해서는 다음과 같은 추가적인 고려를 해야 한다.
오차(목적) 함수 개선
Step1: 교차 엔트로피 오차 함수 (Cross-Entropy Cost Function)
이러한 수렴 속도 문제를 해결하는 방법의 하나는 오차 제곱합 형태가 아닌 교차 엔트로피(Cross-Entropy... | Python Code:
sigmoid = lambda x: 1/(1+np.exp(-x))
sigmoid_prime = lambda x: sigmoid(x)*(1-sigmoid(x))
xx = np.linspace(-10, 10, 1000)
plt.plot(xx, sigmoid(xx));
plt.plot(xx, sigmoid_prime(xx));
Explanation: 신경망 성능 개선
신경망의 예측 성능 및 수렴 성능을 개선하기 위해서는 다음과 같은 추가적인 고려를 해야 한다.
오차(목적) 함수 개선: cross-entropy cost function
정규화: reg... |
2,155 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
The Boston Light Swim temperature analysis with Python
In the past we demonstrated how to perform a CSW catalog search with OWSLib,
and how to obtain near real-time data with pyoos.
In this ... | Python Code:
import warnings
# Suppresing warnings for a "pretty output."
warnings.simplefilter("ignore")
Explanation: The Boston Light Swim temperature analysis with Python
In the past we demonstrated how to perform a CSW catalog search with OWSLib,
and how to obtain near real-time data with pyoos.
In this notebook we... |
2,156 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Example 7
Step1: Part 1
Step2: Now we will do the timing analysis as well as print out the critical path
Step3: We are also able to print out the critical paths as well as get them
back a... | Python Code:
import pyrtl
Explanation: Example 7: Reduction and Speed Analysis
After building a circuit, one might want to do some stuff to reduce the
hardware into simpler nets as well as analyze various metrics of the
hardware. This functionality is provided in the Passes part of PyRTL
and will demonstrated here.
End... |
2,157 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Demo of Max-value Entropy Search Acqusition
This notebook provides a demo of the max-value entropy search (MES) acquisition function of Wang et al [2017].
https
Step1: Set up our toy proble... | Python Code:
### General imports
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import colors as mcolors
import GPy
import time
### Emukit imports
from emukit.test_functions import forrester_function
from emukit.core.loop.user_function import UserFunctionWrapper
from emukit.core i... |
2,158 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2019 The TensorFlow Probability Authors.
Licensed under the Apache License, Version 2.0 (the "License");
Step1: Bayesian Switchpoint Analysis
<table class="tfo-notebook-buttons" a... | Python Code:
#@title Licensed under the Apache License, Version 2.0 (the "License"); { display-mode: "form" }
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in... |
2,159 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Probability Calibration with SplineCalib
This workbook demonstrates the SplineCalib algorithm detailed in the paper
"Spline-Based Probability Calibration" https
Step1: In the next few cells... | Python Code:
# "pip install ml_insights" in terminal if needed
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import ml_insights as mli
%matplotlib inline
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import log_loss... |
2,160 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Some Multiplicative Functionals
Daisuke Oyama, Thomas J. Sargent and John Stachurski
Step1: Plan of the notebook
In other quant-econ lectures
("Markov Asset Pricing" and
"The Lucas Asset Pr... | Python Code:
%matplotlib inline
import itertools
import numpy as np
import matplotlib.pyplot as plt
from quantecon.markov import tauchen, MarkovChain
from mult_functional import MultFunctionalFiniteMarkov
from asset_pricing_mult_functional import (
AssetPricingMultFiniteMarkov, LucasTreeFiniteMarkov
)
Explanation: ... |
2,161 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a href='http
Step1: Get the Data
Step2: Now let's get the movie titles
Step3: We can merge them together
Step4: EDA
Let's explore the data a bit and get a look at some of the best rated... | Python Code:
import numpy as np
import pandas as pd
Explanation: <a href='http://www.pieriandata.com'> <img src='../Pierian_Data_Logo.png' /></a>
Recommender Systems with Python
Welcome to the code notebook for Recommender Systems with Python. In this lecture we will develop basic recommendation systems using Python an... |
2,162 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Interactive Geovisualization of Multimodal Freight Transport Network Criticality
Bramka Arga Jafino
Delft University of Technology
Faculty of Technology, Policy and Management
An introductio... | Python Code:
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
from mpld3 import plugins, utils
import geopandas as gp
import pandas as pd
from shapely.wkt import loads
import os
import sys
module_path = os.path.abspath(os.path.join('..'))
if module_path not in sys.path:
sys.path.append(module_p... |
2,163 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Sufficient statistics for online linear regression
First, I need to recreate the data generating function from here in Python. See the code for plot_xy, plot_abline, and SimpleOnlineLinearRe... | Python Code:
%matplotlib inline
import numpy as np
from scipy import stats
import matplotlib.pyplot as plt
import pandas as pd
from linreg import *
np.random.seed(2016)
def make_data(N):
X = np.linspace(0, 20, N)
Y = stats.norm.rvs(size=N, loc=-1.5*X + X*X/9, scale=2)
return X, Y
X, Y = make_data(21)
print(... |
2,164 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Stochastic optimization landscape of a minimal MLP
In this notebook, we will try to better understand how stochastic gradient works. We fit a very simple non-convex model to data generated f... | Python Code:
import matplotlib.pyplot as plt
import numpy as np
import torch
import torch.nn as nn
from torch.nn import Parameter
from torch.nn.functional import mse_loss
from torch.autograd import Variable
from torch.nn.functional import relu
Explanation: Stochastic optimization landscape of a minimal MLP
In this note... |
2,165 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Python II
Wiederholung
Step1: 2 Viel mächtigere Funktion
Step2: 3 Aber wie sind Funktion, Modules und Libraries aufgebaut?
Step3: 4 Bauen wir die eigenen Funktion
Bauen wir ganze Sätze, a... | Python Code:
lst = [11,2,34, 4,5,5111]
len(lst)
len([11,2,'sort',4,5,5111])
sorted(lst)
lst
lst.sort()
lst
min(lst)
max(lst)
str(1212)
sum([1,2,2])
lst
lst.remove(4)
lst.append(4)
string = 'hello, wie geht, es Dir?'
string.split(',')
Explanation: Python II
Wiederholung: die wichtigsten Funktion
Viel mächtigere Funktion... |
2,166 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Class 27 - Boolean Networks
Step1: Define a function hamming.dist that gives the hamming distance between two states of the Boolean network (as numpy arrays of ones and zeroes)
Step2: Defi... | Python Code:
import numpy
nodes = ['Cell Size',
'Cln3',
'MBF',
'Clb5,6',
'Mcm1/SFF',
'Swi5',
'Sic1',
'Clb1,2',
'Cdc20&Cdc14',
'Cdh1',
'Cln1,2',
'SBF']
N = len(nodes)
# define the transition matrix
a = numpy.ze... |
2,167 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Dark Energy Spectroscopic Instrument
Some calculations to assist with building the DESI model from an existing ZEMAX model and other sources.
You can safely ignore this if you just want to u... | Python Code:
import batoid
import numpy as np
import yaml
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
%matplotlib inline
Explanation: Dark Energy Spectroscopic Instrument
Some calculations to assist with building the DESI model from an existing ZEMAX model and other sources.
You can safely i... |
2,168 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<img src="../Pierian-Data-Logo.PNG">
<br>
<strong><center>Copyright 2019. Created by Jose Marcial Portilla.</center></strong>
CNN on Custom Images
For this exercise we're using a collection ... | Python Code:
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import DataLoader
from torchvision import datasets, transforms, models # add models to the list
from torchvision.utils import make_grid
import os
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%... |
2,169 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Alternate PowerShell Hosts
Metadata
| Metadata | Value |
|
Step1: Download & Process Security Dataset
Step2: Analytic I
Within the classic PowerShell log, event ID 400 indicates... | Python Code:
from openhunt.mordorutils import *
spark = get_spark()
Explanation: Alternate PowerShell Hosts
Metadata
| Metadata | Value |
|:------------------|:---|
| collaborators | ['@Cyb3rWard0g', '@Cyb3rPandaH'] |
| creation date | 2019/08/15 |
| modification date | 2020/09/20 |
| playbook relate... |
2,170 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Chapter 10
Lists
A sequence of elements of any type.
Step1: Lists are mutable while strings are immutable. We can never change a string, only reassign it to something else.
Step2: Some com... | Python Code:
L = [1,2,3]
M = ['a', 'b', 'c']
N = [1, 'a', 2, [32, 64]]
Explanation: Chapter 10
Lists
A sequence of elements of any type.
End of explanation
S = 'abc'
#S[1] = 'z' # <== Doesn't work!
L = ['a', 'b', 'c']
L[1] = 'z'
print L
Explanation: Lists are mutable while strings are immutable. We can never change a s... |
2,171 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Encontro 02, Parte 1
Step1: Configurando a biblioteca
A socnet disponibiliza variáveis de módulo que permitem configurar propriedades visuais. Os nomes são auto-explicativos e os valores ab... | Python Code:
import sys
sys.path.append('..')
import socnet as sn
Explanation: Encontro 02, Parte 1: Revisão de Grafos
Este guia foi escrito para ajudar você a atingir os seguintes objetivos:
formalizar conceitos básicos de teoria dos grafos;
usar funcionalidades básicas da biblioteca da disciplina.
Grafos não-dirigido... |
2,172 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
EventVestor
Step1: Let's go over the columns
Step2: Finally, suppose we want the above as a DataFrame | Python Code:
# import the dataset
from quantopian.interactive.data.eventvestor import contract_win
# or if you want to import the free dataset, use:
# from quantopian.data.eventvestor import contract_win_free
# import data operations
from odo import odo
# import other libraries we will use
import pandas as pd
# Let's u... |
2,173 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Theory and Practice of Visualization Exercise 1
Imports
Step1: Graphical excellence and integrity
Find a data-focused visualization on one of the following websites that is a positive examp... | Python Code:
from IPython.display import Image
Explanation: Theory and Practice of Visualization Exercise 1
Imports
End of explanation
# Add your filename and uncomment the following line:
Image(filename='alcohol-consumption-by-country-pure-alcohol-consumption-per-drinker-2010_chartbuilder-1.png')
Explanation: Graphica... |
2,174 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
T81-558
Step1: Toolkit
Step2: Binary Classification
Binary classification is used to create a model that classifies between only two classes. These two classes are often called "positive"... | Python Code:
from sklearn import preprocessing
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
# Encode text values to dummy variables(i.e. [1,0,0],[0,1,0],[0,0,1] for red,green,blue)
def encode_text_dummy(df,name):
dummies = pd.get_dummies(df[name])
for x in dummies.columns:
dumm... |
2,175 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Computing covariance matrix
Step1: Source estimation method such as MNE require a noise estimations from the
recordings. In this tutorial we cover the basics of noise covariance and
constru... | Python Code:
import os.path as op
import mne
from mne.datasets import sample
Explanation: Computing covariance matrix
End of explanation
data_path = sample.data_path()
raw_empty_room_fname = op.join(
data_path, 'MEG', 'sample', 'ernoise_raw.fif')
raw_empty_room = mne.io.read_raw_fif(raw_empty_room_fname, add_eeg_re... |
2,176 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
A Simple Autoencoder
We'll start off by building a simple autoencoder to compress the MNIST dataset. With autoencoders, we pass input data through an encoder that makes a compressed represen... | 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)
Explanation: A Simple Autoencoder
We'll start off by building a simple autoencoder to c... |
2,177 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Histogram of one column by binning on another continuous
Step1: Lets create a data frame of a column made up of 1's and 0's and another categorical column.
Step2: Now, lets create histogra... | Python Code:
%pylab inline
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
Explanation: Histogram of one column by binning on another continuous
End of explanation
# Class label would be categorical variable derived from binning the continuous column
x = ['Class1']*300 + ['Class2']*400 + ['Class3... |
2,178 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
TensorFlow Data Validation (Advanced)
Learning Objectives
Install TFDV
Compute and visualize statistics
Infer a schema
Check evaluation data for errors
Check for evaluation anomalies and fix... | Python Code:
!pip install pyarrow==5.0.0
!pip install numpy==1.19.2
!pip install tensorflow-data-validation
Explanation: TensorFlow Data Validation (Advanced)
Learning Objectives
Install TFDV
Compute and visualize statistics
Infer a schema
Check evaluation data for errors
Check for evaluation anomalies and fix it
Check... |
2,179 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Departamento de Física - Faculdade de Ciências e Tecnologia da Universidade de Coimbra
Física Computacional - Ficha 3 - Integração e Diferenciação Numérica
Rafael Isaque Santos - 2012144694 ... | Python Code:
from numpy import sin, cos, tan, pi, e, exp, log, copy, linspace
from numpy.polynomial.legendre import leggauss
n_list = [2, 4, 8, 10, 20, 30, 50, 100]
Explanation: Departamento de Física - Faculdade de Ciências e Tecnologia da Universidade de Coimbra
Física Computacional - Ficha 3 - Integração e Diferenci... |
2,180 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2020 The OpenFermion Developers
Step1: Circuits 1
Step2: Background
Second quantized fermionic operators
In order to represent fermionic systems on a quantum computer one must fi... | 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... |
2,181 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
我们的任务
垃圾邮件检测是机器学习在现今互联网领域的主要应用之一。几乎所有大型电子邮箱服务提供商都内置了垃圾邮件检测系统,能够自动将此类邮件分类为“垃圾邮件”。
在此项目中,我们将使用朴素贝叶斯算法创建一个模型,该模型会通过我们对模型的训练将信息数据集分类为垃圾信息或非垃圾信息。对垃圾文本信息进行大致了解十分重要。通常它们都包含“免费”、“赢取”、“获奖者”、“现金”、“奖品... | Python Code:
'''
Solution
'''
import pandas as pd
# Dataset from - https://archive.ics.uci.edu/ml/datasets/SMS+Spam+Collection
df = pd.read_table("smsspamcollection/SMSSpamCollection", sep="\t",names = ['label', 'sms_message'] )
# Output printing out first 5 columns
df.head()
Explanation: 我们的任务
垃圾邮件检测是机器学习在现今互联网领域的主要应用... |
2,182 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<center><u><u>Bayesian Modeling for the Busy and the Confused - Part II</u></u></center>
<center><i>Markov Chain Monte-Carlo</i><center>
Currently, the capacity to gather data is far ahead o... | Python Code:
import pickle
import warnings
import sys
from IPython.display import Image, HTML
import pandas as pd
import numpy as np
from scipy.stats import norm as gaussian, uniform
import pymc3 as pm
from theano import shared
import seaborn as sb
import matplotlib.pyplot as pl
from matplotlib import rcParams
from mat... |
2,183 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Content under Creative Commons Attribution license CC-BY 4.0, code under BSD 3-Clause License © 2018 D. Koehn, notebook style sheet by L.A. Barba, N.C. Clementi
Step1: Mesh generation by Tr... | Python Code:
# Execute this cell to load the notebook's style sheet, then ignore it
from IPython.core.display import HTML
css_file = '../style/custom.css'
HTML(open(css_file, "r").read())
Explanation: Content under Creative Commons Attribution license CC-BY 4.0, code under BSD 3-Clause License © 2018 D. Koehn, notebook... |
2,184 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Does age correlate with motion?
This has been bothering me for so many of our slack chats that I felt I really needed to start here.
What do we know about motion in our sample!?
Step1: Get ... | Python Code:
import matplotlib.pylab as plt
%matplotlib inline
import numpy as np
import os
import pandas as pd
import seaborn as sns
sns.set_style('white')
sns.set_context('notebook')
from scipy.stats import kurtosis
import sys
%load_ext autoreload
%autoreload 2
sys.path.append('../SCRIPTS/')
import kidsmotion_stats a... |
2,185 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
What about writing SVG inside a cell in IPython or Jupyter
Step1: let's create a very simple SVG file
Step2: Now let's create a Svg Scene based
inspired from Isendrak Skatasmid code at | Python Code:
%config InlineBackend.figure_format = 'svg'
url_svg = 'http://clipartist.net/social/clipartist.net/B/base_tux_g_v_linux.svg'
from IPython.display import SVG, display, HTML
# testing svg inside jupyter next one does not support width parameter at the time of writing
#display(SVG(url=url_svg))
display(HTML('... |
2,186 | 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 tabular binary classification model for online predicti... |
2,187 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a href="https
Step1: Functions
Helper functions which will be used later
Step2: Dataset
Now, we will create the dataset. we sample theta_true (probability of occurring head) random variab... | Python Code:
try:
import jax
except ModuleNotFoundError:
%pip install -qqq jax jaxlib
import jax
import jax.numpy as jnp
from jax import lax
try:
from tensorflow_probability.substrates import jax as tfp
except ModuleNotFoundError:
%pip install -qqq tensorflow_probability
from tensorflow_probabil... |
2,188 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introduction to Survival Analysis with scikit-survival
scikit-survival is a Python module for survival analysis built on top of scikit-learn. It allows doing survival analysis while utilizin... | Python Code:
from sksurv.datasets import load_veterans_lung_cancer
data_x, data_y = load_veterans_lung_cancer()
data_y
Explanation: Introduction to Survival Analysis with scikit-survival
scikit-survival is a Python module for survival analysis built on top of scikit-learn. It allows doing survival analysis while utiliz... |
2,189 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<font color='blue'>Data Science Academy - Python Fundamentos - Capítulo 2</font>
Download
Step1: Variáveis e Operadores
Step2: Declaração Múltipla
Step3: Pode-se usar letras, números e un... | Python Code:
# Versão da Linguagem Python
from platform import python_version
print('Versão da Linguagem Python Usada Neste Jupyter Notebook:', python_version())
Explanation: <font color='blue'>Data Science Academy - Python Fundamentos - Capítulo 2</font>
Download: http://github.com/dsacademybr
End of explanation
# Atr... |
2,190 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
EDP Elípticas con Diferencias Finitas
Recordemos que una ecuación diferencial parcial o EDP (PDE en inglés) es una ecuación que involucra funciones en dos o más variables y sus derivadas par... | Python Code:
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.mlab import griddata
m, n = 10, 4
xl, xr = (0.0, 1.0)
yb, yt = (0.0, 1.0)
h = (xr - xl) / (m - 1.0)
k = (yt - yb) / (n - 1.0)
xx = [xl + (i - 1)*h for i in range(1, m+1)]
yy = [yb + (i - 1)*k for i in range(1, n+1)]
plt.f... |
2,191 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Missing Data
pandas uses np.nan to represent missing data. By default, it is not included in computations.
documentation
Step1: reindex() creates a copy (not a view)
Step2: drop rows that ... | Python Code:
browser_index = ['Firefox', 'Chrome', 'Safari', 'IE10', 'Konqueror']
browser_df = pd.DataFrame({
'http_status': [200,200,404,404,301],
'response_time': [0.04, 0.02, 0.07, 0.08, 1.0]},
index=browser_index)
browser_df
Explanation: Missing Data
pandas uses np.nan to represent missing data. ... |
2,192 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Slightly more advanced notebook that fits the restaurants revenue data sets using RFR with a grid optimal parameters searching
Import libraries and prepare the data
Step1: Grid search the p... | Python Code:
## Similar to Regressors_simple...
import pandas as pd
import numpy as np
import csv as csv
from datetime import datetime
from sklearn.ensemble import RandomForestRegressor
from sklearn.preprocessing import LabelEncoder
import scipy as sp
import re
import sklearn
from sklearn.cross_validation import trai... |
2,193 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Construct data and experiments directorys from environment variables
Step1: Specify main run parameters
Step2: Load data and normalise inputs
Step3: Specify prior parameters (data depende... | Python Code:
data_dir = os.path.join(os.environ['DATA_DIR'], 'uci')
exp_dir = os.path.join(os.environ['EXP_DIR'], 'apm_mcmc')
Explanation: Construct data and experiments directorys from environment variables
End of explanation
data_set = 'pima'
method = 'apm(ess+rdss)'
n_chain = 10
chain_offset = 0
seeds = np.random.ra... |
2,194 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Compute source power spectral density (PSD) in a label
Returns an STC file containing the PSD (in dB) of each of the sources
within a label.
Step1: Set parameters
Step2: View PSD of source... | Python Code:
# Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr>
#
# License: BSD-3-Clause
import matplotlib.pyplot as plt
import mne
from mne import io
from mne.datasets import sample
from mne.minimum_norm import read_inverse_operator, compute_source_psd
print(__doc__)
Explanation: Compute source power spectra... |
2,195 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2019 The TensorFlow Authors.
Step1: 使用分布策略保存和加载模型
<table class="tfo-notebook-buttons" align="left">
<td><a target="_blank" href="https
Step2: 使用 tf.distribute.Strategy 准备数据和模型:... | 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... |
2,196 | 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
%matplotlib inline
plt.rcParams['figure.figsize'] = (10.0, 8.0) # set default size of plots
plt.rcParams['image.interpolation'] = 'nearest'
plt.rcParams['image.cmap'] = 'gray'
# for aut... |
2,197 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
This notebook uses mvncall to phase two multiallelic SNPs within VGSC and to add back in the insecticide resistance linked N1570Y SNP filtered out of the PASS callset.
Step1: install mvncal... | Python Code:
%run setup.ipynb
Explanation: This notebook uses mvncall to phase two multiallelic SNPs within VGSC and to add back in the insecticide resistance linked N1570Y SNP filtered out of the PASS callset.
End of explanation
%%bash --err install_err --out install_out
# This script downloads and installs mvncall. W... |
2,198 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Read data
Step1: Add features
Step2: Feature pdfs
Step3: One versus One
Prepare datasets
Step4: Prepare stacking variables
Step5: Multiclassification | Python Code:
treename = 'tag'
data_b = pandas.DataFrame(root_numpy.root2array('datasets/type=5.root', treename=treename)).dropna()
data_b = data_b[::40]
data_c = pandas.DataFrame(root_numpy.root2array('datasets/type=4.root', treename=treename)).dropna()
data_light = pandas.DataFrame(root_numpy.root2array('datasets/type... |
2,199 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Setup data
We're going to look at the IMDB dataset, which contains movie reviews from IMDB, along with their sentiment. Keras comes with some helpers for this dataset.
Step1: This is the wo... | Python Code:
from keras.datasets import imdb
idx = imdb.get_word_index()
Explanation: Setup data
We're going to look at the IMDB dataset, which contains movie reviews from IMDB, along with their sentiment. Keras comes with some helpers for this dataset.
End of explanation
idx_arr = sorted(idx, key=idx.get)
idx_arr[:10]... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.