Unnamed: 0 int64 0 16k | text_prompt stringlengths 110 62.1k | code_prompt stringlengths 37 152k |
|---|---|---|
900 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Forte Tutorial 2.02
Step2: We will start by generating SCF orbitals for methane via psi4 using the forte.util.psi4_scf function
Step3: Next we start forte, setup the MOSpaceInfo object spe... | Python Code:
import psi4
import forte
import forte.utils
Explanation: Forte Tutorial 2.02: Orbital localization
In this tutorial we are going to explore how to localize orbitals and visualize them in Jupyter notebooks using the Python API.
Let's import the psi4 and forte modules, including the forte.utils submodule
End... |
901 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
splot.pysal.lib
Step1: Data Preparation
Let's first have a look at the dataset with pysal.lib.examples.explain
Step2: Load data into a geopandas geodataframe
Step3: This warning tells us ... | Python Code:
from pysal.lib.weights.contiguity import Queen
import pysal.lib
from pysal.lib import examples
import matplotlib.pyplot as plt
import geopandas as gpd
%matplotlib inline
from pysal.viz.splot.pysal.lib import plot_spatial_weights
Explanation: splot.pysal.lib: assessing neighbors & spatial weights
In spatial... |
902 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Plot train and valid set NLL
Step1: Plot ratio of update norms to parameter norms across epochs for different layers | Python Code:
tr = np.array(model.monitor.channels['valid_y_y_1_nll'].time_record) / 3600.
fig = plt.figure(figsize=(12,8))
ax1 = fig.add_subplot(111)
ax1.plot(model.monitor.channels['valid_y_y_1_nll'].val_record)
ax1.plot(model.monitor.channels['train_y_y_1_nll'].val_record)
ax1.set_xlabel('Epochs')
ax1.legend(['Valid'... |
903 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<h1>Building game trees</h1>
<i>Theodore L. Turocy</i><br/>
<i>University of East Anglia</i>
<br/><br/>
<h3>EC'16 Workshop
24 July 2016</h3>
Step1: One can build up extensive games from scr... | Python Code:
import gambit
Explanation: <h1>Building game trees</h1>
<i>Theodore L. Turocy</i><br/>
<i>University of East Anglia</i>
<br/><br/>
<h3>EC'16 Workshop
24 July 2016</h3>
End of explanation
g = gambit.Game.new_tree()
g.title = "A simple poker example"
Explanation: One can build up extensive games from scratch... |
904 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Repeated measures ANOVA on source data with spatio-temporal clustering
This example illustrates how to make use of the clustering functions
for arbitrary, self-defined contrasts beyond stand... | Python Code:
# Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr>
# Eric Larson <larson.eric.d@gmail.com>
# Denis Engemannn <denis.engemann@gmail.com>
#
# License: BSD-3-Clause
import os.path as op
import numpy as np
from numpy.random import randn
import matplotlib.pyplot as plt
import mne
from... |
905 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Интернет, сетевые протоколы, клиент-серверные приложения
Requests for Comment (RFCs) публикуются организацией Internet Engineering Task Force (IETF).
Step1: IP
Internet Assigned Numbers Aut... | Python Code:
import socket
Explanation: Интернет, сетевые протоколы, клиент-серверные приложения
Requests for Comment (RFCs) публикуются организацией Internet Engineering Task Force (IETF).
End of explanation
import socket
hostname = 'httpbin.org'
addr = socket.gethostbyname(hostname)
print(addr)
import socket
hostname... |
906 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Model Category 4
Step1: Module imports
Step2: Overall configuration
These parameters are later used, but shouldn't have to change between different model categories (model 1-5)
Step3: Pre... | Python Code:
# Model category name used throughout the subsequent analysis
model_cat_id = "04"
# Which features from the dataset should be loaded:
# ['all', 'actual', 'entsoe', 'weather_t', 'weather_i', 'holiday', 'weekday', 'hour', 'month']
features = ['actual', 'entsoe', 'calendar']
# LSTM Layer configuration
# =====... |
907 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Create directory if not exists
Step1: Mkdir -p behaviour
Step2: Delete directory
Including subdirectories, if they exist!
foo
└── bar
├── baz
│ └── some-other-file.txt
└── so... | Python Code:
new_directory_path = "/path/to/new/directory"
if not os.path.exists(new_directory_path):
os.mkdir(new_directory_path)
Explanation: Create directory if not exists
End of explanation
new_directory_path = "/path/to/new/directory"
if not os.path.exists(new_directory_path):
os.makedirs(new_directory_pat... |
908 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
A Network Tour of Data Science
Xavier Bresson, Winter 2016/17
Exercise 4 - Code 1
Step1: Question 1a
Step2: Question 1b
Step3: Question 1c
Step4: Question 1d
Step5:... | Python Code:
# Load libraries
# Math
import numpy as np
# Visualization
%matplotlib notebook
import matplotlib.pyplot as plt
plt.rcParams.update({'figure.max_open_warning': 0})
from mpl_toolkits.axes_grid1 import make_axes_locatable
from scipy import ndimage
# Print output of LFR code
import subprocess
# Sparse matri... |
909 | 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', 'mpi-m', 'mpi-esm-1-2-hr', 'toplevel')
Explanation: ES-DOC CMIP6 Model Properties - Toplevel
MIP Era: CMIP6
Institute: MPI-M
Source ID: MPI-ESM-1-2-HR
Sub-Topics: Radiative Forcings.
... |
910 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Understanding Resnet Model Features
We know that the Resnet model works well, but why does it work? How can we have confidence that it is searching out the correct features? A recent paper, ... | Python Code:
import csv
import io
import matplotlib.pyplot as plt
import numpy as np
import os
import pickle
import requests
import tensorflow as tf
from io import BytesIO
from PIL import Image
from subprocess import call
Explanation: Understanding Resnet Model Features
We know that the Resnet model works well, but why... |
911 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Spark SQL Tables via Pyspark
Goals
Step1: Create a SparkSession instance
Step2: Read data from the HELK Elasticsearch via Spark SQL
Step3: Read Sysmon Events
Step4: Register Sysmon SQL t... | Python Code:
from pyspark.sql import SparkSession
Explanation: Spark SQL Tables via Pyspark
Goals:
Practice Spark SQL via PySpark skills
Ensure JupyterLab Server, Spark Cluster & Elasticsearch are communicating
Practice Query execution via Pyspark
Create template for future queries
Import SparkSession Class
End of expl... |
912 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Original basis Q0
Recovered basis Qc (Controlled-bsais)
Effected basis Qeff = Qt.T * Q0
Use effected basis for error sampling
Learn Qt progressively better
When data comes in from the Qeff a... | Python Code:
D = 0.01
N_ERRORS = 1e6
N_TRIALS = 100
N_CYCLES = np.logspace(1, 3, 10).astype(np.int)
RECORDS = []
for trial in tqdm(range(N_TRIALS)):
for n_cycles in N_CYCLES:
n = int(N_ERRORS / n_cycles)
channel = Channel(kx=0.7, ky=0.2, kz=0.1,
Q=np.linalg.qr(np.random.ran... |
913 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
eXtreme Gradient Boosting library (XGBoost)
<center>An unfocused introduction by Ivan Nazarov</center>
Import the main toolkit.
Step1: Now import some ML stuff
Step2: Mind the seed!!
Step3... | Python Code:
import time, os, re, zipfile
import numpy as np, pandas as pd
%matplotlib inline
import matplotlib.pyplot as plt
Explanation: eXtreme Gradient Boosting library (XGBoost)
<center>An unfocused introduction by Ivan Nazarov</center>
Import the main toolkit.
End of explanation
import sklearn as sk, xgboost as x... |
914 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Fine tuning classification example
We will fine-tune an ada classifier to distinguish between the two sports
Step1: ## Data exploration
The newsgroup dataset can be loaded using sklearn. F... | Python Code:
from sklearn.datasets import fetch_20newsgroups
import pandas as pd
import openai
categories = ['rec.sport.baseball', 'rec.sport.hockey']
sports_dataset = fetch_20newsgroups(subset='train', shuffle=True, random_state=42, categories=categories)
Explanation: Fine tuning classification example
We will fine-tu... |
915 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Sveučilište u Zagrebu
Fakultet elektrotehnike i računarstva
Strojno učenje 2018/2019
http
Step1: Zadatci
1. Linearna regresija kao klasifikator
U prvoj laboratorijskoj vježbi koristili sm... | Python Code:
# Učitaj osnovne biblioteke...
import sklearn
import mlutils
import matplotlib.pyplot as plt
%pylab inline
Explanation: Sveučilište u Zagrebu
Fakultet elektrotehnike i računarstva
Strojno učenje 2018/2019
http://www.fer.unizg.hr/predmet/su
Laboratorijska vježba 2: Linearni diskriminativni modeli
Verzija:... |
916 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Linking and brushing with bokeh
Linking and brushing is a powerful method for exploratory data analysis.
One way to create linked plots in the notebook is to use Bokeh.
Step1: We will outpu... | Python Code:
import bokeh
import numpy as np
from astropy.table import Table
sdss = Table.read('data/sdss_galaxies_qsos_50k.fits')
sdss
from bokeh.models import ColumnDataSource
from bokeh.plotting import figure, gridplot, output_notebook, output_file, show
umg = sdss['u'] - sdss['g']
gmr = sdss['g'] - sdss['r']
rmi = ... |
917 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
MNIST from scratch
This notebook walks through an example of training a TensorFlow model to do digit classification using the MNIST data set. MNIST is a labeled set of images of handwritten ... | Python Code:
from __future__ import print_function
from IPython.display import Image
import base64
Image(data=base64.decodestring("iVBORw0KGgoAAAANSUhEUgAAAMYAAABFCAYAAAARv5krAAAYl0lEQVR4Ae3dV4wc1bYG4D3YYJucc8455yCSSIYrBAi4EjriAZHECyAk3rAID1gCIXGRgIvASIQr8UTmgDA5imByPpicTcYGY+yrbx+tOUWpu2e6u7qnZ7qXVFPVVbv2Xutfce+q7hlas... |
918 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Content and Objectives
Confirm theoretical values for variations and combinations
Large number of tuples are sampled and occurrences of according events are being counted
Import
Step1: Par... | Python Code:
# importing
import numpy as np
from scipy import special
import time
Explanation: Content and Objectives
Confirm theoretical values for variations and combinations
Large number of tuples are sampled and occurrences of according events are being counted
Import
End of explanation
# parameters of the combina... |
919 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Fuel
History
Started as a part of Blocks, a framework for building and managing Theano graphs in the context of neural networks.
Became its own project when we realized it was distinct enoug... | Python Code:
import numpy
seed = 1234
rng = numpy.random.RandomState(seed)
features = rng.randint(256, size=(8, 2, 2))
targets = rng.randint(4, size=(8, 1))
Explanation: Fuel
History
Started as a part of Blocks, a framework for building and managing Theano graphs in the context of neural networks.
Became its own projec... |
920 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Programowanie masywnie równoleglych procesorów
Wstęp
Trendy w rozwoju CPU GPU
W XX wieku procesory graficzne służyły do transformacji grafiki, głównie dwuwymiarowej. Potrzeby przemysłu związ... | Python Code:
import numpy as np
import pycuda.driver as cuda
import pycuda.autoinit
from pycuda.compiler import SourceModule
Explanation: Programowanie masywnie równoleglych procesorów
Wstęp
Trendy w rozwoju CPU GPU
W XX wieku procesory graficzne służyły do transformacji grafiki, głównie dwuwymiarowej. Potrzeby przemys... |
921 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
LeNet Lab Solution
Source
Step1: The MNIST data that TensorFlow pre-loads comes as 28x28x1 images.
However, the LeNet architecture only accepts 32x32xC images, where C is the number of colo... | Python Code:
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/", reshape=False)
X_train, y_train = mnist.train.images, mnist.train.labels
X_validation, y_validation = mnist.validation.images, mnist.validation.labels
X_test, y_test = mnist.tes... |
922 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Predicting which passengers survived the sinking of the Titanic
using a random forest this time
Step1: Since Age is missing some data, we'll have to clean it by inserting the median age
Ste... | Python Code:
import csv as csv
import numpy as np
import pandas as pd
# We can use the pandas library in python to read in the csv file.
# This creates a pandas dataframe and assigns it to the titanic variable.
titanic = pd.read_csv("data/train.csv")
# Print the first 5 rows of the dataframe.
print(titanic.head(5))
pri... |
923 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introduction to pandas and sklearn
Recommendation System
We live in a world surrounded by recommendation systems - our shopping habbits, our reading habits, political opinions are heavily in... | Python Code:
!pip install -r requirements.txt
Explanation: Introduction to pandas and sklearn
Recommendation System
We live in a world surrounded by recommendation systems - our shopping habbits, our reading habits, political opinions are heavily influenced by recommendation algorithms. So lets take a closer look at ho... |
924 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
context.trie(data="", format="default", filename="")
Generate a "trie" automaton (a prefix tree) from a finite series, given as a file of (weighted) words.
Arguments
Step1: Weighted words (... | Python Code:
import vcsn
vcsn.B.trie('''foo
bar
baz''')
%%file words
hello
world
hell
word
vcsn.B.trie(filename='words')
Explanation: context.trie(data="", format="default", filename="")
Generate a "trie" automaton (a prefix tree) from a finite series, given as a file of (weighted) words.
Arguments:
- data: a string co... |
925 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Predicting Earnings from Census Data with Random Forests
taken from The Analytics Edge
The Task
The United States government periodically collects demographic information by conducting a cen... | Python Code:
import pandas as pd
import numpy as np
Explanation: Predicting Earnings from Census Data with Random Forests
taken from The Analytics Edge
The Task
The United States government periodically collects demographic information by conducting a census.
In this problem, we are going to use census information abou... |
926 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Quiz - Week 3B
Q1.
Suppose we hash the elements of a set S having 20 members, to a bit array of length 99. The array is initially all-0's, and we set a bit to 1 whenever a member of S hashes... | Python Code:
## Solution 1.
import numpy as np
A = np.array([[0, 0, 1, 0, 0, 1, 0, 0], #A
[0, 0, 0, 0, 1, 0, 0, 1], #B
[1, 0, 0, 1, 0, 1, 0, 0], #C
[0, 0, 1, 0, 1, 0, 1, 0], #D
[0, 1, 0, 1, 0, 0, 0, 1], #E
[1, 0, 1, 0, 0, 0, 1, 0], #F
[... |
927 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Data Exploration
Step1: Data File
Step2: Plotting Functions
Step3: Descriptions of Data
Step4: there are many items that are viewed more than a day before buying
most items are viewed le... | Python Code:
import sys
import os
sys.path.append(os.getcwd()+'/../')
# other
import numpy as np
import glob
import pandas as pd
import ntpath
#keras
from keras.preprocessing import image
# plotting
import seaborn as sns
sns.set_style('white')
import matplotlib.pyplot as plt
%matplotlib inline
# debuggin
from IPython.... |
928 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Full control with the ask-and-tell interface
For day-to-day use, we recommend sampling or optimising via one of the "controller" classes, for example the OptimisationController or the MCMCC... | Python Code:
import pints
import pints.toy as toy
import numpy as np
import matplotlib.pyplot as plt
# Load a forward model
model = toy.LogisticModel()
# Create some toy data
real_parameters = [0.015, 500]
times = np.linspace(0, 1000, 1000)
values = model.simulate(real_parameters, times)
# Add noise
values += np.random... |
929 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a href='http
Step1: The Data
There are some fake data csv files you can read in as dataframes
Step2: Style Sheets
Matplotlib has style sheets you can use to make your plots look a little ... | Python Code:
import numpy as np
import pandas as pd
%matplotlib inline
Explanation: <a href='http://www.pieriandata.com'> <img src='../Pierian_Data_Logo.png' /></a>
Pandas Built-in Data Visualization
In this lecture we will learn about pandas built-in capabilities for data visualization! It's built-off of matplotlib, b... |
930 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Exercise 05
Logistic regression exercise with Titanic data
We'll be working with a dataset from Kaggle's Titanic competition
Step1: Create X and y
Define Pclass and Parch as the features, a... | Python Code:
import pandas as pd
url = 'https://raw.githubusercontent.com/justmarkham/DAT8/master/data/titanic.csv'
titanic = pd.read_csv(url, index_col='PassengerId')
titanic.head()
Explanation: Exercise 05
Logistic regression exercise with Titanic data
We'll be working with a dataset from Kaggle's Titanic competition... |
931 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
At PyCon in Montreal https
Step1: TRMM
A little googling turned up this gem from the NASA's Tropical Rainfall Measuring Mission.
<img src='http
Step2: Landsat data for Bermuda
A major chal... | Python Code:
from IPython import display
# Chris Waigl, Satellite mapping for everyone.
display.YouTubeVideo('MCHpt1FvblI')
Explanation: At PyCon in Montreal https://us.pycon.org/2015/ Chris Waigl gave a talk about satellite mapping and some of the python tools that help with this
Following the talk I decided to take a... |
932 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Backpropagation
Instructions
In this assignment, you will train a neural network to draw a curve.
The curve takes one input variable, the amount travelled along the curve from 0 to 1, and re... | Python Code:
%run "readonly/BackpropModule.ipynb"
# PACKAGE
import numpy as np
import matplotlib.pyplot as plt
# PACKAGE
# First load the worksheet dependencies.
# Here is the activation function and its derivative.
sigma = lambda z : 1 / (1 + np.exp(-z))
d_sigma = lambda z : np.cosh(z/2)**(-2) / 4
# This function init... |
933 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Datasets
機器學習資料集/ 範例一
Step1: (二)資料集介紹
digits = datasets.load_digits() 將一個dict型別資料存入digits,我們可以用下面程式碼來觀察裏面資料
Step2: | 顯示 | 說明 |
| -- | -- |
| ('images', (1797L, 8L, 8L))| 共有 1797 張影像,影像大小為 ... | Python Code:
#這行是在ipython notebook的介面裏專用,如果在其他介面則可以拿掉
%matplotlib inline
from sklearn import datasets
import matplotlib.pyplot as plt
#載入數字資料集
digits = datasets.load_digits()
#畫出第一個圖片
plt.figure(1, figsize=(3, 3))
plt.imshow(digits.images[-1], cmap=plt.cm.gray_r, interpolation='nearest')
plt.show()
Explanation: Dataset... |
934 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
2D PSV wave propagation in a homogenous block-model
The propagation of waves in a general elastic medium can be described by a system of coupled linear partial differential equations. They c... | Python Code:
# load all necessary libraries
import numpy
from matplotlib import pyplot, cm
from mpl_toolkits.mplot3d import Axes3D
from numba import jit
%matplotlib notebook
# spatial discretization
nx = 601
ny = 601
dh = 5.0
x = numpy.linspace(0, dh*(nx-1), nx)
y = numpy.linspace(0, dh*(ny-1), ny)
X, Y = numpy.meshgr... |
935 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<h2> How to read and display Nexrad on AWS using Python </h2>
<h4> Valliappa Lakshmanan, The Climate Corporation, lak@climate.com </h4>
Amazon Web Services is making NEXRAD data <a href="htt... | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy.ma as ma
import numpy as np
import pyart.graph
import tempfile
import pyart.io
import boto
Explanation: <h2> How to read and display Nexrad on AWS using Python </h2>
<h4> Valliappa Lakshmanan, The Climate Corporation, lak@climate.com </h4>
Ama... |
936 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<center>
<a href="http
Step1: Les données peuvent être préalablement téléchargées ou directement lues. Ce sont celles originales du site MNIST DataBase mais préalablement converties au form... | Python Code:
# Graphiques dans la fenêtre
%matplotlib inline
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import time
Explanation: <center>
<a href="http://www.insa-toulouse.fr/" ><img src="http://www.math.univ-toulouse.fr/~besse/Wikistat/Images/logo-insa.jpg" style="float:left; max-width: 120... |
937 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Swiss road accidents 2011 - 2015
Data source
Step1: Importing files on accidents, .csv Files, organised by year
Step2: Importing files on people involved in accidents, .csv Files, organise... | Python Code:
import pandas as pd
import matplotlib.pyplot as plt
plt.style.use("ggplot")
%matplotlib inline
Explanation: Swiss road accidents 2011 - 2015
Data source: Federal Roads Office (FEDRO)
Analysing every road accident in Switzerland from 2011 to 2015 using Pandas.
End of explanation
unfaelle2011 = pd.read_csv("... |
938 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Simulation of 10000 ms of 400 independent descending commands following a gamma distribution with mean of 142 ms and order 10
Step1: The spike times of all descending commands along the 100... | Python Code:
import sys
sys.path.insert(0, '..')
import time
import matplotlib.pyplot as plt
%matplotlib notebook
import numpy as np
import scipy.stats
from Configuration import Configuration
from NeuralTract import NeuralTract
conf = Configuration('confNeuralTractSpikes.rmto')
t = np.arange(0.0, conf.simDuration_ms,... |
939 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a href="https
Step1: Kvswap
<script type="text/javascript">
localStorage.setItem('language', 'language-py')
</script>
<table align="left" style="margin-right
Step2: Examples
In the follow... | 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... |
940 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Repairing artifacts with SSP
This tutorial covers the basics of signal-space projection (SSP) and shows
how SSP can be used for artifact repair; extended examples illustrate use
of SSP for e... | Python Code:
import os
import numpy as np
import matplotlib.pyplot as plt
import mne
from mne.preprocessing import (create_eog_epochs, create_ecg_epochs,
compute_proj_ecg, compute_proj_eog)
Explanation: Repairing artifacts with SSP
This tutorial covers the basics of signal-space projectio... |
941 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
R Programming
<a name="top"></a>
Vahid Mirjalili, Data Scientist
R Data Types
Atomic classes
Object attributes
Create Vectors
Explicit Coercion
Matrices
Lists
Factors
Missing Values
Data Frm... | Python Code:
x <- 0:6
print(x)
print(as.logical(x))
print(as.complex(x))
Explanation: R Programming
<a name="top"></a>
Vahid Mirjalili, Data Scientist
R Data Types
Atomic classes
Object attributes
Create Vectors
Explicit Coercion
Matrices
Lists
Factors
Missing Values
Data Frmaes
Names
Subsetting R objects
Subsetting li... |
942 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
The previous Notebook in this series used multi-group mode to perform a calculation with previously defined cross sections. However, in many circumstances the multi-group data is not given ... | Python Code:
import matplotlib.pyplot as plt
import numpy as np
import os
import openmc
%matplotlib inline
Explanation: The previous Notebook in this series used multi-group mode to perform a calculation with previously defined cross sections. However, in many circumstances the multi-group data is not given and one mu... |
943 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
$$A(t,T) = \Sigma_i A_i P(dI/dt (t)\otimes e^{-t/\tau_i})$$
Step1: Simple exponential basis
$$ \mathbf{A}\mathbf{\alpha} = \mathbf{d}$$ | Python Code:
def AofT(time,T, ai, taui):
return ai*np.exp(-time/taui)/(1.+np.exp(-T/(2*taui)))
from SimPEG import *
import sys
sys.path.append("./DoubleLog/")
from plotting import mapDat
class LinearSurvey(Survey.BaseSurvey):
nD = None
def __init__(self, time, **kwargs):
self.time = time
se... |
944 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Calculation of the divergence of the advection of the perpendicular gradient of the potential times density using Clebsch coordinates
We would here like to calculate
$$
\nabla\cdot\left(\mat... | Python Code:
from IPython.display import display
from sympy import symbols, simplify, sympify, expand
from sympy import init_printing
from sympy import Eq, Function
from clebschVector import ClebschVec
from clebschVector import div, grad, gradPerp, advVec
from common import rho, theta, poisson
from common import displa... |
945 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Molonglo coordinate transforms
Useful coordinate transforms for the molonglo radio telescope
Step1: Below we define the rotation and reflection matrices
Step2: Define a position vectors
St... | Python Code:
import numpy as np
import ephem as e
from scipy.optimize import minimize
import matplotlib.pyplot as plt
np.set_printoptions(precision=5,suppress =True)
Explanation: Molonglo coordinate transforms
Useful coordinate transforms for the molonglo radio telescope
End of explanation
def rotation_matrix(angle, d)... |
946 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Intro to Bookworm
Motivation
Infinite Jest is a very long and complicated novel. There are a lot of brilliant resources connected to the book, which aim to help the reader stay afloat amongs... | Python Code:
from bookworm import *
Explanation: Intro to Bookworm
Motivation
Infinite Jest is a very long and complicated novel. There are a lot of brilliant resources connected to the book, which aim to help the reader stay afloat amongst the chaos of David Foster Wallace's obscure language, interwoven timelines and ... |
947 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Practical Optimisations for Pandas 🐼
Eyal Trabelsi
About Me 🙈
Software Engineer at Salesforce 👷
Big passion for python, data and performance optimisations 🐍🤖
Online at medium | twitter ... | Python Code:
! pip install numba numexpr
import math
import time
import warnings
from dateutil.parser import parse
import janitor
import numpy as np
import pandas as pd
from numba import jit
from sklearn import datasets
from pandas.api.types import is_datetime64_any_dtype as is_datetime
warnings.filterwarnings("ignore"... |
948 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Analyzing unstructured text in product review data
It's common for companies to have useful data hidden in large volumes of text
Step1: Focus on chosen aspects about baby monitors
Step2: P... | Python Code:
import graphlab as gl
from graphlab.toolkits.text_analytics import trim_rare_words, split_by_sentence, extract_part_of_speech, stopwords, PartOfSpeech
def nlp_pipeline(reviews, title, aspects):
print(title)
print('1. Get reviews for this product')
reviews = reviews.filter_by(title, 'name')... |
949 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Basic Types in Core-Python
Python has all types that you already know from other programming languages.
Notes
Step1: The last example shows that Python provides aribtrary precise integer ar... | Python Code:
a = 5 # assigninig the integer value 5 to variable 'a'
b = 2
print(a + b, a - b) # Integer addition and subtraction
print(a * b) # Integer multiplication
print(a**b) # 5 to the power of 2
print(a // b) # Integer division!
print(a % b) # modulo function
print(a / b) # div... |
950 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Semi-supervised Learning
author
Step1: Let's first generate some data in the form of blobs that are close together. Generally one tends to have far more unlabeled data than labeled data, so... | Python Code:
%matplotlib inline
import time
import pandas
import random
import numpy
import matplotlib.pyplot as plt
import seaborn; seaborn.set_style('whitegrid')
import itertools
from pomegranate import *
random.seed(0)
numpy.random.seed(0)
numpy.set_printoptions(suppress=True)
%load_ext watermark
%watermark -m -n -p... |
951 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Media
Introduction
skrf supports some basic circuit simulation based on transmission line models. Network creation is accomplished through methods of the Media class, which represents a tran... | Python Code:
%matplotlib inline
import skrf as rf
rf.stylely()
from skrf import Frequency
from skrf.media import CPW
freq = Frequency(75,110,101,'ghz')
cpw = CPW(freq, w=10e-6, s=5e-6, ep_r=10.6)
cpw
Explanation: Media
Introduction
skrf supports some basic circuit simulation based on transmission line models. Network ... |
952 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
RESIT
Import and settings
In this example, we need to import numpy, pandas, and graphviz in addition to lingam.
Step1: Test data
First, we generate a causal structure with 7 variables. Then... | Python Code:
import numpy as np
import pandas as pd
import graphviz
import lingam
from lingam.utils import print_causal_directions, print_dagc, make_dot
import warnings
warnings.filterwarnings('ignore')
print([np.__version__, pd.__version__, graphviz.__version__, lingam.__version__])
np.set_printoptions(precision=3, su... |
953 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Interpolate Isochrones for Praesepe
Instead of interpolating boundary condition tables and computing a new set of models, we can interpolate between two metallicities to calculate new isochr... | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
Explanation: Interpolate Isochrones for Praesepe
Instead of interpolating boundary condition tables and computing a new set of models, we can interpolate between two metallicities to calculate new isochrones for Praesepe at metallicities... |
954 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
训练
我们对训练集采用随机森林模型,并评估模型效果
Step1: 我们对验证集和测试集使用predict()方法,并得到相应的误差。
Step2: 输出误差 | Python Code:
%pylab inline
# 导入训练集、验证集和测试集
import pandas as pd
samtrain = pd.read_csv('samtrain.csv')
samval = pd.read_csv('samval.csv')
samtest = pd.read_csv('samtest.csv')
# 使用 sklearn的随机森林模型,其模块叫做 sklearn.ensemble.RandomForestClassifier
# 在这里我们需要将标签列 ('activity') 转换为整数表示,
# 因为Python的RandomForest package需要这样的格式。
# ... |
955 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a href='http
Step1: Visualizing eclipse data
Let us find some interesting data to generate elements from, before we consider how to customize them. Here is a dataset containing information... | Python Code:
import pandas as pd
import holoviews as hv
hv.extension('bokeh', 'matplotlib')
Explanation: <a href='http://www.holoviews.org'><img src="assets/hv+bk.png" alt="HV+BK logos" width="40%;" align="left"/></a>
<div style="float:right;"><h2>02. Customizing Visual Appearance</h2></div>
Section 01 focused on speci... |
956 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Eigenvalues and eigenvectors of stiffness matrices
Step1: Predefinition
The constitutive model tensor in Voigt notation (plane stress) is
$$C = \frac{E}{(1 - \nu^2)}
\begin{pmatrix}
1 & \nu... | Python Code:
from sympy.utilities.codegen import codegen
from sympy import *
from sympy import init_printing
init_printing()
r, s, t, x, y, z = symbols('r s t x y z')
k, m, n = symbols('k m n', integer=True)
rho, nu, E = symbols('rho, nu, E')
Explanation: Eigenvalues and eigenvectors of stiffness matrices
End of expla... |
957 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Test Script
Used by tests.
License
Copyright 2020 Google LLC,
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.... | Python Code:
!pip install git+https://github.com/google/starthinker
Explanation: Test Script
Used by tests.
License
Copyright 2020 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 License at
https://... |
958 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introduction to Python
Python <https
Step1: Second, if you have a MATLAB background remember that indexing in Python
starts from zero (and is done with square brackets) | Python Code:
a = 3
print(type(a))
b = [1, 2.5, 'This is a string']
print(type(b))
c = 'Hello world!'
print(type(c))
Explanation: Introduction to Python
Python <https://www.python.org/>_ is a modern general-purpose object-oriented
high-level programming language. First make sure you have a working Python
environme... |
959 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Intensity Weighting
Setup
Let's first make sure we have the latest version of PHOEBE 2.4 installed (uncomment this line if running in an online notebook session such as colab).
Step1: As al... | Python Code:
#!pip install -I "phoebe>=2.4,<2.5"
Explanation: Intensity Weighting
Setup
Let's first make sure we have the latest version of PHOEBE 2.4 installed (uncomment this line if running in an online notebook session such as colab).
End of explanation
import phoebe
from phoebe import u # units
import numpy as np
... |
960 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
SEG Machine Learning (Well Log Facies Prediction) Contest
Entry by Justin Gosses of team Pet_Stromatolite
This is an "open science" contest designed to introduce people to machine learning w... | Python Code:
### loading
%matplotlib inline
import pandas as pd
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.colors as colors
from mpl_toolkits.axes_grid1 import make_axes_locatable
### setting up options in pandas
from pandas import set_option
set_option("display.max_r... |
961 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<center> Interactive generation of Bézier and B-spline curves.<br> Python functional programming implementation of the <br> de Casteljau and Cox-de Boor algorithms </cente... | Python Code:
from IPython.display import Image
Image(filename='Imag/Decast4p.png')
Explanation: <center> Interactive generation of Bézier and B-spline curves.<br> Python functional programming implementation of the <br> de Casteljau and Cox-de Boor algorithms </center>
The aim of this IPython noteboo... |
962 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Gaussian Processes
(c) 2016 by Chris Fonnesbeck
Example of simple GP fit, adapted from Stan's example-models repository.
Step1: This is what our initial covariance matrix looks like. Intuit... | Python Code:
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
sns.set()
import pymc3 as pm
from pymc3 import Model, MvNormal, HalfCauchy, sample, traceplot, summary, find_MAP, NUTS, Deterministic
import theano.tensor as T
from theano import shared
from theano.tensor.nlinalg im... |
963 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
The simplest native coroutine demo
(that I could imagine)
Step1: The driving code starts here
Step2: A slightly more interesting demo
Now the generator-coroutine yields 3 times.
Step3: Dr... | Python Code:
import types
@types.coroutine
def gen():
yield 42
async def delegating():
await gen()
Explanation: The simplest native coroutine demo
(that I could imagine)
End of explanation
coro = delegating()
coro
coro.send(None)
# coro.send(None) # --> StopIteration
Explanation: The driving code starts here:
... |
964 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Ocnbgchem
MIP Era
Step1: Document Authors
Set document authors
Step2: Document Contributors
Specify document contributors
Step3: Document Publication
Speci... | Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'niwa', 'sandbox-3', 'ocnbgchem')
Explanation: ES-DOC CMIP6 Model Properties - Ocnbgchem
MIP Era: CMIP6
Institute: NIWA
Source ID: SANDBOX-3
Topic: Ocnbgchem
Sub-Topics: Tracers.
Prop... |
965 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<center> Doing Math with Python </center>
<center>
<p> <b>Amit Saha</b>
<p>May 29, PyCon US 2016 Education Summit
<p>Portland, Oregon
</center>
## About me
- Software Engineer at [Freelancer... | Python Code:
As I will attempt to describe in the next slides, Python is an amazing way to lead to a more fun learning and teaching
experience.
It can be a basic calculator, a fancy calculator and
Math, Science, Geography..
Tools that will help us in that quest are:
Explanation: <center> Doing Math with Python </cente... |
966 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Brainstorm CTF phantom dataset tutorial
Here we compute the evoked from raw for the Brainstorm CTF phantom
tutorial dataset. For comparison, see [1]_ and
Step1: The data were collected with... | Python Code:
# Authors: Eric Larson <larson.eric.d@gmail.com>
#
# License: BSD (3-clause)
import os.path as op
import numpy as np
import matplotlib.pyplot as plt
import mne
from mne import fit_dipole
from mne.datasets.brainstorm import bst_phantom_ctf
from mne.io import read_raw_ctf
print(__doc__)
Explanation: Brainsto... |
967 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Steepest Gradient Descent Visualization
This code is provided as supplementary material of the lecture Machine Learning and Optimization in Communications (MLOC).<br>
This code illustrates
S... | Python Code:
import importlib
autograd_available = True
# if automatic differentiation is available, use it
try:
import autograd
except ImportError:
autograd_available = False
pass
if autograd_available:
import autograd.numpy as np
from autograd import grad
else:
import numpy as np
import ma... |
968 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
scona
scona is a tool to perform network analysis over correlation networks of brain regions.
This tutorial will go through the basic functionality of scona, taking us from our inputs (a ma... | Python Code:
import numpy as np
import networkx as nx
import scona as scn
import scona.datasets as datasets
Explanation: scona
scona is a tool to perform network analysis over correlation networks of brain regions.
This tutorial will go through the basic functionality of scona, taking us from our inputs (a matrix of s... |
969 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Quartet d'Anscombe
Page wikipedia
Construits en 1973 par le statisticien Francis Anscombe dans le but de démontrer l'importance de tracer des graphiques avant d'analyser un ensemble de donné... | Python Code:
%pylab --no-import-all inline
from scipy.stats import linregress, pearsonr
Explanation: Quartet d'Anscombe
Page wikipedia
Construits en 1973 par le statisticien Francis Anscombe dans le but de démontrer l'importance de tracer des graphiques avant d'analyser un ensemble de données.
End of explanation
all_se... |
970 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Title
Step1: Create a dataframe
Step2: Create a second dataframe
Step3: Create a third dataframe
Step4: Join the two dataframes along rows
Step5: Join the two dataframes along columns
S... | Python Code:
import pandas as pd
from IPython.display import display
from IPython.display import Image
Explanation: Title: Join And Merge Pandas Dataframe
Slug: pandas_join_merge_dataframe
Summary: Join And Merge Pandas Dataframe
Date: 2016-05-01 12:00
Category: Python
Tags: Data Wrangling
Authors: Chris Albon
import... |
971 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: TV Script Generation
In this project, you'll generate your own Simpsons TV scripts using RNNs. You'll be using part of the Simpsons dataset of scripts from 27 seasons. The Neural Ne... | Python Code:
DON'T MODIFY ANYTHING IN THIS CELL
import helper
data_dir = './data/simpsons/moes_tavern_lines.txt'
text = helper.load_data(data_dir)
# Ignore notice, since we don't use it for analysing the data
text = text[81:]
Explanation: TV Script Generation
In this project, you'll generate your own Simpsons TV script... |
972 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Computer Hardware Dataset Analysis - UCI
This is a regression analysis of the <a href="https
Step1: Attribute Information
Attribute Information
Step2: Univariate Analysis
Step3: Bivariate... | Python Code:
import numpy as np
import pandas as pd
%pylab inline
pylab.style.use('ggplot')
import seaborn as sns
url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/cpu-performance/machine.data'
data = pd.read_csv(url, header=None)
data.head()
Explanation: Computer Hardware Dataset Analysis - UCI
This is ... |
973 | 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... |
974 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Ex 1-1 by Keras in Tensflow 2.0
Keras가 이제 텐서플로의 기본 상위 인터페이스가 되었다. 다시 말해 텐서플로에서 인공지능 코드 작성시 케라스를 기본적으로 사용할 수 있게 되었다는 말이다.
Keras를 텐서플로에서 사용하는 방법은 크게 두가지가 있다. 첫 번째는 오리지널 케라스 방식처럼 케라스를 주 인터페이스로... | Python Code:
from tensorflow import keras
import numpy
x = numpy.array([0, 1, 2, 3, 4])
y = x * 2 + 1
model = keras.models.Sequential()
model.add(keras.layers.Dense(1,input_shape=(1,)))
model.compile('SGD', 'mse')
model.fit(x[:2], y[:2], epochs=1000, verbose=0)
print(model.predict(x))
Explanation: Ex 1-1 by Keras in T... |
975 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<small><i>This notebook was prepared by Thunder Shiviah. Source and license info is on GitHub.</i></small>
Challenge Notebook
Problem
Step1: Unit Test
The following unit test is expected to... | Python Code:
def list_primes(n):
primes = []
for i in range(0, n + 1):
for j in range(0, i):
if i % j == 0:
break
else:
primes.append(i)
return primes
Explanation: <small><i>This notebook was prepared by Thunder Shiviah. Source and license info is on ... |
976 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
.загружаем файлы .json
Step1: Смотрим, где именно в файле интересующие нас данные
Step2: Считываем нужные нам данные как датафреймы
Step3: Создаем в датафреймах отдельные столбцы с данным... | Python Code:
path = 'Sessions_Page.json'
path2 = 'Goal1CompletionLocation_Goal1Completions.json'
with open(path, 'r') as f:
sessions_page = json.loads(f.read())
with open(path2, 'r') as f:
goals_page = json.loads(f.read())
Explanation: .загружаем файлы .json
End of explanation
type (sessions_page)
sessions_page... |
977 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Analysis of key agreement data
Step1: Settings
Enter your input below.
Step2: Data processing
Step3: Analysis
Summary
Step4: Selected quantiles
Step5: Info
Step6: Plots
Private key MSB... | Python Code:
%matplotlib notebook
import numpy as np
from scipy.stats import describe
from scipy.stats import norm as norm_dist
from scipy.stats.mstats import mquantiles
from math import log, sqrt
import matplotlib.pyplot as plt
from matplotlib import ticker, colors, gridspec
from copy import deepcopy
from utils import... |
978 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Ordinary Percolation
OpenPNM contains several percolation algorithms which are central to the multiphase models employed by pore networks. The essential idea is to identify pathways for flui... | Python Code:
import openpnm as op
%config InlineBackend.figure_formats = ['svg']
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
np.random.seed(10)
from ipywidgets import interact, IntSlider
%matplotlib inline
mpl.rcParams["image.interpolation"] = "None"
ws = op.Workspace()
ws.settings["logl... |
979 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Load the twobody data
Step1: The Pair Correlation Function (or Radial Distribution Function)
Nice picture/description here
Basically we want to compute the following for a given pair of ato... | Python Code:
xyz = pd.read_hdf('xyz.hdf5', 'xyz')
twobody = pd.read_hdf('twobody.hdf5', 'twobody')
Explanation: Load the twobody data
End of explanation
from scipy.integrate import cumtrapz
def pcf(A, B, a, twobody, dr=0.05, start=0.5, end=7.5):
'''
Pair correlation function between two atom types.
'''
... |
980 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Styling
This document is written as a Jupyter Notebook, and can be viewed or downloaded here.
You can apply conditional formatting, the visual styling of a DataFrame
depending on the data wi... | Python Code:
import matplotlib.pyplot
# We have this here to trigger matplotlib's font cache stuff.
# This cell is hidden from the output
import pandas as pd
import numpy as np
np.random.seed(24)
df = pd.DataFrame({'A': np.linspace(1, 10, 10)})
df = pd.concat([df, pd.DataFrame(np.random.randn(10, 4), columns=list('BCDE... |
981 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
THIS NOTEBOOK HAS BEEN MOVED
See https
Step2: Acquisition failure rate and multiple stars flag rate
Here we examine available statistics on the mean rate of the MS flag being set during gui... | Python Code:
from __future__ import division
import os
import matplotlib.pyplot as plt
from astropy.table import Table
import numpy as np
from Ska.DBI import DBI
%matplotlib inline
# Use development version of chandra_aca which has the new acq stats fit parameters
import sys
import os
sys.path.insert(0, os.path.join(os... |
982 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Resignation prediction using machine learning algorithms
by A. Zayer
1. Introduction
Employees retention, especially in large companies, is and still will be a hot topic. Considerable amount... | Python Code:
%matplotlib inline
import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_sel... |
983 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Strings
Sequenzen von Zeichen
Strings sind Zeichenketten, also Sequenzen von Zeichen.
Die Länge der Sequenz ermitteln
Die Zahl der Element in der Sequenz (also die Zahl der Zeichen) kann mit... | Python Code:
satz = 'Ein String ist eine Zeichenkette.'
len(satz)
Explanation: Strings
Sequenzen von Zeichen
Strings sind Zeichenketten, also Sequenzen von Zeichen.
Die Länge der Sequenz ermitteln
Die Zahl der Element in der Sequenz (also die Zahl der Zeichen) kann mit der Funktion len() ermittelt werden:
End of explan... |
984 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
2/ Exercise solutions
Step1: Definitions
E2.1
E2.2
Given the matrices $A=\begin{pmatrix}1 & 3 \ 4 & 5\end{pmatrix}$ and $B=\begin{pmatrix} -1 & 0 \ 3 & 3 \end{pmatrix}$,
and the vectors $\... | Python Code:
# setup SymPy
from sympy import *
x, y, z, t = symbols('x y z t')
init_printing()
Explanation: 2/ Exercise solutions
End of explanation
# define the matrices A and B, and the vecs v and w
A = Matrix([[1,3],
[4,5]])
B = Matrix([[-1,0],
[ 3,3]])
v = Matrix([[1,2]]).T # the .T make... |
985 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Using custom fonts
Relevant fontName.ttf font need to be downloaded
Step1: Controlling font properties
Pylab examples
pie autopct
Plot labels inside by controlling the radial distance labe... | Python Code:
# help(font_manager)
path = '../fonts/segoeuib.ttf'
prop = font_manager.FontProperties(fname=path)
print prop.get_name()
print prop.get_family()
font0 = FontProperties()
font1 = font0.copy()
font1.set_family(prop.get_name())
Explanation: Using custom fonts
Relevant fontName.ttf font need to be downloaded
E... |
986 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Multi-layer Perceptron (normal neural network) on the Reuters newswire classification
The original script that this notebook is based on is here
Step1: Neural Network Settings
max_words
Ste... | Python Code:
# Imports
from __future__ import print_function
import numpy as np
np.random.seed(1337) # for reproducibility
from keras.datasets import reuters
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation
from keras.utils import np_utils
from keras.preprocessing.text import Tok... |
987 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Line Follower - CompRobo17
This notebook will show the general procedure to use our project data directories and how to do a regression task using convnets
Imports and Directories
Step1: Cr... | Python Code:
#Create references to important directories we will use over and over
import os, sys
#import modules
import numpy as np
from glob import glob
from PIL import Image
from tqdm import tqdm
from scipy.ndimage import zoom
from keras.models import Sequential
from keras.metrics import categorical_crossentropy, ca... |
988 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
This notebook will go through how we match up students to real scientists based on their science interests. This code is heavily based on collaboratr, a project developed at Astro Hack Week.... | Python Code:
!pip install nxpd
%matplotlib inline
import matplotlib.pyplot as plt
import networkx as nx
import pandas as pd
import numpy as np
from operator import truediv
from collections import Counter
import itertools
import random
import collaboratr
#from nxpd import draw
#import nxpd
#reload(collaboratr)
Explanati... |
989 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
================================================================
Compute sparse inverse solution with mixed norm
Step1: Run solver
Step2: View in 2D and 3D ("glass" brain like 3D plot) | Python Code:
# Author: Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr>
#
# License: BSD (3-clause)
import mne
from mne.datasets import sample
from mne.inverse_sparse import mixed_norm
from mne.minimum_norm import make_inverse_operator, apply_inverse
from mne.viz import plot_sparse_source_estimates
print(__... |
990 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Interpolation Exercise 2
Step1: Sparse 2d interpolation
In this example the values of a scalar field $f(x,y)$ are known at a very limited set of points in a square domain
Step2: The follow... | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
sns.set_style('white')
from scipy.interpolate import griddata
Explanation: Interpolation Exercise 2
End of explanation
# left, top, right, bottom
x = np.hstack((np.array([-5]*10), np.linspace(-5, 5, 10), np.array([5... |
991 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Tutorial for the structural-color python package
Copyright 2016, Vinothan N. Manoharan, Victoria Hwang.
This file is part of the structural-color python package.
This package is free softwa... | Python Code:
import structcol
# or
import structcol as sc
Explanation: Tutorial for the structural-color python package
Copyright 2016, Vinothan N. Manoharan, Victoria Hwang.
This file is part of the structural-color python package.
This package is free software: you can redistribute it and/or modify it under
the ter... |
992 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Excercises Electric Machinery Fundamentals
Chapter 6
Problem 6-3
Step1: Description
A three-phase 60-Hz induction motor runs at 715 r/min at no-load and at 670 r/min at full load.
Note
Step... | Python Code:
%pylab notebook
%precision 4
Explanation: Excercises Electric Machinery Fundamentals
Chapter 6
Problem 6-3
End of explanation
fe = 60.0 # [Hz]
n_noload = 715.0 # [r/min]
n_m = 670.0 # [r/min]
Explanation: Description
A three-phase 60-Hz induction motor runs at 715 r/min at no-load and at 670 r/... |
993 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
실제함수 input
Step1: bug fix1
rawArrayDatas -> rawArrayDatas[0]
rawArrayDatas이 이차원 배열이어서 len(rawArrayDatas)=2가 되고,
len(rawArrayDatas[0])가 5가 된다.
Step2: bug fix1
rawArrayDatas -> rawArrayData... | Python Code:
rawArrayDatas=[["2017-08-11", "2017-08-12", "2017-08-13", "2017-08-14", "2017-08-15","2017-08-16"],
[20.0, 30.0, 40.0, 50.0, 60.0,20.0]]
processId=12
forecastDay=4
Explanation: 실제함수 input
End of explanation
mockForecast={}
rmse={}
forecast=[]
realForecast={}
trainSize=int(len(rawArrayDatas[0... |
994 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2018 The TensorFlow Authors.
Step1: Automatic differentiation and gradient tape
<table class="tfo-notebook-buttons" align="left"><td>
<a target="_blank" href="https
Step2: Deriv... | 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... |
995 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Intro. to Snorkel
Step1: We repeat our definition of the Spouse Candidate subclass
Step2: We reload the probabilistic training labels
Step3: We also reload the candidates
Step4: Finally,... | Python Code:
%load_ext autoreload
%autoreload 2
%matplotlib inline
import os
# TO USE A DATABASE OTHER THAN SQLITE, USE THIS LINE
# Note that this is necessary for parallel execution amongst other things...
# os.environ['SNORKELDB'] = 'postgres:///snorkel-intro'
from snorkel import SnorkelSession
session = SnorkelSessi... |
996 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Half Power Estimation of $\zeta$
Step1: We simulate a dynamic testing, using a low sampled, random error affected sequence of frequencies to compute a random error affected sequence of dyna... | Python Code:
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(1969)
Explanation: Half Power Estimation of $\zeta$
End of explanation
b = np.linspace(0.5, 1.5, 51) + (np.random.random(51)-0.5)/100
z = 0.035
D = 1/np.sqrt((1-b*b)**2+(2*z*b)**2) * (1 + (np.random.random(51)-0.5)/100)
pl... |
997 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Atlanta Police Department
The Atlanta Police Department provides Part 1 crime data at http
Step1: Load data (don't change this if you're running the notebook on the cluster)
We have two fi... | Python Code:
### Load libraries
%matplotlib inline
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
help(plt.legend)
Explanation: Atlanta Police Department
The Atlanta Police Department provides Part 1 crime data at http://www.atlantapd.org/crimedatadownloads.aspx
A recent copy of the data file i... |
998 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
The
Step1:
Step2: Now, we can create an
Step3: Epochs behave similarly to
Step4: You can select subsets of epochs by indexing the
Step5: Note the '/'s in the event code labels. The... | Python Code:
import mne
import os.path as op
import numpy as np
from matplotlib import pyplot as plt
Explanation: The :class:Epochs <mne.Epochs> data structure: epoched data
:class:Epochs <mne.Epochs> objects are a way of representing continuous
data as a collection of time-locked trials, stored in an array... |
999 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<table align="left">
<td>
<a href="https
Step1: Set up your GCP project
The following steps are required, regardless of your notebook environment.
Select or create a GCP project. When... | Python Code:
!pip install google-cloud-bigquery
# Automatically restart kernel after installs
import IPython
app = IPython.Application.instance()
app.kernel.do_shutdown(True)
Explanation: <table align="left">
<td>
<a href="https://console.cloud.google.com/ai-platform/notebooks/deploy-notebook?name=Churn%20predi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.