Unnamed: 0 int64 0 16k | text_prompt stringlengths 110 62.1k | code_prompt stringlengths 37 152k |
|---|---|---|
3,500 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Convolutional Neural Network
In this second exercise-notebook we will play with Convolutional Neural Network (CNN).
As you should have seen, a CNN is a feed-forward neural network tipically... | Python Code:
from keras.datasets import cifar10
from keras.utils import np_utils
(X_train, y_train), (X_test, y_test) = cifar10.load_data()
Y_train = np_utils.to_categorical(y_train, nb_classes)
Y_test = np_utils.to_categorical(y_test, nb_classes)
X_train = X_train.astype("float32")
X_test = X_test.astype("float32")
X_... |
3,501 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
PREPROCESSING
Clean article collection
Step2: Save article information in a table
Step3: Remove short (usually advertisements), Guardian (British news), Stack of Stuff (list of links), and... | Python Code:
from sqlalchemy import create_engine
from sqlalchemy_utils import database_exists, create_database
import psycopg2
import newspaper
from datetime import datetime
import pickle
import pandas as pd
import numpy as np
with open ("bubble_popper_postgres.txt","r") as myfile:
lines = [line.replace("\n","") f... |
3,502 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Licensed under the Apache License, Version 2.0 (the "License");
Step1: Read the Human Proteome
Step3: LysC digestion
Step4: Generate binder sets
Step5: A binder set is chosen randomly an... | Python Code:
import collections
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import numpy as np
Explanation: Licensed under the Apache License, Version 2.0 (the "License");
End of explanation
# Download from uniprot: https://www.uniprot.org/help/human_proteome
!wget -O uniprot.fasta "https:... |
3,503 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Depth First Search
The function search take three arguments to solve a search problem
Step1: The function dfs takes five arguments to solve a search problem
- state is a state of the search... | Python Code:
def search(start, goal, next_states):
return dfs(start, goal, next_states, [start], { start })
Explanation: Depth First Search
The function search take three arguments to solve a search problem:
- start is the start state of the search problem,
- goal is the goal state, and
- next_states is a function ... |
3,504 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<h1 style="text-decoration
Step1: Sur le schéma ci-dessus, le nombre de capteurs est de 6 (les capteurs situés devant le robot E-Puck), pour avoir une plus grande utilité des DNF, nous avon... | Python Code:
x = np.array([1, 2, 3, 4, 5, 6])
ir = np.array([0.000000000000000000e+00,
0.000000000000000000e+00,
6.056077528688350031e-03,
8.428876313973869550e-03,
0.000000000000000000e+00,
0.000000000000000000e+00])
ir=ir*100
dnf = np.array([-1.090321063995361328e+00,
-6.263688206672668457e-01,
2.505307266418066447e-... |
3,505 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Minimal Example
Step1: Create fake "observations"
Step2: Create a New System
Step3: Add GPs
See the API docs for b.add_gaussian_process and gaussian_process.
Note that the original Figure... | Python Code:
#!pip install -I "phoebe>=2.4,<2.5"
import matplotlib.pyplot as plt
plt.rc('font', family='serif', size=14, serif='STIXGeneral')
plt.rc('mathtext', fontset='stix')
import phoebe
import numpy as np
logger = phoebe.logger('warning')
# we'll set the random seed so that the noise model is reproducible
np.rando... |
3,506 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Jupyter Notebook desenvolvido por Gustavo S.S.
"Na ciência, o crédito vai para o homem que convence o mundo,
não para o que primeiro teve a ideia" - Francis Darwin
Capacitores e Indutores
Co... | Python Code:
print("Exemplo 6.1")
C = 3*(10**(-12))
V = 20
q = C*V
print("Carga armazenada:",q,"C")
w = q**2/(2*C)
print("Energia armazenada:",w,"J")
Explanation: Jupyter Notebook desenvolvido por Gustavo S.S.
"Na ciência, o crédito vai para o homem que convence o mundo,
não para o que primeiro teve a ideia" - Francis ... |
3,507 | 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: TFP Probabilistic Layers
Step2: Make things Fast!
Before we dive i... | 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... |
3,508 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Marked Point Pattern
In addition to the unmarked point pattern, non-binary attributes might be associated with each point, leading to the so-called marked point pattern. The characteristics ... | Python Code:
from pysal.explore.pointpats import PoissonPointProcess, PoissonClusterPointProcess, Window, poly_from_bbox, PointPattern
import pysal.lib as ps
from pysal.lib.cg import shapely_ext
%matplotlib inline
import matplotlib.pyplot as plt
# open the virginia polygon shapefile
va = ps.io.open(ps.examples.get_path... |
3,509 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Sentiment analysis with TFLearn
In this notebook, we'll continue Andrew Trask's work by building a network for sentiment analysis on the movie review data. Instead of a network written with ... | Python Code:
import pandas as pd
import numpy as np
import tensorflow as tf
import tflearn
from tflearn.data_utils import to_categorical
Explanation: Sentiment analysis with TFLearn
In this notebook, we'll continue Andrew Trask's work by building a network for sentiment analysis on the movie review data. Instead of a n... |
3,510 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Aerosol
MIP Era
Step1: Document Authors
Set document authors
Step2: Document Contributors
Specify document contributors
Step3: Document Publication
Specify... | Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'mohc', 'hadgem3-gc31-ll', 'aerosol')
Explanation: ES-DOC CMIP6 Model Properties - Aerosol
MIP Era: CMIP6
Institute: MOHC
Source ID: HADGEM3-GC31-LL
Topic: Aerosol
Sub-Topics: Transpor... |
3,511 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<p>参考にしました</p>
<p>http
Step1: <p>メトロポリス法</p>
<p>(1)パラメーターqの初期値を選ぶ</p>
<p>(2)qを増やすか減らすかをランダムに決める</p>
<p>(3)q(新)において尤度が大きくなるならqの値をq(新)に変更する</p>
<p>(4)q(新)で尤度が小さくなる場合であっても、確率rでqの値をq(新)に変更する</p... | Python Code:
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
import pymc as pm2
import pymc3 as pm
import time
import math
import numpy.random as rd
import pandas as pd
from pymc3 import summary
from pymc3.backends.base import merge_traces
import theano.tensor as T
Explanation: <p>参考にしました</p>
<p>... |
3,512 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Flight Delay Predictions with PixieDust
<img style="max-width
Step1: <h3>If PixieDust was just installed or upgraded, <span style="color
Step2: Train multiple classification models
The fol... | Python Code:
!pip install --upgrade --user pixiedust
!pip install --upgrade --user pixiedust-flightpredict
Explanation: Flight Delay Predictions with PixieDust
<img style="max-width: 800px; padding: 25px 0px;" src="https://ibm-watson-data-lab.github.io/simple-data-pipe-connector-flightstats/flight_predictor_architectur... |
3,513 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Finding relations between clusters of people and clusters of stuff they purchase
The old saying goes something on the lines of "you are what you eat". On modern, digitally connected societie... | Python Code:
F=graphviz.Graph()#(engine='neato')
F.graph_attr['rankdir'] = 'LR'
F.edge('A_1','B_1')
F.edge('A_1','B_2')
F.edge('A_2','B_1')
F.edge('A_3','B_1')
F.edge('A_4','B_2')
F.edge('A_5','B_2')
F.edge('A_5','B_3')
F
Explanation: Finding relations between clusters of people and clusters of stuff they purchase
The ... |
3,514 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Initialize
Define the Training Data Set
Define the training dataset for the independent and dependent variables
Step1: Define the Test Set
Define the training dataset for the independent va... | Python Code:
x = np.random.RandomState(0).uniform(-5, 5, 20)
#x = np.random.uniform(-5, 5, 20)
y = x*np.sin(x)
#y += np.random.normal(0,0.5,y.size)
y += np.random.RandomState(34).normal(0,0.5,y.size)
Explanation: Initialize
Define the Training Data Set
Define the training dataset for the independent and dependent varia... |
3,515 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<h1>Predicting Student performance</h1>
<br>
Data
Step1: <h3>Male - Female distribution</h3>
Step2: <h3>Age distribution</h3>
Step3: <h3>Grade distribution</h3>
Step4: <h3>SVM</h3>
<h4>... | Python Code:
import os.path
base_dir = os.path.join('data')
input_path_port = os.path.join('student', 'student_port.csv')
input_path_math = os.path.join('student', 'student_math.csv')
file_name_port = os.path.join(base_dir, input_path_port)
file_name_math = os.path.join(base_dir, input_path_math)
filtered_port = sc.tex... |
3,516 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introduction
In my previous blog post, we've seen how we can identify files that change together in one commit.
In this blog post, we take the analysis to an advanced level
Step1: In our ca... | Python Code:
from lib.ozapfdis.git_tc import log_numstat
GIT_REPO_DIR = "../../dropover_git/"
git_log = log_numstat(GIT_REPO_DIR)[['sha', 'file', 'author']]
git_log.head()
Explanation: Introduction
In my previous blog post, we've seen how we can identify files that change together in one commit.
In this blog post, we t... |
3,517 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Finding trials registered on ClinicalTrials.gov that do not have reported results
Reporting of clinical trial results became mandatory for many trials in 2008. However this paper and this in... | Python Code:
import csv
from datetime import datetime
from dateutil.relativedelta import relativedelta
import glob
from pprint import pprint
from slugify import slugify
import sqlite3
import numpy as np
import pandas as pd
import utils
Explanation: Finding trials registered on ClinicalTrials.gov that do not have report... |
3,518 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
What is a dataset?
A dataset is a collection of information (or data) that can be used by a computer. A dataset typically has some number of examples, where each example has features associa... | Python Code:
# Print figures in the notebook
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets # Import datasets from scikit-learn
import matplotlib.cm as cm
from matplotlib.colors import Normalize
Explanation: What is a dataset?
A dataset is a collection of information... |
3,519 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Steps to use the TF Experiment APIs
Define dataset metadata
Define data input function to read the data from csv files + feature processing
Create TF feature columns based on metadata + exte... | Python Code:
MODEL_NAME = 'reg-model-03'
TRAIN_DATA_FILES_PATTERN = 'data/train-*.csv'
VALID_DATA_FILES_PATTERN = 'data/valid-*.csv'
TEST_DATA_FILES_PATTERN = 'data/test-*.csv'
RESUME_TRAINING = False
PROCESS_FEATURES = True
EXTEND_FEATURE_COLUMNS = True
MULTI_THREADING = True
Explanation: Steps to use the TF Experimen... |
3,520 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Lab 06
Step1: Next, let's load the data. This week, we're going to load the Auto MPG data set, which is available online at the UC Irvine Machine Learning Repository. The dataset is in fixe... | Python Code:
%matplotlib inline
import numpy as np
import pandas as pd
from sklearn.dummy import DummyRegressor
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_absolute_error
from sklearn.model_selection import GridSearchCV, KFold, cross_val_predict
Explanation: Lab 06: Linear regress... |
3,521 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Data analytics and machine learning with Python
I - Acquiring data
A simple HTTP request
Step1: Communicating with APIs
Step2: Parsing websites
Step3: Reading local files (CSV/JSON)
Step4... | Python Code:
import requests
print(requests.get("http://example.com").text)
Explanation: Data analytics and machine learning with Python
I - Acquiring data
A simple HTTP request
End of explanation
response = requests.get("https://www.googleapis.com/books/v1/volumes", params={"q":"machine learning"})
raw_data = response... |
3,522 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Landice
MIP Era
Step1: Document Authors
Set document authors
Step2: Document Contributors
Specify document contributors
Step3: Document Publication
Specify... | Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'test-institute-1', 'sandbox-2', 'landice')
Explanation: ES-DOC CMIP6 Model Properties - Landice
MIP Era: CMIP6
Institute: TEST-INSTITUTE-1
Source ID: SANDBOX-2
Topic: Landice
Sub-Topi... |
3,523 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
conversion, drawing, saving, analysis
copy of dan's thing
converts .csv to .gml and .net
draws graph, saves graph.png
try to combine into this
Step1: degree centrality
for a node v is the f... | Python Code:
import pandas as pd
import numpy as np
import networkx as nx
from copy import deepcopy
import matplotlib.pyplot as plt
%matplotlib inline
from matplotlib.backends.backend_pdf import PdfPages
from glob import glob
fileName = 'article0'
def getFiles(fileName):
matches = glob('*'+fileName+'*')
bigFile... |
3,524 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Unit 3
Step1: 1. Describe the results.
Now run time.time() again below.
2. Describe the results and compare them to the first time.time() call.
Read the info on the time module here
Step2: ... | Python Code:
import time
time.time()
Explanation: Unit 3: Simulation
Lesson 18: Non-uniform distributions
Notebook Authors
(fill in your two names here)
Facilitator: (fill in name)
Spokesperson: (fill in name)
Process Analyst: (fill in name)
Quality Control: (fill in name)
If there are only three people in your group... |
3,525 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Pandas 5
Step1: <a id=weo></a>
WEO data on government debt
We use the IMF's data on government debt again, specifically its World Economic Outlook database, commonly referred to as the WEO.... | Python Code:
import sys # system module
import pandas as pd # data package
import matplotlib.pyplot as plt # graphics module
import datetime as dt # date and time module
import numpy as np # foundation for Pandas
%matplotlib ... |
3,526 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Regression Week 5
Step1: Load in house sales data
Dataset is from house sales in King County, the region where the city of Seattle, WA is located.
Step2: Create new features
Step3: As in ... | Python Code:
import graphlab
Explanation: Regression Week 5: Feature Selection and LASSO (Interpretation)
In this notebook, you will use LASSO to select features, building on a pre-implemented solver for LASSO (using GraphLab Create, though you can use other solvers). You will:
* Run LASSO with different L1 penalties.
... |
3,527 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Onset detection
In this tutorial, we will look at how to perform onset detection and mark onset positions in the audio.
Onset detection consists of two steps
Step1: We can now listen to the... | Python Code:
from essentia.standard import *
from tempfile import TemporaryDirectory
# Load audio file.
audio = MonoLoader(filename='../../../test/audio/recorded/hiphop.mp3')()
# 1. Compute the onset detection function (ODF).
# The OnsetDetection algorithm provides various ODFs.
od_hfc = OnsetDetection(method='hfc')
od... |
3,528 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
This is a sketch for Adversarial images in MNIST
Step1: recreate the network structure
Step2: Load previous model
Step3: Extract some "2" images from test set
Step4: one Adversarial vs o... | Python Code:
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('/tmp/tensorflow/mnist/input_data', one_hot=True)
import seaborn as sns
sns.set_style('white')
colors_list = sns.color_palette("Paired", 10)
Explanation: This is a sketch for Adversarial ima... |
3,529 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
IPython extension for drawing circuit diagrams with LaTeX/Circuitikz
Robert Johansson
http
Step1: Load the extension
Step2: Example
Step3: Example | Python Code:
%install_ext http://raw.github.com/jrjohansson/ipython-circuitikz/master/circuitikz.py
Explanation: IPython extension for drawing circuit diagrams with LaTeX/Circuitikz
Robert Johansson
http://github.com/jrjohansson/ipython-circuitikz
Requirements
This IPython magic command uses the following external depe... |
3,530 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Linear models with CNN features
Step1: Introduction
We need to find a way to convert the imagenet predictions to a probability of being a cat or a dog, since that is what the Kaggle competi... | Python Code:
# Rather than importing everything manually, we'll make things easy
# and load them all in utils.py, and just import them from there.
%matplotlib inline
import utils; reload(utils)
from utils import *
Explanation: Linear models with CNN features
End of explanation
%matplotlib inline
from __future__ impor... |
3,531 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Dropout
Dropout [1] is a technique for regularizing neural networks by randomly setting some features to zero during the forward pass. In this exercise you will implement a dropout la... | Python Code:
# As usual, a bit of setup
import time
import numpy as np
import matplotlib.pyplot as plt
from skynet.neural_network.classifiers.fc_net import *
from skynet.utils.data_utils import get_CIFAR10_data
from skynet.utils.gradient_check import eval_numerical_gradient, eval_numerical_gradient_array
from skynet.so... |
3,532 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Determining initial $T_{\rm eff}$ and luminosity for DMESTAR seed polytropes
Currently, we are having difficulty with models in the mass range of $0.14 M_{\odot}$ -- $0.22 M_{\odot}$ not con... | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
Explanation: Determining initial $T_{\rm eff}$ and luminosity for DMESTAR seed polytropes
Currently, we are having difficulty with models in the mass range of $0.14 M_{\odot}$ -- $0.22 M_{\odot}$ not converging after an initial relaxatio... |
3,533 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Plot sensor denoising using oversampled temporal projection
This demonstrates denoising using the OTP algorithm
Step1: Plot the phantom data, lowpassed to get rid of high-frequency artifac... | Python Code:
# Author: Eric Larson <larson.eric.d@gmail.com>
#
# License: BSD (3-clause)
import os.path as op
import mne
import numpy as np
from mne import find_events, fit_dipole
from mne.datasets.brainstorm import bst_phantom_elekta
from mne.io import read_raw_fif
print(__doc__)
Explanation: Plot sensor denoising usi... |
3,534 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Multi-spot Gamma Fitting
Step1: Load Data
Multispot
Load the leakage coefficient from disk (computed in Multi-spot 5-Samples analyis - Leakage coefficient fit)
Step2: Load the direct excit... | Python Code:
from fretbursts import fretmath
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
from cycler import cycler
import seaborn as sns
%matplotlib inline
%config InlineBackend.figure_format='retina' # for hi-dpi displays
import matplotlib as mpl
from cycler import ... |
3,535 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Extracting the time series of activations in a label
We first apply a dSPM inverse operator to get signed activations in a label
(with positive and negative values) and we then compare diffe... | Python Code:
# Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr>
# Eric Larson <larson.eric.d@gmail.com>
#
# License: BSD-3-Clause
import matplotlib.pyplot as plt
import matplotlib.patheffects as path_effects
import mne
from mne.datasets import sample
from mne.minimum_norm import read_inverse_operator,... |
3,536 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2021 The TensorFlow Authors.
Step1: LoggingTensorHook 및 StopAtStepHook을 Keras 콜백으로 마이그레이션
<table class="tfo-notebook-buttons" align="left">
<td><a target="_blank" href="https
St... | 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... |
3,537 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Class Session 4 Exercise
Step1: Now, define a function that returns the index numbers of the neighbors of a vertex i, when the
graph is stored in adjacency matrix format. So your function... | Python Code:
import numpy as np
import igraph
import timeit
import itertools
Explanation: Class Session 4 Exercise:
Comparing asymptotic running time for enumerating neighbors of all vertices in a graph
We will measure the running time for enumerating the neighbor vertices for three different data structures for repres... |
3,538 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Workshop 3 - Practice Makes Perfect
There is a sign-in sheet, sign in or you wont get credit for attendance today!
Today
Step1: Breaking it down
Step2: Problem 1
We are going to plot a saw... | Python Code:
import matplotlib.pyplot as plt
import numpy as np
# Base Python range() doesn't allow decimal numbers
# numpy improved and made thier own:
t = np.arange(0.0, 1., 0.01)
y = t**3.
plt.plot(100 * t, y)
plt.xlabel('Time (% of semester)')
plt.ylabel('Enjoyment of Fridays')
plt.title('Happiness over Time')
plt.... |
3,539 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Using a notebook
The purpose of this notebook is to introduce the Jupyter interface. This notebook is a guide to the Jupyter interface and writing code and text in Jupyter notebooks with the... | Python Code:
# create a range of numbers
numbers = range(0, 5)
# print out each of the numbers in the range
for number in numbers:
print(number)
Explanation: Using a notebook
The purpose of this notebook is to introduce the Jupyter interface. This notebook is a guide to the Jupyter interface and writing code and te... |
3,540 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Keras for Text Classification
Learning Objectives
1. Learn how to create a text classification datasets using BigQuery
1. Learn how to tokenize and integerize a corpus of text for training i... | Python Code:
import os
import pandas as pd
from google.cloud import bigquery
%load_ext google.cloud.bigquery
Explanation: Keras for Text Classification
Learning Objectives
1. Learn how to create a text classification datasets using BigQuery
1. Learn how to tokenize and integerize a corpus of text for training in Keras
... |
3,541 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Here we are using the California Housing dataset to learn more about Machine Learning.
Step1: In the meanwhile we are trying to have more information about pandas. In the following sections... | Python Code:
import pandas as pd
housing = pd.read_csv('housing.csv')
housing.head()
housing.info()
housing.describe()
Explanation: Here we are using the California Housing dataset to learn more about Machine Learning.
End of explanation
housing['total_rooms'].value_counts()
housing['ocean_proximity'].value_counts()
Ex... |
3,542 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Your first neural network
In this project, you'll build your first neural network and use it to predict daily bike rental ridership. We've provided some of the code, but left the implementat... | Python Code:
%matplotlib inline
%config InlineBackend.figure_format = 'retina'
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
Explanation: Your first neural network
In this project, you'll build your first neural network and use it to predict daily bike rental ridership. We've provided some of t... |
3,543 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step3: <div style="text-align
Step4: In this notebook we use this code to show how to solve some particularly perplexing paradoxical probability problems.
Child Paradoxes
In 1959, Martin Ga... | Python Code:
from fractions import Fraction
class ProbDist(dict):
"A Probability Distribution; an {outcome: probability} mapping."
def __init__(self, mapping=(), **kwargs):
self.update(mapping, **kwargs)
# Make probabilities sum to 1.0; assert no negative probabilities
total = sum(self.v... |
3,544 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Climate Projections
https
Step1: Please put your datahub API key into a file called APIKEY and place it to the notebook folder or assign your API key directly to the variable API_key!
Step2... | Python Code:
import json
import pandas as pd
from urllib.request import urlopen
from urllib.parse import quote
import plotly.graph_objects as go
import plotly.e... |
3,545 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Plotting HYCOM Global Ocean Forecast Data
Note
Step2: Let's choose a location near Oahu, Hawaii...
Step3: Important! You'll need to replace apikey below with your actual Planet OS A... | Python Code:
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
import dateutil.parser
import datetime
from urllib.request import urlopen, Request
import simplejson as json
def extract_reference_time(API_data_loc):
Find reference time that corresponds to most complete forecast. Should be the earl... |
3,546 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Building and deploying machine learning solutions with Vertex AI
Step1: Import libraries
Step2: Initialize Vertex AI Python SDK
Initialize the Vertex AI Python SDK with your GCP Project, R... | Python Code:
# Add installed library dependencies to Python PATH variable.
PATH=%env PATH
%env PATH={PATH}:/home/jupyter/.local/bin
# Retrieve and set PROJECT_ID and REGION environment variables.
# TODO: fill in PROJECT_ID.
PROJECT_ID = ""
REGION = "us-central1"
# TODO: Create a globally unique Google Cloud Storage buc... |
3,547 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Title
Step1: Load Features
Step2: Notice that original data contains 569 observations and 30 features.
Step3: Here is what the data looks like.
Step4: Standardize Features
Step5: Conduc... | Python Code:
# Import packages
import numpy as np
from sklearn import decomposition, datasets
from sklearn.preprocessing import StandardScaler
Explanation: Title: Feature Extraction With PCA
Slug: feature_extraction_with_pca
Summary: Feature extraction with PCA using scikit-learn.
Date: 2017-09-13 12:00
Category: M... |
3,548 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Chapter 1
Step1: First , we introduce vector compression by Product Quantization (PQ) [Jegou, TPAMI 11]. The first task is to train an encoder. Let us assume that there are 1000 six-dimensi... | Python Code:
import numpy
import pqkmeans
import sys
import pickle
Explanation: Chapter 1: PQk-means
This chapter contains the followings:
Vector compression by Product Quantization
Clustering by PQk-means
Comparison to other clustering methods
Requisites:
- numpy
- sklearn
- pqkmeans
1. Vector compression by Product Q... |
3,549 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
NumPy and J make Sweet Array Love
Import NumPy using the standard naming convention
Step1: Configure the J Python3 addon
To use the J Python3 addon you must edit path variables in jbase.py ... | Python Code:
import numpy as np
Explanation: NumPy and J make Sweet Array Love
Import NumPy using the standard naming convention
End of explanation
import sys
# local api/python3 path - adjust path for your system
japipath = 'C:\\j64\\j64-807\\addons\\api\\python3'
if japipath not in sys.path:
sys.path.append(japip... |
3,550 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Chapter 9 - Hierarchical Models
9.2.4 - Example
Step1: 9.2.4 - Example
Step2: Figure 9.9
Step3: Model (Kruschke, 2015)
Step4: Figure 9.10 - Marginal posterior distributions
Step5: Shrin... | Python Code:
import pandas as pd
import numpy as np
import pymc3 as pm
import matplotlib.pyplot as plt
import seaborn as sns
import warnings
warnings.filterwarnings("ignore", category=FutureWarning)
from IPython.display import Image
from matplotlib import gridspec
%matplotlib inline
plt.style.use('seaborn-white')
color... |
3,551 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Error Handling Using Try & Except
Errors should never pass silently.
Unless explicitly silenced. ~ Zen of Python
Hi guys, last lecture we looked at common error messages, in this lecture we ... | Python Code:
a_list = [10, 32.4, -14.2, "a", "b", [], [1,2]]
for item in a_list:
try:
print(item * item)
except TypeError:
print(item + item)
Explanation: Error Handling Using Try & Except
Errors should never pass silently.
Unless explicitly silenced. ~ Zen of Python
Hi guys, las... |
3,552 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a href="https
Step1: Example
Step2: The data look like they follow a quadratic function. We can set up the following Vandermonde system and use unconstrained least-squares to estimate pa... | Python Code:
import numpy as np # we can use np.array to specify problem data
import matplotlib.pyplot as plt
%matplotlib inline
import cvxpy as cvx
Explanation: <a href="https://colab.research.google.com/github/stephenbeckr/convex-optimization-class/blob/master/Demos/CVX_demo/cvxpy_intro.ipynb" target="_parent"><img s... |
3,553 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Title
Step1: Create Data
Step2: View Table
Step3: Drop Row Based On A Conditional | Python Code:
# Ignore
%load_ext sql
%sql sqlite://
%config SqlMagic.feedback = False
Explanation: Title: Select First X Rows
Slug: select_first_x_rows
Summary: Drop rows in SQL.
Date: 2017-01-16 12:00
Category: SQL
Tags: Basics
Authors: Chris Albon
Note: This tutorial was written using Catherine Devlin's SQL ... |
3,554 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
OpenMC's general tally system accommodates a wide range of tally filters. While most filters are meant to identify regions of phase space that contribute to a tally, there are a special set ... | Python Code:
%matplotlib inline
import openmc
import numpy as np
import matplotlib.pyplot as plt
# Define fuel and B4C materials
fuel = openmc.Material()
fuel.add_element('U', 1.0, enrichment=4.5)
fuel.add_nuclide('O16', 2.0)
fuel.set_density('g/cm3', 10.0)
b4c = openmc.Material()
b4c.add_element('B', 4.0)
b4c.add_nucl... |
3,555 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Evaluation, Cross-Validation, and Model Selection
By Heiko Strathmann - heiko.strathmann@gmail.com - http
Step1: Types of splitting strategies
As said earlier Cross-validation is based upon... | Python Code:
%pylab inline
%matplotlib inline
# include all Shogun classes
import os
SHOGUN_DATA_DIR=os.getenv('SHOGUN_DATA_DIR', '../../../data')
from modshogun import *
# generate some ultra easy training data
gray()
n=20
title('Toy data for binary classification')
X=hstack((randn(2,n), randn(2,n)+1))
Y=hstack((-ones... |
3,556 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Programmierbeispiel
Fallbeispiel
IntelliJ IDEA
IDE für Java-Entwickler
Fast komplett in Java geschrieben
Großes und lang aktives Projekt
I. Fragestellung (1/3)
Schreibe die Frage explizit au... | Python Code:
import pandas as pd
log = pd.read_csv("dataset/git_log_intellij.csv.gz")
log.head()
Explanation: Programmierbeispiel
Fallbeispiel
IntelliJ IDEA
IDE für Java-Entwickler
Fast komplett in Java geschrieben
Großes und lang aktives Projekt
I. Fragestellung (1/3)
Schreibe die Frage explizit auf
Erkläre die Anayse... |
3,557 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Annotating continuous data
This tutorial describes adding annotations to a
Step1:
Step2: Notice that orig_time is None, because we haven't specified it. In
those cases, when you add the ... | Python Code:
import os
from datetime import timedelta
import mne
sample_data_folder = mne.datasets.sample.data_path()
sample_data_raw_file = os.path.join(sample_data_folder, 'MEG', 'sample',
'sample_audvis_raw.fif')
raw = mne.io.read_raw_fif(sample_data_raw_file, verbose=False)
raw.c... |
3,558 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2018 The TensorFlow Authors.
Step1: Train your first neural network
Step2: Import the Fashion MNIST dataset
This guide uses the Fashion MNIST dataset which contains 70,000 graysc... | 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... |
3,559 | Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
I have a csv file without headers which I'm importing into python using pandas. The last column is the target class, while the rest of the columns are pixel values for images. How c... | Problem:
import numpy as np
import pandas as pd
dataset = load_data()
from sklearn.model_selection import train_test_split
x_train, x_test, y_train, y_test = train_test_split(dataset.iloc[:, :-1], dataset.iloc[:, -1], test_size=0.4,
random_state=42) |
3,560 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Spam detection
The main aim of this project is to build a machine learning classifier that is able to automatically detect
spammy articles, based on their content.
Step1: Custom Helper Fun... | Python Code:
! sh bootstrap.sh
from sklearn.cluster import KMeans
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import random
from sklearn.utils import shuffle
from sklearn.metrics import f1_score
from sklearn.cross_validation import KFold
from sklearn.metrics import recall_score
from sklearn.e... |
3,561 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Average Reward over time
Step1: Visualizing what the agent is seeing
Starting with the ray pointing all the way right, we have one row per ray in clockwise order.
The numbers for each ray a... | Python Code:
g.plot_reward(smoothing=100)
Explanation: Average Reward over time
End of explanation
g.__class__ = KarpathyGame
np.set_printoptions(formatter={'float': (lambda x: '%.2f' % (x,))})
x = g.observe()
new_shape = (x[:-2].shape[0]//g.eye_observation_size, g.eye_observation_size)
print(x[:-2].reshape(new_shape))... |
3,562 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Advanced
Step1: And we'll attach some dummy datasets. See Datasets for more details.
Step2: Available Backends
See the Compute Tutorial for details on adding compute options and using the... | Python Code:
#!pip install -I "phoebe>=2.4,<2.5"
import phoebe
from phoebe import u # units
logger = phoebe.logger()
b = phoebe.default_binary()
Explanation: Advanced: Alternate Backends
Setup
Let's first make sure we have the latest version of PHOEBE 2.4 installed (uncomment this line if running in an online notebook ... |
3,563 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Kirkwood-Buff example
Step1: Load gromacs trajectory/topology
Gromacs was used to sample a dilute solution of sodium chloride in SPC/E water for 100 ns.
The trajectory and .gro loaded below... | Python Code:
%matplotlib inline
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import mdtraj as md
from math import pi
from scipy import integrate
plt.rcParams.update({'font.size': 16})
Explanation: Kirkwood-Buff example: NaCl in water
In this example we calculate Kirkwood-Buff integrals in a solu... |
3,564 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step3: Why do we need to improve the traing method?
In the previous note, we managed to get the neural net to
1. converge to any value at a given input
2. emulate a step function.
However, ... | Python Code:
%pylab inline
%config InlineBackend.figure_format = 'retina'
import numpy as np
from random import random
from IPython.display import FileLink, FileLinks
def σ(z):
return 1/(1 + np.e**(-z))
def σ_prime(z):
return np.e**(z) / (np.e**z + 1)**2
def Plot(fn, *args, **kwargs):
argLength = len(args);... |
3,565 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Find the author that published the most papers on Drosophila virilis.
Step1: We first want to know now many publications have D. virilis in their title or abstract. We use the NCBI history ... | Python Code:
from Bio import Entrez
import re
Explanation: Find the author that published the most papers on Drosophila virilis.
End of explanation
# Remember to edit the e-mail address
Entrez.email = "your_name@yourmailhost.com" # Always tell NCBI who you are
handle = Entrez.esearch(db="pubmed", term="Drosophila viril... |
3,566 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Best report ever
Everything you see here is either markdown, LaTex, Python or BASH.
The spectral function
It looks like this
Step1: Now I can run my script
Step2: Not very elegant, I know.... | Python Code:
!gvim data/SF_Si_bulk/invar.in
Explanation: Best report ever
Everything you see here is either markdown, LaTex, Python or BASH.
The spectral function
It looks like this:
\begin{equation}
A(\omega) = \mathrm{Im}|G(\omega)|
\end{equation}
GW vs Cumulant
Mathematically very different:
\begin{equation}
G^{GW... |
3,567 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Repaso (Módulo 2)
El tema principal en este módulo fueron simulaciones Montecarlo. Al finalizar este módulo, se espera que ustedes tengan las siguientes competencias
- Evaluar integrales (o ... | Python Code:
def int_montecarlo1(f, a, b, N):
# Evaluación numérica de integrales por Montecarlo tipo 1
# f=f(x) es la función a integrar (debe ser declarada previamente) que devuelve para cada x su valor imagen,
# a y b son los límites inferior y superior del intervalo donde se integrará la función, y N es... |
3,568 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
https
Step1: ^ Looks like Augusto de Campos' poems ^.^
Step2: The Python Programming Language | Python Code:
def add_numbers(x,y):
return x+y
a = add_numbers
a(1,2)
x = [1, 2, 4]
x.insert(2, 3) # list.insert(position, item)
x
x = 'This is a string'
print(x[0]) #first character
print(x[0:1]) #first character, but we have explicitly set the end character
print(x[0:2]) #first two characters
x = 'This is a string... |
3,569 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Coords 2
Step1: Section 0
Step2: We can get the right ascension and declination components of the object directly by accessing those attributes.
Step3: Section 1
Step4: There are three d... | Python Code:
# Third-party dependencies
from astropy import units as u
from astropy.coordinates import SkyCoord
import numpy as np
# Set up matplotlib and use a nicer set of plot parameters
from astropy.visualization import astropy_mpl_style
import matplotlib.pyplot as plt
plt.style.use(astropy_mpl_style)
%matplotlib i... |
3,570 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Parallel MULTINEST with 3ML
J. Michael Burgess
MULTINEST
MULTINEST is a Bayesian posterior sampler that has two distinct advantages over traditional MCMC
Step1: Import 3ML and astromodels t... | Python Code:
from ipyparallel import Client
rc = Client(profile='mpi')
# Grab a view
view = rc[:]
# Activate parallel cell magics
view.activate()
Explanation: Parallel MULTINEST with 3ML
J. Michael Burgess
MULTINEST
MULTINEST is a Bayesian posterior sampler that has two distinct advantages over traditional MCMC:
* Reco... |
3,571 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Distributions
Think Bayes, Second Edition
Copyright 2020 Allen B. Downey
License
Step1: In the previous chapter we used Bayes's Theorem to solve a cookie problem; then we solved it again us... | Python Code:
# If we're running on Colab, install empiricaldist
# https://pypi.org/project/empiricaldist/
import sys
IN_COLAB = 'google.colab' in sys.modules
if IN_COLAB:
!pip install empiricaldist
# Get utils.py
from os.path import basename, exists
def download(url):
filename = basename(url)
if not exists(... |
3,572 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ARDC Training
Step1: Browse the available Data Cubes
Step2: Pick a product
Use the platform and product names from the previous block to select a Data Cube.
Step3: Display Latitude-Longit... | Python Code:
import xarray as xr
import numpy as np
import datacube
import utils.data_cube_utilities.data_access_api as dc_api
from datacube.utils.aws import configure_s3_access
configure_s3_access(requester_pays=True)
api = dc_api.DataAccessApi()
dc = api.dc
Explanation: ARDC Training: Python Notebooks
Task-E: This ... |
3,573 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Think Bayes
Step1: The Dice problem
Suppose I have a box of dice that contains a 4-sided die, a 6-sided
die, an 8-sided die, a 12-sided die, and a 20-sided die.
Suppose I select a die from ... | Python Code:
from __future__ import print_function, division
% matplotlib inline
import thinkplot
from thinkbayes2 import Hist, Pmf, Suite, Cdf
Explanation: Think Bayes: Chapter 3
This notebook presents example code and exercise solutions for Think Bayes.
Copyright 2016 Allen B. Downey
MIT License: https://opensource.o... |
3,574 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
http
Step1: Całka oznaczona
$$\int_a^b f(x) dx = \lim_{n\to\infty} \sum_{i=1}^{n} f(\hat x_i) \Delta x_i$$
Step2: Całka nieoznaczona
$$\int_a^x f(y) dy = \lim_{n\to\infty} \sum_{i=1}^{n} f... | Python Code:
import numpy as np
x = np.linspace(1,8,5)
x.shape
y = np.sin(x)
y.shape
for i in range(y.shape[0]-1):
print( (y[i+1]-y[i]),(y[i+1]-y[i])/(x[i+1]-x[i]))
y[1:]-y[:-1]
y[1:]
(y[1:]-y[:-1])/(x[1:]-x[:-1])
np.diff(y)
np.diff(x)
np.roll(y,-1)
y
np.gradient(y)
import sympy
X = sympy.Symbol('X')
expr = ... |
3,575 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
HEP Benchmark Queries Q1 to Q5 - CERN SWAN Version
This follows the IRIS-HEP benchmark
and the article Evaluating Query Languages and Systems for High-Energy Physics Data
and provides implem... | Python Code:
# Start the Spark Session
# When Using Spark on CERN SWAN, run this cell to get the Spark Session
# Note: when running SWAN for this, do not select to connect to a CERN Spark cluster
# If you want to use a cluster anyway, please copy the data to a cluster filesystem first
from pyspark.sql import SparkSessi... |
3,576 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
k-Nearest Neighbor (kNN) exercise
Complete and hand in this completed worksheet (including its outputs and any supporting code outside of the worksheet) with your assignment submission. For ... | Python Code:
# Run some setup code for this notebook.
import random
import numpy as np
from cs231n.data_utils import load_CIFAR10
import matplotlib.pyplot as plt
# This is a bit of magic to make matplotlib figures appear inline in the notebook
# rather than in a new window.
%matplotlib inline
plt.rcParams['figure.figsi... |
3,577 |
Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
making new class prediction for a classification problem
| Python Code::
from keras.models import Sequential
from keras.layers import Dense
from sklearn.datasets import make_blobs
from sklearn.preprocessing import MinMaxScaler
from numpy import array
X, y = make_blobs(n_samples=100, centers=2, n_features=2, random_state=1)
scalar = MinMaxScaler()
scalar.fit(X)
X = scalar.trans... |
3,578 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Ocnbgchem
MIP Era
Step1: Document Authors
Set document authors
Step2: Document Contributors
Specify document contributors
Step3: Document Publication
Speci... | Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'cccr-iitm', 'sandbox-1', 'ocnbgchem')
Explanation: ES-DOC CMIP6 Model Properties - Ocnbgchem
MIP Era: CMIP6
Institute: CCCR-IITM
Source ID: SANDBOX-1
Topic: Ocnbgchem
Sub-Topics: Trac... |
3,579 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Detecting Changes in Sentinel-1 Imagery (Part 3)
Author
Step1: Datasets and Python modules
One dataset will be used in the tutorial
Step4: This cell carries over the chi square cumulative ... | Python Code:
import ee
# Trigger the authentication flow.
ee.Authenticate()
# Initialize the library.
ee.Initialize()
Explanation: Detecting Changes in Sentinel-1 Imagery (Part 3)
Author: mortcanty
Run me first
Run the following cell to initialize the API. The output will contain instructions on how to grant this noteb... |
3,580 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Handwritten Number Recognition with TFLearn and MNIST
In this notebook, we'll be building a neural network that recognizes handwritten numbers 0-9.
This kind of neural network is used in a ... | Python Code:
# Import Numpy, TensorFlow, TFLearn, and MNIST data
import numpy as np
import tensorflow as tf
import tflearn
import tflearn.datasets.mnist as mnist
Explanation: Handwritten Number Recognition with TFLearn and MNIST
In this notebook, we'll be building a neural network that recognizes handwritten numbers 0-... |
3,581 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Example data
Step1: Dot (.) column expression
Create a column expression that will return the original column values. | Python Code:
mtcars = spark.read.csv('../../../data/mtcars.csv', inferSchema=True, header=True)
mtcars = mtcars.withColumnRenamed('_c0', 'model')
mtcars.show(5)
Explanation: Example data
End of explanation
mpg_col_exp = mtcars.mpg
mpg_col_exp
mtcars.select(mpg_col_exp).show(5)
Explanation: Dot (.) column expression
Cre... |
3,582 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Interactive mapping
Alongside static plots, geopandas can create interactive maps based on the folium library.
Creating maps for interactive exploration mirrors the API of static plots in an... | Python Code:
import geopandas
nybb = geopandas.read_file(geopandas.datasets.get_path('nybb'))
world = geopandas.read_file(geopandas.datasets.get_path('naturalearth_lowres'))
cities = geopandas.read_file(geopandas.datasets.get_path('naturalearth_cities'))
Explanation: Interactive mapping
Alongside static plots, geopanda... |
3,583 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Creating datasets for 2D
We begin by reading the csv file, into a data frame. This makes it easier to create.
Step1: Then we want to filter the data set.
We do this by only taking the rows ... | Python Code:
data_path = '../../SFPD_Incidents_-_from_1_January_2003.csv'
data = pd.read_csv(data_path)
Explanation: Creating datasets for 2D
We begin by reading the csv file, into a data frame. This makes it easier to create.
End of explanation
mask = (data.Category == 'PROSTITUTION') & (data.Y != 90)
filterByCat = da... |
3,584 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Working with models in FedJAX
In this chapter, we will learn about fedjax.Model. This notebook assumes you already have finished the "Datasets" chapter. We first overview centralized trainin... | Python Code:
# Uncomment these to install fedjax.
# !pip install fedjax
# !pip install --upgrade git+https://github.com/google/fedjax.git
import itertools
import jax
import jax.numpy as jnp
from jax.experimental import stax
import fedjax
Explanation: Working with models in FedJAX
In this chapter, we will learn about fe... |
3,585 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Part 3
Step1: Import libraries
Step2: Configure GCP environment settings
Update the following variables to reflect the values for your GCP environment
Step3: Authenticate your GCP account... | Python Code:
!pip install -q -U pip
!pip install -q tensorflow==2.2.0
!pip install -q -U google-auth google-api-python-client google-api-core
Explanation: Part 3: Create a model to serve the item embedding data
This notebook is the third of five notebooks that guide you through running the Real-time Item-to-item Recomm... |
3,586 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
2D Histograms in physt
Step1: Multidimensional binning
In most cases, binning methods that apply for 1D histograms, can be used also in higher dimensions. In such cases, each parameter can ... | Python Code:
# Necessary import evil
import physt
from physt import h1, h2, histogramdd
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(42)
# Some data
x = np.random.normal(100, 1, 1000)
y = np.random.normal(10, 10, 1000)
# Create a simple histogram
histogram = h2(x, y, [8, 4], name="Some histogram", ... |
3,587 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Head data is generated for a pumping test in a two-aquifer model. The well starts pumping at time $t=0$ with a discharge $Q=800$ m$^3$/d. The head is measured in an observation well 10 m fro... | Python Code:
def generate_data():
# 2 layer model with some random error
ml = ModelMaq(kaq=[10, 20], z=[0, -20, -22, -42], c=[1000],
Saq=[0.0002, 0.0001], tmin=0.001, tmax=100)
w = Well(ml, 0, 0, rw=0.3, tsandQ=[(0, 800)])
ml.solve()
t = np.logspace(-2, 1, 100)
h = ml.head(10,... |
3,588 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Sample Implementation of Poisson Kriging
This notebook contains a implemention example of Poisson kriging.
The used data is from ZoneA.data (for details, please refer to this link)
Step1: ... | Python Code:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from kriging2 import Kriging
%matplotlib inline
Explanation: Sample Implementation of Poisson Kriging
This notebook contains a implemention example of Poisson kriging.
The used data is from ZoneA.data (for details, please refer to this... |
3,589 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Toplevel
MIP Era
Step1: Document Authors
Set document authors
Step2: Document Contributors
Specify document contributors
Step3: Document Publication
Specif... | Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'ncc', 'noresm2-lmec', 'toplevel')
Explanation: ES-DOC CMIP6 Model Properties - Toplevel
MIP Era: CMIP6
Institute: NCC
Source ID: NORESM2-LMEC
Sub-Topics: Radiative Forcings.
Properti... |
3,590 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Lecture 3
Step1: We'll train a logistic regression model of the form
$$
p(y = 1 ~|~ {\bf x}; {\bf w}) = \frac{1}{1 + \textrm{exp}[-(w_0 + w_1x_1 + w_2x_2)]}
$$
using sklearn's logistic reg... | Python Code:
import matplotlib.pyplot as plt
%matplotlib inline
from sklearn import datasets
iris = datasets.load_iris()
X_train = iris.data[iris.target != 2, :2] # first two features and
y_train = iris.target[iris.target != 2] # first two labels only
fig = plt.figure(figsize=(8,8))
mycolors = {"blue": "steelblue",... |
3,591 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Building your Deep Neural Network
Step2: 2 - Outline of the Assignment
To build your neural network, you will be implementing several "helper functions". These helper functions will be used... | Python Code:
import numpy as np
import h5py
import matplotlib.pyplot as plt
from testCases_v2 import *
from dnn_utils_v2 import sigmoid, sigmoid_backward, relu, relu_backward
%matplotlib inline
plt.rcParams['figure.figsize'] = (5.0, 4.0) # set default size of plots
plt.rcParams['image.interpolation'] = 'nearest'
plt.rc... |
3,592 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
NOTE
Step1: Select columns for city, airport, latitude and longitude info
- City_Airport_Latitude_Longitude_DataFrame (CALL_DF)
Step3: Create database AIRPORTS
Step5: Fill into AIRPORTS i... | Python Code:
import pandas as pd
top_airport_csv = 'hw_5_data/top_airports.csv'
ICAO_airport_csv = 'hw_5_data/ICAO_airports.csv'
top50_df = pd.read_csv(top_airport_csv)
icao_df = pd.read_csv(ICAO_airport_csv)
# merge two data frames to obtain info for the top 50 airports
merged_df = pd.merge(top50_df, icao_df, how='inn... |
3,593 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Image Classification
In this project, you'll classify images from the CIFAR-10 dataset. The dataset consists of airplanes, dogs, cats, and other objects. You'll preprocess the images... | Python Code:
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
from urllib.request import urlretrieve
from os.path import isfile, isdir
from tqdm import tqdm
import problem_unittests as tests
import tarfile
cifar10_dataset_folder_path = 'cifar-10-batches-py'
# Use Floyd's cifar-10 dataset if present
floyd_cifa... |
3,594 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
HOMO energy prediction with kernel ridge regression
In this notebook we will machine-learn the relationship between molecular structure (represented by the Coulomb matrix CM) and their HOMO ... | Python Code:
# initial imports
import numpy as np
import math, random
import matplotlib.pyplot as plt
import pandas as pd
import json
import seaborn as sns
from scipy.sparse import load_npz
from matplotlib.colors import LinearSegmentedColormap
from sklearn.model_selection import GridSearchCV
from sklearn.kernel_ridge i... |
3,595 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
In order to widen Open Context's interoperability with other scientific information systems, we are starting to cross-reference Open Context published biological taxonomy categores with GBIF... | Python Code:
import json
import os
import requests
from time import sleep
import numpy as np
import pandas as pd
# Get the root_path for this jupyter notebook repo.
repo_path = os.path.dirname(os.path.abspath(os.getcwd()))
# Path for the (gzip compressed) CSV data dump from EOL
# with GBIF names and EOL IDs.
eol_gbif_... |
3,596 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<img src="https
Step1: Vérifiez quelle est votre version de Python
Step2: Exécutez cette cellule pour appliquer le style CSS utilisé dans ce notebook
Step3: Dans les séquences de travai... | Python Code:
print("C'est parti") # affiche le texte en dessous
# essayez de modifier le texte et ré-exécuter
Explanation: <img src="https://live.staticflickr.com/3089/3086874879_5eeb26eda6_w_d.jpg" align=center>
SAÉ 03 - TP1 - Tour d'horizon de Python
Bienvenue sur le Jupyter pour préparer la SAÉ Traitement numérique... |
3,597 |
Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
how to read a .csv file using python
| Python Code::
import pandas as pd
df = pd.read_csv('data.csv')
df.head()
|
3,598 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Implement the sorting algorithm you came up with in pseudocode with Python
Test the sorting algorithm with a list of 10, 100, 1000 random numbers and compare the result using the %time to ti... | Python Code:
import random
list10 = []
for x in range(10):
list10.append(random.randrange(100))
list100 = []
for x in range(100):
list100.append(random.randrange(100))
list1000 = []
for x in range(1000):
list1000.append(random.randrange(100))
def sort_list(old_list):
def find_new_index(old_i):
f... |
3,599 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
「%%bigquery」に続いてSQLを記述するとBigQueryにクエリを投げることができます
例えば、WebUIから実行した「重複なしでバイクステーションの数をカウントする」クエリは以下のように実行します
Step1: 同じように、WebUIから実行した各種クエリを実行してみます。
営業しているバイクステーション
Step2: ユーザーの課金モデル
Step3: バイ... | Python Code:
%%bigquery
SELECT
COUNT(DISTINCT station_id) as cnt
FROM
`bigquery-public-data.new_york.citibike_stations`
Explanation: 「%%bigquery」に続いてSQLを記述するとBigQueryにクエリを投げることができます
例えば、WebUIから実行した「重複なしでバイクステーションの数をカウントする」クエリは以下のように実行します
End of explanation
%%bigquery
SELECT
COUNT(station_id) as cnt
FROM
`bigque... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.