Unnamed: 0
int64
0
16k
text_prompt
stringlengths
110
62.1k
code_prompt
stringlengths
37
152k
11,500
Given the following text description, write Python code to implement the functionality described below step by step Description: Predicting sentiment from product reviews Fire up GraphLab Create Step1: Read some product review data Loading reviews for a set of baby products. Step2: Let's explore this data together D...
Python Code: import graphlab Explanation: Predicting sentiment from product reviews Fire up GraphLab Create End of explanation products = graphlab.SFrame('amazon_baby.gl/') Explanation: Read some product review data Loading reviews for a set of baby products. End of explanation products.head() Explanation: Let's explor...
11,501
Given the following text description, write Python code to implement the functionality described below step by step Description: Averaging detector data with Dask We often want to average large detector data across trains, keeping the pulses within each train separate, so we have an average image for pulse 0, another ...
Python Code: from karabo_data import open_run import dask.array as da from dask.distributed import Client, progress from dask_jobqueue import SLURMCluster import numpy as np Explanation: Averaging detector data with Dask We often want to average large detector data across trains, keeping the pulses within each train se...
11,502
Given the following text description, write Python code to implement the functionality described below step by step Description: Blind Source Separation with the Shogun Machine Learning Toolbox By Kevin Hughes This notebook illustrates <a href="http Step1: Next we're going to need a way to play the audio files we're ...
Python Code: import numpy as np import os SHOGUN_DATA_DIR=os.getenv('SHOGUN_DATA_DIR', '../../../data') from scipy.io import wavfile from scipy.signal import resample import shogun as sg def load_wav(filename,samplerate=44100): # load file rate, data = wavfile.read(filename) # convert stereo to mono ...
11,503
Given the following text description, write Python code to implement the functionality described below step by step Description: Step2: Reframing Design Pattern The Reframing design pattern refers to changing the representation of the output of a machine learning problem. For example, we could take something that is i...
Python Code: import numpy as np import seaborn as sns from google.cloud import bigquery import matplotlib as plt %matplotlib inline bq = bigquery.Client() query = SELECT weight_pounds, is_male, gestation_weeks, mother_age, plurality, mother_race FROM `bigquery-public-data.samples.natality` WHERE weight...
11,504
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction to TensorFlow, now leveraging tensors! In this notebook, we modify our intro to TensorFlow notebook to use tensors in place of our for loop. This is a derivation of Jared Ostmey...
Python Code: import numpy as np np.random.seed(42) import pandas as pd import matplotlib.pyplot as plt %matplotlib inline import tensorflow as tf tf.set_random_seed(42) xs = [0., 1., 2., 3., 4., 5., 6., 7.] ys = [-.82, -.94, -.12, .26, .39, .64, 1.02, 1.] fig, ax = plt.subplots() _ = ax.scatter(xs, ys) m = tf.Variabl...
11,505
Given the following text description, write Python code to implement the functionality described below step by step Description: <a href="https Step1: Question 3 Display first 5 rows of the loaded data Step2: ...and do a short summary about the data; The resultant table comes from the CSV served by the URI. The data...
Python Code: import pandas as pd deaths_df = pd.read_csv('https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_deaths_global.csv') Explanation: <a href="https://colab.research.google.com/github/timomwa/50ForReel/blob/master/ITEC610_Python_Code...
11,506
Given the following text description, write Python code to implement the functionality described below step by step Description: Computer programs A program is a sequence of instructions that specifies how to perform a computation. The computation might be something mathematical, such as solving a system of equations ...
Python Code: # example of a syntax error Computer: please write my thesis. # example of an error in structure 'a' + 1 Explanation: Computer programs A program is a sequence of instructions that specifies how to perform a computation. The computation might be something mathematical, such as solving a system of equations...
11,507
Given the following text description, write Python code to implement the functionality described below step by step Description: Fit the poly-spline-tccd acquisition probability model in 2018-04 Fit values here were computed 2018-Apr-03. This is a candidate for the FLIGHT model. This notebook fits the flight acquisit...
Python Code: from __future__ import division import numpy as np import matplotlib.pyplot as plt from astropy.table import Table from astropy.time import Time import tables from scipy import stats import tables3_api from scipy.interpolate import CubicSpline from Chandra.Time import DateTime %matplotlib inline Explanatio...
11,508
Given the following text description, write Python code to implement the functionality described below step by step Description: Align paralogous contigs to reference If you applied the --keep-paralogs flag in the SECAPR find_target_contigs function, the function will print a text file with paralogous information into...
Python Code: %%bash head -n 10 ../../data/processed/target_contigs_paralogs/1061/info_paralogous_loci.txt Explanation: Align paralogous contigs to reference If you applied the --keep-paralogs flag in the SECAPR find_target_contigs function, the function will print a text file with paralogous information into the subfol...
11,509
Given the following text description, write Python code to implement the functionality described below step by step Description: U.S. Business Cycle Data This notebook downloads, manages, and exports several data series for studying business cycles in the US. Four files are created in the csv directory Step1: Downloa...
Python Code: import pandas as pd import numpy as np import fredpy as fp import matplotlib.pyplot as plt plt.style.use('classic') %matplotlib inline # Export path: Set to empty string '' if you want to export data to current directory export_path = '../Csv/' # Load FRED API key fp.api_key = fp.load_api_key('fred_api_key...
11,510
Given the following text description, write Python code to implement the functionality described below step by step Description: Conv2DTranspose [convolutional.Conv2DTranspose.0] 4 3x3 filters on 4x4x2 input, strides=(1,1), padding='valid', data_format='channels_last', activation='linear', use_bias=False Step1: [conv...
Python Code: data_in_shape = (4, 4, 2) conv = Conv2DTranspose(4, (3,3), strides=(1,1), padding='valid', data_format='channels_last', activation='linear', use_bias=False) layer_0 = Input(shape=data_in_shape) layer_1 = conv(layer_0) model = Model(inputs=layer_0, outputs=laye...
11,511
Given the following text description, write Python code to implement the functionality described below step by step Description: Some simple ERDDAP timing tests Time how long it takes to get data via ERDDAP. Here we are using the IOOS NERACOOS ERDDAP service at http Step1: Try CSV response for 1 week of acceleromet...
Python Code: %matplotlib inline import urllib, json import pandas as pd Explanation: Some simple ERDDAP timing tests Time how long it takes to get data via ERDDAP. Here we are using the IOOS NERACOOS ERDDAP service at http://www.neracoos.org/erddap. Lots of factors affect timing, as described at the end. But for ...
11,512
Given the following text description, write Python code to implement the functionality described below step by step Description: Lab 1 Step1: The core tables in the data warehouse are derived from 5 separate core operational systems (each with many tables) Step2: Question Step3: Question - How many columns of data ...
Python Code: %%bigquery SELECT dataset_id, table_id, -- Convert bytes to GB. ROUND(size_bytes/pow(10,9),2) as size_gb, -- Convert UNIX EPOCH to a timestamp. TIMESTAMP_MILLIS(creation_time) AS creation_time, TIMESTAMP_MILLIS(last_modified_time) as last_modified_time, row_count, CASE WHEN type = 1...
11,513
Given the following text description, write Python code to implement the functionality described below step by step Description: Roadrunner Methoden Antimony Modell aus Modell-Datenbank abfragen Step1: Erstelle eine Instanz von roadrunner, indem du gleichzeitig den Repressilator als Modell lädst. Benutze dazu loada()...
Python Code: Repressilator = urllib2.urlopen('http://antimony.sourceforge.net/examples/biomodels/BIOMD0000000012.txt').read() Explanation: Roadrunner Methoden Antimony Modell aus Modell-Datenbank abfragen: Lade mithilfe von urllib2 das Antimony-Modell des "Repressilator" herunter. Benutze dazu die urllib2 Methoden urlo...
11,514
Given the following text description, write Python code to implement the functionality described below step by step Description: Gradient Checking Welcome to the final assignment for this week! In this assignment you will learn to implement and use gradient checking. You are part of a team working to make mobile paym...
Python Code: # Packages import numpy as np from testCases import * from gc_utils import sigmoid, relu, dictionary_to_vector, vector_to_dictionary, gradients_to_vector Explanation: Gradient Checking Welcome to the final assignment for this week! In this assignment you will learn to implement and use gradient checking. ...
11,515
Given the following text description, write Python code to implement the functionality described below step by step Description: Random grids Because sometimes you just want some random data. This module implements 2D fractal noise, combining one or more octaves of Perlin noise. Step1: The noise does not have to be i...
Python Code: import gio g = gio.generate_random_surface(200, res=3, octaves=3) g.plot() Explanation: Random grids Because sometimes you just want some random data. This module implements 2D fractal noise, combining one or more octaves of Perlin noise. End of explanation g = gio.generate_random_surface(200, res=(2, 5), ...
11,516
Given the following text description, write Python code to implement the functionality described below step by step Description: Control de flujo Hasta ahora hemos programado en Python intrucciones sencillas que solo tenían en cuenta una posibilidad. No evaluábamos nada, simplemente dábamos órdenes y Python obedecía. ...
Python Code: # asignamos unos cuantos valores a variables numero1 = 2 numero2 = 34 print(numero1 == numero2) print(numero1 != numero2) print(numero1 == numero1) print(numero2 <= 10) print(19 >= (10 * numero1)) print("------------------") print(10 == (5*2)) print(MiVariable != 10) Explanation: Control de flujo Hasta aho...
11,517
Given the following text description, write Python code to implement the functionality described below step by step Description: 컬럼 이름 출력을 하고싶은 경우 df.columns 컬럼 개수 출력을 하고싶은 경우 len(df.columns) Step1: 고유한 값이 어떻게 되는지 알고 싶다면 np.unique(df[col].astype(str)) col값을 변수로 두고 for문을 돌리면 됩니다-! Step2: 그래프를 그릴 때 도화지를 어떻게 그릴것인가-!!1 ...
Python Code: print(trn.columns) print(len(trn.columns)) Explanation: 컬럼 이름 출력을 하고싶은 경우 df.columns 컬럼 개수 출력을 하고싶은 경우 len(df.columns) End of explanation np.unique(trn["sexo"].astype(str)) Explanation: 고유한 값이 어떻게 되는지 알고 싶다면 np.unique(df[col].astype(str)) col값을 변수로 두고 for문을 돌리면 됩니다-! End of explanation f, ax = plt.subplots...
11,518
Given the following text description, write Python code to implement the functionality described below step by step Description: Building an optical system using GaussOpt GaussOpt can be used to analyze quasioptical systems using Gaussian beam analysis. In this notebook, we walk through the basics of setting up a Gaus...
Python Code: %matplotlib inline from gaussopt import * import matplotlib.pyplot as plt # Formatting for Matplotlib (optional) # pip install SciencePlots plt.style.use(["science", "notebook"]) Explanation: Building an optical system using GaussOpt GaussOpt can be used to analyze quasioptical systems using Gaussian beam...
11,519
Given the following text description, write Python code to implement the functionality described below step by step Description: Expecting the unexpected To handle errors properly deserves a chapter on its own in any programming book. Python gives us many ways do deal with errors fatal and otherwise Step1: This shows...
Python Code: import sys def something_dangerous(x): print("computing reciprocal of", x) return 1 / x try: for x in [2, 1, 0, -1]: print("1/{} = {}".format(x, something_dangerous(x))) except ArithmeticError as error: print("Something went terribly wrong:", error) Explanation: Expecting t...
11,520
Given the following text problem statement, write Python code to implement the functionality described below in problem statement Problem: I'm Looking for a generic way of turning a DataFrame to a nested dictionary
Problem: import pandas as pd df = pd.DataFrame({'name': ['A', 'A', 'B', 'C', 'B', 'A'], 'v1': ['A1', 'A2', 'B1', 'C1', 'B2', 'A2'], 'v2': ['A11', 'A12', 'B12', 'C11', 'B21', 'A21'], 'v3': [1, 2, 3, 4, 5, 6]}) def g(df): if len(df.columns) == 1: if df....
11,521
Given the following text description, write Python code to implement the functionality described below step by step Description: Step2: In a world where data can be collected continuously and storage costs are cheap, issues related to the growing size of interesting datasets can pose a problem unless we have the right...
Python Code: import numpy as np from scipy.io import loadmat # load data from MATLAB file datamat = loadmat('quantum.mat') X = datamat['X'] y = datamat['y'] class LogisticRegressionSGD(object): def __init__(self, X, y, progTol=1e-4, nEpochs=10): self.X = X self.y = y self.n, self.d = X....
11,522
Given the following text problem statement, write Python code to implement the functionality described below in problem statement Problem: Sklearn ROC AUC
Python Code:: from sklearn.metrics import roc_auc_score roc_auc = roc_auc_score(y_test, y_pred)
11,523
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 = "17d" # ph_sel_name = "all-ph" # data_id = "7d" Explanation: Executed: Mon Mar 27 11:37:24 2017 Duration: 10 seconds. usALEX-5samples - Template This notebook is executed through 8-spots paper analysis. For a direct execution, uncomment the cell below. End of explanation fr...
11,524
Given the following text description, write Python code to implement the functionality described below step by step Description: K-Fold Cross Validation Step1: A single train/test split is made easy with the train_test_split function in the cross_validation library Step2: K-Fold cross validation is just as easy; let...
Python Code: import numpy as np from sklearn.model_selection import cross_val_score, train_test_split from sklearn import datasets from sklearn import svm iris = datasets.load_iris() Explanation: K-Fold Cross Validation End of explanation # Split the iris data into train/test data sets with 40% reserved for testing X_t...
11,525
Given the following text description, write Python code to implement the functionality described below step by step Description: How to Efficiently Read BigQuery Data from TensorFlow 2.3 Learning Objectives Build a benchmark model. Find the breakoff point for Keras. Training a TensorFlow/Keras model that reads from Bi...
Python Code: %%bash # create output dataset bq mk advdata %%bigquery CREATE OR REPLACE MODEL advdata.ulb_fraud_detection TRANSFORM( * EXCEPT(Amount), SAFE.LOG(Amount) AS log_amount ) OPTIONS( INPUT_LABEL_COLS=['class'], AUTO_CLASS_WEIGHTS = TRUE, DATA_SPLIT_METHOD='seq', DATA_SPLIT_COL='Time', ...
11,526
Given the following text description, write Python code to implement the functionality described below step by step Description: <img src="http Step1: Throughout this section we fix a constant_short_rate discounting object. Step2: geometric_brownian_motion To instantiate any kind of model class, you need a market_en...
Python Code: from dx import * import seaborn as sns; sns.set() np.set_printoptions(precision=3) Explanation: <img src="http://hilpisch.com/tpq_logo.png" alt="The Python Quants" width="45%" align="right" border="4"> Model Classes The model classes represent the fundamental building blocks to model a financial market. Th...
11,527
Given the following text description, write Python code to implement the functionality described below step by step Description: Tutorial Step1: We can inspect the backend via Step2: Defining the VGG Model We begin by first generating our VGG network. VGG is a popular convolutional neural network with ~19 layers. No...
Python Code: from neon.backends import gen_backend be = gen_backend(batch_size=64, backend='cpu') Explanation: Tutorial: Fine-tuning VGG on CIFAR-10 One of the most common questions we get is how to use neon to load a pre-trained model and fine-tune on a new dataset. In this tutorial, we show how to load a pre-trained ...
11,528
Given the following text description, write Python code to implement the functionality described below step by step Description: MODELED.netconf github.com/modeled/modeled.netconf Highly Pythonized NETCONF and YANG Automagically create YANG modules and data containers from MODELED Python classes >>> Simply turn ...
Python Code: import modeled.netconf modeled.netconf.__requires__ Explanation: MODELED.netconf github.com/modeled/modeled.netconf Highly Pythonized NETCONF and YANG Automagically create YANG modules and data containers from MODELED Python classes >>> Simply turn Python methods into NETCONF/YANG RPC methods usi...
11,529
Given the following text description, write Python code to implement the functionality described below step by step Description: Train a basic TensorFlow Lite for Microcontrollers model This notebook demonstrates the process of training a 2.5 kB model using TensorFlow and converting it for use with TensorFlow Lite for...
Python Code: # Define paths to model files import os MODELS_DIR = 'models/' if not os.path.exists(MODELS_DIR): os.mkdir(MODELS_DIR) MODEL_TF = MODELS_DIR + 'model.pb' MODEL_NO_QUANT_TFLITE = MODELS_DIR + 'model_no_quant.tflite' MODEL_TFLITE = MODELS_DIR + 'model.tflite' MODEL_TFLITE_MICRO = MODELS_DIR + 'model.cc' ...
11,530
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: 0. Before start OK, to begin we need to import some standart Python modules Step2: 1. Setup First, let us setup the working area. Step3: Let's show our all-zero image Step4: 2. Mai...
Python Code: # -*- coding: utf-8 -*- Created on Fri Feb 12 13:21:45 2016 @author: GrinevskiyAS from __future__ import division import numpy as np from numpy import sin,cos,tan,pi,sqrt import matplotlib as mpl import matplotlib.cm as cm import matplotlib.pyplot as plt from ipywidgets import interact, interactive, fixed ...
11,531
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction to Spark and Python Let's learn how to use Spark with Python by using the pyspark library! Make sure to view the video lecture explaining Spark and RDDs before continuing on wit...
Python Code: from pyspark import SparkContext Explanation: Introduction to Spark and Python Let's learn how to use Spark with Python by using the pyspark library! Make sure to view the video lecture explaining Spark and RDDs before continuing on with this code. This notebook will serve as reference code for the Big Dat...
11,532
Given the following text description, write Python code to implement the functionality described below step by step Description: Import needed libraries Step1: We used the library "request" last time in getting Twitter data (REST-ful). We are introducing the new "lxml" library for analyzing & extracting HTML element...
Python Code: import requests from lxml import html Explanation: Import needed libraries End of explanation response = requests.get('http://news.ycombinator.com/') response response.content Explanation: We used the library "request" last time in getting Twitter data (REST-ful). We are introducing the new "lxml" library...
11,533
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="#Chi-Square-Feature-Selection" data-toc-modified-id="Chi-Square-Feature-Selec...
Python Code: # code for loading the format for the notebook import os # path : store the current path to convert back to it later path = os.getcwd() os.chdir(os.path.join('..', 'notebook_format')) from formats import load_style load_style(plot_style = False) os.chdir(path) import numpy as np import pandas as pd # 1. ma...
11,534
Given the following text description, write Python code to implement the functionality described below step by step Description: H2O Tutorial Step1: If you already have an H2O cluster running that you'd like to connect to (for example, in a multi-node Hadoop environment), then you can specify the IP and port of that ...
Python Code: import h2o # Start an H2O Cluster on your local machine h2o.init() Explanation: H2O Tutorial: EEG Eye State Classification Author: Erin LeDell Contact: erin@h2o.ai This tutorial steps through a quick introduction to H2O's Python API. The goal of this tutorial is to introduce through a complete example H2O'...
11,535
Given the following text description, write Python code to implement the functionality described below step by step Description: Generalized Linear Models Step1: GLM Step2: Load the data and add a constant to the exogenous (independent) variables Step3: The dependent variable is N by 2 (Success Step4: The independ...
Python Code: %matplotlib inline import numpy as np import statsmodels.api as sm from scipy import stats from matplotlib import pyplot as plt plt.rc("figure", figsize=(16,8)) plt.rc("font", size=14) Explanation: Generalized Linear Models End of explanation print(sm.datasets.star98.NOTE) Explanation: GLM: Binomial respon...
11,536
Given the following text description, write Python code to implement the functionality described below step by step Description: Volshow A simple volume rendering example Using the pylab API Step1: Visualizating a scan of a male head Included in ipyvolume, is a visualuzation of a scan of a human head, see the sourcec...
Python Code: import numpy as np import ipyvolume as ipv V = np.zeros((128,128,128)) # our 3d array # outer box V[30:-30,30:-30,30:-30] = 0.75 V[35:-35,35:-35,35:-35] = 0.0 # inner box V[50:-50,50:-50,50:-50] = 0.25 V[55:-55,55:-55,55:-55] = 0.0 ipv.figure() ipv.volshow(V, level=[0.25, 0.75], opacity=0.03, level_width=0...
11,537
Given the following text description, write Python code to implement the functionality described below step by step Description: Compare fit of mixture model where the nulldistribution is either with or without prethreshold In this notebook, I did a first effort to see if we can apply the thresholdfree peakdistributio...
Python Code: import matplotlib % matplotlib inline import numpy as np import scipy import scipy.stats as stats import scipy.optimize as optimize import scipy.integrate as integrate from __future__ import print_function, division import BUM import neuropower import os import math from nipy.labs.utils.simul_multisubject_...
11,538
Given the following text description, write Python code to implement the functionality described below step by step Description: 'Grouped' k-fold CV A quick demo by Matt In cross-validating, we'd like to drop out one well at a time. LeaveOneGroupOut is good for this Step1: Isolate X and y Step2: We want the well nam...
Python Code: import pandas as pd training_data = pd.read_csv('../training_data.csv') Explanation: 'Grouped' k-fold CV A quick demo by Matt In cross-validating, we'd like to drop out one well at a time. LeaveOneGroupOut is good for this: End of explanation X = training_data.drop(['Formation', 'Well Name', 'Depth','Facie...
11,539
Given the following text description, write Python code to implement the functionality described below step by step Description: 01 Step1: Having matplotlib play nice with virtual environments The matplotlib library has some issues when you’re using a Python 3 virtual environment. The error looks like this Step2: Re...
Python Code: # !workon dataanalysis import pandas as pd Explanation: 01: Building a pandas Cheat Sheet, Part 1 Use the csv I've attached to answer the following questions Import pandas with the right name End of explanation import matplotlib.pyplot as plt #DISPLAY MOTPLOTLIB INLINE WITH THE NOTEBOOK AS OPPOSED TO POP U...
11,540
Given the following text description, write Python code to implement the functionality described below step by step Description: Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http Step1: Inst...
Python Code: # Create folders !mkdir -p '/android/sdk' # Download and move android SDK tools to specific folders !wget -q 'https://dl.google.com/android/repository/tools_r25.2.5-linux.zip' !unzip 'tools_r25.2.5-linux.zip' !mv '/content/tools' '/android/sdk' # Copy paste the folder !cp -r /android/sdk/tools /android/and...
11,541
Given the following text description, write Python code to implement the functionality described below step by step Description: Defensive programming We've covered Step1: Programs like firefox browser are full of assertions Step2: now look at the post-conditions to help us catch bugs by telling us the calculation i...
Python Code: numbers = [1.5, 2.3, 0.7, -0.001, 4.4] total = 0.0 for n in numbers: assert n > 0.0, 'Data should only contain positve values' total += n print('total is: ', total) Explanation: Defensive programming We've covered: variables and lists, file i/o, loops, conditionals, and functions but we haven't sho...
11,542
Given the following text description, write Python code to implement the functionality described below step by step Description: Comparative barcharts In order to get a glimpse of what specific attribute values could be used to determine if a mushroom was edible or poisonous we generated some barcharts to compare the ...
Python Code: def attr_freqs(attr1, attr2): df = shroom_dealer.get_data_frame() labels1 = shroom_dealer.get_attribute_dictionary()[attr1] labels2 = shroom_dealer.get_attribute_dictionary()[attr2] data = [] for a in df[attr1].cat.categories: column = df[attr2][df[attr1] == a].value_counts() ...
11,543
Given the following text description, write Python code to implement the functionality described below step by step Description: Machine Learning Step1: Protein structures Write a function that loads in the x, y, and z coordinates for all CA atoms from a pdb file. Step2: Load in the pdb files homolog-1.pdb and homol...
Python Code: %matplotlib inline from matplotlib import pyplot as plt import numpy as np from sklearn import datasets from sklearn.decomposition import PCA Explanation: Machine Learning End of explanation def load_pdb(pdb_file): f = open(pdb_file,'r') lines = f.readlines() f.close() all_coord =...
11,544
Given the following text description, write Python code to implement the functionality described below step by step Description: Deep Learning Assignment 2 Previously in 1_notmnist.ipynb, we created a pickle with formatted datasets for training, development and testing on the notMNIST dataset. The goal of this assignm...
Python Code: # These are all the modules we'll be using later. Make sure you can import them # before proceeding further. from __future__ import print_function import numpy as np import tensorflow as tf from six.moves import cPickle as pickle from six.moves import range Explanation: Deep Learning Assignment 2 Previousl...
11,545
Given the following text description, write Python code to implement the functionality described below step by step Description: Day 1 Step1: Use namedtuples, because they're so nice ;) Actually, use them because they are still tuples, look like class-objects, and give more semantic context to the code. In this case,...
Python Code: with open('../inputs/day01.txt', 'r') as f: data = [x.strip() for x in f.read().split(',')] Explanation: Day 1: No Time for a Taxicab author: Harshvardhan Pandit license: MIT link to problem statement Santa's sleigh uses a very high-precision clock to guide its movements, and the clock's oscillator is ...
11,546
Given the following text description, write Python code to implement the functionality described below step by step Description: In contrast to the usually taken %matplotlib inline, we want to have a dedicated window here, where we can just exchange the data being shown. It should work with most matplotlib backends, I...
Python Code: %matplotlib qt5 import qkit qkit.cfg['fid_scan_hdf'] = True #qkit.cfg['datadir'] = r'D:\data\run_0815' #maybe you want to set a path to your data directory manually? qkit.start() import qkit.gui.notebook.quickplot as qp Explanation: In contrast to the usually taken %matplotlib inline, we want to have a de...
11,547
Given the following text description, write Python code to implement the functionality described below step by step Description: <center> Introduction to Hadoop MapReduce </center> 3. Optimization First principle of optimizing Hadoop workflow Step1: What is being passed from Map to Reduce? Can reducer do the same thi...
Python Code: !hdfs dfs -rm -r intro-to-hadoop/output-movielens-02 !yarn jar /usr/hdp/current/hadoop-mapreduce-client/hadoop-streaming.jar \ -input /repository/movielens/ratings.csv \ -output intro-to-hadoop/output-movielens-02 \ -file ./codes/avgRatingMapper04.py \ -mapper avgRatingMapper04.py \ -fi...
11,548
Given the following text description, write Python code to implement the functionality described below step by step Description: ApJdataFrames Shetrone et al. 2015 Title Step1: Download Data Step2: The file is about 24 MB. Data wrangle-- read in the data
Python Code: import pandas as pd from astropy.io import ascii, votable, misc Explanation: ApJdataFrames Shetrone et al. 2015 Title: THE SDSS-III APOGEE SPECTRAL LINE LIST FOR H-BAND SPECTROSCOPY Authors: M Shetrone, D Bizyaev, J E Lawler, C Allende Prieto, J A Johnson, V V Smith, K Cunha, J. Holtzman, A E García Pérez,...
11,549
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="#largest-number-of-fans-and-blotches" data-toc-modified-id="largest-number-of...
Python Code: from planet4 import plotting, catalog_production rm = catalog_production.ReleaseManager('v1.0b4') fans = rm.read_fan_file() blotches = rm.read_blotch_file() cols = ['angle', 'distance', 'tile_id', 'marking_id', 'obsid', 'spread', 'l_s', 'map_scale', 'north_azimuth', 'PlanetographicLat...
11,550
Given the following text description, write Python code to implement the functionality described below step by step Description: Yellowbrick Feature Importance Examples This notebook is a sample of the feature importance examples that yellowbrick provides. Step1: Load Iris Datasets for Example Code Step2: Logistic R...
Python Code: import os import sys sys.path.insert(0, "../..") import importlib import numpy as np import pandas as pd import yellowbrick import yellowbrick as yb from yellowbrick.features.importances import FeatureImportances import matplotlib as mpl import matplotlib.pyplot as plt from sklearn import manifold, dataset...
11,551
Given the following text description, write Python code to implement the functionality described below step by step Description: How to decorate the run_step() method (and why) The use of decorators is optional and intended to structure and make the run_step()method clearer and more compact. In order to use the decora...
Python Code: import progressivis.core.decorators Explanation: How to decorate the run_step() method (and why) The use of decorators is optional and intended to structure and make the run_step()method clearer and more compact. In order to use the decorators you have to import them as follows: End of explanation from pro...
11,552
Given the following text description, write Python code to implement the functionality described below step by step Description: FloPy Parameter Estimation with FloPy This notebook demonstrates the current parameter estimation functionality that is available with FloPy. The capability to write a simple template file ...
Python Code: %matplotlib inline import sys import numpy as np import flopy print(sys.version) print('numpy version: {}'.format(np.__version__)) print('flopy version: {}'.format(flopy.__version__)) Explanation: FloPy Parameter Estimation with FloPy This notebook demonstrates the current parameter estimation functionalit...
11,553
Given the following text description, write Python code to implement the functionality described below step by step Description: Embedding CPLEX in scikit-learn scikit-learn is a widely-used library of Machine-Learning algorithms in Python. In this notebook, we show how to embed CPLEX as a scikit-learn transformer cla...
Python Code: try: import numpy as np except ImportError: raise RuntimError('This notebook requires numpy') try: import pandas as pd from pandas import DataFrame except ImportError: raise RuntimError('This notebook requires pandas (not found)') Explanation: Embedding CPLEX in scikit-learn scikit-lea...
11,554
Given the following text description, write Python code to implement the functionality described below step by step Description: Playing with rasterio and fiona Variable declarations sample_points_filepath – path to sample points shapefile <br /> DEM_filepath – path to DEM raster <br /> elevation_filepath – path to ex...
Python Code: sample_points_filepath = "" DEM_filepath = "" elevation_filepath = "" Explanation: Playing with rasterio and fiona Variable declarations sample_points_filepath – path to sample points shapefile <br /> DEM_filepath – path to DEM raster <br /> elevation_filepath – path to export excel file containing elevati...
11,555
Given the following text description, write Python code to implement the functionality described below step by step Description: cs-1 Numpy Topics Step1: Every ndarray is a homogeneous collection of exactly the same data-type every item takes up the same size block of memory each block of memory in the array is inter...
Python Code: import numpy as np import numpy.matlib Explanation: cs-1 Numpy Topics: Intro to numpy, Ndarray Object, Eg Array creation, Array Attributes Numpy: NumPy is the fundamental package needed for scientific computing with Python. It contains: a powerful N-dimensional array object basic linear algebra functions ...
11,556
Given the following text description, write Python code to implement the functionality described below step by step Description: Using the recommendation library Step1: Understanding Movie Similarity Try with different movies Try with different types of similarity metrics (look in /src/similarity.py) Which similarit...
Python Code: import os os.chdir('..') # Import all the packages we need to generate recommendations import numpy as np import pandas as pd import src.utils as utils import src.recommenders as recommenders import src.similarity as similarity # imports necesary for plotting import matplotlib import matplotlib.pyplot as p...
11,557
Given the following text description, write Python code to implement the functionality described below step by step Description: Machine Learning with Shogun By Saurabh Mahindre - <a href="https Step1: In a general problem setting for the supervised learning approach, the goal is to learn a mapping from inputs $x_i\i...
Python Code: %pylab inline %matplotlib inline import os SHOGUN_DATA_DIR=os.getenv('SHOGUN_DATA_DIR', '../../../data') #To import all Shogun classes from shogun import * Explanation: Machine Learning with Shogun By Saurabh Mahindre - <a href="https://github.com/Saurabh7">github.com/Saurabh7</a> as a part of <a href="htt...
11,558
Given the following text description, write Python code to implement the functionality described below step by step Description: Visualize Glass Brain Step1: 1. Upload all statistical maps into the data folder The data folder can be found in the same folder as this notebook. Just drag and drop your NIfTI file into th...
Python Code: %matplotlib inline Explanation: Visualize Glass Brain End of explanation stats_file = '../test_data/ALL_N95_Mean_cope2_thresh_zstat1.nii.gz' view = 'ortho' colormap = 'RdBu_r' threshold = '2.3' black_bg Explanation: 1. Upload all statistical maps into the data folder The data folder can be found in the sa...
11,559
Given the following text description, write Python code to implement the functionality described below step by step Description: Simple Reinforcement Learning in Tensorflow Part 2 Step1: Loading the CartPole Environment If you don't already have the OpenAI gym installed, use pip install gym to grab it. Step2: What ...
Python Code: from __future__ import division import numpy as np try: import cPickle as pickle except: import pickle import tensorflow as tf %matplotlib inline import matplotlib.pyplot as plt import math try: xrange = xrange except: xrange = range Explanation: Simple Reinforcement Learning in Tensorflow ...
11,560
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2020 Google LLC. Step1: Reformer Step2: Setting up data and model In this notebook, we'll be pushing the limits of just how many tokens we can fit on a single TPU device. The TPU...
Python Code: # 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 # distributed unde...
11,561
Given the following text description, write Python code to implement the functionality described below step by step Description: Block Codes Block codes take serial source symbols and group them into k-symbol blocks. They then take n-k check symbols to make code words of length n > k. The code is denoted (n,k). The fo...
Python Code: cc1 = block.FECCyclic('1011') Explanation: Block Codes Block codes take serial source symbols and group them into k-symbol blocks. They then take n-k check symbols to make code words of length n > k. The code is denoted (n,k). The following shows a general block diagram of block encoder. The block encoder...
11,562
Given the following text description, write Python code to implement the functionality described below step by step Description: Computing in Context sub history Lecture one Number munging This is iPython. It is swell. It is Python in a brower. Pure CS types not love. We hackish types adore! Download anaconda (esp if ...
Python Code: #This is a comment #This is all blackboxed for now--DON'T worry about it # Render our plots inline %matplotlib inline import pandas as pd import matplotlib.pyplot as plt import numpy as np pd.set_option('display.mpl_style', 'default') # Make the graphs a bit prettier plt.rcParams['figure.figsize'] = (15, 5...
11,563
Given the following text description, write Python code to implement the functionality described below step by step Description: In this notebook a Q learner with dyna and a custom predictor will be trained and evaluated. The Q learner recommends when to buy or sell shares of one particular stock, and in which quantit...
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 import pickle %matplotlib inline ...
11,564
Given the following text description, write Python code to implement the functionality described below step by step Description: Example of performing Vector mathmatical function using Python List structures Vector methods to be created Step1: Other vector operations that could be done Step2: List Comprehensions are...
Python Code: class vector_math: ''' This is the base class for vector math - which allows for initialization with two vectors. ''' def __init__(self, vectors = [[1,2,2],[3,4,3]]): self.vect1 = vectors[0] self.vect2 = vectors[1] def set_vects(self, vectors): self...
11,565
Given the following text description, write Python code to implement the functionality described below step by step Description: TUTORIAL 13 - Elliptic Optimal Control Keywords Step1: 3. Affine Decomposition For this problem the affine decomposition is straightforward. Step2: 4. Main program 4.1. Read the mesh for t...
Python Code: from dolfin import * from rbnics import * Explanation: TUTORIAL 13 - Elliptic Optimal Control Keywords: optimal control, inf-sup condition, POD-Galerkin 1. Introduction This tutorial addresses a distributed optimal control problem for the Graetz conduction-convection equation on the domain $\Omega$ shown b...
11,566
Given the following text description, write Python code to implement the functionality described below step by step Description: SC-4-5 Feature Engineering and Classification Step1: The strategy, unlike our first attempt, requires a real train/test split in the dataset because we're going to fit an actual model (alth...
Python Code: import numpy as np import networkx as nx import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import cPickle as pickle from copy import deepcopy from sklearn.utils import shuffle import sklearn_mmadsen.graphs as skmg %matplotlib inline plt.style.use("fivethirtyeight") sns.set() all_gra...
11,567
Given the following text description, write Python code to implement the functionality described below step by step Description: Passband Luminosity 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...
Python Code: !pip install -I "phoebe>=2.1,<2.2" Explanation: Passband Luminosity 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 %matplotlib inline...
11,568
Given the following text description, write Python code to implement the functionality described below step by step Description: ES-DOC CMIP6 Model Properties - Land MIP Era Step1: Document Authors Set document authors Step2: Document Contributors Specify document contributors Step3: Document Publication Specify do...
Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'cnrm-cerfacs', 'sandbox-3', 'land') Explanation: ES-DOC CMIP6 Model Properties - Land MIP Era: CMIP6 Institute: CNRM-CERFACS Source ID: SANDBOX-3 Topic: Land Sub-Topics: Soil, Snow, V...
11,569
Given the following text description, write Python code to implement the functionality described below step by step Description: Distribution Analysis of the data Now that we have familarity with the basic characterstics, lets look at the distribution of various variables starting with the continuous variable Distribu...
Python Code: sub1.describe() Explanation: Distribution Analysis of the data Now that we have familarity with the basic characterstics, lets look at the distribution of various variables starting with the continuous variable Distribution analysis of continuous variable using the describe() End of explanation sub1['extra...
11,570
Given the following text description, write Python code to implement the functionality described below step by step Description: Note Step1: ipython shell Tab Completion and History Search is Great Start typing and use the 'tab' key for auto complete. Can use this on python functions, modules, variables, files, and ...
Python Code: %%writefile hello.py #!/usr/bin/env python def printHello(): print "Hello World" print "File Loaded" Explanation: Note: This is basically a grab-bag of things... Advanced iPython iPython: interactive Python Many different ways to work with Python: type 'python' from the command line run a pytho...
11,571
Given the following text description, write Python code to implement the functionality described below step by step Description: Using a CFSv2 forecast CFSv2 is a seasonal forecast system, used for analysing past climate and also making seasonal, up to 9-month, forecasts. Here we give a brief example on how to use Pl...
Python Code: %matplotlib notebook import numpy as np import pandas as pd import matplotlib.pyplot as plt from API_client.python import datahub from API_client.python.lib import dataset from API_client.python.lib import variables Explanation: Using a CFSv2 forecast CFSv2 is a seasonal forecast system, used for analysin...
11,572
Given the following text description, write Python code to implement the functionality described below step by step Description: Neural Network - Statistical Encoding - Microsoft Malware There aren't any examples of using a neural network to model Microsoft Malware, so I thought I'd post one. Also in this kernel, I sh...
Python Code: # IMPORT LIBRARIES import pandas as pd, numpy as np, os, gc # LOAD AND FREQUENCY-ENCODE FE = ['EngineVersion','AppVersion','AvSigVersion','Census_OSVersion'] # LOAD AND ONE-HOT-ENCODE OHE = [ 'RtpStateBitfield','IsSxsPassiveMode','DefaultBrowsersIdentifier', 'AVProductStatesIdentifier','AVProductsI...
11,573
Given the following text description, write Python code to implement the functionality described below step by step Description: Libraries Step1: EMUstack Step2: Spectra plot Step3: Triangulation field plot
Python Code: # libraries import numpy as np import sys sys.path.append("../backend/") %matplotlib inline import matplotlib.pylab as plt from mpl_toolkits.axes_grid1 import make_axes_locatable import objects import materials # import plotting from stack import * #parallel import concurrent.futures %matplotlib inline Exp...
11,574
Given the following text description, write Python code to implement the functionality described below step by step Description: Ch. 4 - A deeper network & Overfitting In this chapter we will build a neural network with a hidden layer to fit a more complex function. First, what makes a neural network 'deep'? The numbe...
Python Code: # Package imports # Matplotlib is a matlab like plotting library import matplotlib import matplotlib.pyplot as plt # Numpy handles matrix operations import numpy as np # SciKitLearn is a useful machine learning utilities library import sklearn # The sklearn dataset module helps generating datasets import s...
11,575
Given the following text description, write Python code to implement the functionality described below step by step Description: Solution Step1: Print out the wind_speed and sst variables to check yourself. Step2: 2. Create a function to calculate the heat flux Wind speed and temperature should be the required input...
Python Code: ## Your code wind_speed = list(range(0,20,2)) sst = [5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] Explanation: Solution: build a simple program (1 h) By doing this exercise you will apply Python basics that we learned today: loops, lists, functions, strings. In addition, you will try to write data to a text file...
11,576
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: Lesson Step2: Project 1 Step3: Transforming Text into Numbers Step4: Project 2 Step...
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())...
11,577
Given the following text description, write Python code to implement the functionality described below step by step Description: Compute cross-talk functions for LCMV beamformers Visualise cross-talk functions at one vertex for LCMV beamformers computed with different data covariance matrices, which affects their cros...
Python Code: # Author: Olaf Hauk <olaf.hauk@mrc-cbu.cam.ac.uk> # # License: BSD (3-clause) import mne from mne.datasets import sample from mne.beamformer import make_lcmv, make_lcmv_resolution_matrix from mne.minimum_norm import get_cross_talk print(__doc__) data_path = sample.data_path() subjects_dir = data_path + '/s...
11,578
Given the following text description, write Python code to implement the functionality described below step by step Description: Programming Language Correlation This sample notebook demonstrates working with GitHub activity, which has been made possible via the publicly accessible GitHub Timeline BigQuery dataset via...
Python Code: import google.datalab.bigquery as bq import matplotlib.pyplot as plot import numpy as np import pandas as pd Explanation: Programming Language Correlation This sample notebook demonstrates working with GitHub activity, which has been made possible via the publicly accessible GitHub Timeline BigQuery datase...
11,579
Given the following text description, write Python code to implement the functionality described below step by step Description: Latent Dirichlet Allocation for Text Data In this assignment you will apply standard preprocessing techniques on Wikipedia text data use GraphLab Create to fit a Latent Dirichlet allocation ...
Python Code: import graphlab as gl import numpy as np import matplotlib.pyplot as plt %matplotlib inline '''Check GraphLab Create version''' from distutils.version import StrictVersion assert (StrictVersion(gl.version) >= StrictVersion('1.8.5')), 'GraphLab Create must be version 1.8.5 or later.' # import wiki data wik...
11,580
Given the following text description, write Python code to implement the functionality described below step by step Description: cosmo_derived This plugin calculates the following "derived" cosmological quantities Step1: To use cosmo_derived, first call the set_params function to set all the cosmological parameters, ...
Python Code: from cosmoslik import * cosmo_derived = get_plugin('models.cosmo_derived')() Explanation: cosmo_derived This plugin calculates the following "derived" cosmological quantities: * $H(z)$ * $D_A(z)$ * $r_s(z)$ * $\theta_s(z)$ * $z_{\rm drag}$ (Hu & Sugiyama fitting formula) It can also be used as a $\theta$ t...
11,581
Given the following text description, write Python code to implement the functionality described below step by step Description: Delaunay Here, we'll perform various analysis by constructing graphs and measure properties of those graphs to learn more about the data Step1: We'll start with just looking at analysis in ...
Python Code: import csv from scipy.stats import kurtosis from scipy.stats import skew from scipy.spatial import Delaunay import numpy as np import math import skimage import matplotlib.pyplot as plt import seaborn as sns from skimage import future import networkx as nx from ragGen import * %matplotlib inline sns.set_co...
11,582
Given the following text description, write Python code to implement the functionality described below step by step Description: Preprocessing Data for DRQN We take the data from data generator and save them into traces of (s,a,r,sp) tuples. Each trajectory corresponds to a trace. If trajectory has length n, then trac...
Python Code: data = d_utils.load_data(filename="../synthetic_data/test-n10000-l3-random.pickle") dqn_data = d_utils.preprocess_data_for_dqn(data, reward_model="dense") # Single Trace print (dqn_data[0]) # First tuple in a trace s,a,r,sp = dqn_data[0][0] print (s) print (a) print (r) print (sp) # Last tuple s,a,r,sp = d...
11,583
Given the following text description, write Python code to implement the functionality described below step by step Description: Data Science Tutorial 01 @ Data Science Society 那須野薫(Kaoru Nasuno)/ 東京大学(The University of Tokyo) データサイエンスの基礎的なスキルを身につける為のチュートリアルです。 KaggleのコンペティションであるRECRUIT Challenge, Coupon Purchase Pred...
Python Code: # TODO: You Must Change the setting bellow MYSQL = { 'user': 'root', 'passwd': '', 'db': 'coupon_purchase', 'host': '127.0.0.1', 'port': 3306, 'local_infile': True, 'charset': 'utf8', } DATA_DIR = '/home/nasuno/recruit_kaggle_datasets' # ディレクトリの名前に日本語(マルチバイト文字)は使わないでください。 OUTP...
11,584
Given the following text description, write Python code to implement the functionality described below step by step Description: Homework 3 Due Date Step1: Problem 2 Step2: Problem 3 This problem is related to the Lecture 4 exercises. 1. Open the languages.txt file. This file contains all the languages that student...
Python Code: %%bash cd /tmp rm -rf playground git clone https://github.com/crystalzhaizhai/playground.git %%bash cd /tmp/playground git pull origin mybranch1 ls %%bash cd /tmp/playground git status %%bash cd /tmp/playground git reset --hard origin/master ls %%bash cd /tmp/playground git status Explanation: Homework 3 D...
11,585
Given the following text description, write Python code to implement the functionality described below step by step Description: Running pyqz II First things first, let's start by importing pyqz and pyqz_plots. Step1: D) Using custom MAPPINGS grids While pyqz ships with a default set of HII region simulations from MA...
Python Code: %matplotlib inline import pyqz import pyqz.pyqz_plots as pyqzp Explanation: Running pyqz II First things first, let's start by importing pyqz and pyqz_plots. End of explanation fn = pyqz.pyqzt.get_MVphotogrid_fn(Pk=6.7, calibs='GCZO', kappa =10, struct='pp') print fn.split('/')[-1] Explanation: D) Using cu...
11,586
Given the following text description, write Python code to implement the functionality described below step by step Description: <H1>Migration velocity</H1> <P> To compute the velocity of the trajectories of several particles, we generated a file with the 3D coordinates (Position X, Position Y and Position Z) acquired...
Python Code: %pylab inline import pandas as pd # read CSV file in pandas mydf = pd.read_csv('.data/Julie_R1_Bef_S4_cell123_Position.csv', skiprows=2) mydf.head() Explanation: <H1>Migration velocity</H1> <P> To compute the velocity of the trajectories of several particles, we generated a file with the 3D coordinates (P...
11,587
Given the following text description, write Python code to implement the functionality described below step by step Description: Prerequisites Install Theano and Lasagne using the following commands Step1: Data loading Step2: Network definition Step3: Define the update rule, how to train Step4: Compile Step5: Tra...
Python Code: import sys import os import numpy as np import scipy.io import time import theano import theano.tensor as T import theano.sparse as Tsp import lasagne as L import lasagne.layers as LL import lasagne.objectives as LO from lasagne.layers.normalization import batch_norm sys.path.append('..') from icnn import ...
11,588
Given the following text description, write Python code to implement the functionality described below step by step Description: Zipline beginner tutorial Basics Zipline is an open-source algorithmic trading simulator written in Python. The source can be found at Step1: As you can see, we first have to import some fu...
Python Code: !tail ../zipline/examples/buyapple.py Explanation: Zipline beginner tutorial Basics Zipline is an open-source algorithmic trading simulator written in Python. The source can be found at: https://github.com/quantopian/zipline Some benefits include: Realistic: slippage, transaction costs, order delays. Strea...
11,589
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Excel - Paste Import sometimes we just want to import Excel data by pasting it (it pastes as \n separated rows, where the fields are separated by \t Ranges Step2: Export the table be...
Python Code: data_string = 1 2 3 4 11 12 13 14 21 22 23 24 31 32 33 34 41 42 43 44 51 52 53 54 data_string = data_string.strip() data = [line.split('\t') for line in data_string.split('\n')] data data_f = [list(map(float,line.split('\t'))) for line in data_string.split('\n')] data_f data_i = [list(map(int,line.split('...
11,590
Given the following text description, write Python code to implement the functionality described below step by step Description: <a href="https Step1: Epochs Step2: Evoked Step3: Challenge Step4: Machine learning approach Step5: Performing linear regression Step6: Inspecting the weights Step7: What's going on h...
Python Code: import mne epochs = mne.read_epochs('subject04-epo.fif') epochs.metadata Explanation: <a href="https://mybinder.org/v2/gh/wmvanvliet/neuroscience_tutorials/master?filepath=posthoc%2Flinear_regression.ipynb" target="_new" style="float: right"><img src="qr.png" alt="https://mybinder.org/v2/gh/wmvanvliet/neu...
11,591
Given the following text description, write Python code to implement the functionality described below step by step Description: Table of Contents <p><div class="lev1 toc-item"><a href="#Python-implementation-of-Finding-a-&quot;Kneedle&quot;-in-a-Haystack Step1: Example 1 $$ X \sim N(50, 10) $$ Knee point(expected) ...
Python Code: %matplotlib inline import numpy as np import scipy as sp import seaborn as sns from scipy.interpolate import UnivariateSpline import matplotlib.pyplot as plt sns.set_style('white') np.random.seed(42) def draw_plot(X, Y, knee_point=None): plt.plot(X, Y) if knee_point: plt.axvline(x=knee_poin...
11,592
Given the following text description, write Python code to implement the functionality described below step by step Description: Newtonian Tidal Disruption of Compact Binaries We expect certain types of LIGO signals to have electromagnetic (EM) counterparts &mdash; bright, transient explosions visible to optical, radi...
Python Code: # Imports. import numpy as np from numpy import pi import matplotlib.pyplot as plt from matplotlib import ticker %matplotlib inline Explanation: Newtonian Tidal Disruption of Compact Binaries We expect certain types of LIGO signals to have electromagnetic (EM) counterparts &mdash; bright, transient explosi...
11,593
Given the following text description, write Python code to implement the functionality described below step by step Description: Classes & Object Oriented Programming Object-oriented programming or programming using classes is an abstraction that tries to apply the same abstraction rules used for categorizing nature t...
Python Code: import numpy as np Explanation: Classes & Object Oriented Programming Object-oriented programming or programming using classes is an abstraction that tries to apply the same abstraction rules used for categorizing nature to programming techniques. This has the advantage that the process for creating a comp...
11,594
Given the following text description, write Python code to implement the functionality described below step by step Description: <img src="images/logo.jpg" style="display Step1: <p style="text-align Step2: <p style="text-align Step3: <p style="text-align Step4: <span style="text-align Step5: <p style="text-align ...
Python Code: import math def factorize_prime(number): while number % 2 == 0: yield 2 number = number // 2 # `number` must be odd at this point (we've just factored 2 out). # Skip even numbers. Square root is good upper limit, check # https://math.stackexchange.com/a/1039525 ...
11,595
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction to py2cytoscape Step1: Long Description From version 0.4.0, py2cytoscape has wrapper modules for cyREST RESTful API. This means you can access Cytoscape features in more Pytho...
Python Code: from py2cytoscape.data.cynetwork import CyNetwork from py2cytoscape.data.cyrest_client import CyRestClient from py2cytoscape.data.style import StyleUtil import py2cytoscape.util.cytoscapejs as cyjs import py2cytoscape.cytoscapejs as renderer import networkx as nx import pandas as pd import json # !!!!!!!!!...
11,596
Given the following text description, write Python code to implement the functionality described below step by step Description: Let's start with the necessary imports and setup commands Step1: Loading the data, and getting rid of NAs Step2: The fitted linear regression model, using statsmodels R style formula API S...
Python Code: %matplotlib inline import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt import statsmodels.formula.api as smf from statsmodels.graphics.gofplots import ProbPlot plt.style.use('seaborn') # pretty matplotlib plots plt.rc('font', size=14) plt.rc('figure', titlesize=18) ...
11,597
Given the following text description, write Python code to implement the functionality described below step by step Description: NLTK 자연어 처리 패키지 소개 NLTK(Natural Language Toolkit) 패키지는 교육용으로 개발된 자연어 처리 및 문서 분석용 파이썬 패키지다. 다양한 기능 및 예제를 가지고 있으며 실무 및 연구에서도 많이 사용된다. NLTK 패키지가 제공하는 주요 기능은 다음과 같다. 샘플 corpus 및 사전 토큰 생성(tokeniz...
Python Code: nltk.download('averaged_perceptron_tagger') nltk.download("gutenberg") nltk.download('punkt') nltk.download('reuters') nltk.download("stopwords") nltk.download("taggers") nltk.download("webtext") nltk.download("wordnet") nltk.corpus.gutenberg.fileids() emma_raw = nltk.corpus.gutenberg.raw("austen-emma.txt"...
11,598
Given the following text description, write Python code to implement the functionality described below step by step Description: Saving and Loading Models In this notebook, I'll show you how to save and load models with PyTorch. This is important because you'll often want to load previously trained models to use in ma...
Python Code: %matplotlib inline %config InlineBackend.figure_format = 'retina' import matplotlib.pyplot as plt import torch from torch import nn from torch import optim import torch.nn.functional as F from torchvision import datasets, transforms import helper import fc_model # Define a transform to normalize the data t...
11,599
Given the following text description, write Python code to implement the functionality described below step by step Description: Module 12 - Programming Assignment Directions There are general instructions on Blackboard and in the Syllabus for Programming Assignments. This Notebook also has instructions specific to th...
Python Code: from __future__ import division # so that 1/2 = 0.5 and not 0 from IPython.core.display import * import csv, math, copy, random Explanation: Module 12 - Programming Assignment Directions There are general instructions on Blackboard and in the Syllabus for Programming Assignments. This Notebook also has ins...