Unnamed: 0
int64
0
16k
text_prompt
stringlengths
110
62.1k
code_prompt
stringlengths
37
152k
4,000
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2019 The TensorFlow Authors. Step1: TensorFlow Hub によるテキストの分類 Step2: IMDB データセットをダウンロードする IMDB データセットは、imdb reviews または TensorFlow データセットで提供されています。次のコードを使って、IMDB データセットをマシン(または C...
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...
4,001
Given the following text description, write Python code to implement the functionality described below step by step Description: Create a classifier to predict the wine color from wine quality attributes using this dataset Step1: Query for the data and create a numpy array Step2: Split the data into features (x) and...
Python Code: import pg8000 conn = pg8000.connect(host='training.c1erymiua9dx.us-east-1.rds.amazonaws.com', database="training", port=5432, user='dot_student', password='qgis') cursor = conn.cursor() database=cursor.execute("SELECT * FROM winequality") import pandas as pd import matplotlib.pyplot as plt %matplotlib inli...
4,002
Given the following text description, write Python code to implement the functionality described below step by step Description: Basic Principles of Machine Learning Here we'll dive into the basic principles of machine learning, and how to utilize them via the Scikit-Learn API. After briefly introducing scikit-learn's...
Python Code: %matplotlib inline import numpy as np import matplotlib.pyplot as plt Explanation: Basic Principles of Machine Learning Here we'll dive into the basic principles of machine learning, and how to utilize them via the Scikit-Learn API. After briefly introducing scikit-learn's Estimator object, we'll cover sup...
4,003
Given the following text description, write Python code to implement the functionality described below step by step Description: Machine Learning Basics with Sklearn First some imports for the notebook and visualization. Step1: Choosing a dataset First of all you need a dataset to work on. To keep things simple we wi...
Python Code: import numpy as np import matplotlib.pyplot as plt %matplotlib inline Explanation: Machine Learning Basics with Sklearn First some imports for the notebook and visualization. End of explanation from sklearn.datasets import load_iris iris = load_iris() Explanation: Choosing a dataset First of all you need a...
4,004
Given the following text description, write Python code to implement the functionality described below step by step Description: Working with Text Data and Naive Bayes in scikit-learn Agenda Working with text data Representing text as data Reading SMS data Vectorizing SMS data Examining the tokens and their counts Bon...
Python Code: from sklearn.feature_extraction.text import CountVectorizer # start with a simple example simple_train = ['call you tonight', 'Call me a cab', 'please call me... PLEASE!', 'help'] # learn the 'vocabulary' of the training data vect = CountVectorizer() vect.fit(simple_train) # vect.get_feature_names() vect.v...
4,005
Given the following text description, write Python code to implement the functionality described below step by step Description: Fundamentals of audio and music analysis Open source libraries Python librosa (ISC / MIT licensed) pyaudio (MIT licensed) portaudio Prepare sound for analysis NOTE Step1: [Optional] Record...
Python Code: import pyaudio import wave Explanation: Fundamentals of audio and music analysis Open source libraries Python librosa (ISC / MIT licensed) pyaudio (MIT licensed) portaudio Prepare sound for analysis NOTE: Either record your own voice or import a sample from file End of explanation # In this step, find out...
4,006
Given the following text description, write Python code to implement the functionality described below step by step Description: Предобработка данных и логистическая регрессия для задачи бинарной классификации Programming assignment В задании вам будет предложено ознакомиться с основными техниками предобработки данных...
Python Code: import pandas as pd import numpy as np import matplotlib from matplotlib import pyplot as plt matplotlib.style.use('ggplot') %matplotlib inline Explanation: Предобработка данных и логистическая регрессия для задачи бинарной классификации Programming assignment В задании вам будет предложено ознакомиться с ...
4,007
Given the following text description, write Python code to implement the functionality described below step by step Description: Plotting with Folium What is Folium? Folium builds on the data wrangling strengths of the Python ecosystem and the mapping strengths of the leaflet.js library. This allows you to manipulate ...
Python Code: # Import Libraries import pandas as pd import geopandas import folium import matplotlib.pyplot as plt df1 = pd.read_csv('volcano_data_2010.csv') # Keep only relevant columns df = df1.loc[:, ("Year", "Name", "Country", "Latitude", "Longitude", "Type")] df.info() # Create point geometries geometry = geopanda...
4,008
Given the following text description, write Python code to implement the functionality described below step by step Description: Select clean 83mKr events KR83m cuts similar to Adam's note Step1: Get S1s from these events Step2: Save to disk Pandas object array is very memory-ineficient. Takes about 25 MB/dataset to...
Python Code: # Get SR1 krypton datasets dsets = hax.runs.datasets dsets = dsets[dsets['source__type'] == 'Kr83m'] dsets = dsets[dsets['trigger__events_built'] > 10000] # Want a lot of Kr, not diffusion mode dsets = hax.runs.tags_selection(dsets, include='sciencerun0') # Sample ten datasets randomly (with fixed seed,...
4,009
Given the following text description, write Python code to implement the functionality described below step by step Description: <center><h2>Scale your pandas workflows by changing one line of code</h2> Exercise 2 Step1: Dataset Step2: Optional Step3: pandas.read_csv Step4: Expect pandas to take >3 minutes on EC2,...
Python Code: import modin.pandas as pd import pandas import time from IPython.display import Markdown, display def printmd(string): display(Markdown(string)) Explanation: <center><h2>Scale your pandas workflows by changing one line of code</h2> Exercise 2: Speed improvements GOAL: Learn about common functionality t...
4,010
Given the following text description, write Python code to implement the functionality described below step by step Description: Brainstorm Elekta phantom tutorial dataset Here we compute the evoked from raw for the Brainstorm Elekta phantom tutorial dataset. For comparison, see [1]_ and Step1: The data were collecte...
Python Code: # Authors: Eric Larson <larson.eric.d@gmail.com> # # License: BSD (3-clause) import os.path as op import numpy as np import mne from mne import find_events, fit_dipole from mne.datasets.brainstorm import bst_phantom_elekta from mne.io import read_raw_fif print(__doc__) Explanation: Brainstorm Elekta phanto...
4,011
Given the following text description, write Python code to implement the functionality described below step by step Description: 1. Setting things up Let's take a look at game.py, which we use to create games. Right now, Signal only does cheap-talk games with a chance player. That is, games in which the state the send...
Python Code: sender = np.identity(3) receiver = np.identity(3) state_chances = np.array([1/3, 1/3, 1/3]) Explanation: 1. Setting things up Let's take a look at game.py, which we use to create games. Right now, Signal only does cheap-talk games with a chance player. That is, games in which the state the sender observes ...
4,012
Given the following text description, write Python code to implement the functionality described below step by step Description: 机器学习工程师纳米学位 模型评价与验证 项目 1 Step1: 分析数据 在项目的第一个部分,你会对波士顿房地产数据进行初步的观察并给出你的分析。通过对数据的探索来熟悉数据可以让你更好地理解和解释你的结果。 由于这个项目的最终目标是建立一个预测房屋价值的模型,我们需要将数据集分为特征(features)和目标变量(target variable)。特征 'RM', 'LSTA...
Python Code: # Import libraries necessary for this project # 载入此项目所需要的库 import numpy as np import pandas as pd import visuals as vs # Supplementary code from sklearn.model_selection import ShuffleSplit # Pretty display for notebooks # 让结果在notebook中显示 %matplotlib inline # Load the Boston housing dataset # 载入波士顿房屋的数据集 da...
4,013
Given the following text description, write Python code to implement the functionality described below step by step Description: A well-used functionality in PySAL is the use of PySAL to conduct exploratory spatial data analysis. This notebook will provide an overview of ways to conduct exploratory spatial analysis in...
Python Code: data = ps.pdio.read_files(ps.examples.get_path('NAT.shp')) W = ps.queen_from_shapefile(ps.examples.get_path('NAT.shp')) W.transform = 'r' data.head() Explanation: A well-used functionality in PySAL is the use of PySAL to conduct exploratory spatial data analysis. This notebook will provide an overview of w...
4,014
Given the following text description, write Python code to implement the functionality described below step by step Description: Microsoft Emotion API Data Run 4_check_img_size.py This script checks the images are not too large for Micrsofts API, which has a limit of 1kb to 4MB When it finds an image that is too large...
Python Code: def read_jsons(f, candidate): tmp_dict = {} with open(f) as json_file: data = json.load(json_file) data = json.loads(data) print(data) try: tmp_dict['age'] = data[0]['faceAttributes']['age'] tmp_dict['gender'] = data[0]['faceAttr...
4,015
Given the following text description, write Python code to implement the functionality described below step by step Description: Monte Carlo Explorations We will conduct some basic Monte Carlo explorations with the grmpy package. This allows us to revisit the key message of the course. Step1: Questions What are the r...
Python Code: import pickle as pkl import numpy as np import copy from statsmodels.sandbox.regression.gmm import IV2SLS from mc_exploration_functions import * import statsmodels.api as sm import seaborn.apionly as sns import grmpy model_base = get_model_dict('mc_exploration.grmpy.ini') model_base['SIMULATION']['source'...
4,016
Given the following text description, write Python code to implement the functionality described below step by step Description: Easy Ab initio calculation with ASE-Siesta-Pyscf No installation necessary, just download a ready to go container for any system, or run it into the cloud Are we really on the Amazon cloud??...
Python Code: cat /proc/cpuinfo Explanation: Easy Ab initio calculation with ASE-Siesta-Pyscf No installation necessary, just download a ready to go container for any system, or run it into the cloud Are we really on the Amazon cloud?? End of explanation # import libraries and set up the molecule geometry from ase.units...
4,017
Given the following text description, write Python code to implement the functionality described below step by step Description: Spatiotemporal permutation F-test on full sensor data Tests for differential evoked responses in at least one condition using a permutation clustering test. The FieldTrip neighbor templates ...
Python Code: # Authors: Denis Engemann <denis.engemann@gmail.com> # Jona Sassenhagen <jona.sassenhagen@gmail.com> # # License: BSD (3-clause) import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1 import make_axes_locatable import mne from mne.stats import spatio_temporal_cluster_test ...
4,018
Given the following text description, write Python code to implement the functionality described below step by step Description: Goal The goal of this notebook is to explore better methods for the final l2 centorid match during registration in the pipeline. Generate Data Step1: Benchmark Current Approach Step2: KD T...
Python Code: def newRandomCentroids(n, l, u): diff = u-l return [[random()*diff+l for _ in range(3)] for _ in range(n)] newRandomCentroids(10, 10, 100) Explanation: Goal The goal of this notebook is to explore better methods for the final l2 centorid match during registration in the pipeline. Generate Data End ...
4,019
Given the following text description, write Python code to implement the functionality described below step by step Description: Airfoil example In this example we are building a NACA 2412 airfoil from a list of points. Lets import everything we need Step1: Now we build up an array of points from a NACA generator. It...
Python Code: import tigl3.curve_factories from OCC.gp import gp_Pnt from OCC.Display.SimpleGui import init_display Explanation: Airfoil example In this example we are building a NACA 2412 airfoil from a list of points. Lets import everything we need: End of explanation # list of points on NACA2412 profile px = [1.00008...
4,020
Given the following text description, write Python code to implement the functionality described below step by step Description: Support Vector Machine (SVM) (Maximal margin classifiers) Support Vector Machines (SVM) separates classes of data by maximizing the "space" (margin) between pairs of these groups. Classifica...
Python Code: from IPython.display import Image Image(url="http://docs.opencv.org/2.4/_images/separating-lines.png") Explanation: Support Vector Machine (SVM) (Maximal margin classifiers) Support Vector Machines (SVM) separates classes of data by maximizing the "space" (margin) between pairs of these groups. Classificat...
4,021
Given the following text description, write Python code to implement the functionality described below step by step Description: Content Based Filtering by hand This lab illustrates how to implement a content based filter using low level Tensorflow operations. The code here follows the technique explained in Module 2 ...
Python Code: !pip install tensorflow==2.5 Explanation: Content Based Filtering by hand This lab illustrates how to implement a content based filter using low level Tensorflow operations. The code here follows the technique explained in Module 2 of Recommendation Engines: Content Based Filtering. End of explanation impo...
4,022
Given the following text description, write Python code to implement the functionality described below step by step Description: Carnegie Python Bootcamp Welcome to the python bootcamp. This thing you're reading is called an ipython notebook and will be your first introduction to the Python programming language. Noteb...
Python Code: import antigravity Explanation: Carnegie Python Bootcamp Welcome to the python bootcamp. This thing you're reading is called an ipython notebook and will be your first introduction to the Python programming language. Notebooks are a combination of text markup and code that you can run in real time. Importi...
4,023
Given the following text description, write Python code to implement the functionality described below step by step Description: Exploring MzML files with the MS Ontology In this example, we will learn how to use pronto to extract a hierarchy from the MS Ontology, a controlled vocabulary developed by the Proteomics St...
Python Code: import pronto ms = pronto.Ontology.from_obo_library("ms.obo") Explanation: Exploring MzML files with the MS Ontology In this example, we will learn how to use pronto to extract a hierarchy from the MS Ontology, a controlled vocabulary developed by the Proteomics Standards Initiative to hold metadata about ...
4,024
Given the following text description, write Python code to implement the functionality described below step by step Description: String Matching The idea of string matching is to find strings that match a given pattern. We have seen that Pandas provides some useful functions to do that job. Step1: Imagine I want to h...
Python Code: import pandas as pd names = pd.DataFrame({"name" : ["Alice","Bob","Charlie","Dennis"], "surname" : ["Doe","Smith","Sheen","Quaid"]}) names names.name.str.match("A\w+") debts = pd.DataFrame({"debtor":["D.Quaid","C.Sheen"], "amount":[100,10000]}) debts Explanation: S...
4,025
Given the following text description, write Python code to implement the functionality described below step by step Description: Create TensorFlow Wide and Deep Model Learning Objective - Create a Wide and Deep model using the high-level Estimator API - Determine which features to use as wide columns and which to use...
Python Code: PROJECT = "cloud-training-demos" # Replace with your PROJECT BUCKET = "cloud-training-bucket" # Replace with your BUCKET REGION = "us-central1" # Choose an available region for Cloud MLE TFVERSION = "1.14" # TF version for CMLE to use import os os.environ["BUCKET"] = BUCKET os.e...
4,026
Given the following text description, write Python code to implement the functionality described below step by step Description: 6 - Data Compression This short Notebook will introduce you to how to efficiently compress your data within SampleData datasets. <div class="alert alert-info"> **Note** Throughout t...
Python Code: from config import PYMICRO_EXAMPLES_DATA_DIR # import file directory path import os dataset_file = os.path.join(PYMICRO_EXAMPLES_DATA_DIR, 'example_microstructure') # test dataset file path tar_file = os.path.join(PYMICRO_EXAMPLES_DATA_DIR, 'example_microstructure.tar.gz') # dataset archive path Explanatio...
4,027
Given the following text description, write Python code to implement the functionality described below step by step Description: Probabilistic Programming in Python Author Step1: Summary Step2: Summary Random variables are abstract objects. Methods are available for operating on them algebraically. The probabilit...
Python Code: from lea import * # the canonical random variable : a fair coin faircoin = Lea.fromVals('Head', 'Tail') # toss the coin a few times faircoin.random(10) # Amitabh Bachan's coin from Sholay sholaycoin = Lea.fromVals('Head', 'Head') # Amitabh always wins (and, heroically, sacrifices himself for Dharamendra!) ...
4,028
Given the following text description, write Python code to implement the functionality described below step by step Description: Regularization Welcome to the second assignment of this week. Deep Learning models have so much flexibility and capacity that overfitting can be a serious problem, if the training dataset is...
Python Code: # import packages import numpy as np import matplotlib.pyplot as plt from reg_utils import sigmoid, relu, plot_decision_boundary, initialize_parameters, load_2D_dataset, predict_dec from reg_utils import compute_cost, predict, forward_propagation, backward_propagation, update_parameters import sklearn impo...
4,029
Given the following text description, write Python code to implement the functionality described below step by step Description: Le perceptron multicouche avec scikit-learn Documentation officielle Step1: Classification C.f. http Step2: Une fois le réseau de neurones entrainé, on peut tester de nouveaux exemples Ste...
Python Code: import sklearn # version >= 0.18 is required version = [int(num) for num in sklearn.__version__.split('.')] assert (version[0] >= 1) or (version[1] >= 18) Explanation: Le perceptron multicouche avec scikit-learn Documentation officielle: http://scikit-learn.org/stable/modules/neural_networks_supervised.htm...
4,030
Given the following text description, write Python code to implement the functionality described below step by step Description: Clase 3 Step1: Una vez cargados los paquetes, es necesario definir los tickers de las acciones que se usarán, la fuente de descarga (Yahoo en este caso, pero también se puede desde Google) ...
Python Code: #importar los paquetes que se van a usar import pandas as pd import pandas_datareader.data as web import numpy as np import datetime from datetime import datetime import scipy.stats as stats import matplotlib.pyplot as plt import seaborn as sns %matplotlib inline #algunas opciones para Python pd.set_option...
4,031
Given the following text description, write Python code to implement the functionality described below step by step Description: Mechpy Tutorials a mechanical engineering toolbox source code - https Step1: Reading raw test data example 1 This example shows how to read multiple csv files and plot them together Step2: ...
Python Code: # setup import numpy as np import sympy as sp import pandas as pd import scipy from pprint import pprint sp.init_printing(use_latex='mathjax') import matplotlib.pyplot as plt plt.rcParams['figure.figsize'] = (12, 8) # (width, height) plt.rcParams['font.size'] = 14 plt.rcParams['legend.fontsize'] = 16 fro...
4,032
Given the following text description, write Python code to implement the functionality described below step by step Description: Interact Exercise 6 Imports Put the standard imports for Matplotlib, Numpy and the IPython widgets in the following cell. Step1: Exploring the Fermi distribution In quantum statistics, the ...
Python Code: %matplotlib inline import matplotlib.pyplot as plt import numpy as np from IPython.display import Image from IPython.html.widgets import interact, interactive, fixed Explanation: Interact Exercise 6 Imports Put the standard imports for Matplotlib, Numpy and the IPython widgets in the following cell. End of...
4,033
Given the following text description, write Python code to implement the functionality described below step by step Description: Propagate uncertainties with the errors add-on for CO2SYS-Matlab James Orr<br> <img align="left" width="50%" src="http Step1: Specify the directory where you have put the Matlab routines CO...
Python Code: %load_ext oct2py.ipython Explanation: Propagate uncertainties with the errors add-on for CO2SYS-Matlab James Orr<br> <img align="left" width="50%" src="http://www.lsce.ipsl.fr/Css/img/banniere_LSCE_75.png"><br><br> LSCE/IPSL, CEA-CNRS-UVSQ, Gif-sur-Yvette, France 27 February 2018 <br><br> updated: 29 June ...
4,034
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2019 The TensorFlow Authors. Licensed under the Apache License, Version 2.0 (the "License"); Step1: pandas DataFrame を読み込む <table class="tfo-notebook-buttons" align="left"> <td>...
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...
4,035
Given the following text description, write Python code to implement the functionality described below step by step Description: 人人汽车推荐系统调研综述 这里是一个推荐引擎,使用经典数据集movielens,可以将movies数据替换为人人的车型数据,rating数据替换为从日志系统中收集的所有用户对车的点击次数,浏览时间(权重)。这样可以实现C端对车型的推荐 架构: ①日志系统:搜集用户行为提供离线数据 ②推荐引擎:A Step1: 在_产品-产品协同过滤_中的产品之间的相似性值是通过观察所有对两个...
Python Code: import numpy as np import pandas as pd import os # 使用pandas加载csv数据 movies = pd.read_csv(os.path.expanduser("~/ml-latest-small/movies.csv")) ratings = pd.read_csv(os.path.expanduser("~/ml-latest-small/ratings.csv")) # 去掉无用的维度 ratings.drop(['timestamp'],axis=1,inplace=True) movies.head() ratings.head() # 将mo...
4,036
Given the following text description, write Python code to implement the functionality described below step by step Description: Surfaces in pyOpTools The basic object to create optical components in pyOpTools are the surfaces. They are used to define the border that separates 2 materials (for example air-glass) in an...
Python Code: from pyoptools.all import * from numpy import pi Explanation: Surfaces in pyOpTools The basic object to create optical components in pyOpTools are the surfaces. They are used to define the border that separates 2 materials (for example air-glass) in an optical component. Below are some of the Surface Objec...
4,037
Given the following text description, write Python code to implement the functionality described below step by step Description: FCLA/FNLA Fast.ai Numerical/Computational Linear Algebra Lecture 3 Step1: So if A is approx equal to Q•Q.T•A .. but not equal.. then Q is not the identity, but is very close to it. Oh, righ...
Python Code: import torch import numpy as np Q = np.eye(3) print(Q) print(Q.T) print(Q @ Q.T) # construct I matrix Q = torch.eye(3) # torch matrix multip # torch.mm(Q, Q.transpose) Q @ torch.t(Q) Explanation: FCLA/FNLA Fast.ai Numerical/Computational Linear Algebra Lecture 3: New Perspectives on NMF, Randomized SVD Not...
4,038
Given the following text description, write Python code to implement the functionality described below step by step Description: Communication between components Purpose Step1: The simplest thing we can do with the Redis server is to set and get key values. The keys are strings and the values are strings, so you can...
Python Code: import redis r = redis.StrictRedis(host='localhost') r.set('key', 'value') print r.get('key') Explanation: Communication between components Purpose: If we are connecting to hardware or otherwise doing something involving multiple computers or even separate processes on the same computer, we need some easy ...
4,039
Given the following text description, write Python code to implement the functionality described below step by step Description: Un ipython notebook garde ses résultats depuis la dernière fois, mais pas son état. Il convient donc re-exécuter depuis le début. Step1: Example of sampling from a probability distribution...
Python Code: import numpy as np import scipy.stats as ss import matplotlib.pyplot as plt import sklearn import pandas as pd %matplotlib inline x = np.linspace(-100, 100, 201) plt.plot(x, x * x) Explanation: Un ipython notebook garde ses résultats depuis la dernière fois, mais pas son état. Il convient donc re-exécuter...
4,040
Given the following text description, write Python code to implement the functionality described below step by step Description: <a href="https Step1: Tensors Tensors are similar to NumPy’s ndarrays, with the addition being that Tensors can also be used on a GPU to accelerate computing. Step2: Operation on Tensors S...
Python Code: import torch Explanation: <a href="https://colab.research.google.com/github/rishuatgithub/MLPy/blob/master/PyTorchStuff.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> All about Pytorch End of explanation x = torch.empty(5,3) ## empty x ...
4,041
Given the following text description, write Python code to implement the functionality described below step by step Description: Simulate RAD-seq data The simulations software simrrls is available at github.com/dereneaton/simrrls. First we create a directory called ipsimdata/ and then simulate data and put it in this ...
Python Code: ## name for our sim data directory DIR = "./ipsimdata" ## A mouse MT genome used to stick our data into. INPUT_CHR = "/home/deren/Downloads/MusMT.fa" ## number of RAD loci to simulate NLOCI = 1000 ## number of inserts to reference genome and insert size N_INSERTS = 100 INSERT_SIZE = 50 Explanation: Simulat...
4,042
Given the following text description, write Python code to implement the functionality described below step by step Description: 抽象数据类型和 Python 类 抽象数据类型 Abstract data Type, ADT 数据类型 Python 基本数据类型:逻辑类型bool,数值类型int和float,字符串str和组合数据类型 str, tuple, frozenset 是不变数据类型,list, set, dict 是可变数据类型 Python类 在Python中,利用class定义(类定义)实...
Python Code: class Student(object): skills = [] def __init__(self, name): self.name = name stu = Student('ly') print Student.skills # 访问类数据属性 Student.skills.append('Python') print Student.skills print stu.skills # 通过实例也能访问类数据属性 print dir(Student) Student.age = 25 # 通过类名动态添加类...
4,043
Given the following text description, write Python code to implement the functionality described below step by step Description: Welcome to the LIGO data visualization tutorial! Installation Please make sure you have GWpy installed before you begin! Only execute the below cell if you have not already installed GWpy S...
Python Code: #! python3 -m pip install gwpy Explanation: Welcome to the LIGO data visualization tutorial! Installation Please make sure you have GWpy installed before you begin! Only execute the below cell if you have not already installed GWpy End of explanation from gwosc.datasets import find_datasets find_datasets(...
4,044
Given the following text description, write Python code to implement the functionality described below step by step Description: Think Like a Machine - Chapter 5 Logistic Regression ACKNOWLEDGEMENT A lot of the code in this notebook is from John D. Wittenauer's notebooks that cover the exercises in Andrew Ng's course ...
Python Code: # Use the functions from another notebook in this notebook %run SharedFunctions.ipynb # Import our usual libraries import numpy as np import pandas as pd import matplotlib.pyplot as plt %matplotlib inline import os path = os.getcwd() + '/Data/ex2data1.txt' data = pd.read_csv(path, header=None, names=['Exam...
4,045
Given the following text description, write Python code to implement the functionality described below step by step Description: <div align="right">Python 3.6 Jupyter Notebook</div> Introduction to Funf Your completion of the notebook exercises will be graded based on your ability to do the following Step1: 1. Friend...
Python Code: import pandas as pd import numpy as np import folium import matplotlib.pylab as plt import matplotlib %matplotlib inline matplotlib.rcParams['figure.figsize'] = (10, 8) Explanation: <div align="right">Python 3.6 Jupyter Notebook</div> Introduction to Funf Your completion of the notebook exercises will be g...
4,046
Given the following text description, write Python code to implement the functionality described below step by step Description: This notebook contains examples related to survival analysis, based on Chapter 13 of Think Stats, 2nd Edition, by Allen Downey, available from thinkstats2.com Step1: The following code look...
Python Code: from __future__ import print_function, division import marriage import thinkstats2 import thinkplot import pandas import numpy from lifelines import KaplanMeierFitter from collections import defaultdict import itertools import math import matplotlib.pyplot as pyplot from matplotlib import pylab %matplotlib...
4,047
Given the following text description, write Python code to implement the functionality described below step by step Description: Traffic Sign Classification with Keras Keras exists to make coding deep neural networks simpler. To demonstrate just how easy it is, you’re going to use Keras to build a convolutional neural...
Python Code: from urllib.request import urlretrieve from os.path import isfile from tqdm import tqdm class DLProgress(tqdm): last_block = 0 def hook(self, block_num=1, block_size=1, total_size=None): self.total = total_size self.update((block_num - self.last_block) * block_size) self.las...
4,048
Given the following text description, write Python code to implement the functionality described below step by step Description: <div align='center' ><img src='https Step1: 5. Impulse response functions Impulse response functions (IRFs) are a standard tool for analyzing the short run dynamics of dynamic macroeconomic...
Python Code: %matplotlib inline import matplotlib.pyplot as plt import numpy as np import pandas as pd import sympy as sym import solowpy # define model parameters ces_params = {'A0': 1.0, 'L0': 1.0, 'g': 0.02, 'n': 0.03, 's': 0.15, 'delta': 0.05, 'alpha': 0.33, 'sigma': 1.01} # create an instance of the ...
4,049
Given the following text description, write Python code to implement the functionality described below step by step Description: OkNLP This notebook demonstrates the algorithm we used in our project. It shows an example of how we clustered using Nonnegative Matrix Factorization. We manually inspect the output of NMF t...
Python Code: import warnings import numpy as np import pandas as pd from scipy.sparse import hstack from sklearn.cross_validation import cross_val_predict from sklearn.ensemble import RandomForestClassifier from sklearn.linear_model import LogisticRegression from sklearn.metrics import accuracy_score, precision_score, ...
4,050
Given the following text description, write Python code to implement the functionality described below step by step Description: <h1>Basic test of the wflow BMI interface Step1: Startup two models Step2: <h3>Now we can investigate some model parameters Step3: <h3>Start and end times Step4: <h3>Now start the models...
Python Code: import wflow.wflow_bmi as bmi import logging reload(bmi) %pylab inline import datetime from IPython.html.widgets import interact Explanation: <h1>Basic test of the wflow BMI interface End of explanation # This is the LAnd Atmophere (LA) model LA_model = bmi.wflowbmi_csdms() LA_model.initialize('../example...
4,051
Given the following text description, write Python code to implement the functionality described below step by step Description: Divide continuous data into equally-spaced epochs This tutorial shows how to segment continuous data into a set of epochs spaced equidistantly in time. The epochs will not be created based o...
Python Code: import os import numpy as np import matplotlib.pyplot as plt import mne from mne.preprocessing import compute_proj_ecg from mne_connectivity import envelope_correlation sample_data_folder = mne.datasets.sample.data_path() sample_data_raw_file = os.path.join(sample_data_folder, 'MEG', 'sample', ...
4,052
Given the following text description, write Python code to implement the functionality described below step by step Description: Logistic Regression with a Neural Network mindset Welcome to your first (required) programming assignment! You will build a logistic regression classifier to recognize cats. This assignment...
Python Code: import numpy as np import matplotlib.pyplot as plt import h5py import scipy from PIL import Image from scipy import ndimage from lr_utils import load_dataset %matplotlib inline Explanation: Logistic Regression with a Neural Network mindset Welcome to your first (required) programming assignment! You will b...
4,053
Given the following text description, write Python code to implement the functionality described below step by step Description: Fixing BEM and head surfaces Sometimes when creating a BEM model the surfaces need manual correction because of a series of problems that can arise (e.g. intersection between surfaces). Here...
Python Code: # Authors: Marijn van Vliet <w.m.vanvliet@gmail.com> # Ezequiel Mikulan <e.mikulan@gmail.com> # Manorama Kadwani <manorama.kadwani@gmail.com> # # License: BSD-3-Clause import os import shutil import mne data_path = mne.datasets.sample.data_path() subjects_dir = data_path / 'subjects' bem_...
4,054
Given the following text description, write Python code to implement the functionality described below step by step Description: 2D plots Demonstration of the 2D plot capabilities The plot2d plot method make plots of 2-dimensional scalar data using matplotlibs pcolormesh or the contourf functions. Note that this metho...
Python Code: import psyplot.project as psy import xarray as xr %matplotlib inline %config InlineBackend.close_figures = False import numpy as np Explanation: 2D plots Demonstration of the 2D plot capabilities The plot2d plot method make plots of 2-dimensional scalar data using matplotlibs pcolormesh or the contourf fun...
4,055
Given the following text description, write Python code to implement the functionality described below step by step Description: Interactions and ANOVA Note Step1: Take a look at the data Step2: Fit a linear model Step3: Have a look at the created design matrix Step4: Or since we initially passed in a DataFrame, w...
Python Code: %matplotlib inline from urllib.request import urlopen import numpy as np np.set_printoptions(precision=4, suppress=True) import pandas as pd pd.set_option("display.width", 100) import matplotlib.pyplot as plt from statsmodels.formula.api import ols from statsmodels.graphics.api import interaction_plot, abl...
4,056
Given the following text description, write Python code to implement the functionality described below step by step Description: The Fermi-Hubbard Model This notebook shows how to use the tensor_basis constructor to build the Hamiltonian of interacting spinful fermions in 1d, desctibed by the Fermi-Hubbard model (FHM)...
Python Code: from quspin.operators import hamiltonian # Hamiltonians and operators from quspin.basis import spinless_fermion_basis_1d, tensor_basis # Hilbert space fermion and tensor bases import numpy as np # generic math functions ##### define model parameters ##### L=4 # system size J=1.0 # hopping U=np.sqrt(2.0) # ...
4,057
Given the following text description, write Python code to implement the functionality described below step by step Description: Blowing up things! So far we learned about functions, conditions and loops. Lets use our knowledge so far to do something fun - blow up things! In this adventure we will build structures wit...
Python Code: # Run this once before starting your tasks import mcpi.minecraft as minecraft import mcpi.block as block import time import thread mc = minecraft.Minecraft.create() Explanation: Blowing up things! So far we learned about functions, conditions and loops. Lets use our knowledge so far to do something fun - b...
4,058
Given the following text description, write Python code to implement the functionality described below step by step Description: Part 5 Step1: Configure GCP environment settings Update the following variables to reflect the values for your GCP environment Step2: Authenticate your GCP account This is required if you ...
Python Code: import numpy as np import tensorflow as tf Explanation: Part 5: Deploy the solution to AI Platform Prediction This notebook is the fifth of five notebooks that guide you through running the Real-time Item-to-item Recommendation with BigQuery ML Matrix Factorization and ScaNN solution. Use this notebook to ...
4,059
Given the following text description, write Python code to implement the functionality described below step by step Description: State space models - concentrating the scale out of the likelihood function Step1: Introduction (much of this is based on Harvey (1989); see especially section 3.4) State space models can g...
Python Code: import numpy as np import pandas as pd import statsmodels.api as sm dta = sm.datasets.macrodata.load_pandas().data dta.index = pd.PeriodIndex(start='1959Q1', end='2009Q3', freq='Q') Explanation: State space models - concentrating the scale out of the likelihood function End of explanation class LocalLevel(...
4,060
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Face Generation In this project, you'll use generative adversarial networks to generate new images of faces. Get the Data You'll be using two datasets in this project Step3: Explore ...
Python Code: data_dir = './data' # FloydHub - Use with data ID "R5KrjnANiKVhLWAkpXhNBe" #data_dir = '/input' DON'T MODIFY ANYTHING IN THIS CELL import helper helper.download_extract('mnist', data_dir) helper.download_extract('celeba', data_dir) Explanation: Face Generation In this project, you'll use generative adversa...
4,061
Given the following text description, write Python code to implement the functionality described below step by step Description: Github https Step3: List Comprehensions Step4: Dictionaries Python dictionaries are awesome. They are hash tables and have a lot of neat CS properties. Learn and use them well.
Python Code: # Create a [list] days = ['Monday', # multiple lines 'Tuesday', # acceptable 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday', ] # trailing comma is fine! days # Simple for-loop for day in days: print(day) # Double for-loop for day in da...
4,062
Given the following text description, write Python code to implement the functionality described below step by step Description: &larr; Back to Index Novelty Functions To detect note onsets, we want to locate sudden changes in the audio signal that mark the beginning of transient regions. Often, an increase in the sig...
Python Code: x, sr = librosa.load('audio/simple_loop.wav') print(x.shape, sr) Explanation: &larr; Back to Index Novelty Functions To detect note onsets, we want to locate sudden changes in the audio signal that mark the beginning of transient regions. Often, an increase in the signal's amplitude envelope will denote an...
4,063
Given the following text description, write Python code to implement the functionality described below step by step Description: <a id='top'></a> Random Forests May 2017 <br> This is a study for a blog post to appear on Data Simple. It will focus on the theory and scikit-learn implementation of the Random Forest machi...
Python Code: %matplotlib inline import matplotlib.pyplot as plt # Generate data from sklearn.datasets import make_blobs X, y = make_blobs(n_samples=300, n_features=2, centers=3, cluster_std=4, random_state=42) # Plot data plt.plot(X[:, 0][y==0], X[:, 1][y==0], "yo", marker='.') plt.plot(X[:, 0][y==1],...
4,064
Given the following text description, write Python code to implement the functionality described below step by step Description: 2.2 DataFrame Content Step1: 2.1.1 DataFrame Structure Initializing a Dataframe. Step2: 2.2.2 Working with columns Step3: Exercise Step4: There are many commonly used column-wide methods...
Python Code: import numpy as np import pandas as pd Explanation: 2.2 DataFrame Content: - 2.2.1 DataFrame Structure - 2.2.2 Working with Columns - 2.2.3 Working with Rows - 2.2.4 Conditional Selection - 2.2.5 Case Study: Olympic Games A DataFrame is a two dimensional data structure with columns of potentially...
4,065
Given the following text description, write Python code to implement the functionality described below step by step Description: GUI creation and interaction in IPython Step1: A pop up will appear saying The kernel appears to have died and will restart automatically In the terminal, you can also see the following me...
Python Code: %gui from PyQt5 import QtWidgets b1 = QtWidgets.QPushButton("Click Me") Explanation: GUI creation and interaction in IPython End of explanation %gui qt5 from PyQt5 import QtWidgets b1 = QtWidgets.QPushButton("Click Me") b1.show() Explanation: A pop up will appear saying The kernel appears to have died and...
4,066
Given the following text description, write Python code to implement the functionality described below step by step Description: Example of taking 'views' from simulated populations Step1: Get the mutations that are segregating in each population Step2: Look at the raw data in the first element of each list Step3: ...
Python Code: from __future__ import print_function import fwdpy as fp import pandas as pd from background_selection_setup import * Explanation: Example of taking 'views' from simulated populations End of explanation mutations = [fp.view_mutations(i) for i in pops] Explanation: Get the mutations that are segregating in ...
4,067
Given the following text description, write Python code to implement the functionality described below step by step Description: Ordinary Least Squares Step1: OLS estimation Artificial data Step2: Our model needs an intercept so we add a column of 1s Step3: Fit and summary Step4: Quantities of interest can be extr...
Python Code: %matplotlib inline import numpy as np import pandas as pd import matplotlib.pyplot as plt import statsmodels.api as sm from statsmodels.sandbox.regression.predstd import wls_prediction_std np.random.seed(9876789) Explanation: Ordinary Least Squares End of explanation nsample = 100 x = np.linspace(0, 10, 10...
4,068
Given the following text description, write Python code to implement the functionality described below step by step Description: Using groupby(), plot the number of films that have been released each decade in the history of cinema. Step1: Use groupby() to plot the number of "Hamlet" films made each decade. Step2: H...
Python Code: titles.groupby(titles['year']//10 *10)['year'].size().plot(kind='bar') Explanation: Using groupby(), plot the number of films that have been released each decade in the history of cinema. End of explanation titles[titles['title']=='Hamlet'].groupby(titles[titles['title']=='Hamlet']['year']//10 *10)['year']...
4,069
Given the following text description, write Python code to implement the functionality described below step by step Description: 原始 SPN 实现 原理与算法 这里我们实现了教材上的原始 SPN 算法,相关的数据(秘钥,秘钥编排算法,S盒,P盒,轮数)均保持一致,并在程序内部定义。 程序设计 常量规定 | 变量 | 意义 | 类型 | | ------------ | ---- | ---- | | x | 明文 | 整形 | | piS ...
Python Code: m, l = 4, 4 # m S-Boxes, l bits in each piS = {0: 14, 1: 4, 2: 13, 3: 1, 4: 2, 5: 15, 6: 11, 7: 8, 8: 3, 9: 10, 10: 6, 11: 12, 12: 5, 13: 9, 14: 0, 15: 7} piP = {1: 1, 2: 5, 3: 9, 4: 13, 5: 2, 6: 6, 7: 10, 8: 14, 9: 3, 10: 7, 11: 11, 12: 15, 13: 4, 14: 8, 15: 12, 1...
4,070
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction In the last few years speed dating popularity has grown quickly. Despite its popularity lots of people don't seem as satisfied as they'd like. Most users don't end up finding wh...
Python Code: speedDatingDF = pd.read_csv("Speed Dating Data.csv",encoding = "ISO-8859-1") #speedDatingDF.dtypes #We can see which type has each attr. Explanation: Introduction In the last few years speed dating popularity has grown quickly. Despite its popularity lots of people don't seem as satisfied as they'd like. M...
4,071
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Wolf-Sheep-Grass Model with Soil Creep This notebook demonstrates coupling of an ABM implemented in Mesa and a grid-based numerical model written in Landlab. The example is the canoni...
Python Code: try: from mesa import Model except ModuleNotFoundError: print( Mesa needs to be installed in order to run this notebook. Normally Mesa should be pre-installed alongside the Landlab notebook collection. But it appears that Mesa is not already installed on the system on which you are runnin...
4,072
Given the following text description, write Python code to implement the functionality described below step by step Description: Handy small functions related to astronomical research Step3: Defining function Emission related 1. Dust Step8: 2. Opacity Step10: Motions 1. free-fall timescale Step13: 2. Jeans Length ...
Python Code: import math import numpy as np from numpy import size Explanation: Handy small functions related to astronomical research End of explanation def Planckfunc_cgs(freq, temperature): Calculate Planck function. Inputs: freq: frequency, in Hz temperature: temperature in Kelvin Return...
4,073
Given the following text description, write Python code to implement the functionality described below step by step Description: Efficiently searching for optimal tuning parameters From the video series Step1: More efficient parameter tuning using GridSearchCV Allows you to define a grid of parameters that will be se...
Python Code: from sklearn.datasets import load_iris from sklearn.neighbors import KNeighborsClassifier from sklearn.cross_validation import cross_val_score import matplotlib.pyplot as plt %matplotlib inline # read in the iris data iris = load_iris() # create X (features) and y (response) X = iris.data y = iris.target #...
4,074
Given the following text description, write Python code to implement the functionality described below step by step Description: Callables in Research The main purpose of Research is to run pipleines with different configs in parallel but you also can add callables and realize very flexible plans of experiments even w...
Python Code: import sys import os import shutil import warnings warnings.filterwarnings('ignore') from tensorflow import logging logging.set_verbosity(logging.ERROR) os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' import matplotlib %matplotlib inline import numpy as np sys.path.append('../../..') from batchflow import Pipelin...
4,075
Given the following text description, write Python code to implement the functionality described below step by step Description: Bayesian Parametric Regression Notebook version Step1: 1. Model-based parametric regression 1.1. The regression problem. Given an observation vector ${\bf x}$, the goal of the regression pr...
Python Code: # Import some libraries that will be necessary for working with data and displaying plots # To visualize plots in the notebook %matplotlib inline from IPython import display import matplotlib import matplotlib.pyplot as plt import numpy as np import scipy.io # To read matlab files import pylab impor...
4,076
Given the following text description, write Python code to implement the functionality described below step by step Description: Note that you have to execute the command jupyter notebook in the parent directory of this directory for otherwise jupyter won't be able to access the file style.css. Step1: This example h...
Python Code: from IPython.core.display import HTML with open ("../style.css", "r") as file: css = file.read() HTML(css) Explanation: Note that you have to execute the command jupyter notebook in the parent directory of this directory for otherwise jupyter won't be able to access the file style.css. End of explanat...
4,077
Given the following text description, write Python code to implement the functionality described below step by step Description: Data Manipulation with Numpy and Pandas Handling with large data is easy in Python. In the simplest way using arrays. However, they are pretty slow. Numpy and Panda are two great libraries f...
Python Code: import numpy as np # Generating a random array X = np.random.random((3, 5)) # a 3 x 5 array print(X) Explanation: Data Manipulation with Numpy and Pandas Handling with large data is easy in Python. In the simplest way using arrays. However, they are pretty slow. Numpy and Panda are two great libraries for...
4,078
Given the following text description, write Python code to implement the functionality described below step by step Description: <center><h2>Scale your pandas workflows by changing one line of code</h2> Exercise 1 Step1: Concept for exercise Step2: Now that we have created a toy example for playing around with the D...
Python Code: # Modin engine can be specified either by config import modin.config as cfg cfg.Engine.put("dask") # or by setting the environment variable # import os # os.environ["MODIN_ENGINE"] = "dask" Explanation: <center><h2>Scale your pandas workflows by changing one line of code</h2> Exercise 1: How to use Modin G...
4,079
Given the following text description, write Python code to implement the functionality described below step by step Description: Simple Reinforcement Learning in Tensorflow Part 1 Step1: The Bandit Here we define our bandit. For this example we are using a four-armed bandit. The pullBandit function generates a random...
Python Code: import tensorflow as tf import tensorflow.contrib.slim as slim import numpy as np Explanation: Simple Reinforcement Learning in Tensorflow Part 1: The Multi-armed bandit This tutorial contains a simple example of how to build a policy-gradient based agent that can solve the multi-armed bandit problem. For ...
4,080
Given the following text description, write Python code to implement the functionality described below step by step Description: Data Pulling Step1: to find a particular class, open the page using chrome, select the particular subpart of page and click inspect Name of Movie Step2: Ratings from Rotten Tomatoes
Python Code: r = urllib.request.urlopen('https://www.rottentomatoes.com/franchise/batman_movies').read() #Using Beautiful Soup Library to parse the data soup = BeautifulSoup(r, "lxml") type(soup) len(str(soup.prettify())) soup soup.prettify() #We convert the data to a string format using str. #Note in R we use str for...
4,081
Given the following text description, write Python code to implement the functionality described below step by step Description: Illustrating common terms usage using Wikinews in english getting data We get the cirrussearch dump of wikinews (a dump meant for elastic-search indexation). Step1: Preparing data we arrang...
Python Code: LANG="english" %%bash fdate=20170327 fname=enwikinews-$fdate-cirrussearch-content.json.gz if [ ! -e $fname ] then wget "https://dumps.wikimedia.org/other/cirrussearch/$fdate/$fname" fi # iterator import gzip import json FDATE = 20170327 FNAME = "enwikinews-%s-cirrussearch-content.json.gz" % FDATE def ...
4,082
Given the following text description, write Python code to implement the functionality described below step by step Description: Permutation T-test on sensor data One tests if the signal significantly deviates from 0 during a fixed time window of interest. Here computation is performed on MNE sample dataset between 40...
Python Code: # Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr> # # License: BSD-3-Clause import numpy as np import mne from mne import io from mne.stats import permutation_t_test from mne.datasets import sample print(__doc__) Explanation: Permutation T-test on sensor data One tests if the signal significantly...
4,083
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2018 The TensorFlow Authors. Step1: Eager execution basics <table class="tfo-notebook-buttons" align="left"><td> <a target="_blank" href="https Step2: Tensors A Tensor is a multi...
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...
4,084
Given the following text description, write Python code to implement the functionality described below step by step Description: Exercise 1 - Basic SQL DML and DDL Part 1 - Data manipulation (DML) Get the survey.db SQLite3 database file from the Software Carpentry lesson and connect to it. Step1: Basic queries Step2:...
Python Code: !wget http://files.software-carpentry.org/survey.db %load_ext sql %sql sqlite:///survey.db Explanation: Exercise 1 - Basic SQL DML and DDL Part 1 - Data manipulation (DML) Get the survey.db SQLite3 database file from the Software Carpentry lesson and connect to it. End of explanation %%sql SELECT personal,...
4,085
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction Here, you'll use window functions to answer questions about the Chicago Taxi Trips dataset. Before you get started, run the code cell below to set everything up. Step1: The fol...
Python Code: # Set up feedback system from learntools.core import binder binder.bind(globals()) from learntools.sql_advanced.ex2 import * print("Setup Complete") Explanation: Introduction Here, you'll use window functions to answer questions about the Chicago Taxi Trips dataset. Before you get started, run the code cel...
4,086
Given the following text description, write Python code to implement the functionality described below step by step Description: Momentum A stock that's going up tends to keep going up...until it doesn't. Momentum is the theory that stocks that have recently gone up will keep going up disproportionate to their underl...
Python Code: import pandas as pd import matplotlib.pyplot as plt import datetime import pinkfish as pf import strategy # format price data pd.options.display.float_format = '{:0.2f}'.format %matplotlib inline # Set size of inline plots '''note: rcParams can't be in same cell as import matplotlib or %matplotlib inlin...
4,087
Given the following text description, write Python code to implement the functionality described below step by step Description: Sochastic simulation algorithm (SSA) Jens Hahn - 06/06/2016 Last time we have talked about ODE modelling, which is a deterministic and continuous way of modelling. This time, we'll talk ab...
Python Code: import math import numpy as np import matplotlib.pyplot as pyp %matplotlib inline # S -> P*S - B*S*Z - d*S S = 500 # Z -> B*S*Z + G*R - A*S*Z Z = 0 # R -> d*S - G*R R = 0 P = 0.0001 # birth rate d = 0.01 # 'natural' death percent (per day) B = 0.0095 # transmission percent (per day) G = 0.001 # resure...
4,088
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 7</font> Download Step1: Missão Step2: Teste da Solução
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 7</font> Download: http://github.com/dsacademybr End of explanation impor...
4,089
Given the following text description, write Python code to implement the functionality described below step by step Description: Classifying Blobs Step1: Digets examples Classification using (linear) PCA and (nonlinear) Isometric Maps Step2: Unsuperised learning Notice that the training labels are unused. The digits...
Python Code: from sklearn.datasets import make_blobs X, y = make_blobs(random_state=42, centers=3) X[:,1] += 0.25*X[:,0]**2 # print(X.shape) # print(y) # plt.scatter(X[:, 0], X[:, 1], 20, y, edgecolor='none') plt.plot(X[:, 0], X[:, 1], 'ok') from sklearn.cluster import KMeans, AffinityPropagation, SpectralClustering # ...
4,090
Given the following text description, write Python code to implement the functionality described below step by step Description: Replication Archive for "Measuring causes of death in populations Step1: Table 1 Confusion matrices for physician-certified verbal autopsy and random-allocation verbal autopsy. Panel A show...
Python Code: import numpy as np, pandas as pd, matplotlib.pyplot as plt, seaborn as sns %matplotlib inline sns.set_style('whitegrid') sns.set_context('poster') Explanation: Replication Archive for "Measuring causes of death in populations: a new metric that corrects cause-specific mortality fractions for chance" End of...
4,091
Given the following text description, write Python code to implement the functionality described below step by step Description: 1) Make a request from the Forecast.io API for where you were born (or lived, or want to visit!). Tip Step1: 2) What's the current wind speed? How much warmer does it feel than it actually ...
Python Code: import requests # api request for bethesda, maryland response = requests.get('https://api.forecast.io/forecast/a197f06e1906b1a937ad31d4378b8939/38.9847, -77.0947') data = response.json() current = data['currently'] current Explanation: 1) Make a request from the Forecast.io API for where you were born (o...
4,092
Given the following text description, write Python code to implement the functionality described below step by step Description: TensorFlow Step1: Download the Data Step2: Dataset Metadata Step3: Building a TensorFlow Custom Estimator Creating feature columns Creating model_fn Create estimator using the model_fn De...
Python Code: import math import os import pandas as pd import numpy as np from datetime import datetime import tensorflow as tf from tensorflow import data print "TensorFlow : {}".format(tf.__version__) SEED = 19831060 Explanation: TensorFlow: Optimizing Learning Rate End of explanation DATA_DIR='data' # !mkdir $DATA_D...
4,093
Given the following text description, write Python code to implement the functionality described below step by step Description: Evolutionary algorithm to calibrate model 1 get data from S&P500 Step1: Define parameter space bounds We define the parameter bounds as follows. | Parameter | Values (start, stop, step) | ...
Python Code: start_date = '2010-01-01' end_date = '2016-12-31' spy = data.DataReader("SPY", start=start_date, end=end_date, data_source='google')['Close'] spy_returns = spy.pct_change()[1:] spy_volume = data.DataReader("SPY", ...
4,094
Given the following text description, write Python code to implement the functionality described below step by step Description: Implementing an LR-Table-Generator A Grammar for Grammars As the goal is to generate an LR-table-generator we first need to implement a parser for context free grammars. The file arith.g con...
Python Code: !type Examples\c-grammar.g !cat Examples/arith.g Explanation: Implementing an LR-Table-Generator A Grammar for Grammars As the goal is to generate an LR-table-generator we first need to implement a parser for context free grammars. The file arith.g contains an example grammar that describes arithmetic expr...
4,095
Given the following text description, write Python code to implement the functionality described below step by step Description: The Efficient Frontier Step1: Assume that we have 4 assets, each with a return series of length 1000. We can use numpy.random.randn to sample returns from a normal distribution. Step2: The...
Python Code: import numpy as np import matplotlib.pyplot as plt import cvxopt as opt from cvxopt import blas, solvers import pandas as pd np.random.seed(123) # Turn off progress printing solvers.options['show_progress'] = False Explanation: The Efficient Frontier: Markowitz Portfolio optimization in Python Authors: Dr...
4,096
Given the following text description, write Python code to implement the functionality described below step by step Description: Attempting human-like speach Step1: Define our markiv hcain functions. First to create the dics. First attempt only takes triplets of words a b c and adds {'a b' Step2: Load the books and ...
Python Code: import pensieve as pens import textacy from collections import defaultdict from random import random Explanation: Attempting human-like speach: Markov chains In orderto make the activitiy sentences in our memory more human-like, we can attempt to build a simple chatbot from the tex as well. A simple, and m...
4,097
Given the following text description, write Python code to implement the functionality described below step by step Description: lesson1-rxt50-CA.ipynb -- Code Along of Step1: Just looking at the fastai library source code while the above works Step2: Hah! How about that. That settles that mystery. Up above you'll s...
Python Code: # Put these at the top of every notebook, to get automatic reloading and inline plotting %reload_ext autoreload %autoreload 2 %matplotlib inline # This file contains all the main external libs we'll use from fastai.imports import * from fastai.transforms import * from fastai.conv_learner import * from fast...
4,098
Given the following text description, write Python code to implement the functionality described below step by step Description: Adding Parameters With REBOUNDx We start by creating a simulation, attaching REBOUNDx, and adding the effects of general relativity Step1: The documentation page https Step2: We would now ...
Python Code: import rebound import reboundx sim = rebound.Simulation() sim.add(m=1.) sim.add(a=1.) ps = sim.particles rebx = reboundx.Extras(sim) gr = rebx.load_force('gr') rebx.add_force(gr) Explanation: Adding Parameters With REBOUNDx We start by creating a simulation, attaching REBOUNDx, and adding the effects of ge...
4,099
Given the following text description, write Python code to implement the functionality described below step by step Description: Метод главных компонент В данном задании вам будет предложено ознакомиться с подходом, который переоткрывался в самых разных областях, имеет множество разных интерпретаций, а также несколько...
Python Code: import numpy as np import pandas as pd import matplotlib from matplotlib import pyplot as plt import matplotlib.patches as mpatches matplotlib.style.use('ggplot') %matplotlib inline Explanation: Метод главных компонент В данном задании вам будет предложено ознакомиться с подходом, который переоткрывался в ...