Unnamed: 0
int64
0
16k
text_prompt
stringlengths
110
62.1k
code_prompt
stringlengths
37
152k
6,800
Given the following text description, write Python code to implement the functionality described below step by step Description: Chapter 1 - Introduction to Machine Learning This chapter introduces some common concepts about learning (such as supervised and unsupervised learning) and some simples applications. Supervi...
Python Code: %run ../src/LinearRegression.py %run ../src/PolynomialFeatures.py # LINEAR REGRESSION # Generate random data X = np.linspace(0,20,10)[:,np.newaxis] y = 0.1*(X**2) + np.random.normal(0,2,10)[:,np.newaxis] + 20 # Fit model to data lr = LinearRegression() lr.fit(X,y) # Predict new data x_test = np.array([0,20...
6,801
Given the following text description, write Python code to implement the functionality described below step by step Description: Mock Spectra Attempting to make synthetic spectra look real. Step2: We will try to use urllib to pull synthetic spectra from the Phoenix model atmosphere server. This way, we can avoid stor...
Python Code: %matplotlib inline import matplotlib.pyplot as plt import numpy as np import urllib Explanation: Mock Spectra Attempting to make synthetic spectra look real. End of explanation def phoenixFileURL(Teff, logg, FeH=0.0, aFe=0.0, brand='BT-Settl', solar_abund='CIFIST2011_2015'): Create file name for a Pho...
6,802
Given the following text description, write Python code to implement the functionality described below step by step Description: Query for pile-up allignments at region "x" We can query the database to obtain a pile-up of the reads from a given readgroup. Initialize the client As seen in the "1kg.ipynb" example, we ta...
Python Code: import ga4gh.client as client c = client.HttpClient("http://1kgenomes.ga4gh.org") Explanation: Query for pile-up allignments at region "x" We can query the database to obtain a pile-up of the reads from a given readgroup. Initialize the client As seen in the "1kg.ipynb" example, we take the following steps...
6,803
Given the following text description, write Python code to implement the functionality described below step by step Description: Representation of data submission workflow components based on W3C-PROV Step1: generate empty Prov document and load submission workflow representation Step2: The Provenance Model used is ...
Python Code: %load_ext autoreload %autoreload 2 %load_ext autoreload %autoreload 2 import sys sys.path.append('/home/stephan/Repos/ENES-EUDAT/submission_forms') from dkrz_forms import form_handler from dkrz_forms import checks from dkrz_forms.config import test_config from dkrz_forms.config import workflow_steps #print...
6,804
Given the following text description, write Python code to implement the functionality described below step by step Description: <a href="https Step1: Loading sample data We begin by loading the data that we would like to summarize into a Pandas DataFrame. - Variables are in columns - Encounters/observations are in ...
Python Code: # Import numerical libraries import pandas as pd import numpy as np from scipy import stats import matplotlib.pyplot as plt %matplotlib inline # Import tableone try: from tableone import TableOne, load_dataset except (ModuleNotFoundError, ImportError): # install on Colab !pip install tableone ...
6,805
Given the following text description, write Python code to implement the functionality described below step by step Description: This example builds HMM and MSMs on the alanine_dipeptide dataset using varing lag times and numbers of states, and compares the relaxation timescales Step1: First Step2: Now sequences is ...
Python Code: from __future__ import print_function import os %matplotlib inline from matplotlib.pyplot import * from msmbuilder.featurizer import SuperposeFeaturizer from msmbuilder.example_datasets import AlanineDipeptide from msmbuilder.hmm import GaussianHMM from msmbuilder.cluster import KCenters from msmbuilder.ms...
6,806
Given the following text description, write Python code to implement the functionality described below step by step Description: Interactive 3-D Visualization Step1: Loading an example geomodel Step2: Basic plotting API Data plot Step3: Geomodel plot Step4: Interactive plot Passing the notebook=False keyword argum...
Python Code: # Importing GemPy import gempy as gp # Embedding matplotlib figures in the notebooks %matplotlib inline # Importing auxiliary libraries import numpy as np import matplotlib.pyplot as plt Explanation: Interactive 3-D Visualization End of explanation data_path = 'https://raw.githubusercontent.com/cgre-aachen...
6,807
Given the following text description, write Python code to implement the functionality described below step by step Description: Collaborative filtering on Google Analytics data This notebook demonstrates how to implement a WALS matrix refactorization approach to do collaborative filtering. Step2: Create raw dataset ...
Python Code: import os PROJECT = "cloud-training-demos" # REPLACE WITH YOUR PROJECT ID BUCKET = "cloud-training-demos-ml" # REPLACE WITH YOUR BUCKET NAME REGION = "us-central1" # REPLACE WITH YOUR BUCKET REGION e.g. us-central1 # Do not change these os.environ["PROJECT"] = PROJECT os.environ["BUCKET"] = BUCKET os.envir...
6,808
Given the following text description, write Python code to implement the functionality described below step by step Description: 机器学习纳米学位 监督学习 项目2 Step1: 练习:数据探索 首先我们对数据集进行一个粗略的探索,我们将看看每一个类别里会有多少被调查者?并且告诉我们这些里面多大比例是年收入大于50,000美元的。在下面的代码单元中,你将需要计算以下量: 总的记录数量,'n_records' 年收入大于50,000美元的人数,'n_greater_50k'. 年收入最多为50,000美元...
Python Code: # 为这个项目导入需要的库 import numpy as np import pandas as pd from time import time from IPython.display import display # 允许为DataFrame使用display() # 导入附加的可视化代码visuals.py import visuals as vs # 为notebook提供更加漂亮的可视化 %matplotlib inline # 导入人口普查数据 data = pd.read_csv("census.csv") # 成功 - 显示第一条记录 display(data.head()) Expla...
6,809
Given the following text description, write Python code to implement the functionality described below step by step Description: nb2py tutorial All the examples are generated from this notebook and located in the folder tutorial_files. Step1: Exporting marked cells The dump function automatically exports cells starti...
Python Code: import nb2py Explanation: nb2py tutorial All the examples are generated from this notebook and located in the folder tutorial_files. End of explanation #~ #This is a cell example with the standard marker a=2 b=3 print(a+b) nb2py.dump('tutorial.ipynb','tutorial_files/standard.py') #please export this cell ...
6,810
Given the following text description, write Python code to implement the functionality described below step by step Description: Handwritten Number Recognition with TFLearn and MNIST In this notebook, we'll be building a neural network that recognizes handwritten numbers 0-9. This kind of neural network is used in a ...
Python Code: # Import Numpy, TensorFlow, TFLearn, and MNIST data import numpy as np import tensorflow as tf import tflearn import tflearn.datasets.mnist as mnist Explanation: Handwritten Number Recognition with TFLearn and MNIST In this notebook, we'll be building a neural network that recognizes handwritten numbers 0-...
6,811
Given the following text description, write Python code to implement the functionality described below step by step Description: Recovers true coefficients on artificial censored regression data Step1: Note that the truncation values do not have to be the same for e.g. all left-censored observations, or all right-cen...
Python Code: rs = np.random.RandomState(seed=10) ns = 100 nf = 10 x, y_orig, coef = make_regression(n_samples=ns, n_features=nf, coef=True, noise=0.0, random_state=rs) x = pd.DataFrame(x) y = pd.Series(y_orig) n_quantiles = 3 # two-thirds of the data is truncated quantile = 100/float(n_quantiles) lower = np.percentile(...
6,812
Given the following text description, write Python code to implement the functionality described below step by step Description: Whitening versus standardizing Step1: First, just read in data, and take a peek. The data can be found on GitHub. Step2: We're told that for gender, 1 is male, and 2 is female. Part (a) sa...
Python Code: %matplotlib inline import pandas as pd import numpy as np import matplotlib.pyplot as plt from scipy import stats Explanation: Whitening versus standardizing End of explanation raw_data = pd.read_csv("heightWeightData.txt", header=None, names=["gender", "height", "weight"]) raw_data.info() raw_data.head() ...
6,813
Given the following text description, write Python code to implement the functionality described below step by step Description: Your first neural network In this project, you'll build your first neural network and use it to predict daily bike rental ridership. We've provided some of the code, but left the implementat...
Python Code: %matplotlib inline %config InlineBackend.figure_format = 'retina' import numpy as np import pandas as pd import matplotlib.pyplot as plt Explanation: Your first neural network In this project, you'll build your first neural network and use it to predict daily bike rental ridership. We've provided some of t...
6,814
Given the following text description, write Python code to implement the functionality described below step by step Description: Mock community dataset generation Run in a qiime 2.0.6 conda environment. This notebook describes how mock community datasets were retrieved and files were generated for tax-credit compariso...
Python Code: from tax_credit.process_mocks import (extract_mockrobiota_dataset_metadata, extract_mockrobiota_data, batch_demux, denoise_to_phylogeny, transport_to_repo ...
6,815
Given the following text description, write Python code to implement the functionality described below step by step Description: LSESU Applicable Maths Python Lesson 3 1/11/16 Today we will be learning about * Strings and string indexing * Reading files * Lists * List comprehensions Recap from week 2 Functions This i...
Python Code: # Everyone should know how to create (or "declare") a string by now var = 'This is a string' alphabet = 'abcdefghijklmnopqrstuvwxyz' Explanation: LSESU Applicable Maths Python Lesson 3 1/11/16 Today we will be learning about * Strings and string indexing * Reading files * Lists * List comprehensions Recap...
6,816
Given the following text description, write Python code to implement the functionality described below step by step Description: Naive Bayes - Trabalho Questão 1 Implemente um classifacor Naive Bayes para o problema de predizer a qualidade de um carro. Para este fim, utilizaremos um conjunto de dados referente a quali...
Python Code: #Bibliotecas import pandas as pd import numpy as np from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score, classification_report #Lendo o arquivo com os dados df = pd.read_csv('carData.csv', header=None) df.columns = ['buying', 'maint','doors','persons','lug_boot'...
6,817
Given the following text description, write Python code to implement the functionality described below step by step Description: Markov Madness Ok let's get down to business! So the overall goal is to build a mathematical model that predicts with good accuracy who is likely to make it to the sweet 16 in the NCAA tourn...
Python Code: import pandas as pd import numexpr import bottleneck import numpy as np import numpy.linalg as linalg import matplotlib.pyplot as plt %matplotlib inline import scipy.stats as ss reg_14_15 = pd.read_csv('2014_2015 Regular Season Stats.csv') #Testing out our system reg_14_15 Explanation: Markov Madness Ok le...
6,818
Given the following text description, write Python code to implement the functionality described below step by step Description: An RNN model for temperature data This time we will be working with real data Step1: Download Data Step2: <a name="hyperparameters"></a> <a name="assignment1"></a> Hyperparameters <div cla...
Python Code: import math import sys import time import numpy as np sys.path.insert(0, '../temperatures/utils/') #so python can find the utils_ modules import utils_batching import utils_args import tensorflow as tf from tensorflow.python.lib.io import file_io as gfile print("Tensorflow version: " + tf.__version__) from...
6,819
Given the following text description, write Python code to implement the functionality described below step by step Description: Test CacheOutput() class-based function decorator Step1: Make an expensive function and time it Step2: Cache the function results If the exact same inputs are used again before the time li...
Python Code: import datetime as dt import time import fridge Explanation: Test CacheOutput() class-based function decorator End of explanation # This decorator just displays how long a function takes to run def showtime(func): def wrapper(*args,**kwargs): start = dt.datetime.now() result = func(...
6,820
Given the following text description, write Python code to implement the functionality described below step by step Description: Google BigQuery Motivated by the structure in the OKCupid usernames, I looked at the reddit data on Google BigQuery. Try to answer the questions Step1: Had to impose a limit so that I did n...
Python Code: %matplotlib inline import os import glob import pylab import numpy as np import pandas as pd pd.set_option('display.max_rows', 5) import seaborn as sns sns.set_style('whitegrid') from matplotlib.dates import date2num from datetime import datetime from pysurvey.plot import setup_sns as setup from pysurvey.p...
6,821
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="#Evaluating-Imbalanced-Datasets" data-toc-modified-id="Evaluating-Imbalanced-...
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) # 1. magic for inline plot # 2. magic to p...
6,822
Given the following text description, write Python code to implement the functionality described below step by step Description: The situation Type C thermocouples are not NIST calibrated to below 273.15 K. For my research specific scenario, I need to cool my sample (Molybdenum) to cryogenic temperatures and also anne...
Python Code: # import a few packages %matplotlib notebook from thermocouples_reference import thermocouples import numpy as np import pandas as pd import matplotlib.pyplot as plt import sympy as sp from scipy import optimize, interpolate, signal typeC=thermocouples['C'] # make sure you are in the same dir as the file #...
6,823
Given the following text description, write Python code to implement the functionality described below step by step Description: Step2: Classification 1 Step3: Evaluating a classifier Most classifiers are "soft" because they can output a score, higher means more likely to be $Y=1$ - Logistic regression Step4: Confus...
Python Code: import pandas as pd import numpy as np import matplotlib as mpl import plotnine as p9 import matplotlib.pyplot as plt import itertools import warnings warnings.simplefilter("ignore") from sklearn import neighbors, preprocessing, impute, metrics, model_selection, linear_model, svm, feature_selection from ma...
6,824
Given the following text description, write Python code to implement the functionality described below step by step Description: ES-DOC CMIP6 Model Properties - Landice MIP Era Step1: Document Authors Set document authors Step2: Document Contributors Specify document contributors Step3: Document Publication Specify...
Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'ncar', 'sandbox-2', 'landice') Explanation: ES-DOC CMIP6 Model Properties - Landice MIP Era: CMIP6 Institute: NCAR Source ID: SANDBOX-2 Topic: Landice Sub-Topics: Glaciers, Ice. Prop...
6,825
Given the following text description, write Python code to implement the functionality described below step by step Description: Creating Keras DNN model Learning Objectives Create input layers for raw features Create feature columns for inputs Create DNN dense hidden layers and output layer Build DNN model tying all ...
Python Code: !sudo chown -R jupyter:jupyter /home/jupyter/training-data-analyst !pip install --user google-cloud-bigquery==1.25.0 Explanation: Creating Keras DNN model Learning Objectives Create input layers for raw features Create feature columns for inputs Create DNN dense hidden layers and output layer Build DNN mod...
6,826
Given the following text description, write Python code to implement the functionality described below step by step Description: 1T_크롤링 수업(중고나라 모바일) Step1: 이미지 가져오기 Step2: https
Python Code: #네이버 중고나라(모바일) import requests from bs4 import BeautifulSoup # "맥북" 키워드로 검색 url = "http://m.cafe.naver.com/ArticleSearchList.nhn?search.query=맥북&search.menuid=&search.searchBy=0&search.sortBy=sim&search.clubid=10050146" response = requests.get(url) response.status_code, response dom = BeautifulSoup(respons...
6,827
Given the following text description, write Python code to implement the functionality described below step by step Description: <img src="http Step1: Start by defining the parent catalog URL from NCI's THREDDS Data Server Note Step2: <a id='part1'></a> Using Siphon Siphon is a collection of Python utilities for do...
Python Code: from netCDF4 import Dataset import matplotlib.pyplot as plt from siphon import catalog, ncss import datetime %matplotlib inline Explanation: <img src="http://nci.org.au/wp-content/themes/nci/img/img-logo-large.png", width=400> Programmatically accessing data through THREDDS and the VDI ...using Python 3 I...
6,828
Given the following text description, write Python code to implement the functionality described below step by step Description: Equalização de Histograma A transformação de contraste que procura distribuir a ocorrência dos níveis de cinza igualmente na faixa de tons de cinza é denominada equalização de histograma. O ...
Python Code: %matplotlib inline import matplotlib.pyplot as plt import matplotlib.image as mpimg import numpy as np import sys,os ia898path = os.path.abspath('/etc/jupyterhub/ia898_1s2017/') if ia898path not in sys.path: sys.path.append(ia898path) import ia898.src as ia nb = ia.nbshow(2) f = mpimg.imread('../data/c...
6,829
Given the following text description, write Python code to implement the functionality described below step by step Description: 数据结构 这一节介绍pandas中的数据结构。首先,导入numpy和pandas Step1: 我们先对数据结构进行简短的介绍, 然后再详细说明各个数据结构内置的方法。 Series Series是一个一维带label的数组,元素可以是任何数据类型(整数、字符串、浮点数,Python对象等等)。和Python列表一样,Series元素的数据类型可以不同。Series是值可变的...
Python Code: import numpy as np import pandas as pd Explanation: 数据结构 这一节介绍pandas中的数据结构。首先,导入numpy和pandas: End of explanation s = pd.Series(np.random.randn(5), index=['a', 'b', 'c', 'd', 'e']) s s.index pd.Series(np.random.randn(5)) Explanation: 我们先对数据结构进行简短的介绍, 然后再详细说明各个数据结构内置的方法。 Series Series是一个一维带label的数组,元素可以是任何数据...
6,830
Given the following text description, write Python code to implement the functionality described below step by step Description: Custom generators Step1: Custom generator without __init__ method Step2: Explicitly setting the name of generated items Let's repeat the previous example, but explicitly set the name of ge...
Python Code: import tohu from tohu.v4.primitive_generators import * from tohu.v4.derived_generators import * from tohu.v4.dispatch_generators import * from tohu.v4.custom_generator import * from tohu.v4.utils import print_generated_sequence, make_dummy_tuples print(f'Tohu version: {tohu.__version__}') Explanation: Cust...
6,831
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: 2016-10-07 Step2: 1. L1-Regularized Logistic Regression Let us start with default parameters. Step3: Question Compute the cross-validated predictions of the l1-regularized logistic ...
Python Code: import numpy as np %pylab inline # Load the data as usual (here the code for Python 2.7) X = np.loadtxt('data/small_Endometrium_Uterus.csv', delimiter=',', skiprows=1, usecols=range(1, 3001)) y = np.loadtxt('data/small_Endometrium_Uterus.csv', delimiter=',', skiprows=1, usecols=[3001], con...
6,832
Given the following text description, write Python code to implement the functionality described below step by step Description: Carnegie Mellon Data Science Club Step1: Introduction Step2: Let us take a look at the dimension of this data frame. This is held in the shape attribute of the dataframe. Step3: We see t...
Python Code: import warnings warnings.filterwarnings("ignore") Explanation: Carnegie Mellon Data Science Club : Practical Natural Language Processing By Michael Rosenberg. Description: This notebook contains an introduction to document analysis with OkCupid data. It is designed to be used at a workshop for introducing ...
6,833
Given the following text description, write Python code to implement the functionality described below step by step Description: Visualizzazione Facebook Step1: 1. Confronto Salvini, Renzi e M5S Step2: 2. Dettaglio Salvini Step3: 2.1. Distribuzione Totale dei Likes ai Post di Salvini Step4: 2. Focus su Anni 2014, ...
Python Code: import os import pandas as pd import numpy as np import matplotlib.pyplot as plt %pylab inline matplotlib.style.use('ggplot') # Directory di Staging dir_df = os.path.join(os.path.abspath(''),'stg') dir_out = os.path.join(os.path.abspath(''),'out') # Dataset Salvini df_filename = r'df_posts_likes_salvini.pk...
6,834
Given the following text description, write Python code to implement the functionality described below step by step Description: An RNN model for temperature data This time we will be working with real data Step1: <a name="hyperparameters"></a> <a name="assignment1"></a> Hyperparameters <div class="alert alert-block ...
Python Code: import math import sys import time import numpy as np import utils_batching import utils_args import tensorflow as tf from tensorflow.python.lib.io import file_io as gfile print("Tensorflow version: " + tf.__version__) from matplotlib import pyplot as plt import utils_prettystyle import utils_display Expla...
6,835
Given the following text description, write Python code to implement the functionality described below step by step Description: ES-DOC CMIP6 Model Properties - Atmoschem MIP Era Step1: Document Authors Set document authors Step2: Document Contributors Specify document contributors Step3: Document Publication Speci...
Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'test-institute-3', 'sandbox-2', 'atmoschem') Explanation: ES-DOC CMIP6 Model Properties - Atmoschem MIP Era: CMIP6 Institute: TEST-INSTITUTE-3 Source ID: SANDBOX-2 Topic: Atmoschem Su...
6,836
Given the following text description, write Python code to implement the functionality described below step by step Description: Plot MST Measures Here we plot different MST measures from the computed connectivity matrices. Step1: MST Dataset Structure The order of frequency bands is as follows Step2: Plotting of MS...
Python Code: from pprint import pprint import scipy import pandas as pd from pandas.tools.plotting import parallel_coordinates from pandas import concat import matplotlib # Set backend to pgf matplotlib.use('pgf') import matplotlib.pyplot as plt import numpy as np # Some nice default configuration for plots plt.rcParam...
6,837
Given the following text description, write Python code to implement the functionality described below step by step Description: Re-referencing the EEG signal Load raw data and apply some EEG referencing schemes. Step1: Apply different EEG referencing schemes and plot the resulting evokeds.
Python Code: # Authors: Marijn van Vliet <w.m.vanvliet@gmail.com> # Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr> # # License: BSD (3-clause) import mne from mne.datasets import sample from matplotlib import pyplot as plt print(__doc__) # Setup for reading the raw data data_path = sample.data_pa...
6,838
Given the following text description, write Python code to implement the functionality described below step by step Description: Connecting to the database Step1: Create a list of dictionaries that have the following structure Step2: Create a dataframe from list of dicts Step3: FIVE NUMBER SUMMARY for the length of...
Python Code: conn = pg8000.connect(user = 'dot_student', database='training', port=5432, host='training.c1erymiua9dx.us-east-1.rds.amazonaws.com', password='qgis') conn.rollback() cursor = conn.cursor() cursor.execute("SELECT column_name FROM information_schema.columns WHERE table_name='dot_311'") # run the commented o...
6,839
Given the following text description, write Python code to implement the functionality described below step by step Description: Simulation Code The code below will generate a test folume and populate it with a set of clusters. Step1: Cluster Extraction Validation First, be sure that our cluster extraction algorithm ...
Python Code: def generatePointSet(): center = (rand(0, 9), rand(0, 999), rand(0, 999)) toPopulate = [] for z in range(-3, 2): for y in range(-3, 2): for x in range(-3, 2): curPoint = (center[0]+z, center[1]+y, center[2]+x) #only populate valid points ...
6,840
Given the following text description, write Python code to implement the functionality described below step by step Description: Day 23 Pre-class assignment Goals for today's pre-class assignment In this pre-class assignment, you will Step1: Task 2 Step2: Task 3 Step3: Task 4 Step4: Task 5 Step6: Assignment wrapu...
Python Code: # Put your code here! Explanation: Day 23 Pre-class assignment Goals for today's pre-class assignment In this pre-class assignment, you will: Create and slice multi-dimensional numpy arrays Plot 2D numpy arrays Make an animation of 2D numpy arrays Assignment instructions First, work through the Numpy 2D ar...
6,841
Given the following text description, write Python code to implement the functionality described below step by step Description: Query Coordianted Canyon Experiment database for BED information Connect to a remote database, select specific data using Django queries Executing this Notebook requires a personal STOQS ser...
Python Code: acts = (Activity.objects.using('stoqs_cce2015') .filter(name__contains='trajectory') .order_by('name')) Explanation: Query Coordianted Canyon Experiment database for BED information Connect to a remote database, select specific data using Django queries Executing this Notebook requires a pe...
6,842
Given the following text description, write Python code to implement the functionality described below step by step Description: Content and Objectives Show effect and validity of Wiener-Khinchin Method Step1: Parameters Step2: Signals and their spectra Step3: Plotting
Python Code: # importing import numpy as np import matplotlib.pyplot as plt import matplotlib # showing figures inline %matplotlib inline # plotting options font = {'size' : 20} plt.rc('font', **font) plt.rc('text', usetex=True) matplotlib.rc('figure', figsize=(18, 10) ) Explanation: Content and Objectives Show effe...
6,843
Given the following text description, write Python code to implement the functionality described below step by step Description: Real-time Patient Montioring with Streams and BioPy This notebook shows how to use Python to analyze medical data in real time using Streams and existing Python modules like BioSPPY and SciP...
Python Code: from icpd_core import icpd_util from streamsx.topology.context import JobConfig from streamsx.topology import context streams_instance_name = ## Change this to Streams instance try: cfg=icpd_util.get_service_instance_details(name=streams_instance_name, instance_type="streams") except TypeError: cf...
6,844
Given the following text description, write Python code to implement the functionality described below step by step Description: <center> <a href="http Step1: La commande suivante permet de verifier qu'une carte GPU est bien disponible sur la machine utilisée. Si c'est le cas et si Keras a bien été installé dans la c...
Python Code: # Utils import sys import os import shutil import time import pickle import numpy as np # Deep Learning Librairies import tensorflow as tf import keras.preprocessing.image as kpi import keras.layers as kl import keras.optimizers as ko import keras.backend as k import keras.models as km import keras.applica...
6,845
Given the following text description, write Python code to implement the functionality described below step by step Description: Random Variables Frequently, when an experiment is performed, we are interested mainly in some function of the outcome as opposed to the actual outcome itself. For instance,<br> 1) In recent...
Python Code: %matplotlib inline import numpy as np import pandas as pd from itertools import product # from IPython.core.display import HTML # css = open('media/style-table.css').read() + open('media/style-notebook.css').read() # HTML('<style>{}</style>'.format(css)) one_toss = np.array(['H', 'T']) two_tosses = list(pr...
6,846
Given the following text description, write Python code to implement the functionality described below step by step Description: Segmentation Step1: Load the volume, it contains two spheres. You can either identify the regions of interest (ROIs) yourself or use the predefined rectangular regions of interest specified...
Python Code: import SimpleITK as sitk %run update_path_to_download_script from downloaddata import fetch_data as fdata %matplotlib notebook import gui import matplotlib.pyplot as plt import numpy as np from scipy import linalg from ipywidgets import interact, fixed Explanation: Segmentation: Thresholding and Edge Detec...
6,847
Given the following text description, write Python code to implement the functionality described below step by step Description: Generative Adversarial Network In this notebook, we'll be building a generative adversarial network (GAN) trained on the MNIST dataset. From this, we'll be able to generate new handwritten d...
Python Code: %matplotlib inline import pickle as pkl import numpy as np import tensorflow as tf import matplotlib.pyplot as plt from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets('MNIST_data') Explanation: Generative Adversarial Network In this notebook, we'll be building a gen...
6,848
Given the following text description, write Python code to implement the functionality described below step by step Description: Using sci-analysis with pandas Pandas is a python package that simplifies working with tabular or relational data. Because columns and rows of data in a pandas DataFrame are naturally array-...
Python Code: import warnings warnings.filterwarnings("ignore") %matplotlib inline import numpy as np import scipy.stats as st from sci_analysis import analyze import pandas as pd np.random.seed(987654321) df = pd.DataFrame( { 'ID' : np.random.randint(10000, 50000, size=60).astype(str), 'One' ...
6,849
Given the following text description, write Python code to implement the functionality described below step by step Description: Data input for BIDS datasets DataGrabber and SelectFiles are great if you are dealing with generic datasets with arbitrary organization. However if you have decided to use Brain Imaging Data...
Python Code: from bids.grabbids import BIDSLayout layout = BIDSLayout("/data/ds102/") !tree /data/ds102/ Explanation: Data input for BIDS datasets DataGrabber and SelectFiles are great if you are dealing with generic datasets with arbitrary organization. However if you have decided to use Brain Imaging Data Structure (...
6,850
Given the following text description, write Python code to implement the functionality described below step by step Description: Step2: k - means Randomly select starting locations for k points Assign data points to closest k point If no data changed its cluster membership stop If there was a change, compute new means...
Python Code: class KMeans: k-means algo def __init__(self, k): self.k = k # number of clusters self.means = None # means of clusters def classify(self, input): return the index of the cluster to closest to input return min(range(self.k), key = ...
6,851
Given the following text description, write Python code to implement the functionality described below step by step Description: This script is dedicated to querying all needed statistics for the project. Step1: Helpers Step2: Distribution of job posts among job titles Step3: Job posts distribution among standard j...
Python Code: import my_util as my_util; from my_util import * HOME_DIR = 'd:/larc_projects/job_analytics/' DATA_DIR = HOME_DIR + 'data/clean/' title_df = pd.read_csv(DATA_DIR + 'new_titles_2posts_up.csv') Explanation: This script is dedicated to querying all needed statistics for the project. End of explanation def dis...
6,852
Given the following text problem statement, write Python code to implement the functionality described below in problem statement Problem: making predictions for a regression problem
Python Code:: from keras.models import Sequential from keras.layers import Dense from sklearn.datasets import make_regression from sklearn.preprocessing import MinMaxScaler from numpy import array X, y = make_regression(n_samples=100, n_features=2, noise=0.1, random_state=1) scalarX, scalarY = MinMaxScaler(), MinMaxSca...
6,853
Given the following text description, write Python code to implement the functionality described below step by step Description: Unit Models Exploration of model for basic constituent units of a neural network. Perceptron Starting with the perceptron, an early version model based on binary inputs and step function. St...
Python Code: # weights W = np.array([-2,-2]) # bias b = 3 # threshold. Can be discarded using the bias instead (bias=-threshold) #threshold = 3 # perceptron firing rule perceptron = lambda x : 1 if np.dot(X, W) + b >0 else 0 # input array X = np.array([1,1]) # compute perceptron output perceptron(X) Explanation: Unit M...
6,854
Given the following text description, write Python code to implement the functionality described below step by step Description: Mini-Assignment 2 Step1: Let's have a look at what the data looks like for our example paper Step5: Some Utility Functions We'll define some utility functions that allow us to tokenize a s...
Python Code: Summaries_file = 'data/malaria__Summaries.pkl.bz2' Abstracts_file = 'data/malaria__Abstracts.pkl.bz2' import pickle, bz2 from collections import namedtuple Summaries = pickle.load( bz2.BZ2File( Summaries_file, 'rb' ) ) paper = namedtuple( 'paper', ['title', 'authors', 'year', 'doi'] ) for (id, paper_info) ...
6,855
Given the following text description, write Python code to implement the functionality described below step by step Description: Minimizing a <span style="font-variant Step1: The function cart_prod(A, B) computes the Cartesian product $A \times B$ of the sets $A$ and $B$ where $A \times B$ is defined as follows Step2...
Python Code: def arb(M): for x in M: return x assert False, 'Error: arb called with empty set!' Explanation: Minimizing a <span style="font-variant:small-caps;">Fsm</span> The function arb(M) takes a non-empty set M as its argument and returns an arbitrary element from this set. The set M is not changed...
6,856
Given the following text description, write Python code to implement the functionality described below step by step Description: API calls Step1: Now, we can all the rows together to print the tweets with one run. Try/except is also added to except possible errors. Step2: User tweets The library also provides the op...
Python Code: from TwitterSearch import * with open('token.txt','r') as f: token = f.read().split() # pass your credentials to the TwitterSearch class to create and object called "ts" ts = TwitterSearch( consumer_key = token[0], consumer_secret = token[1], access_token = token[2], access_token_secret = token[3] ) ts...
6,857
Given the following text description, write Python code to implement the functionality described below step by step Description: SAM This notebook explores parsing and understanding the SAM (Sequence Alignment/Map) and related BAM format. SAM is an extremely common format for representing read alignments. Most widel...
Python Code: # Here's a string representing a three-line SAM file. I'm temporarily # ignoring the fact that SAM files usually have several header lines at # the beginning. samStr = '''\ r1 0 gi|9626243|ref|NC_001416.1| 18401 42 122M * 0 0 TGAATGCGAACTCCGGGACGCTCAGTAATGTGACGATAGCTGAAAACTGTACGATAAACNGTACGCTGAGGGCAGAAAAA...
6,858
Given the following text description, write Python code to implement the functionality described below step by step Description: NumPy 문제1. NumPy 명령을 사용하여 다음 행렬을 생성하는 코드를 1줄로 작성하세요. Step1: 문제2. X 행렬이 다음과 같을 때 NumPy 슬라이싱 인덱싱을 사용하여 행렬의 짝수 부분만을 선택하여 행렬로 만드는 NumPy코드를 작성하세요.(행렬 인덱싱을 사용하지 말 것!) Step2: 문제3. X행렬이 다음과 같을 때 행...
Python Code: X = np.array([[11, 12], [21, 22], [31, 32]]) X Explanation: NumPy 문제1. NumPy 명령을 사용하여 다음 행렬을 생성하는 코드를 1줄로 작성하세요. End of explanation X = np.array([[1,1,1,1], [1,2,4,8], [1,3,5,7], [1,4,16,32], [1,5,9,13]]) X X[1::2, 1:] Explanation: 문제2. X 행렬이 다음과 같을 때 NumPy 슬라이싱 인덱싱을 사용하여 행렬의 짝수 부분만을 선택하여 행렬로 만드는 NumPy코드를 ...
6,859
Given the following text description, write Python code to implement the functionality described below step by step Description: Part 1 - Setup We will be using * PIL (Python Image Library) for getting the picture * pytesseract for the OCR (Object Character Recognition) * googlemaps and gmaps for mapping Step1: Pa...
Python Code: from PIL import Image import pytesseract import googlemaps import gmaps as jupmap import sys from datetime import datetime # get my private keys for google maps and gmaps f = open('private.key', 'r') for line in f: temp = line.rstrip('').replace(',','').replace('\n','').split(" ") exec(temp[0])...
6,860
Given the following text description, write Python code to implement the functionality described below step by step Description: Übung 2 Problem 2.1 - Lineare Regression mit Least Squares Step1: Numpy Dokumentation Step2: Versuch zur Bestimmung einer linearen Gleichungsfunktion. Hier wird die händische Berechnung du...
Python Code: import matplotlib.pyplot as plt import numpy as np plt.style.use('ggplot') Explanation: Übung 2 Problem 2.1 - Lineare Regression mit Least Squares End of explanation def print_sample(genfromtxt): # column names print(genfromtxt.dtype.names) # data for row in genfromtxt[:min((len(g...
6,861
Given the following text description, write Python code to implement the functionality described below step by step Description: Machine Learning - Hands on Lab - Session #1 Lecturer Step1: 2. Re-Import the Check NaN Function from Part 2 Step2: 3. Loading in the Data from Session #2 Step3: 3. Transforming Categoric...
Python Code: import os from datetime import datetime import numpy as np import pandas as pd import sklearn as sk Explanation: Machine Learning - Hands on Lab - Session #1 Lecturer: Jonathan DEKHTIAR Date: 2017-03-13 <br/><br/> Contact: contact@jonathandekhtiar.eu Twitter: @born2data LinkedIn: JonathanDEKHTIAR Personal ...
6,862
Given the following text description, write Python code to implement the functionality described below step by step Description: Python Python présente plusieurs avantage à l'origine de son choix pour ce cours Step1: Nombres Step2: Chaînes de caractères Step3: Listes et dictionnaires Step4: Structures de contrôle ...
Python Code: print 'Hello World !' a = 5. b = 7. a + b Explanation: Python Python présente plusieurs avantage à l'origine de son choix pour ce cours: C'est un langage généraliste présent dans de nombreuses domaines: calcul scientifique, web, bases de données, jeu vidéo, graphisme, etc. C'est un outil polyvalent qu'un i...
6,863
Given the following text description, write Python code to implement the functionality described below step by step Description: Bayesian Statistics Step1: Is that counter-intuitive? Not really... The false positive rate is actually fairly high, and with the numbers as given, the chance is about ten times higher that...
Python Code: P_positive_if_ill = .99 P_positive_if_notill = .01 P_ill = 1.e-3 P_notill = 1 - P_ill print("P_ill_if_positive = ", P_positive_if_ill * P_ill / (P_positive_if_ill * P_ill + P_positive_if_notill * P_notill )) Explanation: Bayesian Statistics: the what, the why, and the how This notebook contains illu...
6,864
Given the following text description, write Python code to implement the functionality described below step by step Description: Auto-Batched Joint Distributions Step1: <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https Step2: 전제 조건 Step3: 데시데라타(Desiderata) 확률적 추론에서는 종종 두 가지...
Python Code: #@title Licensed under the Apache License, Version 2.0 (the "License"); { display-mode: "form" } # 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...
6,865
Given the following text description, write Python code to implement the functionality described below step by step Description: Experiment logger The logger stores experimental data in a single SQLite database. It is intended to be fast and lightweight, but record all necessary meta data and timestamps for experiment...
Python Code: # import sqlexperiment as sqle # from sqlexperiment import experimentlog from explogger import ExperimentLog # log some JSON data e = ExperimentLog(":memory:", ntp_sync=False) e.log("mouse", data={"x":0, "y":0}) e.log("mouse", data={"x":0, "y":1}) e.log("mouse", data={"x":0, "y":2}) e.close() # from experi...
6,866
Given the following text description, write Python code to implement the functionality described below step by step Description: Кафедра дискретной математики МФТИ Курс математической статистики Никита Волков На основе http Step1: Можно преобразовать список в массив. Step2: print печатает массивы в удобной форме. St...
Python Code: import numpy as np Explanation: Кафедра дискретной математики МФТИ Курс математической статистики Никита Волков На основе http://www.inp.nsk.su/~grozin/python/ Библиотека numpy Пакет numpy предоставляет $n$-мерные однородные массивы (все элементы одного типа); в них нельзя вставить или удалить элемент в пр...
6,867
Given the following text description, write Python code to implement the functionality described below step by step Description: Batch Normalization – Practice Batch normalization is most useful when building deep neural networks. To demonstrate this, we'll create a convolutional neural network with 20 convolutional l...
Python Code: import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("MNIST_data/", one_hot=True, reshape=False) Explanation: Batch Normalization – Practice Batch normalization is most useful when building deep neural networks. To demonstrate this, we'll crea...
6,868
Given the following text description, write Python code to implement the functionality described below step by step Description: ============================================== Read and visualize projections (SSP and other) ============================================== This example shows how to read and visualize Sign...
Python Code: # Author: Joan Massich <mailsik@gmail.com> # # License: BSD (3-clause) import matplotlib.pyplot as plt import mne from mne import read_proj from mne.io import read_raw_fif from mne.datasets import sample print(__doc__) data_path = sample.data_path() subjects_dir = data_path + '/subjects' fname = data_path ...
6,869
Given the following text description, write Python code to implement the functionality described below step by step Description: Built-in plotting methods for Raw objects This tutorial shows how to plot continuous data as a time series, how to plot the spectral density of continuous data, and how to plot the sensor lo...
Python Code: import os import mne sample_data_folder = mne.datasets.sample.data_path() sample_data_raw_file = os.path.join(sample_data_folder, 'MEG', 'sample', 'sample_audvis_raw.fif') raw = mne.io.read_raw_fif(sample_data_raw_file) raw.crop(tmax=60).load_data() Explanation: Built-in...
6,870
Given the following text description, write Python code to implement the functionality described below step by step Description: Installation Ideally, before installation, create a clean python3 virtual environment to deploy the package, using virtualenvwrapper for example (see http Step1: Installation with pip from ...
Python Code: #### REMOVE in README.md #### import JGV as package from IPython.core.display import display, Markdown if "__install_requires__" in package.__dict__: display(Markdown("## Python packages dependencies:\n")) for dep in package.__install_requires__: display(Markdown("* {}\n".format(dep))) ####...
6,871
Given the following text description, write Python code to implement the functionality described below step by step Description: Relationships in the GO Alex Warwick Vesztrocy, March 2016 For some analyses, it is possible to only use the <code>is_a</code> definitions given in the Gene Ontology. However, it is importa...
Python Code: import os from goatools.obo_parser import GODag if not os.path.exists('go-basic.obo'): !wget http://geneontology.org/ontology/go-basic.obo go = GODag('go-basic.obo', optional_attrs=['relationship']) Explanation: Relationships in the GO Alex Warwick Vesztrocy, March 2016 For some analyses, it is possibl...
6,872
Given the following text description, write Python code to implement the functionality described below step by step Description: <img src="../static/images/iterables.png" width="240"> Iterables Some steps in a neuroimaging analysis are repetitive. Running the same preprocessing on multiple subjects or doing statistic...
Python Code: from nipype import Node, Workflow from nipype.interfaces.fsl import BET, IsotropicSmooth # Initiate a skull stripping Node with BET skullstrip = Node(BET(mask=True, in_file='/data/ds000114/sub-01/ses-test/anat/sub-01_ses-test_T1w.nii.gz'), name="skullstrip") Explanat...
6,873
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2021 The TensorFlow Hub Authors. Licensed under the Apache License, Version 2.0 (the "License"); Step1: Transfer Learning for the Audio Domain with Model Maker In this notebook, y...
Python Code: # Copyright 2021 The TensorFlow Hub Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless re...
6,874
Given the following text description, write Python code to implement the functionality described below step by step Description: Sorting Objects in Instance Catalogs Bryce Kalmbach This notebook provides a series of commands that take a Twinkles Phosim Instance Catalog and creates different pandas dataframes for diffe...
Python Code: import pandas as pd import numpy as np Explanation: Sorting Objects in Instance Catalogs Bryce Kalmbach This notebook provides a series of commands that take a Twinkles Phosim Instance Catalog and creates different pandas dataframes for different types of objects in the catalog. It first separates the full...
6,875
Given the following text description, write Python code to implement the functionality described below step by step Description: Regression (predicting unmasked value given (x, y, z, synapses)) Step 1 Step1: Now graphing this data Step2: Step 4/5/6 part b Step3: Now graphing it Step4: Step 7
Python Code: import numpy as np import matplotlib.pyplot as plt import urllib2 %matplotlib inline sample_size = 10000 k_fold = 10 np.random.seed(1) url = ('https://raw.githubusercontent.com/Upward-Spiral-Science' '/data/master/syn-density/output.csv') data = urllib2.urlopen(url) csv = np.genfromtxt(data, delimit...
6,876
Given the following text description, write Python code to implement the functionality described below step by step Description: Transfer Learning Most of the time you won't want to train a whole convolutional network yourself. Modern ConvNets training on huge datasets like ImageNet take weeks on multiple GPUs. Instea...
Python Code: from urllib.request import urlretrieve from os.path import isfile, isdir from tqdm import tqdm vgg_dir = 'tensorflow_vgg/' # Make sure vgg exists if not isdir(vgg_dir): raise Exception("VGG directory doesn't exist!") class DLProgress(tqdm): last_block = 0 def hook(self, block_num=1, block_size=...
6,877
Given the following text description, write Python code to implement the functionality described below step by step Description: <h1>Table de matières<span class="tocSkip"></span></h1> <div class="toc"><ul class="toc-item"><li><span><a href="#Un-exercice-d'algorithmique---mise-en-page-de-paragraphe,-résolutions-gourma...
Python Code: %%bash cat << EOF AA AA AA AA AA AA B ; AA AA AA AA AA AA B ; EOF > /tmp/test_nongreedy_optimal.txt cat /tmp/test_nongreedy_optimal.txt %%bash cat << EOF AA AA AA AA AA AA B AA AA AA AA AA AA ; B ; EOF > test_greedy_suboptimal.txt ca...
6,878
Given the following text description, write Python code to implement the functionality described below step by step Description: You are currently looking at version 1.2 of this notebook. To download notebooks and datafiles, as well as get help on Jupyter notebooks in the Coursera platform, visit the Jupyter Notebook ...
Python Code: import pandas as pd df = pd.read_csv('olympics.csv', index_col=0, skiprows=1) for col in df.columns: if col[:2]=='01': df.rename(columns={col:'Gold'+col[4:]}, inplace=True) if col[:2]=='02': df.rename(columns={col:'Silver'+col[4:]}, inplace=True) if col[:2]=='03': df.ren...
6,879
Given the following text description, write Python code to implement the functionality described below step by step Description: Solving the Cournot Oligopoly Model by Collocation DEMAPP09 Cournot Oligopolist Problem <br> This example is taken from section 6.8.1, page(s) 159-162 of Step1: and set the $\alpha$ and $\e...
Python Code: %matplotlib inline import numpy as np import matplotlib.pyplot as plt from compecon import BasisChebyshev, NLP, nodeunif from compecon.demos import demo Explanation: Solving the Cournot Oligopoly Model by Collocation DEMAPP09 Cournot Oligopolist Problem <br> This example is taken from section 6.8.1, page(s...
6,880
Given the following text description, write Python code to implement the functionality described below step by step Description: Dolsek and Fajfar (2004) This methodology makes use of work by Dolsek and Fajfar (2004) to estimate the inelastic displacement of a SDOF system based on its elastic displacement and the prop...
Python Code: from rmtk.vulnerability.derivation_fragility.R_mu_T_no_dispersion.dolsek_fajfar import DF2004 from rmtk.vulnerability.common import utils %matplotlib inline Explanation: Dolsek and Fajfar (2004) This methodology makes use of work by Dolsek and Fajfar (2004) to estimate the inelastic displacement of a SDOF...
6,881
Given the following text description, write Python code to implement the functionality described below step by step Description: Отчет по Лабоработной работе №3 Результаты определения параметров кэш-памяти Описание процессора моего ноутбука с сайта cpu-world.com Step1: Графики по данным, полученным из main_tooled.cpp...
Python Code: %matplotlib inline from matplotlib import pyplot def prepare_stats(path='compact_report_stats.txt'): graph = dict() curStats = list() for line in open(path): k,v = map(str.strip, line.strip().split('=')) if k == 'n': curStats = dict() graph.setdefault(int...
6,882
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright &copy; 2020 The TensorFlow Authors. 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 ...
Python Code: try: import colab !pip install --upgrade pip except: pass !pip install -Uq tfx==0.25.0 !pip install -Uq tensorflow-text # The tf-text version needs to match the tf version print("Restart your runtime enable after installing the packages") Explanation: Copyright &copy; 2020 The TensorFlow Autho...
6,883
Given the following text description, write Python code to implement the functionality described below step by step Description: 1. Install Dependencies First install the libraries needed to execute recipes, this only needs to be done once, then click play. Step1: 2. Get Cloud Project ID To run this recipe requires a...
Python Code: !pip install git+https://github.com/google/starthinker Explanation: 1. Install Dependencies First install the libraries needed to execute recipes, this only needs to be done once, then click play. End of explanation CLOUD_PROJECT = 'PASTE PROJECT ID HERE' print("Cloud Project Set To: %s" % CLOUD_PROJECT) E...
6,884
Given the following text description, write Python code to implement the functionality described below step by step Description: This notebook implements an array-based version of Heapsort. Heapsort The function call swap(A, i, j) takes an array A and two indexes i and j and exchanges the elements at these indexes. S...
Python Code: def swap(A, i, j): A[i], A[j] = A[j], A[i] Explanation: This notebook implements an array-based version of Heapsort. Heapsort The function call swap(A, i, j) takes an array A and two indexes i and j and exchanges the elements at these indexes. End of explanation def sink(A, k, n): while 2 * k + 1 ...
6,885
Given the following text description, write Python code to implement the functionality described below step by step Description: Average driving speed against GDP In this post I will attempt to combine two datasets I have worked on. Firstly the Average driving speeds by country as estimated by Google's location API, a...
Python Code: df_GDP = pd.read_csv("../data_sets/GDP_by_Country_WorldBank/ny.gdp.mktp.cd_Indicator_en_csv_v2.csv", quotechar='"', skiprows=2) colnames_to_drop = df_GDP.columns[np.array([2, 3, -2, -1])] for c in colnames_to_drop: df_GDP.drop(c, 1, inplace=True) df_GDP = df_GDP[~df_GDP['Country ...
6,886
Given the following text description, write Python code to implement the functionality described below step by step Description: 1. _ builtin _ 模块 1.1 apply Step1: 效果等同于: Step2: 那为什么要使用apply呢? Step3: 何谓“关键字参数”? apply使用字典传递关键字参数,实际上就是字典的键是函数的参数名,字典的值是函数的实际参数值。(相对于形参和实参) 根据上面的例子看,如果部分传递,只能传递后面的关键字参数,不能传递前面的。???? a...
Python Code: def function(a,b): print a, b apply(function, ("wheather", "Canada?")) apply(function, (1, 3+5)) Explanation: 1. _ builtin _ 模块 1.1 apply:使用元组或字典中的参数调用函数 Python 允许你实时地创建函数参数列表. 只要把所有的参数放入一个元组中,然后通过内建的 apply 函数调用函数. End of explanation function("wheather", "Canada?") function(1, 3+5) Explanation: 效果等同于:...
6,887
Given the following text description, write Python code to implement the functionality described below step by step Description: author Step1: Let's try plotting the results. We first need to import the required libraries and methods Step2: Next, we create numpy arrays to store the (x,y) values Step3: We have to re...
Python Code: T0 = 10. # initial temperature Ts = 83. # temp. of the environment r = 0.1 # cooling rate dt = 0.05 # time step tmax = 60. # maximum time nsteps = int(tmax/dt) # number of steps T = T0 for i in range(1,nsteps+1): new_T = T - r*(T-Ts)*dt T = new_T print i,i*dt, T # we can also do t ...
6,888
Given the following text description, write Python code to implement the functionality described below step by step Description: Lecture 8 Step1: Indexing would still work as you would expect, but looping through a matrix--say, to do matrix multiplication--would be laborious and highly inefficient. We'll demonstrate ...
Python Code: matrix = [[ 1, 2, 3], [ 4, 5, 6], [ 7, 8, 9] ] print(matrix) Explanation: Lecture 8: Advanced Data Structures CBIO (CSCI) 4835/6835: Introduction to Computational Biology Overview and Objectives Before we get to some of the more advanced sequence analysis techniques, we need to cover s...
6,889
Given the following text description, write Python code to implement the functionality described below step by step Description: 304 - Medical Entity Extraction with a BiLSTM In this tutorial we use a Bidirectional LSTM entity extractor from the MMLSPark model downloader to extract entities from PubMed medical abstrac...
Python Code: from mmlspark import CNTKModel, ModelDownloader from pyspark.sql.functions import udf, col from pyspark.sql.types import IntegerType, ArrayType, FloatType, StringType from pyspark.sql import Row from os.path import abspath, join import numpy as np import pickle from nltk.tokenize import sent_tokenize, word...
6,890
Given the following text description, write Python code to implement the functionality described below step by step Description: <a href="http Step1: 1. Create the river network model grid First, we need to create a Landlab NetworkModelGrid to represent the river network. Each link on the grid represents a reach of r...
Python Code: import warnings warnings.filterwarnings("ignore") import matplotlib.pyplot as plt import numpy as np from landlab.components import FlowDirectorSteepest, NetworkSedimentTransporter from landlab.data_record import DataRecord from landlab.grid.network import NetworkModelGrid from landlab.plot import graph fr...
6,891
Given the following text description, write Python code to implement the functionality described below step by step Description: Representing Data and Engineering Features Categorical Variables One-Hot-Encoding (Dummy variables) Step1: Checking string-encoded categorical data Step2: Numbers can encode categoricals S...
Python Code: import pandas as pd # The file has no headers naming the columns, so we pass header=None and provide the column names explicitly in "names" data = pd.read_csv("data/adult.data", header=None, index_col=False, names=['age', 'workclass', 'fnlwgt', 'education', 'education-num', ...
6,892
Given the following text description, write Python code to implement the functionality described below step by step Description: Self-Driving Car Engineer Nanodegree Project Step1: Read in an Image Step9: Ideas for Lane Detection Pipeline Some OpenCV functions (beyond those introduced in the lesson) that might be us...
Python Code: #importing some useful packages import matplotlib.pyplot as plt import matplotlib.image as mpimg import numpy as np import cv2 %matplotlib inline Explanation: Self-Driving Car Engineer Nanodegree Project: Finding Lane Lines on the Road In this project, you will use the tools you learned about in the lesson...
6,893
Given the following text description, write Python code to implement the functionality described below step by step Description: <h1>Data setup</h1> <h2>Use our function to read the data file</h2> Step1: <h1>Plotting data on google maps</h1> <h2>gmplot library</h2> https Step2: <h3>Our data dataframe contains latitu...
Python Code: def read_311_data(datafile): import pandas as pd import numpy as np #Add the fix_zip function def fix_zip(input_zip): try: input_zip = int(float(input_zip)) except: try: input_zip = int(input_zip.split('-')[0]) except:...
6,894
Given the following text description, write Python code to implement the functionality described below step by step Description: Advanced Step1: Let's get started with some basic imports. Step2: Overriding Computation Times If compute_times is not empty (by either providing compute_times or compute_phases), the prov...
Python Code: #!pip install -I "phoebe>=2.3,<2.4" Explanation: Advanced: compute_times & compute_phases Setup Let's first make sure we have the latest version of PHOEBE 2.3 installed (uncomment this line if running in an online notebook session such as colab). End of explanation import phoebe from phoebe import u # unit...
6,895
Given the following text description, write Python code to implement the functionality described below step by step Description: Chopsticks! A few researchers set out to determine the optimal length of chopsticks for children and adults. They came up with a measure of how effective a pair of chopsticks performed, call...
Python Code: import pandas as pd # pandas is a software library for data manipulation and analysis # We commonly use shorter nicknames for certain packages. Pandas is often abbreviated to pd. # hit shift + enter to run this cell or block of code path = '/Users/Slimn/Desktop/Work/Project/Udacity/NanoDegree/P0/chopstick-...
6,896
Given the following text description, write Python code to implement the functionality described below step by step Description: What is the True Normal Human Body Temperature? Background The mean normal body temperature was held to be 37$^{\circ}$C or 98.6$^{\circ}$F for more than 120 years since it was first concept...
Python Code: import pandas as pd import matplotlib.pyplot as plt import numpy as np from scipy import stats df = pd.read_csv('data/human_body_temperature.csv') df.head() Explanation: What is the True Normal Human Body Temperature? Background The mean normal body temperature was held to be 37$^{\circ}$C or 98.6$^{\circ}...
6,897
Given the following text description, write Python code to implement the functionality described below step by step Description: 说明 目的: 为探讨在同一个样本点集下,cma-es算法对$f(x)$拟合效果与分段数的关系,实验记录每个分段方案下cma-es过程的迭代时间,关系矩阵变化过程,计算结果,cpu计算时间等进行对比。 函数: <center>$ f(x)=10sin0.6x+uniform(-1.5,1.5)gauss(0,5),x \in[-7,7)$ </center> 分段: ...
Python Code: import makeData as md %pylab inline plt.rc('figure', figsize=(16, 9)) X=md.loadData('result.tl') import numpy as np import pandas as pd b=[] for i in range(5,35,5): temp=[] for j in range(3): temp.append(X[i][j]['iter']) b.append(temp) bs=np.array(b).T ind=range(5,35,5) d={'M1':pd.Serie...
6,898
Given the following text description, write Python code to implement the functionality described below step by step Description: Sentiment Analysis with an RNN In this notebook, you'll implement a recurrent neural network that performs sentiment analysis. Using an RNN rather than a feedfoward network is more accurate ...
Python Code: import numpy as np import tensorflow as tf with open('../sentiment_network/reviews.txt', 'r') as f: reviews = f.read() with open('../sentiment_network/labels.txt', 'r') as f: labels = f.read() reviews[:2000] Explanation: Sentiment Analysis with an RNN In this notebook, you'll implement a recurrent ...
6,899
Given the following text description, write Python code to implement the functionality described below step by step Description: Executed Step1: The data has been generated by running the template notebook usALEX-5samples-PR-raw-dir_ex_aa-fit-AexAem for each sample. To recompute the PR data used by this notebook run ...
Python Code: data_file = 'results/usALEX-5samples-PR-raw-dir_ex_aa-fit-AexAem.csv' Explanation: Executed: Mon Mar 27 11:38:35 2017 Duration: 3 seconds. Direct ecitation coefficient fit This notebook estracts the direct excitation coefficient from the set of 5 us-ALEX smFRET measurements. What it does? This notebook per...