Unnamed: 0
int64
0
16k
text_prompt
stringlengths
110
62.1k
code_prompt
stringlengths
37
152k
14,700
Given the following text description, write Python code to implement the functionality described below step by step Description: Loading data Step1: Add counts for each type into buildings Step2: Normalize longitude and latitude Step3: Analysis features Step4: Cross Validation Step5: According to this simplified ...
Python Code: buildings = pd.read_csv("../data/buildings.csv") events = pd.read_csv("../data/events.csv") buildings.head(2) events.head(2) events['type'].value_counts() # types: 1: 311-calls, 2: crimes, 3: blight violations Explanation: Loading data End of explanation def str_to_list(events_str): events_list = eve...
14,701
Given the following text description, write Python code to implement the functionality described below step by step Description: Python II Hausaufgaben 1.Baue eine Funktion mit dem Namen 'double', der die Zahl 5 vedoppelt Step1: 2.Baue einen for-loop, der durch vordefinierte Zahlen-list geht, und mithilfe der eben kr...
Python Code: def double(number): result = number*2 return result double(5) Explanation: Python II Hausaufgaben 1.Baue eine Funktion mit dem Namen 'double', der die Zahl 5 vedoppelt: End of explanation lst = list(range(1,5)) for elem in lst: print(double(elem)) Explanation: 2.Baue einen for-loop, der durch v...
14,702
Given the following text description, write Python code to implement the functionality described below step by step Description: Reading and manipulating datasets with Pandas This notebook shows how to create Series and Dataframes with Pandas. Also, how to read CSV files and creaate pivot tables. The first part is bas...
Python Code: import numpy as np from __future__ import print_function import pandas as pd pd.__version__ Explanation: Reading and manipulating datasets with Pandas This notebook shows how to create Series and Dataframes with Pandas. Also, how to read CSV files and creaate pivot tables. The first part is based on the c...
14,703
Given the following text description, write Python code to implement the functionality described below step by step Description: Readable Syntax - Quicksort in Python Quicksort Pseudocode from Wikipedia Here the Python implementation Step1: Interactive and Batch possibilities - Munich temperatures Step2: Python is n...
Python Code: import random # A python implementation of the Wikipedia quicksort algorithm def my_quicksort(array): if len(array) < 1: return array pivot = array[0] # select a pivot (first element of list) rest = array[1:] # the array with the pivot # removed less = [x f...
14,704
Given the following text description, write Python code to implement the functionality described below step by step Description: <h1>Getting started with the computational analysis of games Step1: Gambit version 16.0.0 is the current development version. You can get it from http Step2: Inspecting a game The game th...
Python Code: import gambit Explanation: <h1>Getting started with the computational analysis of games:</h1> <h2>Playing "stripped down" poker</h2> <i>Theodore L. Turocy</i><br/> <i>University of East Anglia</i> <br/><br/> <h3>EC'16 Workshop 24 July 2016</h3> End of explanation gambit.__version__ Explanation: Gambit vers...
14,705
Given the following text description, write Python code to implement the functionality described below step by step Description: Pynetics QuickStart In this example we are going to build a very simple and useless algorithm to explore the possibilities of the pynetics library. Our problem will be as follows. We'll goin...
Python Code: from pynetics.ga_bin import BinaryIndividualSpawningPool # Let's define the size of our individuals (the numer of 1's and 0's) individual_size = 25 binary_individual_spawning_pool=BinaryIndividualSpawningPool(size=individual_size) Explanation: Pynetics QuickStart In this example we are going to build a ver...
14,706
Given the following text description, write Python code to implement the functionality described below step by step Description: 20 NEWS GROUPS Antes de nada, hay que importar los paquetes necesarios. Step1: Lectura de los datos A continuación, se define una función para cargar los datos que se encuentran en las carp...
Python Code: %pylab inline from sklearn import datasets Explanation: 20 NEWS GROUPS Antes de nada, hay que importar los paquetes necesarios. End of explanation def loadDataset(directory): dataset = datasets.load_files(directory) print "Loaded %d documents" % len(dataset.data) print "Loaded %d categorie...
14,707
Given the following text description, write Python code to implement the functionality described below step by step Description: 5 minutes to creating your first Machine Learning model There's a number of services out there that make Machine Learning accessible to the masses by abstracting away the complexities of cre...
Python Code: BIGML_USERNAME = '' # fill in your username between the quotes BIGML_API_KEY = '' # fill in your API key BIGML_AUTH = 'username=' + BIGML_USERNAME + ';api_key=' + BIGML_API_KEY # leave as it is print "Authentication variables set!" Explanation: 5 minutes to creating your first Machine Learning model There'...
14,708
Given the following text description, write Python code to implement the functionality described below step by step Description: Step2: Más Álgebra lineal con Python Esta notebook fue creada originalmente como un blog post por Raúl E. López Briega en Matemáticas, análisis de datos y python. El contenido esta bajo la l...
Python Code: # <!-- collapse=True --> # importando modulos necesarios %matplotlib inline import matplotlib.pyplot as plt import numpy as np import scipy.sparse as sp import scipy.sparse.linalg import scipy.linalg as la import sympy # imprimir con notación matemática. sympy.init_printing(use_latex='mathjax') # <!-- coll...
14,709
Given the following text description, write Python code to implement the functionality described below step by step Description: Contest entry by Wouter Kimman Strategy Step1: First steps, reading in and exploring the data are the same as Brendon's steps Step2: 1) Prediction from training set using all wells Let's d...
Python Code: from numpy.fft import rfft from scipy import signal import numpy as np import matplotlib.pyplot as plt import plotly.plotly as py import pandas as pd import timeit from sqlalchemy.sql import text from sklearn import tree from sklearn import cross_validation from sklearn.cross_validation import train_test_s...
14,710
Given the following text description, write Python code to implement the functionality described below step by step Description: Dual CRISPR Screen Analysis Count Plots Amanda Birmingham, CCBB, UCSD (abirmingham@ucsd.edu) Instructions To run this notebook reproducibly, follow these steps Step1: Matplotlib Display Ste...
Python Code: g_timestamp = "" g_dataset_name = "20160510_A549" g_count_alg_name = "19mer_1mm_py" g_fastq_counts_dir = '/Users/Birmingham/Repositories/ccbb_tickets/20160210_mali_crispr/data/interim/20160510_D00611_0278_BHK55CBCXX_A549' g_fastq_counts_run_prefix = "19mer_1mm_py_20160615223822" g_collapsed_counts_dir = "/...
14,711
Given the following text description, write Python code to implement the functionality described below step by step Description: Income dataset https Step1: Merged income, zipcode, and station id for final dataframe
Python Code: income = pd.read_excel("../data/unique/ACS_14_5YR_B19013.xls") income = income.loc[8:] income.head() income = income.drop(['Unnamed: 1', 'Unnamed: 2', 'Unnamed: 3'], axis=1) income = income.rename(columns={'B19013: MEDIAN HOUSEHOLD INCOME IN THE PAST 12 MONTHS (IN 2014 INFLATION-ADJUSTED DOLLARS) - Univers...
14,712
Given the following text description, write Python code to implement the functionality described below step by step Description: Requirement Step1: Sending a mail is, with the proper library, a piece of cake... Step2: ... but if we take it a little further, we can connect our doorbell project to the sending of mail!...
Python Code: MAIL_SERVER = "mail.****.com" FROM_ADDRESS = "noreply@****.com" TO_ADDRESS = "my_friend@****.com" Explanation: Requirement: For sending mail you need an outgoing mail server (that, in the case of this script, also needs to allow unauthenticated outgoing communication). Fill out the required credentials in ...
14,713
Given the following text description, write Python code to implement the functionality described below step by step Description: Tuning BM25 parameters We tune BM25 parameters on a per-field basis including doc2query expansions and bigrammed text fields. These values are used later when optimizing more complex queries...
Python Code: %load_ext autoreload %autoreload 2 import importlib import os import sys from copy import deepcopy from elasticsearch import Elasticsearch from skopt.plots import plot_objective # project library sys.path.insert(0, os.path.abspath('..')) import qopt importlib.reload(qopt) from qopt.notebooks import evaluat...
14,714
Given the following text description, write Python code to implement the functionality described below step by step Description: !!! D . R . A . F . T !!! Luminance The Luminance $L_v$ is the quantity defined by the formula Step1: Note Step2: Note Step3: ASTM D1535-08$^{\epsilon 1}$ (2008) Method Since 1943, the re...
Python Code: import colour colour.utilities.filter_warnings(True, False) sorted(colour.LUMINANCE_METHODS.keys()) Explanation: !!! D . R . A . F . T !!! Luminance The Luminance $L_v$ is the quantity defined by the formula: <a name="back_reference_1"></a><a href="#reference_1">[1]</a> $$ \begin{equation} L_v=\cfrac{d\Phi...
14,715
Given the following text description, write Python code to implement the functionality described below step by step Description: <center><img src="src/ipyleaflet.svg" width="50%"></center> Repository Step1: Layers Marker Step2: Heatmap layer Step3: Velocity Step4: Controls Step5: Clean
Python Code: from ipyleaflet import Map, basemaps, basemap_to_tiles center = (52.204793, 360.121558) m = Map( layers=(basemap_to_tiles(basemaps.NASAGIBS.ModisTerraTrueColorCR, "2018-11-12"), ), center=center, zoom=4 ) m Explanation: <center><img src="src/ipyleaflet.svg" width="50%"></center> Repository: htt...
14,716
Given the following text description, write Python code to implement the functionality described below step by step Description: FMI Hirlam, MET Norway HARMONIE and NCEP GFS comparison demo In this demo notebook we provide short comparison of using three different weather forecast models Step1: Import datahub parsing...
Python Code: %matplotlib notebook import numpy as np print ('numpy version is ', np.__version__) import matplotlib.pyplot as plt import mpl_toolkits.basemap print ('mpl_toolkits.basemap version is ', mpl_toolkits.basemap.__version__) from mpl_toolkits.basemap import Basemap import warnings import datetime import dateut...
14,717
Given the following text description, write Python code to implement the functionality described below step by step Description: Features for Trajectory Recommendation Features Load Data Compute POI Info Construct Travelling Sequences Compute Some Sequence Statistics Compute Transition Probabilities Basic Definitions ...
Python Code: %matplotlib inline import os import re import math import random import pickle import pandas as pd import numpy as np import scipy.stats #from numba import jit from datetime import datetime from joblib import Parallel, delayed import matplotlib.pyplot as plt nfeatures = 8 # number of features EPS = 1e-12 #...
14,718
Given the following text description, write Python code to implement the functionality described below step by step Description: The use of watermark (above) is optional, and we use it to keep track of the changes while developing the tutorial material. (You can install this IPython extension via "pip install watermar...
Python Code: import numpy as np # Setting a random seed for reproducibility rnd = np.random.RandomState(seed=123) # Generating a random array X = rnd.uniform(low=0.0, high=1.0, size=(3, 5)) # a 3 x 5 array print(X) Explanation: The use of watermark (above) is optional, and we use it to keep track of the changes while ...
14,719
Given the following text description, write Python code to implement the functionality described below step by step Description: 内容索引 相关性分析 --- cov函数、diagonal函数、trace函数、corrcoef函数 多项式拟合 --- polyfit函数、polyval函数、roots函数、polyder函数 计算净额成交量 --- sign函数、piecewise函数 模拟交易过程 --- vectorize函数、round函数 数据平滑 --- hanning函数 Step1: 1....
Python Code: %matplotlib inline import numpy as np from matplotlib.pyplot import plot from matplotlib.pyplot import show Explanation: 内容索引 相关性分析 --- cov函数、diagonal函数、trace函数、corrcoef函数 多项式拟合 --- polyfit函数、polyval函数、roots函数、polyder函数 计算净额成交量 --- sign函数、piecewise函数 模拟交易过程 --- vectorize函数、round函数 数据平滑 --- hanning函数 End of...
14,720
Given the following text description, write Python code to implement the functionality described below step by step Description: An RNN model to generate sequences RNN models can generate long sequences based on past data. This can be used to predict stock markets, temperatures, traffic or sales data based on past pat...
Python Code: import math import numpy as np from matplotlib import pyplot as plt import utils_prettystyle import utils_batching import utils_display import tensorflow as tf print("Tensorflow version: " + tf.__version__) Explanation: An RNN model to generate sequences RNN models can generate long sequences based on past...
14,721
Given the following text description, write Python code to implement the functionality described below step by step Description: Lesson 1 & 2 Step1: Set up Structure for VGG 16 Step2: Remove Last Dense Layer (1000 ImageNet Classes) and add a Dense Layer for 2 Classes Step3: Train Cats vs. Dogs model on dataset in b...
Python Code: import tensorflow as tf #path = 'data/dogscats/sample' path = 'data/dogscats/' import os import json from glob import glob import numpy as np from matplotlib import pyplot as plt from matplotlib import image as mpimg %matplotlib inline from tensorflow.contrib.keras.python.keras.models import Model, Sequent...
14,722
Given the following text description, write Python code to implement the functionality described below step by step Description: San Francisco Crime Classification Predict the category of crimes that occurred in the city by the bay From 1934 to 1963, San Francisco was infamous for housing some of the world's most noto...
Python Code: # Step 1 - importing classes we plan to use import csv as csv import math import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.neighbors import KNeighborsClassifier import seaborn as sns # show plots inline %matplotlib inline # # Preparing the data # data = pd.read_csv('../in...
14,723
Given the following text description, write Python code to implement the functionality described below step by step Description: Compiled Sequential Importance Sampling Compiled sequential importance sampling [1], or inference compilation, is a technique to amortize the computational cost of inference by learning a pr...
Python Code: import torch import torch.nn as nn import torch.functional as F import pyro import pyro.distributions as dist import pyro.infer import pyro.optim import os smoke_test = ('CI' in os.environ) n_steps = 2 if smoke_test else 2000 Explanation: Compiled Sequential Importance Sampling Compiled sequential importan...
14,724
Given the following text description, write Python code to implement the functionality described below step by step Description: Python + Astronomy This course will be an introduction to Astropy, a maturing library for astronomy routines and tools in Python. Astropy started as a combination of various common Python li...
Python Code: # First, make sure this works: import astropy # If this doesn't work, raise your hand! Explanation: Python + Astronomy This course will be an introduction to Astropy, a maturing library for astronomy routines and tools in Python. Astropy started as a combination of various common Python libraries (Pyfits, ...
14,725
Given the following text description, write Python code to implement the functionality described below step by step Description: Encoder-Decoder Analysis Model Architecture Step1: Perplexity on Each Dataset Step2: Loss vs. Epoch Step3: Perplexity vs. Epoch Step4: Generations Step5: BLEU Analysis Step6: N-pairs B...
Python Code: report_file = '/Users/bking/IdeaProjects/LanguageModelRNN/experiment_results/encdec_noing23_200_512_04drb/encdec_noing23_200_512_04drb.json' log_file = '/Users/bking/IdeaProjects/LanguageModelRNN/experiment_results/encdec_noing23_200_512_04drb/encdec_noing23_200_512_04drb_logs.json' import json import matp...
14,726
Given the following text description, write Python code to implement the functionality described below step by step Description: 类元编程是指在运行时创建或定制类的技艺,在 Python 中,类是一等对象,因此任何时候都可以使用函数新建类,无需使用 class 关键字。类装饰器也是函数,不公审查,修改甚至可以把被装饰类替换成其它类。最后,元类是类元编程最高级的工具,使用元类可以创建具有某种特质的全新类种,例如我们见过的抽象基类 类工厂函数 标准库的一个类工厂函数 -- collections.namedt...
Python Code: class Dog: def __init__(self, name, weight, owner): self.name = name self.weight = weight self.owner = owner rex = Dog('Rex', 30, 'Bob') rex Explanation: 类元编程是指在运行时创建或定制类的技艺,在 Python 中,类是一等对象,因此任何时候都可以使用函数新建类,无需使用 class 关键字。类装饰器也是函数,不公审查,修改甚至可以把被装饰类替换成其它类。最后,元类是类元编程最高级...
14,727
Given the following text description, write Python code to implement the functionality described below step by step Description: Loschmidt Plots Plots for the recirq.otoc.loschmidt.tilted_sqare_lattice algorithmic benchmark. See the analysis-walkthrough.ipynb notebook for more detail into the functions used to create ...
Python Code: %matplotlib inline from matplotlib import pyplot as plt # Set up reasonable defaults for figure fonts import matplotlib matplotlib.rcParams.update(**{ 'axes.titlesize': 14, 'axes.labelsize': 14, 'xtick.labelsize': 12, 'ytick.labelsize': 12, 'legend.fontsize': 12, 'legend.title_fonts...
14,728
Given the following text description, write Python code to implement the functionality described below step by step Description: Compute source power using DICS beamformer Compute a Dynamic Imaging of Coherent Sources (DICS) Step1: Reading the raw data and creating epochs Step2: We are interested in the beta band. ...
Python Code: # Author: Marijn van Vliet <w.m.vanvliet@gmail.com> # Roman Goj <roman.goj@gmail.com> # Denis Engemann <denis.engemann@gmail.com> # Stefan Appelhoff <stefan.appelhoff@mailbox.org> # # License: BSD (3-clause) import os.path as op import numpy as np import mne from mne.datasets import...
14,729
Given the following text description, write Python code to implement the functionality described below step by step Description: Summary tutorial Step1: To check that everything is operating as expected we can check that the imports succeed. Step2: Basic Example Let's say that we have the following function and we w...
Python Code: !pip install --upgrade git+https://github.com/google/learned_optimization.git oryx tensorflow==2.8.0rc0 numpy Explanation: Summary tutorial: Getting metrics out of your models The goal of the learned_optimization.summary module is to seamlessly allow researchers to annotate and extract data from within a j...
14,730
Given the following text description, write Python code to implement the functionality described below step by step Description: Reusable Embeddings Learning Objectives 1. Learn how to use a pre-trained TF Hub text modules to generate sentence vectors 1. Learn how to incorporate a pre-trained TF-Hub module into a Kera...
Python Code: import os import pandas as pd from google.cloud import bigquery Explanation: Reusable Embeddings Learning Objectives 1. Learn how to use a pre-trained TF Hub text modules to generate sentence vectors 1. Learn how to incorporate a pre-trained TF-Hub module into a Keras model 1. Learn how to deploy and use a...
14,731
Given the following text description, write Python code to implement the functionality described below step by step Description: Absorbing Random Walk Centrality A short introduction by example The absorbing-centrality module contains an implementation for a greedy algorithm to compute the k-central nodes in a graph ...
Python Code: graph = nx.karate_club_graph() # load the graph node_positions = nx.spring_layout(graph) # fix the node positions make_graph_plot(graph, node_positions, node_size = 0, node_color = "white", with_labels = True) Explanation: Absorbing Random Walk Centrality A short introduction by example...
14,732
Given the following text description, write Python code to implement the functionality described below step by step Description: Receptive Field Estimation and Prediction This example reproduces figures from Lalor et al.'s mTRF toolbox in MATLAB Step1: Load the data from the publication First we will load the data c...
Python Code: # Authors: Chris Holdgraf <choldgraf@gmail.com> # Eric Larson <larson.eric.d@gmail.com> # Nicolas Barascud <nicolas.barascud@ens.fr> # # License: BSD (3-clause) import numpy as np import matplotlib.pyplot as plt from scipy.io import loadmat from os.path import join import mne from mne.dec...
14,733
Given the following text description, write Python code to implement the functionality described below step by step Description: Datasets 機器學習資料集/ 範例三 Step1: (二)資料集介紹 digits = datasets.load_digits() 將一個dict型別資料存入digits,我們可以用下面程式碼來觀察裏面資料 Step2: | 顯示 | 說明 | | -- | -- | | ('target_names', (3L,))| 共有三種鳶尾花 setosa, versic...
Python Code: #這行是在ipython notebook的介面裏專用,如果在其他介面則可以拿掉 %matplotlib inline import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from sklearn import datasets from sklearn.decomposition import PCA # import some data to play with iris = datasets.load_iris() X = iris.data[:, :2] # we only take the first t...
14,734
Given the following text problem statement, write Python code to implement the functionality described below in problem statement Problem: evaluate predictions
Python Code:: mean_absolute_error(y_test, predictions)
14,735
Given the following text description, write Python code to implement the functionality described below step by step Description: Initialization Welcome to the first assignment of "Improving Deep Neural Networks". Training your neural network requires specifying an initial value of the weights. A well chosen initializ...
Python Code: import numpy as np import matplotlib.pyplot as plt import sklearn import sklearn.datasets from init_utils import sigmoid, relu, compute_loss, forward_propagation, backward_propagation from init_utils import update_parameters, predict, load_dataset, plot_decision_boundary, predict_dec %matplotlib inline plt...
14,736
Given the following text description, write Python code to implement the functionality described below step by step Description: Tuples and Lists Tuples A Python Tuple is an immutable sequence of fixed sized. They are created using round brackets () with commas to separate the elements. Step1: The elements of a tupl...
Python Code: ('x', 'y', 'z') Explanation: Tuples and Lists Tuples A Python Tuple is an immutable sequence of fixed sized. They are created using round brackets () with commas to separate the elements. End of explanation (1, 'b', 2.5) Explanation: The elements of a tuple need not have the same type. End of explanation ...
14,737
Given the following text description, write Python code to implement the functionality described below step by step Description: # Overall Summary Step1: Monthly stats Step2: Daily stats -- weekdays Step3: There are weekly pattern in booking time, high from Monday to Fri, low in the Friday and weekend. Monthly stat...
Python Code: daily_stats[['count_click', 'count_booking_train', 'count_booking_test']].sum()/1000 print 'booking ratio for train set: ', daily_stats.count_booking_train.sum() * 1.0 \ / (daily_stats.count_click.sum() + daily_stats.count_booking_train.sum()) print 'daily booking in train set: ', daily_stats.count_booki...
14,738
Given the following text description, write Python code to implement the functionality described below step by step Description: Exercise Answer Key Step1: Helper Functions Step2: Exercise 1 Step3: b. $1 Bets By running 1000 simulations, find the mean and standard deviation of the payout if instead you bet $1 at a ...
Python Code: import numpy as np import pandas as pd import scipy.stats as stats import matplotlib.pyplot as plt import math import cvxpy Explanation: Exercise Answer Key: Position Concentration Risk Lecture Link This exercise notebook refers to this lecture. Please use the lecture for explanations and sample code. http...
14,739
Given the following text description, write Python code to implement the functionality described below step by step Description: Exercise 5.1 Step1: Optimization Maximum likelihood optimization is a statistical method for finding the best fitting set of parameters for a model. A likelihood function can be made up of ...
Python Code: import scipy.optimize as so import numpy import toyplot Explanation: Exercise 5.1: Likelihood model optimization This exercise uses the Python programming language. We will make use of the statistical libraries scipy and numpy to generate data under a parametric model (a model that takes one or more variab...
14,740
Given the following text description, write Python code to implement the functionality described. Description: Check whether product of digits at even places is divisible by sum of digits at odd place of a number Below function checks whether product of digits at even places is divisible by sum of digits at odd places ...
Python Code: def productSumDivisible(n ) : sum = 0 product = 1 num = str(n ) for i in range(len(num ) ) : if(i % 2 != 0 ) : product = product * int(num[i ] )  else : sum = sum + int(num[i ] )   if(product % sum == 0 ) : return True  return False  if __name__== "__main __": n = 1234 ...
14,741
Given the following text description, write Python code to implement the functionality described below step by step Description: Five programming problems every Software Engineer should be able to solve in less than 1 hour http Step1: Problem 2 Write a function that combines two lists by alternatingly taking elements...
Python Code: a = [1,2,3,4,5,6,7] def adding(x): total = 0 for i in x: total += i print(total) total = 0 i = 0 while i < len(x): total += x[i] i += 1 print(total) return adding(a) b = [1,2,3,4,5,6,7] def recur(lst,counter,total): if counter == le...
14,742
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Convolutional Networks So far we have worked with deep fully-connected networks, using them to explore different optimization strategies and network architectures. Fully-connected net...
Python Code: # As usual, a bit of setup from __future__ import print_function import numpy as np import matplotlib.pyplot as plt from cs231n.classifiers.cnn import * from cs231n.data_utils import get_CIFAR10_data from cs231n.gradient_check import eval_numerical_gradient_array, eval_numerical_gradient from cs231n.layers...
14,743
Given the following text description, write Python code to implement the functionality described below step by step Description: Working with CTF data Step1: To reduce memory consumption and running time, some of the steps are precomputed. To run everything from scratch change use_precomputed to False. With use_preco...
Python Code: # Authors: Mainak Jas <mainak.jas@telecom-paristech.fr> # Eric Larson <larson.eric.d@gmail.com> # Jaakko Leppakangas <jaeilepp@student.jyu.fi> # # License: BSD-3-Clause import os.path as op import pandas as pd import numpy as np import mne from mne import combine_evoked from mne.minimum_n...
14,744
Given the following text problem statement, write Python code to implement the functionality described below in problem statement Problem: split into train test sets
Python Code:: from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33)
14,745
Given the following text description, write Python code to implement the functionality described below step by step Description: Porkchops with poliastro Porkchops are also known as mission design curves since they show different parameters used to design the ballistic trajectories for the targetting problem such us S...
Python Code: import astropy.units as u from poliastro.plotting.porkchop import porkchop from poliastro.bodies import Earth, Mars from poliastro.util import time_range launch_span = time_range("2005-04-30", end="2005-10-07") arrival_span = time_range("2005-11-16", end="2006-12-21") Explanation: Porkchops with poliastro ...
14,746
Given the following text description, write Python code to implement the functionality described below step by step Description: 최적 정규화 알파 최적화 문제 오차-분산 트레이드오프 모형 최적화 뒤의 편향 오차(bias)와 오차 분산(variance)는 다음과 같은 트레이드-오프(trade-off) 관계를 가진다. 즉, 어느 하나가 작아지면 다른 하나는 커지게 된다. * 이 방식 잘 안 쓴다. 안 쓰는 이유는 분산과 바이어스를 또 얼만큼 맞춰야 하는지 기준을 정해야...
Python Code: from sklearn.preprocessing import PolynomialFeatures from sklearn.linear_model import LinearRegression from sklearn.pipeline import Pipeline from sklearn.cross_validation import cross_val_score n_samples = 1000 np.random.seed(0) X = np.sort(np.random.rand(n_samples)) y = np.cos(1.5 * np.pi * X) + np.random...
14,747
Given the following text description, write Python code to implement the functionality described below step by step Description: BottomUpParceLiNGAM Import and settings In this example, we need to import numpy, pandas, and graphviz in addition to lingam. Step1: Test data First, we generate a causal structure with 7 v...
Python Code: import numpy as np import pandas as pd import graphviz import lingam from lingam.utils import print_causal_directions, print_dagc, make_dot import warnings warnings.filterwarnings('ignore') print([np.__version__, pd.__version__, graphviz.__version__, lingam.__version__]) np.set_printoptions(precision=3, su...
14,748
Given the following text description, write Python code to implement the functionality described below step by step Description: BASIC CONCEPTS TO REMEMBER Step1: USING EXPRESSIONS AS INDICES Step2: List slices Step3: List comprehensions Step4: modular operator Step5: String operations Step6: string indexes and ...
Python Code: x = [5, 10, 15, 20, 25, 30] x[3] [2, 4, 6, 8, 10][4] #Index Beyond list #this is suppose to go wrong x[90] type(x) type(x[0]) #type of list values can be diffetent from the list. len([10]) #empty list is an starting point len([]) len([]) max(x), sum(x) sorted([x]) #bring is it to you in order range(0,10) l...
14,749
Given the following text description, write Python code to implement the functionality described below step by step Description: Titanic Survival with DNN Predicting survival on the Titanic using an artificial neural network in Keras Supervised Learning. Binary classification This project is based on a dataset contain...
Python Code: import os import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import helper import keras helper.info_gpu() helper.reproducible(seed=0) # Setup reproducible results from run to run using Keras %matplotlib inline Explanation: Titanic Survival with DNN Predicting survi...
14,750
Given the following text description, write Python code to implement the functionality described below step by step Description: Facies classification using Machine Learning- Majority voting Contest entry by Priyanka Raghavan and Steve Hall This notebook demonstrates how to train a machine learning algorithm to predic...
Python Code: %matplotlib inline import pandas as pd import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt import matplotlib.colors as colors from mpl_toolkits.axes_grid1 import make_axes_locatable from pandas import set_option set_option("display.max_rows", 10) pd.options.mode.chained_assignment =...
14,751
Given the following text description, write Python code to implement the functionality described below step by step Description: An Introduction to K-Means Clustering by Scott Hendrickson & Fiona Pigott K-Means is for learning unknown categories K-means is a machine learning technique for learning unknown categories--...
Python Code: # Import some python libraries that we'll need import matplotlib.pyplot as plt import random import math import sys %matplotlib inline def make_data(n_points, n_clusters=2, dim=2, sigma=1): x = [[] for i in range(dim)] for i in range(n_clusters): for d in range(dim): x[d].extend...
14,752
Given the following text description, write Python code to implement the functionality described below step by step Description: Primitive generators This notebook contains tests for tohu's primitive generators. Step1: Constant Constant simply returns the same, constant value every time. Step2: Boolean Boolean retur...
Python Code: import tohu from tohu.v5.primitive_generators import * from tohu.v5.utils import print_generated_sequence print(f'Tohu version: {tohu.__version__}') Explanation: Primitive generators This notebook contains tests for tohu's primitive generators. End of explanation g = Constant('quux') print_generated_sequen...
14,753
Given the following text description, write Python code to implement the functionality described below step by step Description: <a href="https Step1: Predict Shakespeare with Cloud TPUs and Keras Overview This example uses tf.keras to build a language model and train it on a Cloud TPU. This language model predicts t...
Python Code: # Copyright 2018 The TensorFlow Hub Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless re...
14,754
Given the following text description, write Python code to implement the functionality described below step by step Description: Integration Exercise 2 Imports Step1: Indefinite integrals Here is a table of definite integrals. Many of these integrals has a number of parameters $a$, $b$, etc. Find five of these integr...
Python Code: %matplotlib inline import matplotlib.pyplot as plt import numpy as np import seaborn as sns from scipy import integrate Explanation: Integration Exercise 2 Imports End of explanation def integrand(x, a): return 1.0/(x**2 + a**2) def integral_approx(a): # Use the args keyword argument to feed extra ...
14,755
Given the following text description, write Python code to implement the functionality described below step by step Description: Field correlations in Atom-Cavity systems A reproduction and verification of Rebic et al. PRA 69, 035804 (2004) Step1: The states will be $\big|m\big\rangle \otimes \big|n\big\rangle$ where...
Python Code: from qutip import * import numpy as np import matplotlib.pyplot as plt %matplotlib inline print(qutip.__version__) import sys print(sys.version) # Note, it works fine to truncate at 4 (as in the paper) # QuTiP can do much larger space just fine so feel free to increase this. N=4 taus=np.linspace(0,10,500) ...
14,756
Given the following text description, write Python code to implement the functionality described below step by step Description: <a href="https Step2: Imports Step3: tf.data.Dataset Step4: Let's have a look at the data Step5: Keras model If you are not sure what cross-entropy, dropout, softmax or batch-normalizati...
Python Code: BATCH_SIZE = 128 EPOCHS = 10 training_images_file = 'gs://mnist-public/train-images-idx3-ubyte' training_labels_file = 'gs://mnist-public/train-labels-idx1-ubyte' validation_images_file = 'gs://mnist-public/t10k-images-idx3-ubyte' validation_labels_file = 'gs://mnist-public/t10k-labels-idx1-ubyte' Expl...
14,757
Given the following text description, write Python code to implement the functionality described below step by step Description: Exercises Step1: Data Step2: Exercise 1 Step3: b. Standard Deviation Determine standard deviation of the sample. Step4: c. Standard Error Using the standard deviation and sample_size, de...
Python Code: def generate_autocorrelated_data(theta, mu, sigma, N): X = np.zeros((N, 1)) for t in range(1, N): X[t] = theta * X[t-1] + np.random.normal(mu, sigma) return X def newey_west_SE(data): ind = range(0, len(data)) ind = sm.add_constant(ind) model = regression.linear_model.OLS(da...
14,758
Given the following text description, write Python code to implement the functionality described below step by step Description: Variables In computer programming, a variable is a storage location and an associated symbolic name (an identifier) which contains some known or unknown quantity or information, a value. C c...
Python Code: ''' variable assignments this is a variable assignment ''' x = 1.0 my_variable = 12 print type(x) print type(my_variable) Explanation: Variables In computer programming, a variable is a storage location and an associated symbolic name (an identifier) which contains some known or unknown quantity or inform...
14,759
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...
14,760
Given the following text description, write Python code to implement the functionality described below step by step Description: Text-to-Video retrieval with S3D MIL-NCE <table class="tfo-notebook-buttons" align="left"> <td><a target="_blank" href="https Step3: 导入 TF-Hub 模型 本教程演示了如何使用 TensorFlow Hub 中的 S3D MIL-NCE ...
Python Code: !pip install -q opencv-python import os import tensorflow.compat.v2 as tf import tensorflow_hub as hub import numpy as np import cv2 from IPython import display import math Explanation: Text-to-Video retrieval with S3D MIL-NCE <table class="tfo-notebook-buttons" align="left"> <td><a target="_blank" href=...
14,761
Given the following text description, write Python code to implement the functionality described below step by step Description: Data Handling Utilities tiff file directory to tiff stack conversion A utility script that can be executed from the command line to convert tif files in a directory into a tif stack Step1: ...
Python Code: %%bash build_tiff_stack.py --help Explanation: Data Handling Utilities tiff file directory to tiff stack conversion A utility script that can be executed from the command line to convert tif files in a directory into a tif stack: End of explanation %%bash extract_channels_from_raw.py --help Explanation: Th...
14,762
Given the following text description, write Python code to implement the functionality described below step by step Description: Generate data needed for visualization in Tableau Start with the standard imports we have used for every notebook in this class. Step1: Each of the datasheets downloaded from ELSI had downl...
Python Code: %matplotlib inline import numpy as np import scipy as sp import matplotlib as mpl import matplotlib.cm as cm import matplotlib.pyplot as plt import pandas as pd pd.set_option('display.width', 500) pd.set_option('display.max_columns', 100) pd.set_option('display.notebook_repr_html', True) import seaborn as ...
14,763
Given the following text description, write Python code to implement the functionality described below step by step Description: Question 2 Step1: Question 3.1 Step2: Question 3.2 Does the most popular of all the 'lil' has the more followers? Step3: Question 4 (first part) Step4: Question 5 Picking up artists Step...
Python Code: #Question 2 awnser. for artist in artists: print(artist['name'], artist['popularity']) if len(artist['genres']) == 0: print("no genres listed") else: genres = ", ".join(artist['genres']) print("Genres list: ", genres) Explanation: Question 2: What genres are most represe...
14,764
Given the following text description, write Python code to implement the functionality described below step by step Description: &larr; Back to Index Basic Feature Extraction Somehow, we must extract the characteristics of our audio signal that are most relevant to the problem we are trying to solve. For example, if w...
Python Code: kick_signals = [ librosa.load(p)[0] for p in Path().glob('audio/drum_samples/train/kick_*.mp3') ] snare_signals = [ librosa.load(p)[0] for p in Path().glob('audio/drum_samples/train/snare_*.mp3') ] len(kick_signals) len(snare_signals) Explanation: &larr; Back to Index Basic Feature Extraction Someh...
14,765
Given the following text problem statement, write Python code to implement the functionality described below in problem statement Problem: I'm using tensorflow 2.10.0.
Problem: import tensorflow as tf x = tf.Variable(0) x.assign(114514)
14,766
Given the following text description, write Python code to implement the functionality described below step by step Description: Compare evoked responses for different conditions In this example, an Epochs object for visual and auditory responses is created. Both conditions are then accessed by their respective names ...
Python Code: # Authors: Denis Engemann <denis.engemann@gmail.com> # Alexandre Gramfort <alexandre.gramfort@inria.fr> # License: BSD-3-Clause import matplotlib.pyplot as plt import mne from mne.viz import plot_evoked_topo from mne.datasets import sample print(__doc__) data_path = sample.data_path() Explanation:...
14,767
Given the following text description, write Python code to implement the functionality described below step by step Description: Importing the CSV files This CSV file is available on Irans dataset in World bank](https Step1: As I wanted the emission types be my coloumns and the years be the rows, I used transpose() f...
Python Code: # Importing Iran`s dataset IRAN_SOURCE_FILE = 'iran_emission_dataset.csv' iran_csv = pd.read_csv(IRAN_SOURCE_FILE) iran_csv.head(5) # Importing Turkey`s dataset TURKEY_SOURCE_FILE = 'turkey_emission_dataset.csv' turkey_csv = pd.read_csv(TURKEY_SOURCE_FILE) turkey_csv.head(5) Explanation: Importing the CSV...
14,768
Given the following text description, write Python code to implement the functionality described below step by step Description: operator* multiplies the same reference Step1: Changing l[1] actually references a different object Integers are immutable. Step2: Setting l[2] to the same number does not create a new obj...
Python Code: l = [[]] * 3 l[0] is l[1], l[0] is l[2] l[0].append("abc") l l = [1] * 3 print(l) l[0] is l[1], l[0] is l[2] Explanation: operator* multiplies the same reference End of explanation l[1] = 2 print(l) l[0] is l[1], l[0] is l[2], l[1] is l[2] Explanation: Changing l[1] actually references a different object I...
14,769
Given the following text description, write Python code to implement the functionality described below step by step Description: An introduction to NumPy NumPy provides an efficient representation of multidimensional datasets like vectors and matricies, and tools for linear algebra and general matrix manipulations - e...
Python Code: import numpy as np Explanation: An introduction to NumPy NumPy provides an efficient representation of multidimensional datasets like vectors and matricies, and tools for linear algebra and general matrix manipulations - essential building blocks of virtually all technical computing Typically NumPy is impo...
14,770
Given the following text description, write Python code to implement the functionality described below step by step Description: Vertex SDK Step1: Install the latest GA version of google-cloud-storage library as well. Step2: Restart the kernel Once you've installed the additional packages, you need to restart the no...
Python Code: import os # Google Cloud Notebook if os.path.exists("/opt/deeplearning/metadata/env_version"): USER_FLAG = "--user" else: USER_FLAG = "" ! pip3 install --upgrade google-cloud-aiplatform $USER_FLAG Explanation: Vertex SDK: Custom training tabular regression model for batch prediction with explainabi...
14,771
Given the following text description, write Python code to implement the functionality described below step by step Description: Calculating Seasonal Averages from Timeseries of Monthly Means Author Step1: Some calendar information so we can support any netCDF calendar. Step4: A few calendar functions to determine t...
Python Code: %matplotlib inline import numpy as np import pandas as pd import xarray as xr from netCDF4 import num2date import matplotlib.pyplot as plt print("numpy version : ", np.__version__) print("pandas version : ", pd.__version__) print("xarray version : ", xr.__version__) Explanation: Calculating Seasonal Ave...
14,772
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Batch Normalization One way to make deep networks easier to train is to use more sophisticated optimization procedures such as SGD+momentum, RMSProp, or Adam. Another strategy is to c...
Python Code: # As usual, a bit of setup from __future__ import print_function import time import numpy as np import matplotlib.pyplot as plt from cs231n.classifiers.fc_net import * from cs231n.data_utils import get_CIFAR10_data from cs231n.gradient_check import eval_numerical_gradient, eval_numerical_gradient_array fro...
14,773
Given the following text description, write Python code to implement the functionality described below step by step Description: The EM algorithm for Hawkes processes Here we explore the optimisation algorithm for parameter estimation given in Mohler et al. "Randomized Controlled Field Trials of Predictive Policing". ...
Python Code: %matplotlib inline import matplotlib.pyplot as plt import numpy as np Explanation: The EM algorithm for Hawkes processes Here we explore the optimisation algorithm for parameter estimation given in Mohler et al. "Randomized Controlled Field Trials of Predictive Policing". Journal of the American Statistica...
14,774
Given the following text description, write Python code to implement the functionality described below step by step Description: <a href="https Step1: Neural style transfer <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https Step2: Download images and choose a style image and ...
Python Code: #@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # dist...
14,775
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="#Introduction" data-toc-modified-id="Introduction-1">Introduction</a></span><...
Python Code: id_ = 'N1467344745' Explanation: <h1>Table of Contents<span class="tocSkip"></span></h1> <div class="toc"><ul class="toc-item"><li><span><a href="#Introduction" data-toc-modified-id="Introduction-1">Introduction</a></span><ul class="toc-item"><li><span><a href="#Setup" data-toc-modified-id="Setup-1.1">Setu...
14,776
Given the following text description, write Python code to implement the functionality described below step by step Description: PySAL Change Log Statistics This notebook generates the summary statistics for a package. It assumes you are running this under the tools directory at the toplevel of the package Change the...
Python Code: package_name = 'spint' release_date = '2020-09-08' start_date = '2019-07-22' Explanation: PySAL Change Log Statistics This notebook generates the summary statistics for a package. It assumes you are running this under the tools directory at the toplevel of the package Change the values only in the next ce...
14,777
Given the following text description, write Python code to implement the functionality described below step by step Description: Lecture Step1: When to use python? -- 50xp, Status Step3: Python as a calculator -- 100xp, Status Step5: Lecture Step7: 2. Calculations with variables Remember how you calculated the...
Python Code: # working with print function print(5 / 8) # Add another print function on new line print(7 + 10) Explanation: Lecture : Hello Python! [RQ-1] : Which of the following statements is correct? Ans: The Ipython Shell is typically used to work with Python interactively. [RQ-2] : Which file extension is used for...
14,778
Given the following text description, write Python code to implement the functionality described below step by step Description: Object Model bqplot is based on Grammar of Graphics paradigm. The Object Model in bqplot gives the user the full flexibility to build custom plots. This means the API is verbose but fully cu...
Python Code: from bqplot import (LinearScale, Axis, Figure, OrdinalScale, LinearScale, Bars, Lines, Scatter) # first, let's create two vectors x and y to plot using a Lines mark import numpy as np x = np.linspace(-10, 10, 100) y = np.sin(x) # 1. Create the scales xs = LinearScale() ys = LinearScale...
14,779
Given the following text description, write Python code to implement the functionality described below step by step Description: Character level language model - Dinosaurus land Welcome to Dinosaurus Island! 65 million years ago, dinosaurs existed, and in this assignment they are back. You are in charge of a special t...
Python Code: import numpy as np from utils import * import random Explanation: Character level language model - Dinosaurus land Welcome to Dinosaurus Island! 65 million years ago, dinosaurs existed, and in this assignment they are back. You are in charge of a special task. Leading biology researchers are creating new b...
14,780
Given the following text description, write Python code to implement the functionality described below step by step Description: Pandas Step1: Datafreymin əsasına yerləşəcək verilənlər mənbə üzrə üzrə daxili və xarici formalara bölünür Step2: Növbəti email_list_lst_cln dəyşəninə isə sütun adlarından ibarət siyahı tə...
Python Code: import pandas as pd Explanation: Pandas: DataFreym yaratmağın müxtəlif üsulları İlk öncə pandas-da verilənlərin 2D əndazəli forma (sadə dil ilə "cədvəl") daxilində saxlanma vasitəsi və forması olan Dataframe yaratmaqdan başlayaq. Bu dərs tam olaraq müxtəlif mənbələrdən və formalarda əldə edilmiş məlumatı D...
14,781
Given the following text description, write Python code to implement the functionality described below step by step Description: ES-DOC CMIP6 Model Properties - Ocnbgchem MIP Era Step1: Document Authors Set document authors Step2: Document Contributors Specify document contributors Step3: Document Publication Speci...
Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'nerc', 'sandbox-3', 'ocnbgchem') Explanation: ES-DOC CMIP6 Model Properties - Ocnbgchem MIP Era: CMIP6 Institute: NERC Source ID: SANDBOX-3 Topic: Ocnbgchem Sub-Topics: Tracers. Prop...
14,782
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="#Intro" data-toc-modified-id="Intro-1"><span class="toc-item-num">1&nbsp;&nbs...
Python Code: # Basic libraries import import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt import matplotlib from matplotlib import animation from PIL import Image, ImageDraw import os import sys import itertools import collections from math import cos, sin, pi # Plotting %matplo...
14,783
Given the following text description, write Python code to implement the functionality described below step by step Description: Learning avalanche problems by meteorological factors Step1: Split into test and traininng data to run a prediction We use the avalanche forecasts from Nordvestlandet including the forecast...
Python Code: import pandas as pd import numpy as np import json import graphviz import matplotlib.pyplot as plt from sklearn import tree from sklearn.preprocessing import LabelEncoder from pprint import pprint pd.set_option("display.max_rows",6) %matplotlib inline Explanation: Learning avalanche problems by meteorologi...
14,784
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction to numerical simulations Step1: Next, we will need parameters for the simulation. These are known as initial condititons. For a 2 body gravitation problem, we'll need to know t...
Python Code: #Physical Constants (SI units) G=6.67e-11 #Universal Gravitational constant in m^3 per kg per s^2 AU=1.5e11 #Astronomical Unit in meters = Distance between sun and earth daysec=24.0*60*60 #seconds in a day Explanation: Introduction to numerical simulations: The 2 Body Problem Many problems in statistical p...
14,785
Given the following text description, write Python code to implement the functionality described below step by step Description: Beta Hedging By Evgenia "Jenny" Nitishinskaya and Delaney Granizo-Mackenzie with example algorithms by David Edwards Part of the Quantopian Lecture Series Step1: Now we can perform the regr...
Python Code: # Import libraries import numpy as np from statsmodels import regression import statsmodels.api as sm import matplotlib.pyplot as plt import math # Get data for the specified period and stocks start = '2014-01-01' end = '2015-01-01' asset = get_pricing('TSLA', fields='price', start_date=start, end_date=end...
14,786
Given the following text description, write Python code to implement the functionality described below step by step Description: Load the data from our JSON file. The data is stored as a dictionary of dictionaries in the json file. We store it that way beacause it's easy to add data to the existing master data file. A...
Python Code: with open('../pipeline/data/ProcessedDay90ApartmentData.json') as g: my_dict2 = json.load(g) dframe2 = DataFrame(my_dict2) dframe2 = dframe2.T dframe2 = dframe2[['content', 'laundry', 'price', 'dog', 'bed', 'bath', 'feet', 'long', 'parking', 'lat', 'smoking', 'getphotos', 'cat', 'hasmap', 'wheelchai...
14,787
Given the following text description, write Python code to implement the functionality described below step by step Description: Creating Ukulele Chord Diagrams in SVG with Python With the Python modul uchord you can create ukulele chord diagrams in SVG format. Step1: <img src="pic/c.svg" align="left"><br><br><br><br...
Python Code: import uchord uchord.write_chord('c.svg','C','0003') Explanation: Creating Ukulele Chord Diagrams in SVG with Python With the Python modul uchord you can create ukulele chord diagrams in SVG format. End of explanation pip install uchord Explanation: <img src="pic/c.svg" align="left"><br><br><br><br><br> If...
14,788
Given the following text description, write Python code to implement the functionality described below step by step Description: The largest prime (so far) A new record for the largest prime has been found lately. Let explore this number and know more about it and how to deal with it using some Python, Numpy and final...
Python Code: import numpy as np import math from datetime import datetime %load_ext Cython Explanation: The largest prime (so far) A new record for the largest prime has been found lately. Let explore this number and know more about it and how to deal with it using some Python, Numpy and finally using we will take a lo...
14,789
Given the following text description, write Python code to implement the functionality described below step by step Description: On this notebook the best models and input parameters will be searched for. The problem at hand is predicting the price of any stock symbol 28 days ahead, assuming one model for all the symb...
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 %matplotlib inline %pylab inline pylab.rcParams['figure.figsize'] ...
14,790
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Named Entity Recognition In any text document, there are particular terms that represent specific entities that are more informative and have a unique context. These entities are know...
Python Code: text = Three more countries have joined an “international grand committee” of parliaments, adding to calls for Facebook’s boss, Mark Zuckerberg, to give evidence on misinformation to the coalition. Brazil, Latvia and Singapore bring the total to eight different parliaments across the world, with plans to...
14,791
Given the following text description, write Python code to implement the functionality described below step by step Description: Using Interrupts and asyncio for Buttons and Switches This notebook provides a simple example for using asyncio I/O to interact asynchronously with multiple input devices. A task is created ...
Python Code: from pynq import PL from pynq.overlays.base import BaseOverlay base = BaseOverlay("base.bit") Explanation: Using Interrupts and asyncio for Buttons and Switches This notebook provides a simple example for using asyncio I/O to interact asynchronously with multiple input devices. A task is created for each i...
14,792
Given the following text description, write Python code to implement the functionality described below step by step Description: <img src="images/JHI_STRAP_Web.png" style="width Step1: <a id="load"></a> Load results We load data from the multiplexed run that was performed on the JHI cluster, as described in README.md...
Python Code: %pylab inline import os import pickle import warnings; warnings.filterwarnings('ignore') import numpy as np import pandas as pd import scipy import seaborn as sns; sns.set_context('notebook') import tools Explanation: <img src="images/JHI_STRAP_Web.png" style="width: 150px; float: right;"> Supplementary In...
14,793
Given the following text description, write Python code to implement the functionality described below step by step Description: Features as a Representation of Time Series for Classification version 0.1 By AA Miller (Northwestern CIERA/Adler Planetarium) 10 June 2019 This lecture is about machine learning... But hone...
Python Code: def lc_plot(t, m, m_unc, period=0.0): if period == 0.0: fig, ax = plt.subplots() ax.errorbar(t, m, m_unc, fmt='o', color='MediumAquaMarine', mec="0.2",mew=0.5) ax.set_xlabel('HJD (d)') ax.set_ylabel(r'$V_\mathrm{ASAS}\;(\mathrm{ma...
14,794
Given the following text description, write Python code to implement the functionality described below step by step Description: Data Augmentation Este notebook ha sido creado para el uso de Data augmentation sobre nuestro conjunto de caras. Con el objetivo de aumentar y ofrecer un conjunto más variado de imagenes. Ca...
Python Code: from sklearn.datasets import fetch_lfw_people # Importamos mediante una de las dos alternativas # 1ª alternativa devuelve las imagenes en RGB pero con sus # respectivos tres valores faces = fetch_lfw_people(color = True) positive_patches = faces.images positive_patches.shape Explanation: Data Augmentation ...
14,795
Given the following text description, write Python code to implement the functionality described below step by step Description: UCI Datasets Step1: The standard datasets are taken from the UCI Machine Learning Repository. For each dataset, header rows are added manually. Binary Ionosphere radar data, where 'good' is...
Python Code: import os import pandas as pd import numpy as np from mclearn.tools import fetch_data, download_data %load_ext autoreload %autoreload 2 uci_url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/' Explanation: UCI Datasets End of explanation url = uci_url + 'ionosphere/ionosphere.data' dest = 'da...
14,796
Given the following text description, write Python code to implement the functionality described below step by step Description: Problem-set-Jupyter-Pyplot-and-Numpy Write a note about the data set Fisher's Iris Data Set is a well known data set that has become a common test case in machine learning. Each row in the d...
Python Code: import numpy as np # Load in data from csv file. sepal_length, sepal_width, petal_length, petal_width = np.genfromtxt('../data/IRIS.csv', delimiter=',', usecols=(0,1,2,3), unpack=True, dtype=float) iris_class = np.genfromtxt('../data/IRIS.csv', delimiter=',', usecols=(4), unpack=True, dtype=str) # Loaded t...
14,797
Given the following text description, write Python code to implement the functionality described below step by step Description: Tutorial Part 3 Step1: Now, let's use MoleculeNet to load the Tox21 dataset. We need to make sure to process the data in a way that graph convolutional networks can use For that, we make su...
Python Code: import deepchem as dc from deepchem.models.tensorgraph.models.graph_models import GraphConvModel Explanation: Tutorial Part 3: Introduction to Graph Convolutions In the previous sections of the tutorial, we learned about Dataset and Model objects. We learned how to load some data into DeepChem from files o...
14,798
Given the following text description, write Python code to implement the functionality described below step by step Description: Laplace approximation ( Quadratic approximation) In this notebook we will approximate posterior of beta-bernouli model for coin toss problem using laplace approximation method Step1: Laplac...
Python Code: try: from probml_utils import latexify, savefig except: %pip install git+https://github.com/probml/probml-utils.git from probml_utils import latexify, savefig import jax import jax.numpy as jnp from jax import lax try: from tensorflow_probability.substrates import jax as tfp except ModuleNo...
14,799
Given the following text description, write Python code to implement the functionality described below step by step Description: <font color='blue'>Data Science Academy - Python Fundamentos - Capítulo 6</font> Download Step1: Leitura de dados
Python Code: # Versão da Linguagem Python from platform import python_version print('Versão da Linguagem Python Usada Neste Jupyter Notebook:', python_version()) Explanation: <font color='blue'>Data Science Academy - Python Fundamentos - Capítulo 6</font> Download: http://github.com/dsacademybr End of explanation impor...