Unnamed: 0 int64 0 16k | text_prompt stringlengths 110 62.1k | code_prompt stringlengths 37 152k |
|---|---|---|
14,500 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Example 2
Step2: # Role of pure dephasing
It is more useful to explicitly construct the various parts of the Bloch-Redfield master equation explicitly, and show that it is the pure-d... | Python Code:
%pylab inline
%load_ext autoreload
%autoreload 2
import contextlib
import time
import numpy as np
from qutip import *
from qutip.nonmarkov.heom import HEOMSolver, HSolverDL, BosonicBath, DrudeLorentzBath, DrudeLorentzPadeBath
from qutip.ipynbtools import HTMLProgressBar
def cot(x):
return 1./np.tan(x)
... |
14,501 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Convolutions for Computer Vision
To build and test your intuition for convolutions, you will designa vertical line detector.
We'll apply that detector to each part of an image to create a ne... | Python Code:
import sys
from packages.learntools.deep_learning.exercise_1 import load_my_image, apply_conv_to_image, show, print_hints
Explanation: Convolutions for Computer Vision
To build and test your intuition for convolutions, you will designa vertical line detector.
We'll apply that detector to each part of an im... |
14,502 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Vertex SDK
Step1: Install the latest GA version of google-cloud-storage library as well.
Step2: Restart the kernel
Once you've installed the additional packages, you need to restart the no... | Python Code:
import os
# Google Cloud Notebook
if os.path.exists("/opt/deeplearning/metadata/env_version"):
USER_FLAG = "--user"
else:
USER_FLAG = ""
! pip3 install --upgrade google-cloud-aiplatform $USER_FLAG
Explanation: Vertex SDK: AutoML training text entity extraction model for batch prediction
<table alig... |
14,503 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Collaborative filtering on Google Analytics data
This notebook demonstrates how to implement a WALS matrix refactorization approach to do collaborative filtering.
Step2: Create raw dataset
... | Python Code:
import os
PROJECT = "cloud-training-demos" # REPLACE WITH YOUR PROJECT ID
BUCKET = "cloud-training-demos-ml" # REPLACE WITH YOUR BUCKET NAME
REGION = "us-central1" # REPLACE WITH YOUR BUCKET REGION e.g. us-central1
# Do not change these
os.environ["PROJECT"] = PROJECT
os.environ["BUCKET"] = BUCKET
os.envir... |
14,504 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Traffic Sign Classification with Keras
Keras exists to make coding deep neural networks simpler. To demonstrate just how easy it is, you’re going to use Keras to build a convolutional neural... | Python Code:
from urllib.request import urlretrieve
from os.path import isfile
from tqdm import tqdm
class DLProgress(tqdm):
last_block = 0
def hook(self, block_num=1, block_size=1, total_size=None):
self.total = total_size
self.update((block_num - self.last_block) * block_size)
self.las... |
14,505 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Head model and forward computation
The aim of this tutorial is to be a getting started for forward
computation.
For more extensive details and presentation of the general
concepts for forwar... | Python Code:
import os.path as op
import mne
from mne.datasets import sample
data_path = sample.data_path()
# the raw file containing the channel location + types
raw_fname = data_path + '/MEG/sample/sample_audvis_raw.fif'
# The paths to Freesurfer reconstructions
subjects_dir = data_path + '/subjects'
subject = 'sampl... |
14,506 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
70. データの入手・整形
文に関する極性分析の正解データを用い,以下の要領で正解データ(sentiment.txt)を作成せよ.
rt-polarity.posの各行の先頭に"+1 "という文字列を追加する(極性ラベル"+1"とスペースに続けて肯定的な文の内容が続く)
rt-polarity.negの各行の先頭に"-1 "という文字列を追加する(極性ラベル"-1"とスペースに... | Python Code:
import random
with open('rt-polarity.neg.utf8', 'r') as f:
negative_list = ['-1 '+i for i in f]
with open("rt-polarity.pos.utf8", "r") as f:
positive_list = ["+1"+i for i in f]
#for sentence in temp:
# positive_list.append('+1 '+"".join([i.encode('replace') for i in sentence]))
concatenate = po... |
14,507 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Create Conference Consultant Sayuri
Steps
Make Training Data
会議中の画像の収集
画像のデータ化
ラベルの付与
Make Model
モデルに利用する特徴量の選択
学習
予測結果の可視化
Save the Model
モデルの保存
Step1: Make Training Data
会議の画像をGoogle等から収集... | Python Code:
# enable showing matplotlib image inline
%matplotlib inline
# autoreload module
%load_ext autoreload
%autoreload 2
# load local package
import sys
import os
sys.path.append(os.path.join(os.getcwd(), "../../../")) # load project root
Explanation: Create Conference Consultant Sayuri
Steps
Make Training Data... |
14,508 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a href="https
Step1: load data
Step2: pre-process data into chunks
Step3: Recurrent Neural Networks
RNNs work on sequences of input data and can learn which part of the history is releva... | Python Code:
# for colab
!pip install -q tf-nightly-gpu-2.0-preview
import tensorflow as tf
print(tf.__version__)
# a small sanity check, does tf seem to work ok?
hello = tf.constant('Hello TF!')
print("This works: {}".format(hello))
# this should return True even on Colab
tf.test.is_gpu_available()
tf.test.is_built_wi... |
14,509 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introduction
This kernel gives a starter over the contents of the Gliding Data dataset.
The dataset includes metadata and calculated phases for over 100000 gliding flights from 2016 to 2019,... | Python Code:
import datetime
import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
import random
import os
for dirname, _, filenames in os.walk('/tmp/gliding-data'):
for filename in filenames:
print(os.path.join(dirname, filename))
flight_websource = pd.r... |
14,510 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Urban vs. rural living and suicide rates
May 2016
Written by Kara Frantzich at NYU Stern
Contact
Step1: The Data
Data used is from the Center for Disease Control from 2014.
The CDC has defi... | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import pandas as pd
from pandas.io import wb
Explanation: Urban vs. rural living and suicide rates
May 2016
Written by Kara Frantzich at NYU Stern
Contact: kara.frantzich@st
... |
14,511 | Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
I have problems using scipy.sparse.csr_matrix: | Problem:
from scipy import sparse
sa = sparse.random(10, 10, density = 0.01, format = 'csr')
sb = sparse.random(10, 10, density = 0.01, format = 'csr')
result = sparse.hstack((sa, sb)).tocsr() |
14,512 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Hand tuning hyperparameters
Learning Objectives
Step1: Set Up
In this first cell, we'll load the necessary libraries.
Step2: Next, we'll load our data set.
Step3: Examine the data
It's a ... | Python Code:
!sudo chown -R jupyter:jupyter /home/jupyter/training-data-analyst
Explanation: Hand tuning hyperparameters
Learning Objectives:
* Use the LinearRegressor class in TensorFlow to predict median housing price, at the granularity of city blocks, based on one input feature
* Evaluate the accuracy of a mode... |
14,513 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Author
Step1: Job fiches
First load all the job_groups (fiche metier) from the XML files
Step2: Visualize the distributions of Holland Codes for job fiches
Step3: Holland Codes of activit... | Python Code:
from __future__ import division
import glob
import json
import os
import itertools as it
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
import xmltodict
import numpy as np
from bob_emploi.data_analysis.lib import read_data
data_folder = os.getenv('DATA_FOLDER')
def riasec_dist(fi... |
14,514 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Ocean
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', 'ncc', 'noresm2-hh', 'ocean')
Explanation: ES-DOC CMIP6 Model Properties - Ocean
MIP Era: CMIP6
Institute: NCC
Source ID: NORESM2-HH
Topic: Ocean
Sub-Topics: Timestepping Framework, Ad... |
14,515 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Building a Model
Model, Reactions and Metabolites
This simple example demonstrates how to create a model, create a reaction, and then add the reaction to the model.
We'll use the '3OAS140' r... | Python Code:
from cobra import Model, Reaction, Metabolite
model = Model('example_model')
reaction = Reaction('R_3OAS140')
reaction.name = '3 oxoacyl acyl carrier protein synthase n C140 '
reaction.subsystem = 'Cell Envelope Biosynthesis'
reaction.lower_bound = 0. # This is the default
reaction.upper_bound = 1000. # ... |
14,516 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Univariate Data with the Normal Inverse Chi-Square Distribution
One of the simplest examples of data is univariate data
Let's consider a timeseries example
Step1: Let's plot the kernel dens... | Python Code:
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
%matplotlib inline
sns.set_context('talk')
sns.set_style('darkgrid')
lynx = pd.read_csv('https://vincentarelbundock.github.io/Rdatasets/csv/datasets/lynx.csv',
index_col=0)
lynx = lynx.set_inde... |
14,517 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Homework 1
Google Trends is pretty awesome, except that on the site you cannot do more than overlay plots. Here we'll play with search term data downloaded from Google and draw our own concl... | Python Code:
%pylab inline
Explanation: Homework 1
Google Trends is pretty awesome, except that on the site you cannot do more than overlay plots. Here we'll play with search term data downloaded from Google and draw our own conclusions.
Data from:
https://www.google.com/trends/explore#q=spring%20break%2C%20textbooks%... |
14,518 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Run many Batch Normalization experiments using Cloud using ML Engine
Step1: Let’s test how Batch Normalization impacts models of varying depths. We can launch many experiments in parallel u... | Python Code:
# change these to try this notebook out
BUCKET = 'crawles-sandbox' # change this to your GCP bucket
PROJECT = 'crawles-sandbox' # change this to your GCP project
REGION = 'us-central1'
# Import os environment variables
import os
os.environ['BUCKET'] = BUCKET
os.environ['PROJECT'] = PROJECT
os.environ['RE... |
14,519 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Example flow for processing and aggregating stats about committee meeting attendees and protocol parts
See the DataFlows documentation for more details regarding the Flow object and processi... | Python Code:
# Limit processing of protocol parts for development
PROCESS_PARTS_LIMIT = 500
# Enable caching of protocol parts data (not efficient, should only be used for local development with sensible PROCESS_PARTS_LIMIT)
PROCESS_PARTS_CACHE = True
# Filter the meetings to be processed, these kwargs are passed along... |
14,520 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Lifetime Value prediction for Kaggle Acquire Valued Customer Challenge
<table align="left">
<td>
<a target="_blank" href="https
Step1: Global variables
Step2: Data
Download data
Setu... | Python Code:
import os
import numpy as np
import pandas as pd
from scipy import stats
import seaborn as sns
from sklearn import model_selection
from sklearn import preprocessing
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import backend as K
import tensorflow_probability as tfp
import tqd... |
14,521 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Goal
Questions
How is incorporator identification accuracy affected by the percent isotope incorporation of taxa?
How variable is sensitivity depending on model stochasticity
Each simulation... | Python Code:
workDir = '/home/nick/notebook/SIPSim/dev/bac_genome1210/'
buildDir = os.path.join(workDir, 'percIncorpUnifRep')
genomeDir = '/home/nick/notebook/SIPSim/dev/bac_genome1210/genomes/'
R_dir = '/home/nick/notebook/SIPSim/lib/R/'
Explanation: Goal
Questions
How is incorporator identification accuracy affected ... |
14,522 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Compute envelope correlations in volume source space
Compute envelope correlations of orthogonalized activity [1] [2] in source
space using resting state CTF data in a volume source space.
S... | Python Code:
# Authors: Eric Larson <larson.eric.d@gmail.com>
# Sheraz Khan <sheraz@khansheraz.com>
# Denis Engemann <denis.engemann@gmail.com>
#
# License: BSD (3-clause)
import os.path as op
import mne
from mne.beamformer import make_lcmv, apply_lcmv_epochs
from mne.connectivity import envelope_corr... |
14,523 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Running and evaluating a block algorithm
In this notebook we run a block-wise algorithm on a training data set and evaluate performance.
Setup environment
Step1: Setup plotting
Step2: Load... | Python Code:
import numpy as np
from scipy.stats import norm
from thunder import SourceExtraction
from thunder.extraction import OverlapBlockMerger
Explanation: Running and evaluating a block algorithm
In this notebook we run a block-wise algorithm on a training data set and evaluate performance.
Setup environment
End ... |
14,524 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<table class="ee-notebook-buttons" align="left"><td>
<a target="_blank" href="http
Step1: Obtain a private key file for your service account
You should already have a service account regis... | Python Code:
# INSERT YOUR PROJECT HERE
PROJECT = 'your-project'
!gcloud auth login --project {PROJECT}
Explanation: <table class="ee-notebook-buttons" align="left"><td>
<a target="_blank" href="http://colab.research.google.com/github/google/earthengine-api/blob/master/python/examples/ipynb/Earth_Engine_REST_API_compu... |
14,525 | 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 with pipeline for onl... |
14,526 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
CVC Data Summaries (with simple method hydrology)
Setup the basic working environment
Step1: Load water quality data
External sources
Step2: CVC tidy data
Data using the Simple Method hydr... | Python Code:
%matplotlib inline
import os
import sys
import datetime
import warnings
import numpy as np
import matplotlib.pyplot as plt
import pandas
import seaborn
seaborn.set(style='ticks', context='paper')
import wqio
from wqio import utils
import pybmpdb
import pynsqd
import pycvc
min_precip = 1.9999
big_storm_date... |
14,527 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<img src="https
Step1: Basics
Set-up a simple run with a constant linear bed. We will first define the bed
Step2: Now we have to decide how wide our glacier is, and what it the shape of it... | Python Code:
# The commands below are just importing the necessary modules and functions
# Plot defaults
%matplotlib inline
import matplotlib.pyplot as plt
plt.rcParams['figure.figsize'] = (9, 6) # Default plot size
# Scientific packages
import numpy as np
# Constants
from oggm.cfg import SEC_IN_YEAR, A
# OGGM models
... |
14,528 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step 0
Step4: Step 1
Step5: Step 2
Step6: Step 3
Step7: Step 4
Step8: Step 5
Step9: Step 6
Step10: Step 7
Step11: TODO
Step12: Deployment Option 1
Step13: Deployment Option 2 | Python Code:
df = spark.read.format("csv") \
.option("inferSchema", "true").option("header", "true") \
.load("s3a://datapalooza/airbnb/airbnb.csv.bz2")
df.registerTempTable("df")
print(df.head())
print(df.count())
Explanation: Step 0: Load Libraries and Data
End of explanation
df_filtered = df.filter("price >= 50 A... |
14,529 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
コブ・ダクラス型生産関数と課題文で例に出された関数を用いる。
いずれも定義域は0≤x≤1である。
<P>コブ・ダグラス型生産関数は以下の通りである。</P>
<P>z = x_1**0.5*x_2*0.5</P>
Step1: <P>課題の例で使われた関数は以下の通りである。</P>
<P>z = (1+np.sin(4*math.pi*x_1))*x_2*1/2</P>
N... | Python Code:
def example1(x_1, x_2):
z = x_1**0.5*x_2*0.5
return z
fig = pl.figure()
ax = Axes3D(fig)
X = np.arange(0, 1, 0.1)
Y = np.arange(0, 1, 0.1)
X, Y = np.meshgrid(X, Y)
Z = example1(X, Y)
ax.plot_surface(X, Y, Z, rstride=1, cstride=1)
pl.show()
Explanation: コブ・ダクラス型生産関数と課題文で例に出された関数を用いる。
いずれも定義域は0≤x≤1であ... |
14,530 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Exercício 01
Step1: Exercício 02 | Python Code:
G1 = nx.erdos_renyi_graph(10,0.4)
nx.draw_shell(G1)
G2 = nx.barabasi_albert_graph(10,3)
nx.draw_shell(G2)
G3 = nx.barabasi_albert_graph(10,4)
nx.draw_shell(G3)
Explanation: Exercício 01: Calcule a distância média, o diâmetro e o coeficiente de agrupamento das redes abaixo.
End of explanation
G4 = nx.baraba... |
14,531 | 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', 'nasa-giss', 'giss-e2-1h', 'atmos')
Explanation: ES-DOC CMIP6 Model Properties - Atmos
MIP Era: CMIP6
Institute: NASA-GISS
Source ID: GISS-E2-1H
Topic: Atmos
Sub-Topics: Dynamical Core... |
14,532 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Saving Data
Once you request data, Hydrofunctions can automatically save the JSON in a compact zip file. The next time that you re-run your request, the data are retrieved automatically from... | Python Code:
import hydrofunctions as hf
new = hf.NWIS('01585200', 'dv', start_date='2018-01-01', end_date='2019-01-01', file='save_example.json.gz')
new
Explanation: Saving Data
Once you request data, Hydrofunctions can automatically save the JSON in a compact zip file. The next time that you re-run your request, the ... |
14,533 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Word 2 Vec
Step1: Install necessary NL modules.
Step2: Load data for Natural Language processing.
Step3: Load both labelled and unlabelled train datasets.
Step4: Define preprocessors
Ste... | Python Code:
import numpy as np, sklearn as sk, pandas as pd
from bs4 import BeautifulSoup as bs
import matplotlib.pyplot as plt
import time as tm, os, regex as re
%matplotlib inline
import warnings
warnings.filterwarnings("ignore")
DATAPATH = os.path.realpath( os.path.join( ".", "data", "imdb" ) )
Explanation: Word 2 ... |
14,534 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Training a classification model for wine production quality
Objective
Step1: The Wine Quality Dataset
The dataset is available in the UCI Machine Learning Repository.
Get the data
There is ... | Python Code:
# Ensure the right version of Tensorflow is installed.
!pip freeze | grep tensorflow==2.1 || pip install tensorflow==2.1
from __future__ import absolute_import, division, print_function, unicode_literals
import pathlib
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import tensorflow... |
14,535 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<img src="images/logo.jpg" style="display
Step1: <p style="text-align
Step2: <p style="text-align
Step3: <div class="align-center" style="display
Step4: <p style="text-align
Step5: <p s... | Python Code:
counter = 0
while counter < 10
print("Stop it!")
counter += 1
Explanation: <img src="images/logo.jpg" style="display: block; margin-left: auto; margin-right: auto;" alt="לוגו של מיזם לימוד הפייתון. נחש מצויר בצבעי צהוב וכחול, הנע בין האותיות של שם הקורס: לומדים פייתון. הסלוגן המופיע מעל לשם הקורס ה... |
14,536 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Week 3
Step1: (1) We will fit the data contained within Fig. 3B. Plot this data and describe the relationship you see between Kx, Kd, and valency.
Step2: (2) First, to do so, we'll need a ... | Python Code:
% matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
from scipy.special import binom
from scipy.optimize import brentq
np.seterr(over='raise')
def StoneMod(Rtot, Kd, v, Kx, L0):
'''
Returns the number of mutlivalent ligand bound to a cell with Rtot
receptors, granted each epit... |
14,537 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Find all leaves up to length maximum_superleave_length (takes a couple of minutes for length of 6)
Step1: Load in current file with ev
Step2: Function below calculates a "pseudo-superleave... | Python Code:
t0 = time.time()
maximum_superleave_length = 6
leaves = {i:sorted(list(set(list(combinations(tilebag,i))))) for i in
range(1,maximum_superleave_length+1)}
for i in range(1,maximum_superleave_length+1):
leaves[i] = [''.join(leave) for leave in leaves[i]]
t1 = time.time()
print('Calculate... |
14,538 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Using a pre-trained convnet
This notebook contains the code sample found in Chapter 5, Section 3 of Deep Learning with Python. Note that the original text features far more content, in parti... | Python Code:
from keras.applications import VGG16
conv_base = VGG16(weights='imagenet',
include_top=False,
input_shape=(150, 150, 3))
Explanation: Using a pre-trained convnet
This notebook contains the code sample found in Chapter 5, Section 3 of Deep Learning with Python. Note that ... |
14,539 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Setup
We're going to download the collected works of Nietzsche to use as our data for this class.
Step1: Sometimes it's useful to have a zero value in the dataset, e.g. for padding
Step2: ... | Python Code:
path = get_file('nietzsche.txt', origin="https://s3.amazonaws.com/text-datasets/nietzsche.txt")
text = open(path).read()
print('corpus length:', len(text))
chars = sorted(list(set(text)))
vocab_size = len(chars)+1
print('total chars:', vocab_size)
Explanation: Setup
We're going to download the collected wo... |
14,540 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: IPython magic functions for Pyspark
Examples of shortcuts for executing SQL in Spark
Step2: Define test tables
Step3: Examples of how to use %SQL magic functions with Spark
Use %sql... | Python Code:
#
# IPython magic functions to use with Pyspark and Spark SQL
# The following code is intended as examples of shorcuts to simplify the use of SQL in pyspark
# The defined functions are:
#
# %sql <statement> - return a Spark DataFrame for lazy evaluation of the SQL
# %sql_show <statement> - run... |
14,541 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Machine Learning Engineer Nanodegree
Introduction and Foundations
Project 0
Step1: From a sample of the RMS Titanic data, we can see the various features present for each passenger on the s... | Python Code:
import numpy as np
import pandas as pd
# RMS Titanic data visualization code
from titanic_visualizations import survival_stats
from IPython.display import display
%matplotlib inline
# Load the dataset
in_file = 'titanic_data.csv'
full_data = pd.read_csv(in_file)
# Print the first few entries of the RMS Ti... |
14,542 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Compute induced power in the source space with dSPM
Returns STC files ie source estimates of induced power
for different bands in the source space. The inverse method
is linear based on dSPM... | Python Code:
# Authors: Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr>
#
# License: BSD (3-clause)
import matplotlib.pyplot as plt
import mne
from mne import io
from mne.datasets import sample
from mne.minimum_norm import read_inverse_operator, source_band_induced_power
print(__doc__)
Explanation: Compute... |
14,543 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Execution Configuration Options
Nipype gives you many liberties on how to create workflows, but the execution of them uses a lot of default parameters. But you have of course all the freedom... | Python Code:
from nipype import config, logging
import os
os.makedirs('/output/log_folder', exist_ok=True)
os.makedirs('/output/crash_folder', exist_ok=True)
config_dict={'execution': {'remove_unnecessary_outputs': 'true',
'keep_inputs': 'false',
... |
14,544 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Let's say we want to prepare data and try some scalers and classifiers for prediction in a classification problem. We will tune paramaters of classifiers by grid search technique.
Data prepa... | Python Code:
from sklearn.datasets import make_classification
X, y = make_classification()
Explanation: Let's say we want to prepare data and try some scalers and classifiers for prediction in a classification problem. We will tune paramaters of classifiers by grid search technique.
Data preparing:
End of explanation
f... |
14,545 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Atmoschem
MIP Era
Step1: Document Authors
Set document authors
Step2: Document Contributors
Specify document contributors
Step3: Document Publication
Speci... | Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'ipsl', 'sandbox-2', 'atmoschem')
Explanation: ES-DOC CMIP6 Model Properties - Atmoschem
MIP Era: CMIP6
Institute: IPSL
Source ID: SANDBOX-2
Topic: Atmoschem
Sub-Topics: Transport, Emi... |
14,546 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Deep learning for Natural Language Processing
Simple text representations, bag of words
Word embedding and... not just another word2vec this time
1-dimensional convolutions for text
Aggregat... | Python Code:
low_RAM_mode = True
very_low_RAM = False #If you have <3GB RAM, set BOTH to true
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
Explanation: Deep learning for Natural Language Processing
Simple text representations, bag of words
Word embedding and... not just ano... |
14,547 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Matrix multiplication tutorial
This tutorial demonstrates how to use Kernel Tuner to test and tune kernels, using matrix multiplication as an example.
Matrix multiplication is one of the mos... | Python Code:
%%writefile matmul_naive.cu
#define WIDTH 4096
__global__ void matmul_kernel(float *C, float *A, float *B) {
int x = blockIdx.x * block_size_x + threadIdx.x;
int y = blockIdx.y * block_size_y + threadIdx.y;
float sum = 0.0;
for (int k=0; k<WIDTH; k++) {
sum += A[y*WIDTH+k] * B[k*WID... |
14,548 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Critical Radii
Step1: As always, let's do imports and initialize a logger and a new Bundle.
Step2: Contact Systems
Contact systems are created by passing contact_binary=True to phoebe.defa... | Python Code:
#!pip install -I "phoebe>=2.3,<2.4"
Explanation: Critical Radii: Contact Systems
Setup
Let's first make sure we have the latest version of PHOEBE 2.3 installed (uncomment this line if running in an online notebook session such as colab).
End of explanation
import phoebe
from phoebe import u # units
import ... |
14,549 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
K Nearest Neighbours is a algorithim for finding out the similarity or distance b/w two things, to find out how alike/different they are.
Say we have a bunch of fruit, KNN will classify the... | Python Code:
iris = sns.load_dataset("iris")
print(f"Iris dataset shape: {iris.shape}")
iris.head()
Explanation: K Nearest Neighbours is a algorithim for finding out the similarity or distance b/w two things, to find out how alike/different they are.
Say we have a bunch of fruit, KNN will classify them into clusters b... |
14,550 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Cell Composition Adjustement
One very important step to note is that we are adjusting each patient's beta-values by the expected value given their cell composition. We are including this st... | Python Code:
cd /cellar/users/agross/TCGA_Code/Methlation/
import NotebookImport
from Setup.Imports import *
Explanation: Cell Composition Adjustement
One very important step to note is that we are adjusting each patient's beta-values by the expected value given their cell composition. We are including this step to re... |
14,551 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Watch your tail!
Allen Downey 2019
MIT License
Step1: Loading historical data from the S&P 500
Step2: One day rally after the 2008 crash
Step3: Black Monday
Step13: To compare data to a ... | Python Code:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from empiricaldist import Pmf
from utils import decorate
Explanation: Watch your tail!
Allen Downey 2019
MIT License
End of explanation
# https://finance.yahoo.com/quote/%5EGSPC/history?period1=-630961200&period2=1... |
14,552 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Assignment 2
Create two models for the relationship between height and weight based on gender
Modify the code in Assignment 1 to ask for a person's gender as well as their height to produce ... | Python Code:
import pandas as pd
import matplotlib.pyplot as plt
plt.style.use('fivethirtyeight')
%matplotlib inline
import statsmodels.formula.api as smf
df = pd.read_csv('heights_weights_genders.csv')
df.head(3)
female_df = df[df['Gender'] == 'Female']
male_df = df[df['Gender'] == 'Male']
Explanation: Assignment 2
Cr... |
14,553 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Create a Vertex AI Feature Store Using the SDK
Learning objectives
In this notebook, you learn how to
Step1: Restart the kernel
After you install the SDK, you need to restart the notebook k... | Python Code:
import os
# The Google Cloud Notebook product has specific requirements
IS_GOOGLE_CLOUD_NOTEBOOK = os.path.exists("/opt/deeplearning/metadata/env_version")
# Google Cloud Notebook requires dependencies to be installed with '--user'
USER_FLAG = ""
if IS_GOOGLE_CLOUD_NOTEBOOK:
USER_FLAG = "--user"
# Inst... |
14,554 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<img src="fuellogo.svg" style="float
Step1: declare constants
Step2: declare free variables
Step3: Check the vector constraints
Step4: Form the optimization problem
In the 3-element vect... | Python Code:
import numpy as np
from gpkit.shortcuts import *
import gpkit.interactive
%matplotlib inline
Explanation: <img src="fuellogo.svg" style="float:left; padding-right:1em;" width=150 />
AIRPLANE FUEL
Minimize fuel burn for a plane that can sprint and land quickly.
Set up the modelling environment
First we'll t... |
14,555 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
1. Bitcoin and Cryptocurrencies
Step1: 2. Discard the cryptocurrencies without a market capitalization
<p>Why do the <code>count()</code> for <code>id</code> and <code>market_cap_usd</code>... | Python Code:
# Importing pandas
import pandas as pd
# Importing matplotlib and setting aesthetics for plotting later.
import matplotlib.pyplot as plt
%matplotlib inline
%config InlineBackend.figure_format = 'svg'
plt.style.use('fivethirtyeight')
# Reading datasets/coinmarketcap_06122017.csv into pandas
dec6 = pd.read_... |
14,556 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Identify Factors that Predict Intro CS Experience Based on Gender
Step1: Problem Statement
I am interested in identify the leading indicators of experience broken down by gender in introduc... | Python Code:
from IPython.display import display
from IPython.display import HTML
import IPython.core.display as di # Example: di.display_html('<h3>%s:</h3>' % str, raw=True)
# This line will hide code by default when the notebook is exported as HTML
di.display_html('<script>jQuery(function() {if (jQuery("body.notebook... |
14,557 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Lesson 7
Python Basic, Lesson 5, v1.0.1, 2016.12 by David.Yi
Python Basic, Lesson 5, v1.0.2, 2017.03 modified by Yimeng.Zhang
v1.1, 2020.4 2020.5 edit by David Yi
本次内容要点
文件和目录操作之一:文件和目录操作... | Python Code:
import os
# 操作系统路径分隔符
print(os.sep)
# 操作系统平台名称
print(os.name)
# 获取当前路径
os.getcwd()
# 记录一下这是 zhang yimeng 当时执行后的结果:'C:\\Users\\yimeng.zhang\\Desktop\\Class\\python基础\\python_basic'
# 这是我现在在 windows 电脑上执行的结果:'C:\\dev_python\\python_study\\python_study_basic_notebook'
# 切换路径
# os.chdir('/Users/david.yi')
# 切换... |
14,558 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
PoS tagging en Español
En este ejercicio vamos a jugar con uno de los corpus en español que está disponible desde NLTK
Step1: Fíjate que las etiquetas que se usan en el treebank español son... | Python Code:
import nltk
from nltk.corpus import cess_esp
cess_esp = cess_esp.tagged_sents()
print(cess_esp[5])
Explanation: PoS tagging en Español
En este ejercicio vamos a jugar con uno de los corpus en español que está disponible desde NLTK: CESS_ESP, un treebank anotado a partir de una colección de noticias en espa... |
14,559 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Outline
Glossary
Positional Astronomy
Previous
Step1: Import section specific modules
Step2: Direction Cosine Coordinates
There is another useful astronomical coordinate system that we oug... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
from IPython.display import HTML
HTML('../style/course.css') #apply general CSS
Explanation: Outline
Glossary
Positional Astronomy
Previous: Horizontal Coordinates
Next: Further Reading
Import standard modules:
End of explanation
from ... |
14,560 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<header class="w3-container w3-teal">
<img src="images/utfsm.png" alt="" height="100px" align="left"/>
<img src="images/mat.png" alt="" height="100px" align="right"/>
</header>
<br/><br/><br... | Python Code:
# Configuracion para recargar módulos y librerías
%reload_ext autoreload
%autoreload 2
%matplotlib inline
from IPython.core.display import HTML
HTML(open("style/mat281.css", "r").read())
from mat281_code.lab import greetings
alumno_1 = ("Sebastian Flores", "2004001-7")
alumno_2 = ("Maria Jose Vargas", "20... |
14,561 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Poincare surface of section
This example uses rebound to create a Poincare surface of section of the restricted circular three body problem (RC3BP). First, a series of RC3BP simulations with... | Python Code:
import rebound
import numpy as np
import matplotlib.pyplot as plt
def get_sim(m_pert,n_pert,a_tp,l_pert,l_tp,e_tp,pomega_tp):
sim = rebound.Simulation()
sim.add(m=1)
P_pert = 2 * np.pi / n_pert
sim.add(m=m_pert,P=P_pert,l=l_pert)
sim.add(m=0.,a = a_tp,l=l_tp,e=e_tp,pomega=pomega_tp)
... |
14,562 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2018 The TensorFlow Hub Authors.
Licensed under the Apache License, Version 2.0 (the "License");
Step1: Universal Sentence Encoder-Lite 데모
<table class="tfo-notebook-buttons" alig... | Python Code:
# Copyright 2018 The TensorFlow Hub Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless re... |
14,563 | Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
Lists have a very simple method to insert elements: | Problem:
import numpy as np
a = np.asarray([1,2,3,4])
pos = 2
element = 66
a = np.insert(a, pos, element) |
14,564 | 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', 'cnrm-cerfacs', 'sandbox-1', 'landice')
Explanation: ES-DOC CMIP6 Model Properties - Landice
MIP Era: CMIP6
Institute: CNRM-CERFACS
Source ID: SANDBOX-1
Topic: Landice
Sub-Topics: Glac... |
14,565 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Skip-gram word2vec
In this notebook, I'll lead you through using TensorFlow to implement the word2vec algorithm using the skip-gram architecture. By implementing this, you'll learn about emb... | Python Code:
import time
import numpy as np
import tensorflow as tf
import utils
Explanation: Skip-gram word2vec
In this notebook, I'll lead you through using TensorFlow to implement the word2vec algorithm using the skip-gram architecture. By implementing this, you'll learn about embedding words for use in natural lang... |
14,566 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a href="https
Step1: TensorFlow 2 quickstart for experts
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https
Step2: Load and prepare the MNIST data... | 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... |
14,567 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
(ADBLUCO)=
3.2 Algoritmos de descenso y búsqueda de línea en Unconstrained Convex Optimization (UCO)
```{admonition} Notas para contenedor de docker
Step1: Los candidatos a ser mínimos los ... | Python Code:
import numpy as np
import sympy
from sympy.tensor.array import derive_by_array
import matplotlib.pyplot as plt
from scipy.optimize import fsolve
from scipy.optimize import fmin
import pandas as pd
import cvxpy as cp
from pytest import approx
np.set_printoptions(precision=3, suppress=True)
Explanation: (ADB... |
14,568 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Regularization
Welcome to the second assignment of this week. Deep Learning models have so much flexibility and capacity that overfitting can be a serious problem, if the training dataset is... | Python Code:
# import packages
import numpy as np
import matplotlib.pyplot as plt
from reg_utils import sigmoid, relu, plot_decision_boundary, initialize_parameters, load_2D_dataset, predict_dec
from reg_utils import compute_cost, predict, forward_propagation, backward_propagation, update_parameters
import sklearn
impo... |
14,569 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Fit a simple poisson/gaussian model to IPNO test bench data
calin/examples/calib/ipno spe fits poisson gaussian.ipynb - Stephen Fegan - 2017-04-21
Copyright 2017, Stephen Fegan sf&... | Python Code:
%pylab inline
import calin.diagnostics.functional
import calin.io.sql_transceiver
import calin.calib.spe_fit
import calin.math.histogram
import calin.math.optimizer
import calin.math.pdf_1d
import calin.iact_data.ipno
import calin.plotting
import calin.math.data_modeling
Explanation: Fit a simple poisson/g... |
14,570 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2019 The TensorFlow Authors.
Step1: 분산 전략을 사용한 모델 저장 및 불러오기
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https
Step2: tf.distribute.Strat... | 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... |
14,571 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
[Py-OO] Aula 01
Introdução a Orientação a Objetos em Python
O que você vai aprender nesta aula?
Após o término da aula você terá aprendido
Step1: O dicionários possui diversos métodos que u... | Python Code:
notas = {'bia': 10, 'pedro': 0, 'ana': 7}
notas
Explanation: [Py-OO] Aula 01
Introdução a Orientação a Objetos em Python
O que você vai aprender nesta aula?
Após o término da aula você terá aprendido:
Objetos em Python
Como funcionam
Tipagem
Mutabilidade
Como funciona atribuição e variáveis
Classes
Sintaxe... |
14,572 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Gaussian Mixture Models and Expectation Maximisation in Shogun
By Heiko Strathmann - heiko.strathmann@gmail.com - http
Step2: Set up the model in Shogun
Step3: Sampling from mixture... | Python Code:
%pylab inline
%matplotlib inline
import os
SHOGUN_DATA_DIR=os.getenv('SHOGUN_DATA_DIR', '../../../data')
# import all Shogun classes
from shogun import *
from matplotlib.patches import Ellipse
# a tool for visualisation
def get_gaussian_ellipse_artist(mean, cov, nstd=1.96, color="red", linewidth=3):
... |
14,573 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Seaice
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', 'cccr-iitm', 'sandbox-2', 'seaice')
Explanation: ES-DOC CMIP6 Model Properties - Seaice
MIP Era: CMIP6
Institute: CCCR-IITM
Source ID: SANDBOX-2
Topic: Seaice
Sub-Topics: Dynamics, The... |
14,574 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Python Programming for Data Analysis
1. 데이터 분석을 위한 환경 구성 (패키지 설치 포함)
Step1: TicTaeToe 게임
Step2: TicTaeToe게임을 간단 버젼으로 구현한 것으로 사용자가 먼저 착수하여 승부를 겨루게 됩니다.
향후에는 기계학습으로 발전시켜 실력을 키워 보려 합니다. | Python Code:
# 운영체제
!ver
# 현재 위치 및 하위 디렉토리 구조
!dir
# 파이선 버전
!python --version
# 가상환경 버전
!virtualenv --version
# 존재하는 가상환경 목록
!workon
# 가상환경 kookmin1에 진입
# workon kookmin1
# 가상환경 kookmin1에 설치된 패키지
# 데이터 분석 : numpy, pandas
# 시각화 : matplotlib
!pip freeze
Explanation: Python Programming for Data Analysis
1. 데이터 분석을 위한 환경 구... |
14,575 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Title
Step1: Load Iris Dataset
Step2: Create Decision Tree Using Gini Impurity
Step3: Train Model
Step4: Create Observation To Predict
Step5: Predict Observation
Step6: View Predicted ... | Python Code:
# Load libraries
from sklearn.tree import DecisionTreeClassifier
from sklearn import datasets
Explanation: Title: Decision Tree Classifier
Slug: decision_tree_classifier
Summary: Training a decision tree classifier in scikit-learn.
Date: 2017-09-19 12:00
Category: Machine Learning
Tags: Trees And Forests
A... |
14,576 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<figure>
<IMG SRC="../../logo/logo.png" WIDTH=250 ALIGN="right">
</figure>
IHE Python course, 2017
List, dict and set comprehensions, list generators and filtering using a key function
T.N... | Python Code:
from pprint import pprint
import numpy as np
Explanation: <figure>
<IMG SRC="../../logo/logo.png" WIDTH=250 ALIGN="right">
</figure>
IHE Python course, 2017
List, dict and set comprehensions, list generators and filtering using a key function
T.N.Olsthoorn, Feb2017
List comprehensions (listcomps) dict co... |
14,577 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2021 Google LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the Licens... | Python Code:
def char2vec(word):
from collections import Counter
from math import sqrt
# count the characters in word
cw = Counter(word)
# precomputes a set of the unique characters
sw = set(cw)
# precomputes the "length" of the word vector
lw = sqrt(sum(c*c for c in cw.values()))
# ... |
14,578 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Visual mathhammer for 8th edition
Introduction to plots
The charts and numbers below visually present the distribution of total wounds lost for various attack situations under 8th edition ru... | Python Code:
profiles[0] = {'shots': 10, 'p_hit': 1 / 2, 'p_wound': 1 / 2, 'p_unsaved': 4 / 6, 'damage': '1'}
profile_damage = damage_dealt(profiles[0])
wound_chart(profile_damage, profiles)
Explanation: Visual mathhammer for 8th edition
Introduction to plots
The charts and numbers below visually present the distributi... |
14,579 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Ordinal Regression
Some data are discrete but intrinsically ordered, these are called ordinal data. One example is the likert scale for questionairs ("this is an informative tutorial"
Step1:... | Python Code:
# !pip install -q numpyro@git+https://github.com/pyro-ppl/numpyro
from jax import numpy as np, random
import numpyro
from numpyro import sample, handlers
from numpyro.distributions import (
Categorical,
Dirichlet,
ImproperUniform,
Normal,
OrderedLogistic,
TransformedDistribution,
... |
14,580 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Moving to the Cloud
Setup TensorFlow locally
Follow the instructions to install TensorFlow locally on your computer
Step1: Create VM
Prerequisite
Step2: Use your own data
Create a new sto... | Python Code:
import os
import tensorflow as tf
print('version={}, CUDA={}, GPU={}, TPU={}'.format(
tf.__version__, tf.test.is_built_with_cuda(),
# GPU attached? Note that you can "Runtime/Change runtime type..." in Colab.
len(tf.config.list_physical_devices('GPU')) > 0,
# TPU accessible? (only works on ... |
14,581 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<center>
<a href="http
Step1: 2.2 Vérification
Step2: 2.3 Tableau disjonctif
La documentation de la fonction MCA est inexistante. Cette fonction peut en principe analyser un DataFrame mais... | Python Code:
# Librairies
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
# Lire les données avec plusieurs espaces comme séparateur
# oublier la première colonne et utilisaer la première ligne pour le nom des variables
datFic=pd.read_table('Data/afcfic.dat',header=0,sep='\s+',usecols=[1,2])
datF... |
14,582 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<!--BOOK_INFORMATION-->
<a href="https
Step1: This will download the data from the Amazon Cloud (might take a while depending on
your internet connection) and automatically split the data i... | Python Code:
from keras.datasets import mnist
(X_train, y_train), (X_test, y_test) = mnist.load_data()
Explanation: <!--BOOK_INFORMATION-->
<a href="https://www.packtpub.com/big-data-and-business-intelligence/machine-learning-opencv" target="_blank"><img align="left" src="data/cover.jpg" style="width: 76px; height: 100... |
14,583 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Composing and fitting distributions
Gilles Louppe, January 2016.
This notebook introduces the carl.distributions module. It illustrates how distributions can be defined and composed, and how... | Python Code:
%matplotlib inline
from matplotlib import pyplot as plt
import numpy as np
import theano
import theano.tensor as T
Explanation: Composing and fitting distributions
Gilles Louppe, January 2016.
This notebook introduces the carl.distributions module. It illustrates how distributions can be defined and compos... |
14,584 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
FDMS TME3
Kaggle How Much Did It Rain? II
Florian Toque & Paul Willot
Dear professor Denoyer...
Warning
This is an early version of our entry for the Kaggle challenge
It's still very mes... | Python Code:
# from __future__ import exam_success
from __future__ import absolute_import
from __future__ import print_function
%matplotlib inline
import sklearn
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
import random
import pandas as pd
# Sk cheats
from sklearn.cross_validation import cr... |
14,585 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<img src="../images/qiskit-heading.gif" alt="Note
Step2: Notice that each of the codes is represented by a bitstring of length 64. By comparing characters at the same position in the string... | Python Code:
YEAST = "----------------------------------MM----------------------------"
PROTOZOAN = "--MM---------------M------------MMMM---------------M------------"
BACTERIAL = "---M---------------M------------MMMM---------------M------------"
Explanation: <img src="../images/qiskit-heading.gif" alt="Note: In ord... |
14,586 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Sebastian Raschka
back to the matplotlib-gallery at https
Step1: <font size="1.5em">More info about the %watermark extension</font>
Step2: <br>
<br>
Matplotlib Formatting II
Step3: <br>
<... | Python Code:
%load_ext watermark
%watermark -u -v -d -p matplotlib,numpy
Explanation: Sebastian Raschka
back to the matplotlib-gallery at https://github.com/rasbt/matplotlib-gallery
End of explanation
%matplotlib inline
Explanation: <font size="1.5em">More info about the %watermark extension</font>
End of explanation
i... |
14,587 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<img src='http
Step1: Funkcje wbudowane
Step2: Tuple (krotka)
Step3: Czym się różni krotka od listy?
Set (zbiory)
Step4: Prosta matematyka
Step5: Trochę programowania funkcyjnego
map, f... | Python Code:
help([1, 2, 3])
dir([1, 2, 3])
sum??
Explanation: <img src='http://pycircle.org/static/pycircle_big.png' style="margin-left:auto; margin-right:auto; height:70%; width:70%">
Wprowadzenie część 2
End of explanation
all([1==1, True, 10, -1]), all([1==5, True, 10, -1])
any([False, True]), any([False, False])
b... |
14,588 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Data Preprocess
Zhiang Chen, March 2017
This notebook is to get training dataset, validation dataset and test dataset. First, it reads the 24 pickle files. These 24 pickle files contain data... | Python Code:
from six.moves import cPickle as pickle
import matplotlib.pyplot as plt
import os
from random import sample, shuffle
import numpy as np
Explanation: Data Preprocess
Zhiang Chen, March 2017
This notebook is to get training dataset, validation dataset and test dataset. First, it reads the 24 pickle files. Th... |
14,589 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Land
MIP Era
Step1: Document Authors
Set document authors
Step2: Document Contributors
Specify document contributors
Step3: Document Publication
Specify do... | Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'cccr-iitm', 'iitm-esm', 'land')
Explanation: ES-DOC CMIP6 Model Properties - Land
MIP Era: CMIP6
Institute: CCCR-IITM
Source ID: IITM-ESM
Topic: Land
Sub-Topics: Soil, Snow, Vegetatio... |
14,590 | Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
I want to process a gray image in the form of np.array. | Problem:
import numpy as np
im = np.array([[0,0,0,0,0,0],
[0,0,1,1,1,0],
[0,1,1,0,1,0],
[0,0,0,1,1,0],
[0,0,0,0,0,0]])
mask = im == 0
rows = np.flatnonzero((~mask).sum(axis=1))
cols = np.flatnonzero((~mask).sum(axis=0))
if rows.shape[0] == 0:
result = np.a... |
14,591 | Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
I have a DataFrame and I would like to transform it to count views that belong to certain bins. | Problem:
import pandas as pd
df = pd.DataFrame({'username': ['john', 'john', 'john', 'john', 'jane', 'jane', 'jane', 'jane'],
'post_id': [1, 2, 3, 4, 7, 8, 9, 10],
'views': [3, 23, 44, 82, 5, 25,46, 56]})
bins = [1, 10, 25, 50, 100]
def g(df, bins):
groups = df.groupby(['userna... |
14,592 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Deep learning goes to the movies
Kaggle tutorial Part 1
Step1: 读取数据
Step2: 清洗数据
Step3: 计算特征向量(词向量)
Step4: Cross validation Score of RandomForestClassifier
RandomForestClassifier
在机器学习中,... | Python Code:
import os
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.ensemble import RandomForestClassifier
from KaggleWord2VecUtility import KaggleWord2VecUtility # in the same folader
import pandas as pd
import numpy as np
Explanation: Deep learning goes to the movies
Kaggle tutorial Part ... |
14,593 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Title
Step1: Load Iris Dataset
Step2: Use Cross-Validation To Find The Best Value Of C | Python Code:
# Load libraries
from sklearn import linear_model, datasets
Explanation: Title: Fast C Hyperparameter Tuning
Slug: fast_c_hyperparameter_tuning
Summary: How to fast C hyperparameter tuning for logistic regression in scikit-learn for machine learning in Python.
Date: 2017-09-18 12:00
Category: Machine Lear... |
14,594 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Language Translation
In this project, you’re going to take a peek into the realm of neural network machine translation. You’ll be training a sequence to sequence model on a dataset o... | Python Code:
DON'T MODIFY ANYTHING IN THIS CELL
import helper
import problem_unittests as tests
source_path = 'data/small_vocab_en'
target_path = 'data/small_vocab_fr'
source_text = helper.load_data(source_path)
target_text = helper.load_data(target_path)
Explanation: Language Translation
In this project, you’re going ... |
14,595 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<font color="blue">
Vitali C.
Data Scientist<br>
Step1: Column names
Number of times pregnant
Plasma glucose concentration a 2 hours in an oral glucose tolerance test
Diastolic blood pressu... | Python Code:
# Importing libraries
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
plt.style.use('bmh')
%matplotlib inline
# To learn more about the data set https://archive.ics.uci.edu/ml/datasets/pima+indians+diabetes
data_url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/pima-in... |
14,596 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
GEM-PRO - Genes & Sequences
This notebook gives an example of how to run the GEM-PRO pipeline with a dictionary of gene IDs and their protein sequences.
<div class="alert alert-info">
**Inpu... | Python Code:
import sys
import logging
# Import the GEM-PRO class
from ssbio.pipeline.gempro import GEMPRO
# Printing multiple outputs per cell
from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"
Explanation: GEM-PRO - Genes & Sequences
This notebook gives an examp... |
14,597 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Neural Network demo
Start a Mosquitto container first. For example
Step1: List of neurons
Step2: Start client
Step3: Utility functions
Step4: Reset neurons
Step5: Probe neurons by blink... | Python Code:
import os
import sys
import time
sys.path.append(os.path.abspath(os.path.join(os.path.pardir, os.path.sep.join(['..', 'codes']), 'client')))
sys.path.append(os.path.abspath(os.path.join(os.path.pardir, os.path.sep.join(['..', 'codes']), 'node')))
sys.path.append(os.path.abspath(os.path.join(os.path.pardi... |
14,598 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Case study
Given a user’s past reviews on Yelp (available from yelp-challenge dataset),
When the user writes a review for a business she hasn't reviewed before,
How likely will it be a Five-... | Python Code:
import pandas as pd
PATH = '/scratch/xun/docs/yelp_dataset_challenge_round10/'
biz_df = pd.read_csv(PATH + 'business.csv')
user_df = pd.read_csv(PATH + 'user.csv')
review_df = pd.read_csv(PATH + 'review.csv')
review_df = review_df.set_index('review_id')
user_df = user_df.set_index('user_id')
biz_df = biz_d... |
14,599 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
FD_1D_stability 1-D FD stability calculation
GNU General Public License v3.0
Author
Step1: Input Parameter
Step2: Calculate Taylor coefficient
Calculate the Taylor coefficient in an arbitr... | Python Code:
import numpy as np
Explanation: FD_1D_stability 1-D FD stability calculation
GNU General Public License v3.0
Author: Florian Wittkamp
Calculate stability limit of FD-simulations
Stability limit is calculated in terms of the CFL-number, which is
defined as: CFL=v_(max)DT/DX
You get the maximum DT by DT=CFLD... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.