Unnamed: 0 int64 0 16k | text_prompt stringlengths 110 62.1k | code_prompt stringlengths 37 152k |
|---|---|---|
500 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Widgets Demo
IPython widgets allow you to quickly and easily create interactive APIs with Python.
To run this notebook, you'll first have to install ipywidgets using, e.g.
$ conda install ip... | Python Code:
from ipywidgets import interact
def times_ten(x):
return 10 * x
interact(times_ten, x=10);
interact(times_ten, x='(^_^)')
interact(times_ten, x=True)
Explanation: Widgets Demo
IPython widgets allow you to quickly and easily create interactive APIs with Python.
To run this notebook, you'll first have to... |
501 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<font color='blue'>Data Science Academy - Python Fundamentos - Capítulo 4</font>
Download
Step1: ** ATENÇÃO ****
Caso você tenha problemas com acentos nos arquivos
Step2: Usando a expressã... | Python Code:
# Versão da Linguagem Python
from platform import python_version
print('Versão da Linguagem Python Usada Neste Jupyter Notebook:', python_version())
Explanation: <font color='blue'>Data Science Academy - Python Fundamentos - Capítulo 4</font>
Download: http://github.com/dsacademybr
End of explanation
texto... |
502 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
general
Step1: fw_ids for user-submitted workflows
Step2: pause controller, defuse/fizzle workflows with >20 nodes
Step3: prioritized user-submitted "Add to SNL" tasks to get duplicate ch... | Python Code:
user_remarks = [
"new ICSD batch", "Pauling file", "Heusler ABC2 phases",
"proton conducting materials for fuel cells", "solid solution metal", "solid solution oxide", "intermetallic",
"CNGMD Nitrides", "MAGICS calculation of band structures of 2D TMDC stacked heterostructures"
]
Explanation: g... |
503 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Content-Based Filtering Using Neural Networks
This notebook relies on files created in the content_based_preproc.ipynb notebook. Be sure to run the code in there before completing this noteb... | Python Code:
%%bash
pip freeze | grep tensor
Explanation: Content-Based Filtering Using Neural Networks
This notebook relies on files created in the content_based_preproc.ipynb notebook. Be sure to run the code in there before completing this notebook.
Also, you'll be using the python3 kernel from here on out so don't ... |
504 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
A Simple Autoencoder
We'll start off by building a simple autoencoder to compress the MNIST dataset. With autoencoders, we pass input data through an encoder that makes a compressed represen... | Python Code:
%matplotlib inline
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('MNIST_data', validation_size=0)
Explanation: A Simple Autoencoder
We'll start off by building a simple autoencoder to c... |
505 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Esta será una microentrada para presentar una extensión para el notebook que estoy usando en un curso interno que estoy dando en mi empresa.
Si a alguno más os puede valer para mostrar cosas... | Python Code:
%load_ext jupytor
Explanation: Esta será una microentrada para presentar una extensión para el notebook que estoy usando en un curso interno que estoy dando en mi empresa.
Si a alguno más os puede valer para mostrar cosas básicas de Python (2 y 3, además de Java y Javascript) para muy principiantes me aleg... |
506 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Nonlinear Dimensionality Reduction
G. Richards (2016), based on materials from Ivezic, Connolly, Miller, Leighly, and VanderPlas.
Today we will talk about the concepts of
* manifold learnin... | Python Code:
import numpy as np
from sklearn.manifold import LocallyLinearEmbedding
X = np.random.normal(size=(1000,2)) # 1000 points in 2D
R = np.random.random((2,10)) # projection matrix
X = np.dot(X,R) # now a 2D linear manifold in 10D space
k = 5 # Number of neighbors to use in fit
n = 2 # Number of dimensions to f... |
507 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2020 The TensorFlow Authors.
Step1: 你好,量子世界
<table class="tfo-notebook-buttons" align="left">
<td><a target="_blank" href="https
Step2: 安装 TensorFlow Quantum:
Step3: 现在,导入 Ten... | 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... |
508 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Ordinary Differential Equations Exercise 2
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 2
Imports
End of explanation
def lorentz_derivs(yvec, t, sigma, rho, beta):
Compute the the der... |
509 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Cervix EDA
In this competition we have a multi-class classification problem with three classes. We are asked, given an image, to identify the cervix type.
From the data description
Step1: W... | Python Code:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from skimage.io import imread, imshow
import cv2
%matplotlib inline
import plotly.offline as py
py.init_notebook_mode(connected=True)
import plotly.graph_objs as go
import plotly.tools as tls
from subprocess import... |
510 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a href="https
Step1: Building the LSTM model for Language Modeling
Now that we know exactly what we are doing, we can start building our model using TensorFlow. The very first thing we nee... | Python Code:
import time
import numpy as np
import tensorflow as tf
import os
print('TensorFlow version: ', tf.__version__)
tf.reset_default_graph()
if not os.path.isfile('./penn_treebank_reader.py'):
print('Downloading penn_treebank_reader.py...')
!wget -q -O ../../data/Penn_Treebank/ptb.zip https://ibm.box.co... |
511 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Web-Scraping
Sous ce nom se cache une pratique très utile pour toute personne souhaitant travailler sur des informations disponibles en ligne, mais n'existant pas forcément sous la forme d'u... | Python Code:
from jyquickhelper import add_notebook_menu
add_notebook_menu()
Explanation: Web-Scraping
Sous ce nom se cache une pratique très utile pour toute personne souhaitant travailler sur des informations disponibles en ligne, mais n'existant pas forcément sous la forme d'un tableau Excel ...
Le webscraping est u... |
512 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Sentiment Classification & How To "Frame Problems" for a Neural Network
by Andrew Trask
Twitter
Step1: Note
Step2: Lesson
Step3: Project 1
Step4: We'll create three Counter objects, one ... | Python Code:
def pretty_print_review_and_label(i):
print(labels[i] + "\t:\t" + reviews[i][:80] + "...")
g = open('reviews.txt','r') # What we know!
reviews = list(map(lambda x:x[:-1],g.readlines()))
g.close()
g = open('labels.txt','r') # What we WANT to know!
labels = list(map(lambda x:x[:-1].upper(),g.readlines())... |
513 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Tutorial
Step1: Note
Step2: Definition of the layers
So let us define the layers for the convolutional net. In general, layers are assembled in a list. Each element of the list is a tuple ... | Python Code:
import os
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
from lasagne.layers import DenseLayer
from lasagne.layers import InputLayer
from lasagne.layers import DropoutLayer
from lasagne.layers import Conv2DLayer
from lasagne.layers import MaxPool2DLayer
from lasagne.nonlinearities im... |
514 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Robot Calibration
Nominal Robot
A nominal robot model
Step1: Real Robots
Real robots do not conform perfectly to the nominal parameters
Small errors in the robot model can generate large er... | Python Code:
from pybotics.robot import Robot
from pybotics.predefined_models import ur10
nominal_robot = Robot.from_parameters(ur10())
import pandas as pd
def display_robot_kinematics(robot: Robot):
df = pd.DataFrame(robot.kinematic_chain.matrix)
df.columns = ["alpha", "a", "theta", "d"]
display(df)
displa... |
515 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
PIPITS Fungal ITS-dedicated Pipeline
The default pair merge algorithm in vsearch discards 90% of the data. This was observed in other datasets and is believe to be overly conservative. PIPIT... | Python Code:
import os
# Provide the directory for your index and read files
ITS = '/home/roli/FORESTs_BHAVYA/WoodsLake/raw_seq/ITS/'
# Provide
datasets = [['ITS',ITS,'ITS.metadata.pipits.Woods.tsv']]
# Ensure your reads files are named accordingly (or modify to suit your needs)
readFile1 = 'read1.fq.gz'
readFile2 = '... |
516 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Toplevel
MIP Era
Step1: Document Authors
Set document authors
Step2: Document Contributors
Specify document contributors
Step3: Document Publication
Specif... | Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'ncc', 'sandbox-1', 'toplevel')
Explanation: ES-DOC CMIP6 Model Properties - Toplevel
MIP Era: CMIP6
Institute: NCC
Source ID: SANDBOX-1
Sub-Topics: Radiative Forcings.
Properties: 85... |
517 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Kind recipe to extract clusters from thresholded SPMt maps and make them as a map of ROIs
First threshold your SPMt map
Step1: Define a folder containing rough hand-drawn ROIs over the clus... | Python Code:
original_fp = '/home/grg/spm/analyses/analysis_20170228/MD_DARTEL_csf5_interaction_linearage/estimatecontrasts/spmT_0028.nii'
thresholded_map, threshold = thresholding.map_threshold(original_fp, threshold=1e-3)
thresholded_fp = '/tmp/thresholded_map.nii.gz'
thresholded_map.to_filename(thresholded_fp) # Sa... |
518 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
CS446/546 - Class Session 19 - Correlation network
In this class session we are going to analyze gene expression data from a human bladder cancer cohort, using python. We will load a data ma... | Python Code:
import pandas
import scipy.stats
import matplotlib
import pylab
import numpy
import statsmodels.sandbox.stats.multicomp
import igraph
import math
Explanation: CS446/546 - Class Session 19 - Correlation network
In this class session we are going to analyze gene expression data from a human bladder cancer co... |
519 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Using Convolutional Neural Networks
Welcome to the first week of the first deep learning certificate! We're going to use convolutional neural networks (CNNs) to allow our computer to see - s... | Python Code:
%matplotlib inline
Explanation: Using Convolutional Neural Networks
Welcome to the first week of the first deep learning certificate! We're going to use convolutional neural networks (CNNs) to allow our computer to see - something that is only possible thanks to deep learning.
Introduction to this week's t... |
520 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Matrix factorization is a very interesting area of machine learning research. Formulating a problem as a 2D matrix $X$ to be decomposed into multiple matrices, which combine to return an app... | Python Code:
from IPython.display import YouTubeVideo
YouTubeVideo('JgfK46RA8XY')
Explanation: Matrix factorization is a very interesting area of machine learning research. Formulating a problem as a 2D matrix $X$ to be decomposed into multiple matrices, which combine to return an approximation of $X$, can lead to stat... |
521 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Code-HotSpots
Welche Dateien werden wie oft geändert?
Input
Git-Versionskontrollsystemdaten einlesen.
Step1: Bereinigen
Nur Produktions-Code ausgewerten.
Step2: Aggregation
HotSpots ermitt... | Python Code:
from ozapfdis import git
log = git.log_numstat_existing("../../../dropover/")
log.head()
Explanation: Code-HotSpots
Welche Dateien werden wie oft geändert?
Input
Git-Versionskontrollsystemdaten einlesen.
End of explanation
java_prod = log[log['file'].str.contains("backend/src/main/java/")].copy()
java_prod... |
522 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Python Basics at PyCAR2020
Let's search some text
You already know the components of programming. You have been exercising the reasoning programming relies on for your entire life, probably ... | Python Code:
# This could just as easily be 'horse' or 'Helen' or 'Agamemnon' or `sand` -- or 'Trojan'
search_term = 'Achilles'
Explanation: Python Basics at PyCAR2020
Let's search some text
You already know the components of programming. You have been exercising the reasoning programming relies on for your entire life... |
523 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Creating temporary files with unique names securely, so they cannot be guessed by someone wanting to break the application or steal the data, is challenging. The tempfile module provides sev... | Python Code:
import os
import tempfile
print('Building a filename with PID:')
filename = '/tmp/guess_my_name.{}.txt'.format(os.getpid())
with open(filename, 'w+b') as temp:
print('temp:')
print(' {!r}'.format(temp))
print('temp.name:')
print(' {!r}'.format(temp.name))
# Clean up the temporary file you... |
524 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
In this tutorial you'll learn all about histograms and density plots.
Set up the notebook
As always, we begin by setting up the coding environment. (This code is hidden, but you can un-hide... | Python Code:
#$HIDE$
import pandas as pd
pd.plotting.register_matplotlib_converters()
import matplotlib.pyplot as plt
%matplotlib inline
import seaborn as sns
print("Setup Complete")
Explanation: In this tutorial you'll learn all about histograms and density plots.
Set up the notebook
As always, we begin by setting up ... |
525 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
The SparkContext.addPyFiles() function can be used to add py files. We can define objects and variables in these files and make them available to the Spark cluster.
Create a SparkContext obj... | Python Code:
from pyspark import SparkConf, SparkContext, SparkFiles
from pyspark.sql import SparkSession
sc = SparkContext(conf=SparkConf())
Explanation: The SparkContext.addPyFiles() function can be used to add py files. We can define objects and variables in these files and make them available to the Spark cluster.
... |
526 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Knows What It Knows (KWIK)
A framework for self-aware learning
Combines elements of Probably Approximately Correct (PAC) and mistake-bound models
Useful for active learning
Motivation
Polyno... | Python Code:
from collections import Counter
class Kwik:
def __init__(self, number_of_patrons):
# Init
self.current_i_do_not_knows = 0
self.number_of_patrons = number_of_patrons
self.max_i_do_not_knows = self.number_of_patrons * (self.number_of_patrons - 1)
self.instigator = ... |
527 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
In this notebook a simple Q learner will be trained and evaluated. The Q learner recommends when to buy or sell shares of one particular stock, and in which quantity (in fact it determines t... | Python Code:
# Basic imports
import os
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import datetime as dt
import scipy.optimize as spo
import sys
from time import time
from sklearn.metrics import r2_score, median_absolute_error
from multiprocessing import Pool
%matplotlib inline
%pylab inline
... |
528 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Toplevel
MIP Era
Step1: Document Authors
Set document authors
Step2: Document Contributors
Specify document contributors
Step3: Document Publication
Specif... | Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'noaa-gfdl', 'gfdl-esm4', 'toplevel')
Explanation: ES-DOC CMIP6 Model Properties - Toplevel
MIP Era: CMIP6
Institute: NOAA-GFDL
Source ID: GFDL-ESM4
Sub-Topics: Radiative Forcings.
Pr... |
529 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ApJdataFrames Luhman1999
Title
Step1: Table 1 - Data for Spectroscopic Sample in ρ Ophiuchi
Step2: Save data | Python Code:
import warnings
warnings.filterwarnings("ignore")
from astropy.io import ascii
import pandas as pd
Explanation: ApJdataFrames Luhman1999
Title: Low-Mass Star Formation and the Initial Mass Function in the ρ Ophiuchi Cloud Core
Authors: K. L. Luhman and G.H. Rieke
Data is from this paper:
http://iopscience.... |
530 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Import necessary modules
Step1: Filepath management
Step2: Load the data from the hdf store
Step3: Visualize the data
Step4: Adding in missing times (zero volume minutes)
Before evaluati... | Python Code:
import time
import pandas as pd
import numpy as np
import datetime as dt
from collections import OrderedDict
from copy import copy
import warnings
import matplotlib.pyplot as plt
import seaborn as sns
from pprint import pprint
%matplotlib inline
Explanation: Import necessary modules
End of explanation
proj... |
531 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Using Pickle to manage memory in Python
Author
Step1: Function to track memory utilization
Step2: Create a dataframe with random integers between 0 and 1000
Step3: Create Pickle dump
Step... | Python Code:
import gc
import pickle
import psutil
import numpy as np
import pandas as pd
Explanation: Using Pickle to manage memory in Python
Author: Dr. Rahul Remanan, CEO, Moad Computer
Run this notebook in Google Colab
Import dependencies
End of explanation
def memory_utilization():
print('Current memory utilizat... |
532 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a href="https
Step1: Neural Tangents Cookbook
In this notebook we explore the training of infinitely-wide, Bayesian, neural networks using a library called Neural Tangents. Recent work has... | Python Code:
!pip install --upgrade pip
!pip install --upgrade jax[cuda11_cudnn805] -f https://storage.googleapis.com/jax-releases/jax_releases.html
!pip install -q git+https://www.github.com/google/neural-tangents
import jax.numpy as np
from jax import random
from jax.example_libraries import optimizers
from jax impor... |
533 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Regression
Copyright 2015 Allen Downey
License
Step1: Let's load up the NSFG data again.
Step2: And select live, full-term births.
Step3: And drop rows with missing data (just for the var... | Python Code:
from __future__ import print_function, division
import numpy as np
import pandas as pd
import first
import thinkstats2
import thinkplot
%matplotlib inline
Explanation: Regression
Copyright 2015 Allen Downey
License: Creative Commons Attribution 4.0 International
End of explanation
live, firsts, others = fi... |
534 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a href="https
Step1: Keys
<script type="text/javascript">
localStorage.setItem('language', 'language-py')
</script>
<table align="left" style="margin-right
Step2: Example
In the following... | Python Code:
#@title Licensed under the Apache License, Version 2.0 (the "License")
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this fi... |
535 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Poincare Map
This example shows how to calculate a simple Poincare Map with REBOUND. A Poincare Map (or sometimes calles Poincare Section) can be helpful to understand dynamical systems.
Ste... | Python Code:
import rebound
import numpy as np
Explanation: Poincare Map
This example shows how to calculate a simple Poincare Map with REBOUND. A Poincare Map (or sometimes calles Poincare Section) can be helpful to understand dynamical systems.
End of explanation
sim = rebound.Simulation()
sim.add(m=1.)
sim.add(m=1e-... |
536 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Classification with Support Vector Machines
by Soeren Sonnenburg | Saurabh Mahindre - <a href=\"https
Step1: Liblinear, a library for large- scale linear learning focusing on SVM, is used t... | Python Code:
import matplotlib.pyplot as plt
%matplotlib inline
import os
SHOGUN_DATA_DIR=os.getenv('SHOGUN_DATA_DIR', '../../../data')
import matplotlib.patches as patches
#To import all shogun classes
import shogun as sg
import numpy as np
#Generate some random data
X = 2 * np.random.randn(10,2)
traindata=np.r_[X + 3... |
537 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Executed
Step1: Load software and filenames definitions
Step2: Data folder
Step3: Check that the folder exists
Step4: List of data files in data_dir
Step5: Data load
Initial loading of ... | Python Code:
ph_sel_name = "all-ph"
data_id = "7d"
# ph_sel_name = "all-ph"
# data_id = "7d"
Explanation: Executed: Mon Mar 27 11:37:05 2017
Duration: 9 seconds.
usALEX-5samples - Template
This notebook is executed through 8-spots paper analysis.
For a direct execution, uncomment the cell below.
End of explanation
from... |
538 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introduction
This workbook contains some examples for reading, analysing and plotting processed MT data. It covers most of the steps available in MTPy. For more details on specific input par... | Python Code:
# import required modules
from mtpy.core.mt import MT
# Define the path to your edi file
edi_file = "C:/mtpywin/mtpy/examples/data/edi_files_2/Synth00.edi"
# Create an MT object
mt_obj = MT(edi_file)
Explanation: Introduction
This workbook contains some examples for reading, analysing and plotting processe... |
539 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Nucleic acids structure analysis
analysis of the nucleic acids backbone torsion angles.
The 'nucleic_acid_torsion' function can be used to compute the backbone torsion angles. For example
St... | Python Code:
from SBio import *
s3 = create_molecule('D:\\python\\structural bioinformatics_in_python\\examples\\S3.pdb').m1
torsions = nucleic_acid_torsion(s3, ('A','B'),(1,12))
print(torsions[1]) # residue.serial , α, β, γ, δ, ε, ξ, χ,
Explanation: Nucleic acids structure analysis
analysis of the nucleic acids... |
540 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Multiple Stripe Analysis (MSA) for Single Degree of Freedom (SDOF) Oscillators
In this method, a single degree of freedom (SDOF) model of each structure is subjected to non-linear time histo... | Python Code:
import MSA_on_SDOF
from rmtk.vulnerability.common import utils
import numpy as np
import MSA_utils
%matplotlib inline
Explanation: Multiple Stripe Analysis (MSA) for Single Degree of Freedom (SDOF) Oscillators
In this method, a single degree of freedom (SDOF) model of each structure is subjected to non-li... |
541 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
scikit-learn-k-means
Credits
Step1: K-Means Clustering
Step2: K Means is an algorithm for unsupervised clustering
Step3: By eye, it is relatively easy to pick out the four clusters. If yo... | Python Code:
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
import seaborn;
from sklearn.linear_model import LinearRegression
from scipy import stats
import pylab as pl
seaborn.set()
Explanation: scikit-learn-k-means
Credits: Forked from PyCon 2015 Scikit-learn Tutorial by Jake VanderPlas
End of... |
542 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Mass-univariate twoway repeated measures ANOVA on single trial power
This script shows how to conduct a mass-univariate repeated measures
ANOVA. As the model to be fitted assumes two fully c... | Python Code:
# Authors: Denis Engemann <denis.engemann@gmail.com>
# Eric Larson <larson.eric.d@gmail.com>
# Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr>
#
# License: BSD (3-clause)
import numpy as np
import matplotlib.pyplot as plt
import mne
from mne.time_frequency import tfr_morlet
f... |
543 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
This notebook was created by Sergey Tomin for Workshop
Step1: Change RF parameters for the comparison with ASTRA
Step2: Initializing SpaceCharge
Step3: Comparison with ASTRA
Beam tracking... | Python Code:
# the output of plotting commands is displayed inline within frontends,
# directly below the code cell that produced it
%matplotlib inline
from time import time
# this python library provides generic shallow (copy) and deep copy (deepcopy) operations
from copy import deepcopy
# import from Ocelot main m... |
544 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
< 3. Traitement de données | Contents | 6. Analyse statistique >
Step1: Géocodage
Le géocodage consiste à obtenir les points de référence géographique d'objets du monde réel. Un cas intéres... | Python Code:
import geopandas
Explanation: < 3. Traitement de données | Contents | 6. Analyse statistique >
End of explanation
geopandas.tools.geocode('2900 boulevard Edouard Montpetit, Montreal', provider='nominatim', user_agent="mon-application")
Explanation: Géocodage
Le géocodage consiste à obtenir les points de ré... |
545 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Passive
Plots a passive learning curve w.r.t. ATLAS objects. Trained, tested on RGZ, split on compact/resolved. Testing on RGZ instead of Norris because we believe it to be reasonably accura... | Python Code:
import astropy.io.ascii as asc, numpy, h5py, sklearn.linear_model, crowdastro.crowd.util, pickle, scipy.spatial
import matplotlib.pyplot as plt
%matplotlib inline
with open('/Users/alger/data/Crowdastro/sets_atlas.pkl', 'rb') as f:
atlas_sets = pickle.load(f)
atlas_sets_compact = atlas_sets['RGZ & ... |
546 | 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', 'test-institute-3', 'sandbox-3', 'seaice')
Explanation: ES-DOC CMIP6 Model Properties - Seaice
MIP Era: CMIP6
Institute: TEST-INSTITUTE-3
Source ID: SANDBOX-3
Topic: Seaice
Sub-Topics:... |
547 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Minimization
When using a Maximum Likelihood analysis we want to find the maximum of the likelihood $L(\vec{\theta})$ given one or more datasets (i.e., plugin instances) and one model contai... | Python Code:
from threeML import *
import matplotlib.pyplot as plt
%matplotlib inline
from threeML.minimizer.tutorial_material import *
Explanation: Minimization
When using a Maximum Likelihood analysis we want to find the maximum of the likelihood $L(\vec{\theta})$ given one or more datasets (i.e., plugin instances) a... |
548 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Largest product in a grid
Problem 11
In the 20 × 20 grid below, four numbers along a diagonal line have been marked in red.
08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08
49 49 ... | Python Code:
from euler import Seq, timer
import numpy as np
def p011():
table = np.loadtxt(open("data/p011.txt","rb"),delimiter=" ", dtype=np.int)
rows, columns = np.shape(table)
def collect(i,j,di,dj):
step = 4
acc = 1
while True:
if step==0:
return acc
... |
549 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
SEER Data Analysis
Phase 3
Step1: To begin exploring the data we took a sample of the SEER data, defined the features and dependent variable, printed the top few lines to ensure a successfu... | Python Code:
%matplotlib inline
import os
import time
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from MasterSeer import MasterSeer
from sklearn.feature_selection import SelectPercentile, f_classif, SelectFromModel
from sklearn.linear_model import LinearRegression
from lifelines.plotting impo... |
550 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
The Evoked data structure
Step1: Creating Evoked objects from Epochs
Step2: Basic visualization of Evoked objects
We can visualize the average evoked response for left-auditory stimuli usi... | Python Code:
import os
import mne
Explanation: The Evoked data structure: evoked/averaged data
This tutorial covers the basics of creating and working with :term:evoked
data. It introduces the :class:~mne.Evoked data structure in detail,
including how to load, query, subselect, export, and plot data from an
:class:~mne... |
551 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ABU量化系统使用文档
<center>
<img src="./image/abu_logo.png" alt="" style="vertical-align
Step1: 受限于沙盒中数据限制,本节示例的相关性分析只限制在abupy内置沙盒数据中,首先将内置沙盒中美股,A股,港股, 比特币,莱特币,期货市场中的symbol都列出来
Step2: 如上所... | Python Code:
# 基础库导入
from __future__ import print_function
from __future__ import division
import warnings
warnings.filterwarnings('ignore')
warnings.simplefilter('ignore')
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
import os
import sys
# 使用insert 0即只使用github,避免交叉使用了pip安装的... |
552 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
1A.e - TD noté, 21 février 2017
Solution du TD noté, celui-ci présente un algorithme pour calculer les coefficients d'une régression quantile et par extension d'une médiane dans un espace à ... | Python Code:
from jyquickhelper import add_notebook_menu
add_notebook_menu()
Explanation: 1A.e - TD noté, 21 février 2017
Solution du TD noté, celui-ci présente un algorithme pour calculer les coefficients d'une régression quantile et par extension d'une médiane dans un espace à plusieurs dimensions.
End of explanation... |
553 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Unconstrained global optimization with Scipy
TODO
Step1: Define the objective function
Step2: The "basin-hopping" algorithm
Basin-hopping is a stochastic algorithm which attempts to find t... | Python Code:
# Init matplotlib
%matplotlib inline
import matplotlib
matplotlib.rcParams['figure.figsize'] = (8, 8)
# Setup PyAI
import sys
sys.path.insert(0, '/Users/jdecock/git/pub/jdhp/pyai')
import numpy as np
import time
import warnings
from scipy import optimize
# Plot functions
from pyai.optimize.utils import plo... |
554 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
벡터 공간
벡터의 기하학적 의미
길이가 $K$인 벡터(vector) $a$는 $K$차원의 공간에서 원점과 벡터 $a$의 값으로 표시되는 점을 연결한 화살표(arrow)로 간주할 수 있다.
$$ a = \begin{bmatrix}1 \ 2 \end{bmatrix} $$
Step1: 벡터의 길이
벡터 $a$ 의 길이를 놈(norm) $\|... | Python Code:
a = [1, 2]
plt.annotate('', xy=a, xytext=(0,0), arrowprops=dict(facecolor='black'))
plt.plot(0, 0, 'ro', ms=10)
plt.plot(a[0], a[1], 'ro', ms=10)
plt.text(0.35, 1.15, "$a$", fontdict={"size": 18})
plt.xticks(np.arange(-2, 4))
plt.yticks(np.arange(-1, 4))
plt.xlim(-2.4, 3.4)
plt.ylim(-1.2, 3.2)
plt.show()
E... |
555 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Convolutional Neural Networks
In this notebook, we train a CNN to classify images from the CIFAR-10 database.
1. Load CIFAR-10 Database
Step1: 2. Visualize the First 24 Training Images
Step... | Python Code:
import keras
from keras.datasets import cifar10
# load the pre-shuffled train and test data
(x_train, y_train), (x_test, y_test) = cifar10.load_data()
Explanation: Convolutional Neural Networks
In this notebook, we train a CNN to classify images from the CIFAR-10 database.
1. Load CIFAR-10 Database
End of ... |
556 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
CNN for CIFAR10
CNN model that can be used for classification tasks.
In this demo, we will train a 3-layer CNN on the CIFAR10 dataset. We will show 2 implementations of the CNN model. First... | Python Code:
import torch
import torchvision
import wandb
import math
import time
import numpy as np
import matplotlib.pyplot as plt
from torch import nn
from einops import rearrange
from argparse import ArgumentParser
from pytorch_lightning import LightningModule, Trainer, Callback
from pytorch_lightning.loggers impor... |
557 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Feature Extraction and Preprocessing
Step1: DictVectorizer
Step2: CountVectorizer
Step3: Stop Word Filtering
Step4: Stemming and Lemmatization
Lemmatization is the process of determin... | Python Code:
from sklearn.feature_extraction import DictVectorizer
from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer, HashingVectorizer
from sklearn.metrics.pairwise import euclidean_distances
from sklearn import preprocessing
from nltk.stem.wordnet import WordNetLemmatizer
from nltk.stem imp... |
558 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
In this example you will learn how to make use of the periodicity of the electrodes.
As seen in TB 4 the transmission calculation takes a considerable amount of time. In this example we will... | Python Code:
graphene = sisl.geom.graphene(orthogonal=True)
Explanation: In this example you will learn how to make use of the periodicity of the electrodes.
As seen in TB 4 the transmission calculation takes a considerable amount of time. In this example we will redo the same calculation, but speed it up (no approxima... |
559 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
PyBroMo - GUI Trajectory explorer
<small><i>
This notebook is part of PyBroMo a
python-based single-molecule Brownian motion diffusion simulator
that simulates confocal smFRET
experiments.... | Python Code:
%matplotlib inline
import numpy as np
import tables
import matplotlib.pyplot as plt
plt.rcParams['path.simplify_threshold'] = 1.0
import pybromo as pbm
print('Numpy version:', np.__version__)
print('Matplotlib version:', plt.matplotlib.__version__)
print('PyTables version:', tables.__version__)
print('PyBr... |
560 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
2. Parámetros de ecuaciones de estado cúbicas (SRK, PR, RKPR)
En esta sección se presenta una implementación en Python para calcular los parámetros de ecuaciones de estado cúbicas (SRK, PR, ... | Python Code:
import numpy as np
import pandas as pd
import pyther as pt
Explanation: 2. Parámetros de ecuaciones de estado cúbicas (SRK, PR, RKPR)
En esta sección se presenta una implementación en Python para calcular los parámetros de ecuaciones de estado cúbicas (SRK, PR, RKPR). Las 2 primeras ecuaciónes de estado SR... |
561 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<h1 align="center">TensorFlow Neural Network Lab</h1>
<img src="image/notmnist.png">
In this lab, you'll use all the tools you learned from Introduction to TensorFlow to label images of Engl... | Python Code:
import hashlib
import os
import pickle
from urllib.request import urlretrieve
import numpy as np
from PIL import Image
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelBinarizer
from sklearn.utils import resample
from tqdm import tqdm
from zipfile import ZipFile
p... |
562 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
NMT-Keras tutorial
2. Creating and training a Neural Translation Model
Now, we'll create and train a Neural Machine Translation (NMT) model. Since there is a significant number of hyperparam... | Python Code:
from config import load_parameters
from model_zoo import TranslationModel
import utils
from keras_wrapper.cnn_model import loadModel
from keras_wrapper.dataset import loadDataset
from keras_wrapper.extra.callbacks import PrintPerformanceMetricOnEpochEndOrEachNUpdates
params = load_parameters()
dataset = lo... |
563 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Morph surface source estimate
This example demonstrates how to morph an individual subject's
Step1: Setup paths
Step2: Load example data
Step3: Setting up SourceMorph for SourceEstimate
I... | Python Code:
# Author: Tommy Clausner <tommy.clausner@gmail.com>
#
# License: BSD (3-clause)
import os
import os.path as op
import mne
from mne.datasets import sample
print(__doc__)
Explanation: Morph surface source estimate
This example demonstrates how to morph an individual subject's
:class:mne.SourceEstimate to a c... |
564 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Fractionating $2^k$ Factorial Designs
Motivation
The prior section showed an example of what an experimental design might like look like for 6 variables. However, this resulted in a $2^6 = 6... | Python Code:
import pandas as pd
import itertools
import numpy as np
import seaborn as sns
import pylab
import scipy.stats as stats
import statsmodels.api as sm
Explanation: Fractionating $2^k$ Factorial Designs
Motivation
The prior section showed an example of what an experimental design might like look like for 6 var... |
565 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Chicago taxi fare training experience
This experiment using Scikit-learn Random Forest to train a ML model on Chicago taxi dataset to estimate taxi trip fare in a given time and start... | Python Code:
import numpy as np
import pandas as pd
from pandas_profiling import ProfileReport
from scipy import stats
from sklearn.ensemble import RandomForestRegressor
from sklearn.compose import ColumnTransformer
from sklearn.model_selection import train_test_split, cross_val_score, GridSearchCV
from sklearn.pipelin... |
566 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
We start off with a single import statement. Nice! Note the TensorFlow backend...
Step1: Great, now I have a model.
Let's so something with it, like build a 34-layer residual network. | Python Code:
model = KerasGraphModel()
Explanation: We start off with a single import statement. Nice! Note the TensorFlow backend...
End of explanation
model.build_residual_network()
model.graph.summary()
from data_preparation.image_preparation import ImageLoader
from pathlib import Path
image_loader = ImageLoader()
i... |
567 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Experimental data assessment and model parameters optimisation
Data preparation
The first step to generate three-dimensional (3D) models of a specific genomic regions is to filter columns wi... | Python Code:
from pytadbit import load_chromosome
from pytadbit.parsers.hic_parser import load_hic_data_from_bam
crm = load_chromosome('results/fragment/chr3.tdb')
B, PSC = crm.experiments
B, PSC
Explanation: Experimental data assessment and model parameters optimisation
Data preparation
The first step to generate thre... |
568 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Encoding Categorical Data
Step1: Simple data frame with categorical data
Represent each category as an integer. Trouble is, the meaning of each integer is specific to each feature, so the 1... | Python Code:
import pandas as pd
import numpy as np
Explanation: Encoding Categorical Data
End of explanation
data = pd.DataFrame(data=[[0, 0, 3], [1, 1, 0], [0, 2, 1], [1, 0, 2]], columns=['feature 1', 'feature 2', 'feature 3'])
data
Explanation: Simple data frame with categorical data
Represent each category as an i... |
569 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Finding the Root (Zero) of a Function
Finding the root, or zero, of a function is a very common task in exploratory computing. This Notebook presents the Bisection method and Newton's method... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
Explanation: Finding the Root (Zero) of a Function
Finding the root, or zero, of a function is a very common task in exploratory computing. This Notebook presents the Bisection method and Newton's method for finding the root, or 0, of a ... |
570 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step6: Game Tree Search
We start with defining the abstract class Game, for turn-taking n-player games. We rely on, but do not define yet, the concept of a state of the game; we'll see later... | Python Code:
from collections import namedtuple, Counter, defaultdict
import random
import math
import functools
cache = functools.lru_cache(10**6)
class Game:
A game is similar to a problem, but it has a terminal test instead of
a goal test, and a utility for each terminal state. To create a game,
subcl... |
571 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<h1>Table of Contents<span class="tocSkip"></span></h1>
<div class="toc"><ul class="toc-item"><li><span><a href="#Compare-weighted-and-unweighted-mean-temperature" data-toc-modified-id="Comp... | Python Code:
%matplotlib inline
import cartopy.crs as ccrs
import matplotlib.pyplot as plt
import numpy as np
import xarray as xr
Explanation: <h1>Table of Contents<span class="tocSkip"></span></h1>
<div class="toc"><ul class="toc-item"><li><span><a href="#Compare-weighted-and-unweighted-mean-temperature" data-toc-modi... |
572 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<center>
Shenfun - High-Performance Computing platform for the Spectral Galerkin method
<div><img src="https
Step1: Inside the terminal any Python code can be executed and if something is p... | Python Code:
print('hello world icsca')
Explanation: <center>
Shenfun - High-Performance Computing platform for the Spectral Galerkin method
<div><img src="https://rawcdn.githack.com/spectralDNS/spectralutilities/f3419a3e6c40dad55be5dcca51f6e0e21713dd90/figures/Chebyshev_Polynomials_of_the_First_Kind.svg" width="300"><... |
573 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Data generation
@cesans
Step1: dc.data.get_trajectory can be used to get an optimal trajectory for some initial conditions
Step2: The trajectory can be visualized (xy) with dc.vis.vis_traj... | Python Code:
import matplotlib as plt
%matplotlib inline
import sys
sys.path.append('..')
import numpy as np
import deep_control as dc
Explanation: Data generation
@cesans
End of explanation
conditions = {'x0': 200, 'z0': 1000, 'vx0':-30, 'vz0': 0, 'theta0': 0, 'm0': 10000}
col_names = ['t', 'm', 'x', 'vx', 'z' , 'vz',... |
574 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Insert / read whole numpy arrays
http
Step1: Create a DB/table for storing results
http
Step2: Insert a single row into the results table
Each insert is synchronous
This is safest, but is ... | Python Code:
def adapt_array(arr):
out = io.BytesIO()
np.save(out, arr)
out.seek(0)
return sqlite3.Binary(out.read())
def convert_array(text):
out = io.BytesIO(text)
out.seek(0)
return np.load(out)
# Converts np.array to TEXT when inserting
sqlite3.register_adapter(np.ndarray, adapt_array)
#... |
575 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Eccentricity (Volume Conservation)
Setup
Let's first make sure we have the latest version of PHOEBE 2.1 installed. (You can comment out this line if you don't use pip for your installation o... | Python Code:
!pip install -I "phoebe>=2.1,<2.2"
Explanation: Eccentricity (Volume Conservation)
Setup
Let's first make sure we have the latest version of PHOEBE 2.1 installed. (You can comment out this line if you don't use pip for your installation or don't want to update to the latest release).
End of explanation
%ma... |
576 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<br>
Performing gauss, aperture and modelimg extractions with TDOSE<br>
Step1: Performing default aperture extraction using corresponding setup file.<br>
Hence, tdose will simply drop down ... | Python Code:
print(' - Importing functions')
import glob
import tdose
import tdose_utilities as tu
workingdirectory = '../examples_workingdir'
setupname = 'Rafelski-MXDF_ZAP_COR_V2'
setupdir = workingdirectory+'tdose_setupfiles/'
Explanation: <br>
Performing gauss, aperture and modelimg extractions with ... |
577 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Tutorial 08
Step1: 2. Example Network
In this tutorial, we use the Luxembourg SUMO Traffic (LuST) Scenario as an example use case. This example consists of a well-calibrated model of vehicl... | Python Code:
# the TestEnv environment is used to simply simulate the network
from flow.envs import TestEnv
# the Experiment class is used for running simulations
from flow.core.experiment import Experiment
# the base scenario class
from flow.scenarios import Scenario
# all other imports are standard
from flow.core.par... |
578 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Modified introduction using forex data
This is the trading rule example shown in the introduction but modified to use Interactive Brokers instead of CSV files as data source.
IB requires a... | Python Code:
from sysbrokers.IB.ib_connection import connectionIB
from sysbrokers.IB.ib_Fx_prices_data import ibFxPricesData
from ib_insync import util
util.startLoop() #only required when running inside a notebook
Explanation: Modified introduction using forex data
This is the trading rule example shown in the introdu... |
579 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
${t\bar{t}H\left(b\bar{b}\right)}$ scikit-learn BDT for classification of ${t\bar{t}H}$ and ${t\bar{t}b\bar{b}}$ events
For each signal region, information from the output of the reconstruct... | Python Code:
import datetime
import graphviz
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
plt.rcParams["figure.figsize"] = (17, 10)
import pandas as pd
import seaborn as sns
sns.set(context = "paper", font = "monospace")
import sklearn.datasets
from sklearn.preprocessing import MinMaxScaler
imp... |
580 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Método de la secante
El método de la secante es una extensión del método de Newton-Raphson, la derivada de la función se calcula usando una diferencia finita hacia atrás
\begin{equation}
... | Python Code:
def diferencia_atras(f, x_0, x_1):
pendiente = (f(x_0) - f(x_1))/(x_0 - x_1)
return pendiente
def raiz(f, a, b):
c = b - f(b)/diferencia_atras(f, a, b)
return b, c
Explanation: Método de la secante
El método de la secante es una extensión del método de Newton-Raphson, la derivada de la fun... |
581 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2020 The TensorFlow Authors.
Step1: 양자화 인식 훈련 종합 가이드
<table class="tfo-notebook-buttons" align="left">
<td><a target="_blank" href="https
Step2: 양자화 인식 모델을 정의합니다.
다음과 같은 방법으로 모... | 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... |
582 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Integration Exercise 2
Imports
Step1: Indefinite integrals
Here is a table of definite integrals. Many of these integrals has a number of parameters $a$, $b$, etc.
Find five of these integr... | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
from scipy import integrate
Explanation: Integration Exercise 2
Imports
End of explanation
def integrand(x, a):
return 1.0/(x**2 + a**2)
def integral_approx(a):
# Use the args keyword argument to feed extra ... |
583 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Transforms and Resampling <a href="https
Step1: Creating and Manipulating Transforms
A number of different spatial transforms are available in SimpleITK.
The simplest is the Identity Transf... | Python Code:
import SimpleITK as sitk
import numpy as np
%matplotlib inline
import gui
from matplotlib import pyplot as plt
from ipywidgets import interact, fixed
# Utility method that either downloads data from the Girder repository or
# if already downloaded returns the file name for reading from disk (cached data).
... |
584 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
1. Acquire the Data
"Data is the new oil"
Ways to acquire data (typical data source)
Download from an internal system
Obtained from client, or other 3rd party
Extracted from a web-based API
... | Python Code:
# Load the libraries
import pandas as pd
import numpy as np
# Load the dataset
df = pd.read_csv("data/Weed_Price.csv")
# Shape of the dateset - rows & columns
df.shape
# Check for type of each variable
df.dtypes
# Lets load this again with date as date type
df = pd.read_csv("data/Weed_Price.csv", parse_dat... |
585 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Point Charge Dynamics
Akiva Lipshitz, February 2, 2017
Particles and their dynamics are incredibly fascinating, even wondrous. Give me some particles and some simple equations describ... | Python Code:
import numpy as np
import numpy.ma as ma
from scipy.integrate import odeint
mag = lambda r: np.sqrt(np.sum(np.power(r, 2)))
def g(y, t, q, m, n,d, k):
n: the number of particles
d: the number of dimensions
(for fun's sake I want this
to work for k-dimensional systems)
y: an (... |
586 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Testing the trained weight matrices (not in an ensemble)
Step1: Load the weight matrices from the training
Step2: Visualize the digit from one hot representation through the activity weigh... | Python Code:
import nengo
import numpy as np
import cPickle
import matplotlib.pyplot as plt
from matplotlib import pylab
import matplotlib.animation as animation
Explanation: Testing the trained weight matrices (not in an ensemble)
End of explanation
#Weight matrices generated by the neural network after training
#Maps... |
587 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Archimedes and Pi
by Paulo Marques, 2014/03/09 (Adapted in 2018/10/15 to Python from Julia)
Since high school I've been fascinated with $\pi$ -- this infinite non-repeating irrational transc... | Python Code:
from math import sqrt, pi
def side_next(side):
return sqrt(2. - sqrt(4. - side**2.0))
Explanation: Archimedes and Pi
by Paulo Marques, 2014/03/09 (Adapted in 2018/10/15 to Python from Julia)
Since high school I've been fascinated with $\pi$ -- this infinite non-repeating irrational transcendent number.... |
588 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Learning how to move a human arm
In this tutorial we will show how to train a basic biomechanical model using keras-rl.
Installation
To make it work, follow the instructions in
https
Step1: ... | Python Code:
# Derived from keras-rl
import opensim as osim
import numpy as np
import sys
from keras.models import Sequential, Model
from keras.layers import Dense, Activation, Flatten, Input, concatenate
from keras.optimizers import Adam
import numpy as np
from rl.agents import DDPGAgent
from rl.memory import Sequenti... |
589 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
数据抓取:
使用Python编写网络爬虫
王成军
wangchengjun@nju.edu.cn
计算传播网 http
Step1: 一般的数据抓取,使用urllib2和beautifulsoup配合就可以了。
尤其是对于翻页时url出现规则变化的网页,只需要处理规则化的url就可以了。
以简单的例子是抓取天涯论坛上关于某一个关键词的帖子。
在天涯论坛,关于雾霾的帖子的第一页... | Python Code:
import urllib2
from bs4 import BeautifulSoup
Explanation: 数据抓取:
使用Python编写网络爬虫
王成军
wangchengjun@nju.edu.cn
计算传播网 http://computational-communication.com
需要解决的问题
页面解析
获取Javascript隐藏源数据
自动翻页
自动登录
连接API接口
End of explanation
from IPython.display import display_html, HTML
HTML('<iframe src=http://bbs.tianya.cn/l... |
590 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
The Power of IPython Notebook + Pandas + and Scikit-learn
IPython Notebook, Numpy, Pandas, MongoDB, R — for the better part of a year now, I have been trying out these technologies as part o... | Python Code:
import matplotlib.pyplot as plt
import matplotlib
import pickle
import pandas as pd
import numpy as np
from IPython.display import display
%matplotlib notebook
enron_data = pickle.load(open("./ud120-projects/final_project/final_project_dataset.pkl", "rb"))
print("Number of people: %d"%len(enron_data.keys(... |
591 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
you should use GPU but if it is busy then you always can fall back to your CPU
Step1: Use indexing of tokens from vocabulary-embedding this does not clip the indexes of the words to vocab_s... | Python Code:
import os
# os.environ['THEANO_FLAGS'] = 'device=cpu,floatX=float32'
import keras
keras.__version__
Explanation: you should use GPU but if it is busy then you always can fall back to your CPU
End of explanation
FN0 = 'vocabulary-embedding'
Explanation: Use indexing of tokens from vocabulary-embedding this ... |
592 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<!--BOOK_INFORMATION-->
<a href="https
Step1: Then, loading the dataset is a one-liner
Step2: The structure of the boston object is identical to the iris object. We can get more informatio... | Python Code:
import numpy as np
import cv2
from sklearn import datasets
from sklearn import metrics
from sklearn import model_selection
from sklearn import linear_model
%matplotlib inline
import matplotlib.pyplot as plt
plt.style.use('ggplot')
plt.rcParams.update({'font.size': 16})
Explanation: <!--BOOK_INFORMATION-->
... |
593 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2020 The TensorFlow Authors.
Step1: TensorFlow Addons Losses
Step2: Prepare the Data
Step3: Build the Model
Step4: Train and Evaluate | Python Code:
#@title Licensed under the Apache License, Version 2.0
# 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
# distributed under the... |
594 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Regression Week 1
Step1: Load house sales data
Dataset is from house sales in King County, the region where the city of Seattle, WA is located.
Step2: Split data into training and testing
... | Python Code:
import graphlab
Explanation: Regression Week 1: Simple Linear Regression
In this notebook we will use data on house sales in King County to predict house prices using simple (one input) linear regression. You will:
* Use graphlab SArray and SFrame functions to compute important summary statistics
* Write a... |
595 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Weighted-residual method
Let us consider the equation
$$A u = f\quad \text{in } \Omega$$
For an approximation $u_N$ of $u$, the residual, $R_N$, is defined by
$$R_N \equiv Au_N - f$$
When th... | Python Code:
from __future__ import division, print_function
import numpy as np
from sympy import *
from sympy.plotting import plot3d
from scipy.linalg import eigh
from scipy.special import jn_zeros as Jn_zeros, jn as Jn
import matplotlib.pyplot as plt
init_session()
%matplotlib inline
plt.style.use("seaborn-notebook")... |
596 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Most of the public Colour API is available from the colour namespace.
Step1: For example, computing the CIE 2017 Colour Fidelity Index of a light source can be done as follows
Step2: The c... | Python Code:
import colour
Explanation: Most of the public Colour API is available from the colour namespace.
End of explanation
sd = colour.SDS_ILLUMINANTS.get('FL2')
colour.colour_fidelity_index(sd)
Explanation: For example, computing the CIE 2017 Colour Fidelity Index of a light source can be done as follows:
End of... |
597 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
San Diego Burrito Analytics
Step1: Load data
Step2: Process
Step3: Process Cali burrito data | Python Code:
%config InlineBackend.figure_format = 'retina'
%matplotlib inline
import numpy as np
import scipy as sp
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
sns.set_style("white")
Explanation: San Diego Burrito Analytics: Coordinates
Determine the longitude and latitude for each restau... |
598 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
python 3.0以后, reduce已经不在built-in function里了, 要用它就得from functools import reduce.
reduce函数即为化简,它是这样一个过程:每次迭代,将上一次的迭代结果(第一次时为init的元素,如没有init则为seq的第一个元素)与下一个元素一同执行一个二元的func函数。在reduce函数中,init是可选的... | Python Code:
格式:reduce( func, seq[, init] )
Explanation: python 3.0以后, reduce已经不在built-in function里了, 要用它就得from functools import reduce.
reduce函数即为化简,它是这样一个过程:每次迭代,将上一次的迭代结果(第一次时为init的元素,如没有init则为seq的第一个元素)与下一个元素一同执行一个二元的func函数。在reduce函数中,init是可选的,如果使用,则作为第一次迭代的第一个元素使用。
End of explanation
reduce( func, [1, 2, 3] ) = fu... |
599 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Vertex AI Pipelines
Step1: Install the latest GA version of google-cloud-storage library as well.
Step2: Install the latest GA version of google-cloud-pipeline-components library as well.
... | 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 AI Pipelines: AutoML text classification pipelines using google-cloud-pipeline-com... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.