Unnamed: 0 int64 0 16k | text_prompt stringlengths 110 62.1k | code_prompt stringlengths 37 152k |
|---|---|---|
12,100 | 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', 'bnu', 'sandbox-2', 'landice')
Explanation: ES-DOC CMIP6 Model Properties - Landice
MIP Era: CMIP6
Institute: BNU
Source ID: SANDBOX-2
Topic: Landice
Sub-Topics: Glaciers, Ice.
Proper... |
12,101 | 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... |
12,102 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: HW4
Step2: Description of the data set
The data set has been extracted from the Yelp Phoenix restaurants dataset. It is available here.
Step3: The data frame is a frame of reviews. ... | Python Code:
%matplotlib inline
from collections import defaultdict
import json
import numpy as np
import scipy as sp
import matplotlib.pyplot as plt
import pandas as pd
from matplotlib import rcParams
import matplotlib.cm as cm
import matplotlib as mpl
#colorbrewer2 Dark2 qualitative color table
dark2_colors = [(0.105... |
12,103 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Week 4
Step1: 1. 3D Heatmap
NOTE
Step2: 2. Heatmap after thresholding
Here, we assume that there is some level of noise, which can be defined by redefining THRESH below. The same heatmap i... | Python Code:
import numpy as np
import seaborn as sns
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import csv
data = open('../data/data.csv', 'r').readlines()
fieldnames = ['x', 'y', 'z', 'unmasked', 'synapses']
reader = csv.reader(data)
reader.next()
rows = [[int(col) for col in row] for row... |
12,104 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Plot learning curves of different classifiers
This example is a small modification of the sciki-learn tutorial test.
Comparison of different linear SVM classifiers on a 2D projection ... | Python Code:
print(__doc__)
import numpy as np
import matplotlib.pyplot as plt
from sklearn.naive_bayes import GaussianNB
from sklearn.svm import SVC
from sklearn.datasets import load_digits
from sklearn.model_selection import learning_curve
from sklearn.model_selection import ShuffleSplit
def plot_learning_curve(estim... |
12,105 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Send email Clint
Main file for send mail. Function define here
Importing all dependency
Step1: User Details Function
Step2: Login function
In this function we call user details function an... | Python Code:
# ! /usr/bin/python
__author__ = 'Shahariar Rabby'
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.header import Header
from email.utils import formataddr
import getpass
Explanation: Send email Clint
Main file for send mail. Function define here... |
12,106 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Lesson 25
Step1: However, it cannot match multiple repititions
Step2: We can use this to find strings that may or may not include elements, like phone numbers with and without area codes.
... | Python Code:
import re
batRegex = re.compile(r'Bat(wo)?man') # The ()? says this group can appear 0 or 1 times to match; it is optional
mo = batRegex.search('The Adventures of Batman')
print(mo.group())
mo = batRegex.search('The Adventures of Batwoman')
print(mo.group())
Explanation: Lesson 25:
RegEx groups and the Pip... |
12,107 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
To address an interesting and practical case (entanglement doesn't grow too much) we'll use as
an initial state the all zero state apart from two flipped spins
Step1: We'll also set up some... | Python Code:
L = 44
zeros = '0' * ((L - 2) // 3)
binary = zeros + '1' + zeros + '1' + zeros
print('psi0:', f"|{binary}>")
psi0 = qtn.MPS_computational_state(binary)
psi0.show() # prints ascii representation of state
H = qtn.NNI_ham_heis(L)
tebd = qtn.TEBD(psi0, H)
# Since entanglement will not grow too much, we can se... |
12,108 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
1.- Regresión Lineal Ordinaria (LSS)
En esta sección trabajaremos con un dataset conocido como House Sales in King County, USA, presentado
en la plataforma de Kaggle [4], el cual es un gran ... | Python Code:
import pandas as pd
import numpy as np
df = pd.read_csv("kc_house_data.csv")
df.drop(['id','date','zipcode',],axis=1,inplace=True)
df.head()
Explanation: 1.- Regresión Lineal Ordinaria (LSS)
En esta sección trabajaremos con un dataset conocido como House Sales in King County, USA, presentado
en la platafor... |
12,109 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
LAB 1a
Step2: The source dataset
Our dataset is hosted in BigQuery. The CDC's Natality data has details on US births from 1969 to 2008 and is a publically available dataset, meaning anyone ... | Python Code:
%%bash
sudo pip freeze | grep google-cloud-bigquery==1.6.1 || \
sudo pip install google-cloud-bigquery==1.6.1
from google.cloud import bigquery
Explanation: LAB 1a: Exploring natality dataset.
Learning Objectives
Use BigQuery to explore natality dataset
Use Cloud AI Platform Notebooks to plot data explora... |
12,110 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
The objective of this notebook is to show how to read and plot data from a mooring (time series).
Step1: Data reading
The data file is located in the datafiles directory.
Step2: As the pla... | Python Code:
%matplotlib inline
import netCDF4
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib import colors
from mpl_toolkits.basemap import Basemap
Explanation: The objective of this notebook is to show how to read and plot data from a mooring (time series).
End of explanat... |
12,111 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: 12 - Introduction to Deep Learning
by Alejandro Correa Bahnsen
version 0.1, May 2016
Part of the class Machine Learning for Security Informatics
This notebook is licensed under a Cre... | Python Code:
import numpy as np
from load import mnist
X_train, X_test, y_train2, y_test2 = mnist(onehot=True)
y_train = np.argmax(y_train2, axis=1)
y_test = np.argmax(y_test2, axis=1)
X_train[1].reshape((28, 28)).round(2)[:, 4:9].tolist()
from pylab import imshow, show, cm
import matplotlib.pylab as plt
%matplotlib in... |
12,112 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
First TranSiesta example.
This example will only create the structures for input into TranSiesta. I.e. sisl's capabilities of creating geometries with different species is a core functionali... | Python Code:
graphene = sisl.geom.graphene(1.44, orthogonal=True)
graphene.write('STRUCT_ELEC_SMALL.fdf')
graphene.write('STRUCT_ELEC_SMALL.xyz')
elec = graphene.tile(2, axis=0)
elec.write('STRUCT_ELEC.fdf')
elec.write('STRUCT_ELEC.xyz')
Explanation: First TranSiesta example.
This example will only create the structure... |
12,113 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Overview
This CodeLab demonstrates how to build a fused TFLite LSTM model for MNIST recognition using Keras, and how to convert it to TensorFlow Lite.
The CodeLab is very similar to the Kera... | Python Code:
!pip install tf-nightly
Explanation: Overview
This CodeLab demonstrates how to build a fused TFLite LSTM model for MNIST recognition using Keras, and how to convert it to TensorFlow Lite.
The CodeLab is very similar to the Keras LSTM CodeLab. However, we're creating fused LSTM ops rather than the unfused v... |
12,114 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Integrating XML with Python
NLTK, the Python Natural Languge ToolKit package, is designed to work with plain text input, but sometimes your input is in XML. There are two principal paths to ... | Python Code:
import nltk
# nltk.download()
Explanation: Integrating XML with Python
NLTK, the Python Natural Languge ToolKit package, is designed to work with plain text input, but sometimes your input is in XML. There are two principal paths to reconciliation: either use an XML environment that supports NLP (natural l... |
12,115 | 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 classification model for batch prediction
<tabl... |
12,116 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
This notebook provides a way to download data files using the <a href="http
Step1: All of the data files for Particle Physics Playground are currently hosted in this Google Drive folder. To... | Python Code:
import pps_tools as pps
#pps.download_drive_file()
#pps.download_file()
Explanation: This notebook provides a way to download data files using the <a href="http://docs.python-requests.org/en/latest/">Python requests library</a>. You'll need to have this library installed on your system to do any work.
The... |
12,117 | Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
I have a pandas series which values are numpy array. For simplicity, say | Problem:
import pandas as pd
import numpy as np
series = pd.Series([np.array([1,2,3,4]), np.array([5,6,7,8]), np.array([9,10,11,12])], index=['file1', 'file2', 'file3'])
def g(s):
return pd.DataFrame.from_records(s.values,index=s.index)
df = g(series.copy()) |
12,118 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Rebalancing Design Pattern
The Rebalancing Design Pattern provides various approaches for handling datasets that are inherently imbalanced. By this we mean datasets where one label makes up ... | Python Code:
import itertools
import math
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import tensorflow as tf
import xgboost as xgb
from tensorflow import keras
from tensorflow.keras import Sequential
from sklearn.metrics import confusion_matrix
from sklearn.preprocessing import MinMaxScaler... |
12,119 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Big Query Machine Learning (BQML)
Learning Objectives
- Understand that it is possible to build ML models in Big Query
- Understand when this is appropriate
- Experience building a model usi... | Python Code:
from google import api_core
from google.cloud import bigquery
PROJECT = !gcloud config get-value project
PROJECT = PROJECT[0]
%env PROJECT=$PROJECT
Explanation: Big Query Machine Learning (BQML)
Learning Objectives
- Understand that it is possible to build ML models in Big Query
- Understand when this is a... |
12,120 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Upper Air Analysis using Declarative Syntax
The MetPy declarative syntax allows for a simplified interface to creating common
meteorological analyses including upper air observation plots.
S... | Python Code:
from datetime import datetime
import pandas as pd
from metpy.cbook import get_test_data
import metpy.plots as mpplots
from metpy.units import units
Explanation: Upper Air Analysis using Declarative Syntax
The MetPy declarative syntax allows for a simplified interface to creating common
meteorological analy... |
12,121 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: What's this TensorFlow business?
You've written a lot of code in this assignment to provide a whole host of neural network functionality. Dropout, Batch Norm, and 2D convolutions are ... | Python Code:
import tensorflow as tf
import numpy as np
import math
import timeit
import matplotlib.pyplot as plt
%matplotlib inline
from cs231n.data_utils import load_CIFAR10
def get_CIFAR10_data(num_training=49000, num_validation=1000, num_test=10000):
Load the CIFAR-10 dataset from disk and perform preproce... |
12,122 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Fast GP implementations
Step5: Benchmarking our implementation
Let's do some timing tests and compare them to what we get with two handy GP packages
Step6: <div style="background-color
Ste... | Python Code:
%matplotlib inline
%config InlineBackend.figure_format = 'retina'
from matplotlib import rcParams
rcParams["savefig.dpi"] = 100
rcParams["figure.dpi"] = 100
rcParams["figure.figsize"] = 12, 4
rcParams["font.size"] = 16
rcParams["text.usetex"] = False
rcParams["font.family"] = ["sans-serif"]
rcParams["font.... |
12,123 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
MTA Subway Stations dataset cleaning
In this notebook we will clean the Subway Stations dataset made available by MTA.
Let's start by opening and examining it.
Step1: Let's extract the lati... | Python Code:
import pandas as pd
stations = pd.read_csv('data/DOITT_SUBWAY_STATION_01_13SEPT2010.csv')
stations.head(4)
Explanation: MTA Subway Stations dataset cleaning
In this notebook we will clean the Subway Stations dataset made available by MTA.
Let's start by opening and examining it.
End of explanation
import c... |
12,124 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Lab 5.2 - Using your own images
In the next part of the lab we will download another set of images from the web and format them for use with a Convolutional Neural Network (CNN). In this exa... | Python Code:
%matplotlib inline
from matplotlib.pyplot import imshow
import matplotlib.pyplot as plt
import numpy as np
from scipy import misc
import os
import random
import pickle
Explanation: Lab 5.2 - Using your own images
In the next part of the lab we will download another set of images from the web and format the... |
12,125 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
kneed -- knee detection in Python
For the purposes of the walkthrough, import DataGenerator to create simulated datasets.
In practice, the KneeLocator class will be used to identify the knee... | Python Code:
%matplotlib inline
from kneed.data_generator import DataGenerator as dg
from kneed.knee_locator import KneeLocator
import seaborn as sns
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
x = [3.07, 3.38, 3.55, 3.68, 3.78, 3.81, 3.85, 3.88, 3.9, 3.93]
y = [0.0, 0.3, 0.47, 0.6, 0.69, 0.78... |
12,126 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
TF-Slim Walkthrough
This notebook will walk you through the basics of using TF-Slim to define, train and evaluate neural networks on various tasks. It assumes a basic knowledge of neural net... | Python Code:
import matplotlib
%matplotlib inline
import matplotlib.pyplot as plt
import math
import numpy as np
import tensorflow as tf
import time
from datasets import dataset_utils
# Main slim library
slim = tf.contrib.slim
Explanation: TF-Slim Walkthrough
This notebook will walk you through the basics of using TF-S... |
12,127 | 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', 'ncar', 'sandbox-1', 'landice')
Explanation: ES-DOC CMIP6 Model Properties - Landice
MIP Era: CMIP6
Institute: NCAR
Source ID: SANDBOX-1
Topic: Landice
Sub-Topics: Glaciers, Ice.
Prop... |
12,128 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Compute iterative reweighted TF-MxNE with multiscale time-frequency dictionary
The iterative reweighted TF-MxNE solver is a distributed inverse method
based on the TF-MxNE solver, which prom... | Python Code:
# Author: Mathurin Massias <mathurin.massias@gmail.com>
# Yousra Bekhti <yousra.bekhti@gmail.com>
# Daniel Strohmeier <daniel.strohmeier@tu-ilmenau.de>
# Alexandre Gramfort <alexandre.gramfort@inria.fr>
#
# License: BSD (3-clause)
import os.path as op
import mne
from mne.datasets im... |
12,129 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
This tutorial is based on example in Jake Vanderplas' PyCon 2015 tutorial.
What is Machine Learning
Machine Learning is a subfield of computer science that utilizes statistics and mathemathi... | Python Code:
YouTubeVideo("IFACrIx5SZ0", start = 85, end = 95)
Explanation: This tutorial is based on example in Jake Vanderplas' PyCon 2015 tutorial.
What is Machine Learning
Machine Learning is a subfield of computer science that utilizes statistics and mathemathical optimization to learn generalizable patterns from ... |
12,130 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Experience
Based on annoted ground truth, we tried to learn a model to classify domains specific words.
We use as input a combinaison of 4 datasets
Step1: Considering the nature of the date... | Python Code:
summaryDf = pd.DataFrame([extractSummaryLine(l) for l in open('../../data/learnedModel/domain/summary.txt').readlines()],
columns=['domain', 'strict', 'clf', 'feature', 'post', 'precision', 'recall', 'f1'])
summaryDf = summaryDf[summaryDf['clf'] != 'KNeighborsClassifier'].sort_value... |
12,131 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Inference plots - Histogram plots
This example builds on adaptive covariance MCMC, and shows you how to plot the MCMC chain histograms, also known as the marginal posterior distributions.
Ot... | Python Code:
import pints
import pints.toy as toy
import numpy as np
import matplotlib.pyplot as plt
# Load a forward model
model = toy.LogisticModel()
# Create some toy data
real_parameters = [0.015, 500] # growth rate, carrying capacity
times = np.linspace(0, 1000, 100)
org_values = model.simulate(real_parameters, t... |
12,132 |
Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
How to plot a scatter plot using pyhton
| Python Code::
import matplotlib.pyplot as plt
plt.scatter(x, y)
plt.show()
|
12,133 |
Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
Example of generating samples from the two circle problem
| Python Code::
from sklearn.datasets import make_circles
from matplotlib import pyplot
from numpy import where
X, y = make_circles(n_samples=1000, noise=0.1, random_state=1)
for i in range(2):
samples_ix = where(y == i)
pyplot.scatter(X[samples_ix, 0], X[samples_ix, 1])
pyplot.show()
|
12,134 | 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... |
12,135 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
If you are running this notebook on google collab, uncomment and execute the cell below. Otherwise you can jump down to the other import statements.
Step1: Multi-Dimensional Integration wit... | Python Code:
#!pip install emcee==3.0rc2
#!pip install corner
import numpy as np
import pandas as pd
from scipy.optimize import minimize, newton
import emcee
import corner
import matplotlib.pyplot as plt
np.random.seed(42)
Explanation: If you are running this notebook on google collab, uncomment and execute the cell be... |
12,136 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Contents
This notebook shows how to use the functionality in the HealpixTree class. This is a useful function to find groups of Healpixels at high resolution which are connected and nearby. ... | Python Code:
from mpl_toolkits.basemap import Basemap
import opsimsummary as oss
oss.__VERSION__
from opsimsummary import HealpixTree, pixelsForAng, HealpixTiles
import numpy as np
%matplotlib inline
import matplotlib.pyplot as plt
import healpy as hp
Explanation: Contents
This notebook shows how to use the functionali... |
12,137 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Watch Me Code 1
Step1: Manual Plotting in Matplotlib
Step2: Plotting chart types
Step3: Plotting with Pandas | Python Code:
# Jupyter Directive
%matplotlib inline
# imports
import matplotlib
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
matplotlib.rcParams['figure.figsize'] = (20.0, 10.0) # larger figure size
Explanation: Watch Me Code 1: Matplotlib
We will demonstrate Pythons data visualization librar... |
12,138 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Traduction du notebook Discover your Poppy Ergo Jr par Georges Saliba sous licence CC BY SA
Découvrir votre Poppy Ergo Jr
Ce notebook qui permet à la fois d'insérer du code pour faire fonc... | Python Code:
%pylab inline
from __future__ import print_function
Explanation: Traduction du notebook Discover your Poppy Ergo Jr par Georges Saliba sous licence CC BY SA
Découvrir votre Poppy Ergo Jr
Ce notebook qui permet à la fois d'insérer du code pour faire fonctionner le robot et de le commenter dans le même tem... |
12,139 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Example of DOV search methods for lithologische beschrijvingen
Use cases
Step1: Get information about code base
Step2: The cost is an arbitrary attribute to indicate if the information is ... | Python Code:
%matplotlib inline
import os, sys
import inspect
import pydov
Explanation: Example of DOV search methods for lithologische beschrijvingen
Use cases:
Select records in a bbox
Select records in a bbox with selected properties
Select records in a municipality
Get records using info from wfs fields, not availa... |
12,140 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Comparing fast XGM data from two simultaneous recordings
Here we will look at XGM data that was recorded by the X-ray photon diagnostics group at the same short time interval, but at differe... | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
import xarray as xr
from karabo_data import RunDirectory
Explanation: Comparing fast XGM data from two simultaneous recordings
Here we will look at XGM data that was recorded by the X-ray photon diagnostics group at the same short time i... |
12,141 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
DeepDreaming with TensorFlow
Loading and displaying the model graph
Naive feature visualization
Multiscale image generation
Laplacian Pyramid Gradient Normalization
Playing with feature visu... | Python Code:
# boilerplate code
from __future__ import print_function
import os
from io import BytesIO
import numpy as np
from functools import partial
import PIL.Image
from IPython.display import clear_output, Image, display, HTML
import tensorflow as tf
Explanation: DeepDreaming with TensorFlow
Loading and displaying... |
12,142 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
http
Step1: p
Step2: Train - Test | Python Code:
from __future__ import division
from os import path, remove
import numpy as np
import pandas as pd
import csv
from sklearn.model_selection import StratifiedShuffleSplit
from time import time
from matplotlib import pyplot as plt
import seaborn as sns
from tensorflow.contrib import rnn
from tensorflow.contri... |
12,143 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Fill Database WaveForm Headers
1) Import de las librerias que utilizaremos
Step1: 2) Leemos el archivo con las WaveForm que vamos a utilizar
Step2: 3) Limpiamos los caracteres extraños y D... | Python Code:
import urllib.request
import wfdb
import psycopg2
from psycopg2.extensions import AsIs
Explanation: Fill Database WaveForm Headers
1) Import de las librerias que utilizaremos
End of explanation
target_url = "https://physionet.org/physiobank/database/mimic2wdb/matched/RECORDS-waveforms"
data = urllib.reques... |
12,144 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Predicting house prices using Linear Regression
(See Getting Started with SFrames for setup instructions)
Step2: Load house sales data
Dataset is from house sales in King County, the... | Python Code:
import os
from urllib import urlretrieve
import graphlab
# Limit number of worker processes. This preserves system memory, which prevents hosted notebooks from crashing.
graphlab.set_runtime_config('GRAPHLAB_DEFAULT_NUM_PYLAMBDA_WORKERS', 4)
URL = 'https://d396qusza40orc.cloudfront.net/phoenixassets/home_d... |
12,145 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Sentiment Analysis
Jose Manuel Vera Aray
Import libraries to be used
Step1: Import training data
Step2: Separate tweets into two sets
Step3: Split the data into the training set and test ... | Python Code:
import numpy as np
import itertools
import math
import pandas as pd
import csv
import time
from sklearn.cross_validation import train_test_split, KFold
from sklearn.naive_bayes import MultinomialNB
from sklearn.linear_model import LogisticRegression, SGDClassifier
from sklearn.model_selection import learni... |
12,146 | Given the following text description, write Python code to implement the functionality described.
Description:
Minimum number of given operations required to reduce the array to 0 element
Function to return the minimum operations required ; Count the frequency of each element ; Maximum element from the array ; Find all... | Python Code:
def minOperations(arr , n ) :
result = 0
freq =[0 ] * 1000001
for i in range(0 , n ) :
freq[arr[i ] ] += 1
maxi = max(arr )
for i in range(1 , maxi + 1 ) :
if freq[i ] != 0 :
for j in range(i * 2 , maxi + 1 , i ) :
freq[j ] = 0
result += 1
return result
if __name__== ... |
12,147 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Planar data classification with one hidden layer
Welcome to your week 3 programming assignment. It's time to build your first neural network, which will have a hidden layer. You will see a b... | Python Code:
# Package imports
import numpy as np
import matplotlib.pyplot as plt
from testCases_v2 import *
import sklearn
import sklearn.datasets
import sklearn.linear_model
from planar_utils import plot_decision_boundary, sigmoid, load_planar_dataset, load_extra_datasets
%matplotlib inline
np.random.seed(1) # set a ... |
12,148 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Pandas and Scikit-learn
Pandas is a Python library that contains high-level data structures and manipulation tools designed for data analysis. Think of Pandas as a Python version of Excel. S... | Python Code:
import pandas as pd
import numpy as np
df = pd.read_csv('../data/train.csv')
Explanation: Pandas and Scikit-learn
Pandas is a Python library that contains high-level data structures and manipulation tools designed for data analysis. Think of Pandas as a Python version of Excel. Scikit-learn, on the other h... |
12,149 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
=================================
Decoding sensor space data (MVPA)
=================================
Decoding, a.k.a MVPA or supervised machine learning applied to MEG
data in sensor space.... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
import mne
from mne.datasets import sample
from mne.decoding import (SlidingEstimator, GeneralizingEstimator,
... |
12,150 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Text Using Markdown
If you double click on this cell, you will see the text change so that all of the formatting is removed. This allows you to edit this block of text. This block of text is... | Python Code:
# Hit shift + enter or use the run button to run this cell and see the results
print 'hello world'
# The last line of every code cell will be displayed by default,
# even if you don't print it. Run this cell to see how this works.
2 + 2 # The result of this line will not be displayed
3 + 3 # The result of... |
12,151 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Crime prediction from Hawkes processes
Here we continue to explore the EM algorithm for Hawkes processes, but now concentrating upon
Step1: Simulation of the process in a single cell
Step2:... | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
Explanation: Crime prediction from Hawkes processes
Here we continue to explore the EM algorithm for Hawkes processes, but now concentrating upon:
Mohler et al. "Randomized Controlled Field Trials of Predictive Policing". Journal of the ... |
12,152 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Grade
Step1: 2) What genres are most represented in the search results? Edit your previous printout to also display a list of their genres in the format "GENRE_1, GENRE_2, GENRE_3". If ther... | Python Code:
# !pip3 install requests
import requests
response = requests.get('https://api.spotify.com/v1/search?query=Lil+&offset=0&limit=50&type=artist&market=US')
data = response.json()
data.keys()
artist_data = data['artists']['items']
for artist in artist_data:
print(artist['name'], artist['popularity'], artis... |
12,153 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Test distribution of errors
Step1: Attempts to fit nonparametric distributions | Python Code:
import scipy
import scipy.stats
diff = (network_out-true_out[:,8:])
#print(diff.shape)
y = diff[:,5]
print(y.shape)
#y = np.square(y)
x = np.arange(-3,3,0.01)
size = diff.shape[0]
h = plt.hist(y, bins=100, color='w')
plt.xlim(-3,3)
plt.ylim(0,1000)
dist_names = ['t']
for dist_name in dist_names:
dist ... |
12,154 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Handling bad channels
This tutorial covers manual marking of bad channels and reconstructing bad
channels based on good signals at other sensors.
As usual we'll start by importing the module... | Python Code:
import os
from copy import deepcopy
import numpy as np
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, verbos... |
12,155 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Compute spatial resolution metrics in source space
Compute peak localisation error and spatial deviation for the point-spread
functions of dSPM and MNE. Plot their distributions and differen... | Python Code:
# Author: Olaf Hauk <olaf.hauk@mrc-cbu.cam.ac.uk>
#
# License: BSD (3-clause)
import mne
from mne.datasets import sample
from mne.minimum_norm import make_inverse_resolution_matrix
from mne.minimum_norm import resolution_metrics
print(__doc__)
data_path = sample.data_path()
subjects_dir = data_path + '/sub... |
12,156 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Matplotlib Exercise 2
Imports
Step1: Exoplanet properties
Over the past few decades, astronomers have discovered thousands of extrasolar planets. The following paper describes the propertie... | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
Explanation: Matplotlib Exercise 2
Imports
End of explanation
!head -n 30 open_exoplanet_catalogue.txt
Explanation: Exoplanet properties
Over the past few decades, astronomers have discovered thousands of extrasolar planets. The followin... |
12,157 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Graficación
Antes que nada, tenemos que aprender a graficar en Python, lo manera mas fácil de graficar es usando la función plot de la libería matplotlib, asi que importamos esta función
Ste... | Python Code:
from matplotlib.pyplot import plot
Explanation: Graficación
Antes que nada, tenemos que aprender a graficar en Python, lo manera mas fácil de graficar es usando la función plot de la libería matplotlib, asi que importamos esta función:
End of explanation
plot([0,1], [2,3])
Explanation: y la usamos como cua... |
12,158 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Summary
We will use PyMC3 to estimate the posterior PDF for the true rating of a set of artificial teams using data from a simulated season. The idea is to test our model on a small set of a... | Python Code:
import pandas as pd
import os
import numpy as np
import pymc3 as pm
import seaborn as sns
import matplotlib.pyplot as plt
%matplotlib inline
true_rating = {
'All Stars': 2.0,
'Average': 0.0,
'Just Having Fun': -1.2,
}
true_index = {
0: 'All Stars',
1: 'Average',
2: 'Just Having Fun'... |
12,159 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Create Basic Charts (Plots)
In this notebook we'll be creating a number of basic charts from our data, including a histogram, box plot, and scatterplot.
Step1: Import The Data
Step2: Creat... | Python Code:
# To show matplotlib plots in iPython Notebook we can use an iPython magic function
%matplotlib inline
# Import everything we need
import pandas as pd
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
Explanation: Create Basic Charts (Plots)
In this notebook we'll be creating a nu... |
12,160 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Atmos
MIP Era
Step1: Document Authors
Set document authors
Step2: Document Contributors
Specify document contributors
Step3: Document Publication
Specify d... | Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'cnrm-cerfacs', 'cnrm-cm6-1', 'atmos')
Explanation: ES-DOC CMIP6 Model Properties - Atmos
MIP Era: CMIP6
Institute: CNRM-CERFACS
Source ID: CNRM-CM6-1
Topic: Atmos
Sub-Topics: Dynamica... |
12,161 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
import fgm tables
Step1: Function libaries
ResBlock
res_block is the backbone of the resnet structure. The resblock has multi branch, bottle neck layer and skip connection build in. This m... | Python Code:
!pip install gdown
!mkdir ./data
import gdown
def data_import():
ids = {
"tables_of_fgm.h5":"1XHPF7hUqT-zp__qkGwHg8noRazRnPqb0"
}
url = 'https://drive.google.com/uc?id='
for title, g_id in ids.items():
try:
output_file = open("/content/data/" + title, 'wb')
gdown.download(url... |
12,162 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Fit X in the gmm model for 1, 2, ... 10 components. Hint
Step1: Calculate the AIC and BIC for each of these 10 models, and find the best model.
Step2: Plot the AIC and BIC
Step3: Define ... | Python Code:
gmms = [GMM(i).fit(X) for i in range(1,10)]
Explanation: Fit X in the gmm model for 1, 2, ... 10 components. Hint: You should create 10 instances of a GMM model, e.g. GMM(?).fit(X) would be one instance of a GMM model with ? components.
End of explanation
aics = [g.aic(X) for g in gmms]
bics = [g.bic(X) f... |
12,163 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
载入数据、查阅基本信息
用户的基本信息,逾期情况,接待对象,金额
'注册日期', '来源渠道', '用户级别', '拨打次数', '客户ID', '客户性别', '年龄', '客户设备', '客户所属省',
'客户公司地址', '客户授信状态', '评分原因', '标识原因', '总分', '初审审核说明', '审核人', '备注', '授信额度',
... | Python Code:
user_info = pd.read_excel('2000_sample.xlsx', 'user_info')
user_info.head()
# 独立检验
user_info.客户ID.unique().shape
# 总的分析
user_info.describe()
Explanation: 载入数据、查阅基本信息
用户的基本信息,逾期情况,接待对象,金额
'注册日期', '来源渠道', '用户级别', '拨打次数', '客户ID', '客户性别', '年龄', '客户设备', '客户所属省',
'客户公司地址', '客户授信状态', '评分原因', '标识原因', '总分', ... |
12,164 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Interruptible optimization runs with checkpoints
Christian Schell, Mai 2018
Reformatted by Holger Nahrstaedt 2020
.. currentmodule
Step1: Simple example
We will use pretty much the same opt... | Python Code:
print(__doc__)
import sys
import numpy as np
np.random.seed(777)
import os
Explanation: Interruptible optimization runs with checkpoints
Christian Schell, Mai 2018
Reformatted by Holger Nahrstaedt 2020
.. currentmodule:: skopt
Problem statement
Optimization runs can take a very long time and even run for m... |
12,165 | 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: Custom training tabular regression model for online prediction... |
12,166 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Malaysian MP Statistics
A live notebook of working examples of using Sinar's Popit API and database of Malaysian MPs.
TODO
Detailed information of Persons should probably be appended to post... | Python Code:
import requests
import json
#Dewan Rakyat MP Posts in Sinar Malaysia Popit Database
posts = []
for page in range(1,10):
dewan_rakyat_request = requests.get('http://sinar-malaysia.popit.mysociety.org/api/v0.1/search/posts?q=organization_id:53633b5a19ee29270d8a9ecf'+'&page='+str(page))
for post in (j... |
12,167 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
TP2 - Object recognition using neural networks and convolutional neural networks
M4108C/M4109C - INFOgr2D
Student 1
Step1: Your response
Step2: Your comment
Step3: On a divisé par deux le... | Python Code:
from __future__ import print_function
import numpy as np
np.random.seed(7)
import keras
from keras.datasets import cifar10
# load and split data into training and test sets --> it may take some times with your own laptop
(x_train, y_train), (x_test, y_test) = cifar10.load_data()
# describe your data (use p... |
12,168 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Self-Driving Car Engineer Nanodegree
Deep Learning
Project
Step1: Step 1
Step2: An Exploratory Visualization of the Dataset
Number of Samples in Each Category
The categories with minimum/m... | Python Code:
# Load pickled data
import pickle
import pandas as pd
# Data's location
training_file = "traffic-sign-data/train.p"
validation_file = "traffic-sign-data/valid.p"
testing_file = "traffic-sign-data/test.p"
with open(training_file, mode='rb') as f:
train = pickle.load(f)
with open(validation_file, mode='r... |
12,169 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Plotting
In this notebook, I'll develop a function to plot subjects and their labels.
Step1: Displaying radio images
Radio images look pretty terrible, so let's run a filter over them to ma... | Python Code:
from astropy.coordinates import SkyCoord
import astropy.io.fits
import astropy.wcs
import h5py
import matplotlib.pyplot as plt
from matplotlib.pyplot import cm
import numpy
import skimage.exposure
import sklearn.neighbors
import sklearn.pipeline
import sklearn.preprocessing
CROWDASTRO_H5_PATH = 'data/crowd... |
12,170 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Atmos
MIP Era
Step1: Document Authors
Set document authors
Step2: Document Contributors
Specify document contributors
Step3: Document Publication
Specify d... | Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'dwd', 'mpi-esm-1-2-hr', 'atmos')
Explanation: ES-DOC CMIP6 Model Properties - Atmos
MIP Era: CMIP6
Institute: DWD
Source ID: MPI-ESM-1-2-HR
Topic: Atmos
Sub-Topics: Dynamical Core, Ra... |
12,171 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Studio
Step2: Solution with only Number
Step3: Solution provided in class | Python Code:
days_of_week = [
# 0 1 2
'Sunday', 'Monday', 'Tuesday',
# 3 4 5
'Wednesday', 'Thursday', 'Friday',
# 6
'Saturday',
]
# Gather user input
# Need to use the `int` call so that it'll correctly be
# an integer for mathmatical operations
leaving_d... |
12,172 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Ordinary Differential Equations Exercise 1
Imports
Step2: Lorenz system
The Lorenz system is one of the earliest studied examples of a system of differential equations that exhibits chaotic... | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
from scipy.integrate import odeint
from IPython.html.widgets import interact, fixed
Explanation: Ordinary Differential Equations Exercise 1
Imports
End of explanation
def lorentz_derivs(yvec, t, sigma, rho, beta):
Compute the the der... |
12,173 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<table align="left">
<td>
<a href="https
Step3: Clone and build tensorflow_cloud
To use the latest version of the tensorflow_cloud, we will clone and build the repo. The resulti... | Python Code:
import sys
# If you are running this notebook in Colab, run this cell and follow the
# instructions to authenticate your Google Cloud account. This provides access
# to your Cloud Storage bucket and lets you submit training jobs and prediction
# requests.
if 'google.colab' in sys.modules:
from google.c... |
12,174 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Wine Selection
Framing
I want to buy a fine wine but I have no idea about wine selection.I'm not good at wine tasting.
I will use the data and understand what goes into making fine wine
Step... | Python Code:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
plt.style.use('ggplot')
plt.rcParams['figure.figsize'] = (13,8)
df = pd.read_csv("./winequality-red.csv")
df.head()
df.shape
Explanation: Wine Selection
Framing
I want to buy a fine wine but I ha... |
12,175 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introduction to the Lomb-Scargle Periodogram
Version 0.2
By AA Miller (Northwester/CIERA)
15 Sep 2021
Today we examine the detection of periodic signals in noisy, irregular data (the standar... | Python Code:
def gen_periodic_data(x, period=1, amplitude=1, phase=0, noise=0):
'''Generate periodic data given the function inputs
y = A*sin(2*pi*x/p - phase) + noise
Parameters
----------
x : array-like
input values to evaluate the array
period : float (default=1)
... |
12,176 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step4: Example
Step5: Problem data
this algorithm has the same flavor as the thing I'd like to do, but actually converges very slowly
will take a very long time to converge anything other t... | Python Code:
import numpy as np
from scipy.linalg import cho_factor, cho_solve
%matplotlib inline
import matplotlib.pyplot as plt
def factor(A,b):
Return cholesky factorization data to project onto Ax=b.
AAt = A.dot(A.T)
chol = cho_factor(AAt, overwrite_a=True)
c = cho_solve(chol, b, overwrite_b=Fa... |
12,177 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
verify pyEMU null space projection with the freyberg problem
Step1: instaniate pyemu object and drop prior info. Then reorder the jacobian and save as binary. This is needed because the p... | Python Code:
%matplotlib inline
import os
import shutil
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import pyemu
Explanation: verify pyEMU null space projection with the freyberg problem
End of explanation
mc = pyemu.MonteCarlo(jco="freyberg.jcb",verbose=False,forecasts=[])
mc.drop_prior_info... |
12,178 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
2. Gender Detection
Figuring out genders from names
We're going to use 3 different methods, all of which use a similar philosophy. Essentially, each of these services have build databases fr... | Python Code:
import os
os.chdir("../data/pubdata")
names = []
with open("comp.csv") as infile:
for line in infile:
names.append(line.split(",")[5])
Explanation: 2. Gender Detection
Figuring out genders from names
We're going to use 3 different methods, all of which use a similar philosophy. Essentially, eac... |
12,179 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Trace Analysis Examples
Tasks Latencies
This notebook shows the features provided for task latency profiling. It will be necessary to collect the following events
Step1: Target Configuratio... | Python Code:
import logging
from conf import LisaLogging
LisaLogging.setup()
# Generate plots inline
%matplotlib inline
import json
import os
# Support to access the remote target
import devlib
from env import TestEnv
# Support for workload generation
from wlgen import RTA, Ramp
# Support for trace analysis
from trace ... |
12,180 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Titanic Survival Analysis
Step1: The next step is to explore the dataset
Step2: We can see that Passenger ID, Name and Cabin have little value to the analysis, so we drop these columns off... | Python Code:
# Import the libraries
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import scipy
# Read the csv file
titanic = pd.read_csv("titanic-data.csv")
Explanation: Titanic Survival Analysis:
First steps:
First, we need to import all the libraries needed for the analy... |
12,181 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Dieses Notebook ist ein Skript (Drehbuch) zur Vorstellung grundlegender Funktionen von Jupyter, Python, Pandas und matplotlib, um ein Gefühl für die Arbeit mit den Biblotheken zu bekommen. D... | Python Code:
"Hello World"
Explanation: Dieses Notebook ist ein Skript (Drehbuch) zur Vorstellung grundlegender Funktionen von Jupyter, Python, Pandas und matplotlib, um ein Gefühl für die Arbeit mit den Biblotheken zu bekommen. Daher ist das gewählte Beispiel so gewählt, dass wir typische Aufgaben während einer Datena... |
12,182 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<center> Pachetul Python Networkx. Popularitatea nodurilor unei retele</center>
Networkx este un pachet Python destinat generarii si analizei structurii si proprietatilor unei retele.
O rete... | Python Code:
import numpy as np
A=np.array([0, 1, 0, 1, 1,
1, 0, 0, 0, 1,
0, 0, 0, 1, 1,
1, 0, 1, 0, 1,
1, 1, 1, 1, 0], float).reshape((5,5))
print A
Explanation: <center> Pachetul Python Networkx. Popularitatea nodurilor unei retele</center>
Networkx este un pachet Python destinat generarii si analizei s... |
12,183 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Sparse and dense representations for text data
Before we can start training we need to prepare our input data in a way that our model will understand it.
Step1: Since we're dealing with tex... | Python Code:
import tensorflow as tf
import numpy as np
import pandas as pd
%matplotlib inline
Explanation: Sparse and dense representations for text data
Before we can start training we need to prepare our input data in a way that our model will understand it.
End of explanation
from utils import SentenceEncoder
sents... |
12,184 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Chapter 8
Modeling and Simulation in Python
Copyright 2021 Allen Downey
License
Step1: In the previous chapter we developed a quadratic model of world
population growth from 1950 to 2016. I... | Python Code:
# install Pint if necessary
try:
import pint
except ImportError:
!pip install pint
# download modsim.py if necessary
from os.path import exists
filename = 'modsim.py'
if not exists(filename):
from urllib.request import urlretrieve
url = 'https://raw.githubusercontent.com/AllenDowney/ModSim/... |
12,185 |
Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
We will describe the model in three parts:
1) Photo Feature Extractor. This is a 16-layer VGG model pre-trained on the ImageNet dataset. We have pre-processed the photos with the V... | Python Code::
# define the captioning model
def define_model(vocab_size, max_length):
# feature extractor model
inputs1 = Input(shape=(4096,))
fe1 = Dropout(0.5)(inputs1)
fe2 = Dense(256, activation='relu')(fe1)
# sequence model
inputs2 = Input(shape=(max_length,))
se1 = Embedding(vocab_size, 256, mask_zero=True... |
12,186 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Image features exercise
Complete and hand in this completed worksheet (including its outputs and any supporting code outside of the worksheet) with your assignment submission. For more detai... | Python Code:
import random
import numpy as np
from cs231n.data_utils import load_CIFAR10
import matplotlib.pyplot as plt
%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 auto-reloading ex... |
12,187 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Problem statement
The Stokes problem is a classical example of a mixed problem.
Initialize
Step1: Geometry and mesh generation
Step2: Assembly
Step3: Next we create assemblers for the ele... | Python Code:
import sys
sys.path.append('../')
import numpy as np
import matplotlib.pyplot as plt
from spfem.geometry import GeometryMeshPyTriangle
%matplotlib inline
Explanation: Problem statement
The Stokes problem is a classical example of a mixed problem.
Initialize
End of explanation
g = GeometryMeshPyTriangle(np.... |
12,188 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Connecting Spectra to Mocks
The purpose of this notebook is to demonstrate how to generate spectra and apply target selection cuts for various mock catalogs and target types. Here we genera... | Python Code:
import os
import sys
import numpy as np
import matplotlib.pyplot as plt
from desiutil.log import get_logger, DEBUG
log = get_logger()
import seaborn as sns
sns.set(style='white', font_scale=1.1, palette='Set2')
%matplotlib inline
Explanation: Connecting Spectra to Mocks
The purpose of this notebook is to d... |
12,189 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Testing for data analysis
In a data analysis context, we want to test our code, as usual, but also our data (i.e., expected schema; e.g., data types) and our statistics (i.e., expected prope... | Python Code:
import pandas as pd
df = pd.read_csv('../data/tidy_who.csv')
df.sample(5)
Explanation: Testing for data analysis
In a data analysis context, we want to test our code, as usual, but also our data (i.e., expected schema; e.g., data types) and our statistics (i.e., expected properties of distributions; e.g., ... |
12,190 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Prediction Failed Movies
Loading the dataset
Step1: Feature Generation
Generating some additional basic features
Step2: The number of null values per column
Step3: Keeping all genre dummy... | Python Code:
import os
import pandas as pd
import sklearn as skl
import holcrawl.shared
dataset_dir = holcrawl.shared._get_dataset_dir_path()
dataset_path = os.path.join(dataset_dir, 'movies_dataset.csv')
df = pd.read_csv(dataset_path)
Explanation: Prediction Failed Movies
Loading the dataset
End of explanation
df['ROI... |
12,191 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Using Python to Access NCEI Archived NEXRAD Level 2 Data
This notebook shows how to access the THREDDS Data Server (TDS) instance that is serving up archived NEXRAD Level 2 data hosted on Am... | Python Code:
import matplotlib
import warnings
warnings.filterwarnings("ignore", category=matplotlib.cbook.MatplotlibDeprecationWarning)
%matplotlib inline
Explanation: Using Python to Access NCEI Archived NEXRAD Level 2 Data
This notebook shows how to access the THREDDS Data Server (TDS) instance that is serving up ar... |
12,192 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Plot bokeh graphs
The purpose of this notebook is to create a bokeh representation of the latest data (incl. QC) from socib mooring stations.
Define Imports
Step1: In case, the output wants... | Python Code:
import numpy as np
import pandas as pd
from urllib2 import Request, urlopen, URLError
from lxml import html
import time
from netCDF4 import Dataset
import datetime
import calendar
from collections import OrderedDict
from bokeh.plotting import figure, ColumnDataSource
from bokeh.models import HoverTool
from... |
12,193 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Classifying newswires
Step1: Like with the IMDB dataset, the argument num_words=10000 restricts the data to the 10,000 most frequently occurring words found in the
data.
We have 8,982 trai... | Python Code:
from keras.datasets import reuters
(train_data, train_labels), (test_data, test_labels) = reuters.load_data(num_words=10000)
Explanation: Classifying newswires: a multi-class classification example
This notebook contains the code samples found in Chapter 3, Section 5 of Deep Learning with Python. Note that... |
12,194 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<h3>Basic Recipe for Training a POS Tagger with SpaCy</h3>
<ol>
<li id="loaddatatitle"><a href="#-Load-Data-">Load Data </a>
<ol><li>We'll be using a sample from Web Treebank corpus, in Conl... | Python Code:
import sys
sys.path.append('/home/jupyter/site-packages/')
import requests
from spacy.syntax.arc_eager import PseudoProjectivity
def read_conllx(text):
bad_lines = 0
#t = text.strip()
#print(type(t), type('\n\n'))
# u = t.split(b'\n\n')
n_sent = 0
n_line = 0
print('... |
12,195 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
QuTiP example
Step1: Colors
In quantum mechanics, complex numbers are as natual as real numbers.
Before going into details of particular plots, we show how complex_array_to_rgb maps $z = x ... | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
from qutip import *
Explanation: QuTiP example: Qubism visualizations
by Piotr Migdał, June 2014
For more information about QuTiP see http://qutip.org.
For more information about Qubism see:
* J. Rodriguez-Laguna, P. Migdał, M. Ibanez Be... |
12,196 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Rotten Tomatoes movie review classifier using Keras and Tensorflow
Author
Step1: Download the Rotten Tomatoes movie reviews dataset
Step2: Import dependencies
Step3: Read the train data f... | Python Code:
import os
colab_mode = True
download_rawData = True
setup = True
ROOT_DIR = '/content/'
WEIGHTS_FILENAME = 'RT_LSTM.h5'
WEIGHTS_FILE = os.path.join(ROOT_DIR, WEIGHTS_FILENAME)
from google.colab import files
if colab_mode and download_rawData:
files.upload()
if colab_mode and download_rawData:
! mkdir /... |
12,197 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Hand-crafted features for GTZAN
The goal of this notebook is to create several audio features descriptors for the GTZAN dataset, as proposed for many year as input for machine learning algor... | Python Code:
import os
import librosa
import itertools
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy.stats import kurtosis
from scipy.stats import skew
import sklearn
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import accuracy_score
from sklearn.metrics impo... |
12,198 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Score functions
Original environment score function
The environment score depends on
Step2: Using cube root instead of log
Step3: Shannon index, based on number of individuals
Step4: Shan... | Python Code:
def environmentScoreNoRounding(speciesData, nodeConfig, biomassData):
numTimesteps = len(biomassData[nodeConfig[0]['nodeId']])
scores = np.empty(numTimesteps)
for timestep in range(numTimesteps):
# Calculate the Ecosystem Score for this timestep
biomass = 0
numSpecies = ... |
12,199 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
In this guided project, you'll practice recreating some of the plots using Matplotlib that Seaborn and Pandas allow you to generate using high-level functions. This deliberate practice will ... | Python Code:
# Setup the environment by importing the libraries we need
import pandas as pd
import matplotlib.pyplot as plt
# And run the necessary Jupyter magic so plots are displayed inline
%matplotlib notebook
# Read the dataset into a DataFrame
recent_grads = pd.read_csv('../data/recent-grads.csv')
# Start explorin... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.