Unnamed: 0
int64
0
16k
text_prompt
stringlengths
110
62.1k
code_prompt
stringlengths
37
152k
9,800
Given the following text description, write Python code to implement the functionality described below step by step Description: How to generate histograms using YugabyteDB (PostgreSQL-compatible) This provides and example of how to generate frequency histograms using YugabyteDB. Disambiguation Step2: Define the quer...
Python Code: # connect to PostgreSQL using psycopg2 # !pip install psycopg2-binary import psycopg2 # Connect to an existing database and create the test table with psycopg2.connect("dbname=yugabyte user=yugabyte host=localhost port=5433") as yb_conn: cur = yb_conn.cursor() # use this drop statement if you...
9,801
Given the following text description, write Python code to implement the functionality described below step by step Description: Tutorial 3 Step1: We can now import the deepchem package to play with. Step2: MoleculeNet Overview In the last two tutorials we loaded the Delaney dataset of molecular solubilities. Let's...
Python Code: !curl -Lo conda_installer.py https://raw.githubusercontent.com/deepchem/deepchem/master/scripts/colab_install.py import conda_installer conda_installer.install() !/root/miniconda/bin/conda info -e !pip install --pre deepchem Explanation: Tutorial 3: An Introduction To MoleculeNet One of the most powerful f...
9,802
Given the following text description, write Python code to implement the functionality described below step by step Description: Electric Machinery Fundamentals 5th edition Chapter 6 (Code examples) Example 6-5 (d) Creates a plot of the torque-speed curve of the induction motor as depicted in Figure 6-23. Note Step1: ...
Python Code: %pylab notebook Explanation: Electric Machinery Fundamentals 5th edition Chapter 6 (Code examples) Example 6-5 (d) Creates a plot of the torque-speed curve of the induction motor as depicted in Figure 6-23. Note: You should first click on "Cell → Run All" in order that the plots get generated. Import ...
9,803
Given the following text description, write Python code to implement the functionality described below step by step Description: <a href="https Step2: Assignment 3b Step3: Encoding issues with txt files For Windows users, the file “AnnaKarenina.txt” gets the encoding cp1252. In order to open the file, you have to a...
Python Code: %%capture !wget https://github.com/cltl/python-for-text-analysis/raw/master/zips/Data.zip !wget https://github.com/cltl/python-for-text-analysis/raw/master/zips/images.zip !wget https://github.com/cltl/python-for-text-analysis/raw/master/zips/Extra_Material.zip !unzip Data.zip -d ../ !unzip images.zip -d ....
9,804
Given the following text description, write Python code to implement the functionality described below step by step Description: Columns to remove Step1: Run decision tree Step2: Check variance inflation factors If the VIF is equal to 1 there is no multicollinearity among factors, but if the VIF is greater than 1, t...
Python Code: plt.scatter(train['avg_blocktime_6'], train['avg_blocktime_60']) Explanation: Columns to remove: Possible leakage: avg_price_6, avg_price_60, avg_gasUsed_b_6, avg_gasUsed_t_6, avg_gasUsed_b_60, avg_gasUsed_t_60, avg_price_60 Poor performance: gasLimit_t, gasUsed_t, newContract, avg_uncle_count_6, avg_txcn...
9,805
Given the following text description, write Python code to implement the functionality described below step by step Description: Load from here Step1: https Step2: Manual overwrites
Python Code: dc=pd.read_csv('dcg.csv') Explanation: Load from here End of explanation pop2=pd.read_csv('worldcities.csv') pop2 def ccc(c,country): if c=='Moscow region (oblast)': return 'Moscow' if c=='Rostov-on-Don': return 'Rostov-na-Donu' if c=='Gdansk, Gdynia and Sopot': return 'Gdansk+Gdynia' if c=...
9,806
Given the following text description, write Python code to implement the functionality described below step by step Description: Polynomial Regression and Overfitting Step1: In this notebook we want to discuss both <em style="color Step2: Let us plot the data. We will use colors to distinguish between x1 and x2. T...
Python Code: import numpy as np import sklearn.linear_model as lm Explanation: Polynomial Regression and Overfitting End of explanation np.random.seed(42) N = 20 # number of data points X1 = np.array([k for k in range(N)]) X2 = np.array([k + 0.2 * (np.random.rand() - 0.5) for k in ra...
9,807
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction to Brian part 1 Step1: In Python, the notation ''' is used to begin and end a multi-line string. So the equations are just a string with one line per equation. The equations ar...
Python Code: tau = eqs = ''' ''' Explanation: Introduction to Brian part 1: Neurons Adapted form brian2 tutorial All Brian scripts start with the following. If you're trying this notebook out in IPython, you should start by running this cell. Later we'll do some plotting in the notebook, so we activate inline plotting...
9,808
Given the following text description, write Python code to implement the functionality described below step by step Description: Example notebook Step1: Create a structure analysis object If you include a 'mapfile' then we will use locus information to subsample just a single SNP from each locus so that the resulting...
Python Code: # conda install ipyrad -c ipyrad # conda install structure clumpp -c ipyrad # conda install toytree -c eaton-lab import ipyrad.analysis as ipa import toyplot Explanation: Example notebook: Structure with pop assignments This notebook shows how to use the ipyrad.analysis toolkit to generate structure input ...
9,809
Given the following text description, write Python code to implement the functionality described below step by step Description: Bayesian Logistic Regression with PyMC3 This is a reproduction with a few slight alterations of Bayesian Log Reg by J. Benjamin Cook Author Step1: The Adult Data Set is commonly used to ben...
Python Code: %matplotlib inline import pandas as pd import numpy as np import pymc3 as pm import matplotlib.pyplot as plt import seaborn import warnings warnings.filterwarnings('ignore') from collections import OrderedDict from time import time import numpy as np import pandas as pd import matplotlib.pyplot as plt from...
9,810
Given the following text description, write Python code to implement the functionality described below step by step Description: Transport through a barrier All systems so far had a flat potential. In this notebook, we will change this. Basic setup (like in the previous notebook) Step1: "MOSFET" toy model Let's cons...
Python Code: import numpy as np import kwant %run matplotlib_setup.ipy from matplotlib import pyplot lat = kwant.lattice.square() Explanation: Transport through a barrier All systems so far had a flat potential. In this notebook, we will change this. Basic setup (like in the previous notebook): End of explanation def ...
9,811
Given the following text description, write Python code to implement the functionality described below step by step Description: Your first neural network In this project, you'll build your first neural network and use it to predict daily bike rental ridership. We've provided some of the code, but left the implementat...
Python Code: %matplotlib inline %config InlineBackend.figure_format = 'retina' import numpy as np import pandas as pd import matplotlib.pyplot as plt Explanation: Your first neural network In this project, you'll build your first neural network and use it to predict daily bike rental ridership. We've provided some of t...
9,812
Given the following text description, write Python code to implement the functionality described below step by step Description: Sentiments analysis challenge on movie review Designed by Step1: Trainning and testing the model with cross validation. Step2: The next cell may take some time. Step3: Trainning the mode...
Python Code: from __future__ import division, print_function import pandas as pd import numpy as np data_dir = 'data/' # Load Original Data / contains data + labels 10 k train = pd.read_csv("../data/train.data")#.drop('id',axis =1 ) # Your validation data / we provide also a validation dataset, contains only data : 5k...
9,813
Given the following text description, write Python code to implement the functionality described below step by step Description: This notebook is largely based on material of the Python Scientific Lecture Notes (https Step1: Note Step2: Parameters Mandatory parameters (positional arguments) Step3: Optional paramete...
Python Code: def the_answer_to_the_universe(): print(42) the_answer_to_the_universe() Explanation: This notebook is largely based on material of the Python Scientific Lecture Notes (https://scipy-lectures.github.io/), adapted with some exercises. Reusing code <div class="alert alert-danger"> <b>Rule of thumb</b>: <...
9,814
Given the following text description, write Python code to implement the functionality described below step by step Description: Sockets can be configured to act as a server and listen for incoming messages, or connect to other applications as a client. After both ends of a TCP/IP socket are connected, communication i...
Python Code: # %load socket_echo_server.py import socket import sys # Create a TCP/IP socket sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Bind the socket to the port server_address = ('localhost', 10000) print('starting up on {} port {}'.format(*server_address)) sock.bind(server_address) # Listen for inco...
9,815
Given the following text description, write Python code to implement the functionality described below step by step Description: A Simple Compiler for a Fragment of C This file shows how a simple compiler for a fragment of the programming language C can be implemented using Ply. Specification of the Scanner Step1: Th...
Python Code: import ply.lex as lex tokens = [ 'NUMBER', 'ID', 'EQ', 'NE', 'LE', 'GE', 'AND', 'OR', 'INT', 'IF', 'ELSE', 'WHILE', 'RETURN' ] Explanation: A Simple Compiler for a Fragment of C This file shows how a simple compiler for a fragment of the programming language C can be implemented using P...
9,816
Given the following text description, write Python code to implement the functionality described below step by step Description: Quiz 2 Intelligent Systems 2016-1 After solving all the questions in the exam save your notebook with the name username.ipynb and submit it to Step3: 1. (1.7) Implement a MDP that solves th...
Python Code: from mdp import * from rl import * Explanation: Quiz 2 Intelligent Systems 2016-1 After solving all the questions in the exam save your notebook with the name username.ipynb and submit it to: https://www.dropbox.com/request/0Eh9d2PvQMdAyJviK4Nl End of explanation class LinearMDP(GridMDP): A two-dimensi...
9,817
Given the following text description, write Python code to implement the functionality described below step by step Description: Interact Exercise 3 Imports Step1: Using interact for animation with data A soliton is a constant velocity wave that maintains its shape as it propagates. They arise from non-linear wave eq...
Python Code: %matplotlib inline from matplotlib import pyplot as plt import numpy as np from math import sqrt from IPython.html.widgets import interact, interactive, fixed from IPython.display import display Explanation: Interact Exercise 3 Imports End of explanation def soliton(x, t, c, a): z = (0.5) * c * (((1) /...
9,818
Given the following text description, write Python code to implement the functionality described below step by step Description: Notebook is a revised version of notebook from Sara Robinson and Ivan Chueng E2E ML on GCP Step1: Restart the kernel After you install the additional packages, you need to restart the noteb...
Python Code: import os # The Vertex AI Workbench Notebook product has specific requirements IS_WORKBENCH_NOTEBOOK = os.getenv("DL_ANACONDA_HOME") IS_USER_MANAGED_WORKBENCH_NOTEBOOK = os.path.exists( "/opt/deeplearning/metadata/env_version" ) # Vertex AI Notebook requires dependencies to be installed with '--user' U...
9,819
Given the following text description, write Python code to implement the functionality described below step by step Description: Resit Assignment part A Deadline Step1: Please make sure you can load the English spaCy model Step2: Exercise 1 Step3: Please test your function using the following function call Step4: ...
Python Code: import spacy Explanation: Resit Assignment part A Deadline: Tuesday, November 30, 2021 before 17:00 Please name your files: ASSIGNMENT-RESIT-A.ipynb utils.py (from part B) raw_text_to_coll.py (from part B) Please name your zip file as follows: RESIT-ASSIGNMENT.zip and upload it via Canvas (Resit Assignme...
9,820
Given the following text description, write Python code to implement the functionality described below step by step Description: Making predictions Load Model This notebook loads a model previously trained in 2_keras.ipynb or 3_eager.ipynb from earlier in the TensorFlow Basics workshop. Note Step2: Live Predictions ...
Python Code: # In Jupyter, you would need to install TF 2 via !pip. %tensorflow_version 2.x ## Load models from Drive (Colab only). models_path = '/content/gdrive/My Drive/amld_data/models' data_path = '/content/gdrive/My Drive/amld_data/zoo_img' ## Or load models from local machine. # models_path = './amld_models' # d...
9,821
Given the following text description, write Python code to implement the functionality described below step by step Description: What's going on with ROCAUC for Binary Classification? We've identified a bug in ROCAUC Step1: Binary Classification with 1D Coefficients or Feature Importances When the function has 1D coe...
Python Code: %matplotlib inline import os import sys # Modify the path sys.path.append("..") import pandas as pd import yellowbrick as yb import matplotlib.pyplot as plt from yellowbrick.classifier import ROCAUC from sklearn.model_selection import train_test_split occupancy = pd.read_csv('data/occupancy/occupancy.cs...
9,822
Given the following text description, write Python code to implement the functionality described below step by step Description: Large-scale multi-label text classification Author Step1: Perform exploratory data analysis In this section, we first load the dataset into a pandas dataframe and then perform some basic ex...
Python Code: from tensorflow.keras import layers from tensorflow import keras import tensorflow as tf from sklearn.model_selection import train_test_split from ast import literal_eval import matplotlib.pyplot as plt import pandas as pd import numpy as np Explanation: Large-scale multi-label text classification Author: ...
9,823
Given the following text description, write Python code to implement the functionality described below step by step Description: Objective Predict the survival of Titanic passengers using a K-Means algorithm. Data Analysis Data Import Step1: Selection of Features Step2: Cleaning Data Step6: Experiment Heueristics (...
Python Code: import pandas import numpy as np from sklearn.cross_validation import train_test_split from sklearn.cluster import KMeans from pprint import pprint TITANIC_TRAIN = 'train.csv' TITANIC_TEST = 'test.csv' # t_df refers to titanic_dataframe t_df = pandas.read_csv(TITANIC_TRAIN, header=0) Explanation: Objective...
9,824
Given the following text description, write Python code to implement the functionality described below step by step Description: Deep Convolutional GANs In this notebook, you'll build a GAN using convolutional layers in the generator and discriminator. This is called a Deep Convolutional GAN, or DCGAN for short. The D...
Python Code: %matplotlib inline import pickle as pkl import matplotlib.pyplot as plt import numpy as np from scipy.io import loadmat import tensorflow as tf !mkdir data Explanation: Deep Convolutional GANs In this notebook, you'll build a GAN using convolutional layers in the generator and discriminator. This is called...
9,825
Given the following text description, write Python code to implement the functionality described below step by step Description: Einops tutorial, part 1 Step1: Load a batch of images to play with Step2: Composition of axes transposition is very common and useful, but let's move to other capabilities provided by eino...
Python Code: # Examples are given for numpy. This code also setups ipython/jupyter # so that numpy arrays in the output are displayed as images import numpy from utils import display_np_arrays_as_images display_np_arrays_as_images() Explanation: Einops tutorial, part 1: basics <!-- <img src='http://arogozhnikov.github....
9,826
Given the following text description, write Python code to implement the functionality described below step by step Description: ZIKA CLASSIFICATION MODEL IMPORTS Step1: LOAD DATA Step2: ALGORITHMS Step3: TRAIN MODELS Step4: OPTIMIZE N PRINCIPAL COMPONENTS Step5: SAVE MODELS Step6: RUN MODEL
Python Code: # Algorithms from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier from sklearn.linear_model import LogisticRegression from sklearn.naive_bayes import GaussianNB # Metrics from sklearn.metrics import confusion_matrix, roc_curve, auc, accuracy_score from sklearn.metrics import cla...
9,827
Given the following text description, write Python code to implement the functionality described below step by step Description: Compute source power spectral density (PSD) in a label Returns an STC file containing the PSD (in dB) of each of the sources within a label. Step1: Set parameters Step2: View PSD of source...
Python Code: # Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr> # # License: BSD (3-clause) import matplotlib.pyplot as plt import mne from mne import io from mne.datasets import sample from mne.minimum_norm import read_inverse_operator, compute_source_psd print(__doc__) Explanation: Compute source power spect...
9,828
Given the following text description, write Python code to implement the functionality described below step by step Description: Minimal Waveguide Example In this example we show how to calculate the stationary paraxial field for a slab and cylindircal waveguide using PyPropagate. Step1: Setting up the propagators We...
Python Code: from pypropagate import * %matplotlib inline Explanation: Minimal Waveguide Example In this example we show how to calculate the stationary paraxial field for a slab and cylindircal waveguide using PyPropagate. End of explanation settings = presets.settings.create_paraxial_wave_equation_settings() settings...
9,829
Given the following text description, write Python code to implement the functionality described below step by step Description: Class 9 Step1: The Solow model with exogenous population growth Now, let's suppose that production is a function of the supply of labor $L_t$ Step2: An alternative approach Suppose that we...
Python Code: # Initialize parameters for the simulation (A, s, T, delta, alpha, K0) K0 = 20 T= 100 A= 10 alpha = 0.35 delta = 0.1 s = 0.15 # Initialize a variable called capital as a (T+1)x1 array of zeros and set first value to K0 capital = np.zeros(T+1) capital[0] = K0 # Compute all capital values by iterating over t...
9,830
Given the following text description, write Python code to implement the functionality described below step by step Description: Python Language Basics, IPython, and Jupyter Notebooks Step1: The Python Interpreter ```python $ python Python 3.6.0 | packaged by conda-forge | (default, Jan 13 2017, 23 Step2: from numpy...
Python Code: import numpy as np np.random.seed(12345) np.set_printoptions(precision=4, suppress=True) Explanation: Python Language Basics, IPython, and Jupyter Notebooks End of explanation import numpy as np data = {i : np.random.randn() for i in range(7)} data Explanation: The Python Interpreter ```python $ python Pyt...
9,831
Given the following text description, write Python code to implement the functionality described below step by step Description: Boolean Generator This notebook will show how to use the boolean generator to generate a boolean combinational function. The function that is implemented is a 2-input XOR. Step 1 Step1: Ste...
Python Code: from pynq.overlays.logictools import LogicToolsOverlay logictools_olay = LogicToolsOverlay('logictools.bit') Explanation: Boolean Generator This notebook will show how to use the boolean generator to generate a boolean combinational function. The function that is implemented is a 2-input XOR. Step 1: Downl...
9,832
Given the following text description, write Python code to implement the functionality described below step by step Description: Pcygni-Profile Calculator Tool Tutorial This brief tutorial should give you a basic overview of the main features and capabilities of the Python P-Cygni Line profile calculator, which is bas...
Python Code: import matplotlib.pyplot as plt Explanation: Pcygni-Profile Calculator Tool Tutorial This brief tutorial should give you a basic overview of the main features and capabilities of the Python P-Cygni Line profile calculator, which is based on the Elementary Supernova Model (ES) of Jefferey and Branch 1990. I...
9,833
Given the following text description, write Python code to implement the functionality described below step by step Description: Solutions to Tutorial "Algorithmic Methods for Network Analysis with NetworKit" (Part 4) Determining Important Nodes (cont'd) Betweenness Centrality If you interpret the Facebook graph as we...
Python Code: from networkit import * %matplotlib inline cd ~/Documents/workspace/NetworKit G = readGraph("input/PGPgiantcompo.graph", Format.METIS) # Code for 7-1) # exact computation bc = centrality.Betweenness(G, True) %time bc.run() bc.ranking()[:15] # Code for 7-2) # approximate computation bca = centrality.ApproxB...
9,834
Given the following text description, write Python code to implement the functionality described below step by step Description: Semi-supervision and domain adaptation with AdaMatch Author Step1: Before we proceed, let's review a few preliminary concepts underlying this example. Preliminaries In semi-supervised learn...
Python Code: !pip install -q tf-models-official Explanation: Semi-supervision and domain adaptation with AdaMatch Author: Sayak Paul<br> Date created: 2021/06/19<br> Last modified: 2021/06/19<br> Description: Unifying semi-supervised learning and unsupervised domain adaptation with AdaMatch. Introduction In this exampl...
9,835
Given the following text description, write Python code to implement the functionality described below step by step Description: SQL Bootcamp Sarah Beckett-Hile | NYU Stern School of Business | March 2015 Today's plan SQL, the tool of business Relational Databases Why can't I do this in Excel? Setting up this course...
Python Code: # check to see if support code is there import os print('List of files in working directory:') [print(file) for file in os.listdir()] file = 'SQL_support_code.py' if not os.path.isfile(file): raise Exception('***** Program halted, file missing *****') Explanation: SQL Bootcamp Sarah Beckett-Hile | NYU ...
9,836
Given the following text description, write Python code to implement the functionality described below step by step Description: Time-frequency beamforming using DICS Compute DICS source power [1]_ in a grid of time-frequency windows. References .. [1] Dalal et al. Five-dimensional neuroimaging Step1: Read raw data S...
Python Code: # Author: Roman Goj <roman.goj@gmail.com> # # License: BSD (3-clause) import mne from mne.event import make_fixed_length_events from mne.datasets import sample from mne.time_frequency import csd_fourier from mne.beamformer import tf_dics from mne.viz import plot_source_spectrogram print(__doc__) data_path ...
9,837
Given the following text description, write Python code to implement the functionality described below step by step Description: Steady-state space-charge-limited current with traps This example shows how to simulate effects of a single trap level on current-voltage characteristics of a single carrier device. Step1: ...
Python Code: %matplotlib inline import matplotlib.pylab as plt import oedes import numpy as np oedes.init_notebook() # for displaying progress bars Explanation: Steady-state space-charge-limited current with traps This example shows how to simulate effects of a single trap level on current-voltage characteristics of a...
9,838
Given the following text description, write Python code to implement the functionality described below step by step Description: <h1 STYLE="background Step1: <h4 style="border-bottom Step2: <h4 style="border-bottom Step3: <h2 STYLE="background Step4: 上図から分かるように、奇数と偶数が等確率で出るルーレットを10回プレイして、奇数と偶数が同じ回数だけ出る確率(5回ずつ出る確率)...
Python Code: # 乱数を扱うためのライブラリをインポートする。 import random sample_size = 10 # 乱数発生回数 # 一様乱数を dist に格納する (distribution : 分布) dist = [random.random() for i in range(sample_size)] # dist の中身を確認する。 dist # 図やグラフを図示するためのライブラリをインポートする。 import matplotlib.pyplot as plt %matplotlib inline # ヒストグラムを描く。 plt.hist(dist) plt.grid() plt.show...
9,839
Given the following text description, write Python code to implement the functionality described below step by step Description: Manuscript7 - Compute percent of significant information transfers FROM source regions Analysis for Fig. 7 Master code for Ito et al., 2017¶ Takuya Ito (takuya.ito@rutgers.edu) Step1: 0.0 B...
Python Code: import sys sys.path.append('utils/') import numpy as np import loadGlasser as lg import scipy.stats as stats import matplotlib.pyplot as plt import statsmodels.sandbox.stats.multicomp as mc import sys import warnings warnings.filterwarnings('ignore') %matplotlib inline import nibabel as nib import os impor...
9,840
Given the following text description, write Python code to implement the functionality described below step by step Description: Logistic Regression In this example we will see how to classify images as horses or people using logistic regression. The tutorial builds upon the concepts introduced in the Objax basics tut...
Python Code: %pip --quiet install objax import matplotlib.pyplot as plt import os import numpy as np import tensorflow_datasets as tfds import objax from objax.util import EasyDict Explanation: Logistic Regression In this example we will see how to classify images as horses or people using logistic regression. The tuto...
9,841
Given the following text description, write Python code to implement the functionality described below step by step Description: Modeling and Simulation in Python Chapter 1 Copyright 2020 Allen Downey License Step1: The first time you run this on a new installation of Python, it might produce a warning message in pin...
Python Code: try: import pint except ImportError: !pip install pint import pint try: from modsim import * except ImportError: !pip install modsimpy from modsim import * Explanation: Modeling and Simulation in Python Chapter 1 Copyright 2020 Allen Downey License: Creative Commons Attribution 4.0 ...
9,842
Given the following text description, write Python code to implement the functionality described below step by step Description: Read and dump calin and ACTL header and event calin/examples/iact_data/read and dump calin and ACTL raw header and event from zfits file.ipynb - Stephen Fegan - 2017-03-09 Copyright 2017, St...
Python Code: %pylab inline import calin.iact_data.raw_actl_event_data_source import calin.iact_data.telescope_data_source import json import struct import base64 Explanation: Read and dump calin and ACTL header and event calin/examples/iact_data/read and dump calin and ACTL raw header and event from zfits file.ipynb - ...
9,843
Given the following text description, write Python code to implement the functionality described below step by step Description: Nearest neighbor classification Arguably the most simplest classification method. We are given example input vectors $x_i$ and corresponding class labels $c_i$ for $i=1,\dots, N$. The colle...
Python Code: import numpy as np import pandas as pd import matplotlib.pylab as plt df = pd.read_csv(u'data/iris.txt',sep=' ') df X = np.hstack([ np.matrix(df.sl).T, np.matrix(df.sw).T, np.matrix(df.pl).T, np.matrix(df.pw).T]) print X[:5] # sample view c = np.matrix(df.c).T print c[:5]...
9,844
Given the following text description, write Python code to implement the functionality described below step by step Description: Writing Cython In this notebook, we'll take a look at how to implement a simple function using Cython. The operation we'll implement is the first-order diff, which takes in an array of lengt...
Python Code: import numpy as np x = np.random.randn(10000) Explanation: Writing Cython In this notebook, we'll take a look at how to implement a simple function using Cython. The operation we'll implement is the first-order diff, which takes in an array of length $n$: $$\mathbf{x} = \begin{bmatrix} x_1 \ x_2 \ \vdots \...
9,845
Given the following text description, write Python code to implement the functionality described below step by step Description: Item-Based Collaborative Filtering As before, we'll start by importing the MovieLens 100K data set into a pandas DataFrame Step1: Now we'll pivot this table to construct a nice matrix of us...
Python Code: import pandas as pd r_cols = ['user_id', 'movie_id', 'rating'] ratings = pd.read_csv('e:/sundog-consult/udemy/datascience/ml-100k/u.data', sep='\t', names=r_cols, usecols=range(3), encoding="ISO-8859-1") m_cols = ['movie_id', 'title'] movies = pd.read_csv('e:/sundog-consult/udemy/datascience/ml-100k/u.item...
9,846
Given the following text description, write Python code to implement the functionality described below step by step Description: The Evoked data structure Step1: Creating Evoked objects from Epochs Step2: You may have noticed that MNE informed us that "baseline correction" has been applied. This happened automatical...
Python Code: import os import mne Explanation: The Evoked data structure: evoked/averaged data This tutorial covers the basics of creating and working with :term:evoked data. It introduces the :class:~mne.Evoked data structure in detail, including how to load, query, subselect, export, and plot data from an :class:~mne...
9,847
Given the following text description, write Python code to implement the functionality described below step by step Description: Least squares problems We sometimes wish to solve problems of the form $$ \boldsymbol{A} \boldsymbol{x} = \boldsymbol{b} $$ where $\boldsymbol{A}$ is a $m \times n$ matrix. If $m > n$, in ge...
Python Code: %matplotlib inline import matplotlib.pyplot as plt # Use seaborn to style the plots and use accessible colors import seaborn as sns sns.set() sns.set_palette("colorblind") import numpy as np N = 100 x = np.linspace(-1, 1, N) def runge(x): return 1 /(25 * (x**2) + 1) plt.xlabel('$x$') plt.ylabel('$y$') ...
9,848
Given the following text description, write Python code to implement the functionality described below step by step Description: Theano example Step1: The model Logistic regression is a probabilistic, linear classifier. It is parametrized by a weight matrix $W$ and a bias vector $b$. Classification is done by project...
Python Code: import os import requests import gzip import six from six.moves import cPickle if not os.path.exists('mnist.pkl.gz'): r = requests.get('http://www.iro.umontreal.ca/~lisa/deep/data/mnist/mnist.pkl.gz') with open('mnist.pkl.gz', 'wb') as data_file: data_file.write(r.content) with gzip.open('m...
9,849
Given the following text description, write Python code to implement the functionality described below step by step Description: <center> <h1>Introduction to Jet Images and Computer Vision</h1> <h3>Michela Paganini - Yale University</h3> <h4>High Energy Phenomenology, Experiment and Cosmology Seminar Series</h4> <img ...
Python Code: import os from keras.utils.data_utils import get_file # Info for downloading the dataset from Zenodo MD5_HASH = 'f9b11c46b6a0ff928bec2eccf865ecf0' DATAFILE = 'jet-images_Mass60-100_pT250-300_R1.25_Pix25.hdf5' URL_TEMPLATE = 'https://zenodo.org/record/{record}/files/{filename}' print('[INFO] MD5 verificatio...
9,850
Given the following text description, write Python code to implement the functionality described below step by step Description: Building a LAS file from scratch Step1: Step 1 Create some fake data, and make some of the values at the bottom NULL (numpy.nan). Note that of course every curve in a LAS file is recorded a...
Python Code: import lasio import datetime import numpy import os import matplotlib.pyplot as plt %matplotlib inline Explanation: Building a LAS file from scratch End of explanation depths = numpy.arange(10, 50, 0.5) fake_curve = numpy.random.random(len(depths)) fake_curve[-10:] = numpy.nan # Add some null values at t...
9,851
Given the following text description, write Python code to implement the functionality described below step by step Description: Development notebook Step1: Photo-count detection Theory Stochastic master equation in Milburn's formulation $\displaystyle d\rho(t) = dN(t) \mathcal{G}[a] \rho(t) - dt \gamma \mathcal{H}[\...
Python Code: %matplotlib inline import matplotlib.pyplot as plt import numpy as np from qutip import * Explanation: Development notebook: Tests for QuTiP's stochastic master equation solver Copyright (C) 2011 and later, Paul D. Nation & Robert J. Johansson In this notebook we test the qutip stochastic master equation s...
9,852
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2021 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the Licens...
Python Code: from collections import Counter import math def char2vec(word): # Counts each of the the characters in word. # We use a dictionary instead of a sparse matrix to describe the characters, # however the concept is identical. return Counter(word) def support(v): # The support of a vector over a basis...
9,853
Given the following text description, write Python code to implement the functionality described below step by step Description: Recurrent Neural Networks for Vietnamese Name Entity Recognition Step1: This the second part of the Recurrent Neural Network Tutorial. The first part is here. In this part we will implement...
Python Code: import csv import itertools import operator import numpy as np import nltk import sys from datetime import datetime from utils import * import matplotlib.pyplot as plt %matplotlib inline # Download NLTK model data (you need to do this once) nltk.download("book") Explanation: Recurrent Neural Networks for V...
9,854
Given the following text description, write Python code to implement the functionality described below step by step Description: Reading the output from sinsin2dtex.cu We go from a flattened std Step1: Quick aside on Wireframe plots in matplotlib cf. mplot3d tutorial, matplotlib Step2: EY
Python Code: %matplotlib inline import matplotlib.pyplot as plt import csv ld = [ 1., 1.] WIDTH = 640 HEIGHT = 640 print WIDTH*HEIGHT hd = [ld[0]/(float(WIDTH)), ld[1]/(float(HEIGHT)) ] with open('sinsin2dtex_result.csv','r') as csvfile_result: plot_results = csv.reader(csvfile_result, delimiter=',') result_li...
9,855
Given the following text description, write Python code to implement the functionality described below step by step Description: Maze Solver In this notebook, we write a maze solver by solving the Poisson equation with two Dirichlet boundary conditions imposed on the two faces that correspond to the start and end of t...
Python Code: # Install the required pmeal packages in the current Jupyter kernel import sys try: import openpnm as op except: !{sys.executable} -m pip install openpnm import openpnm as op try: import porespy as ps except: !{sys.executable} -m pip install porespy import porespy as ps import reque...
9,856
Given the following text description, write Python code to implement the functionality described below step by step Description: 1. Признаки по одному 1.1. Количественные Гистограмма и боксплот Step1: 1.2. Категориальные countplot Step2: 2. Взаимодействия признаков 2.1. Количественный с количественным pairplot, scat...
Python Code: df['Total day minutes'].hist(); sns.boxplot(df['Total day minutes']); df.hist(); Explanation: 1. Признаки по одному 1.1. Количественные Гистограмма и боксплот End of explanation df['State'].value_counts().head() df['Churn'].value_counts() sns.countplot(df['Churn']); sns.countplot(df['State']); sns.countplo...
9,857
Given the following text description, write Python code to implement the functionality described below step by step Description: https Step1: Now read the train and test questions into list of questions. Step2: Using keras tokenizer to tokenize the text and then do padding the sentences to 30 words Step3: Now let u...
Python Code: import os import csv import codecs import numpy as np import pandas as pd np.random.seed(1337) from keras.preprocessing.text import Tokenizer from keras.preprocessing.sequence import pad_sequences from keras.utils.np_utils import to_categorical from keras.layers import Dense, Input, Flatten, merge, LSTM, L...
9,858
Given the following text description, write Python code to implement the functionality described below step by step Description: Tutorial This tutorial will show you how to use the Table-Cleaner validation framework. First, let's import the necessary modules. My personal style is to abbreviate the scientific python li...
Python Code: import numpy as np import pandas as pd from IPython import display import table_cleaner as tc Explanation: Tutorial This tutorial will show you how to use the Table-Cleaner validation framework. First, let's import the necessary modules. My personal style is to abbreviate the scientific python libraries wi...
9,859
Given the following text description, write Python code to implement the functionality described below step by step Description: pandas-validator example This is example of pandas-validator in English. Step1: Series Validator Step2: DataFrame Validator DataFrameValidator class can validate panda's dataframe object. ...
Python Code: # Please install this package using following command. # $ pip install pandas-validator import pandas_validator as pv import pandas as pd import numpy as np Explanation: pandas-validator example This is example of pandas-validator in English. End of explanation # Create validator's instance validator = pv....
9,860
Given the following text description, write Python code to implement the functionality described below step by step Description: TensorFlow Test https Step1: The Computational Graph You might think of TensorFlow Core programs as consisting of two discrete sections Step2: Notice that printing the nodes does not outpu...
Python Code: import tensorflow as tf hello = tf.constant('Hello, TensorFlow!') sess = tf.Session() print(sess.run(hello)) Explanation: TensorFlow Test https://www.tensorflow.org/get_started/ End of explanation node1 = tf.constant(3.0, tf.float32) node2 = tf.constant(4.0) # also tf.float32 implicitly print(node1, node2)...
9,861
Given the following text description, write Python code to implement the functionality described below step by step Description: Parsing and cleaning tweets This notebook is a slight modification of @wwymak's word2vec notebook, with different tokenization, and a way to iterate over tweets linked to their named user W...
Python Code: import gensim import os import numpy as np import itertools import json import re import pymoji import importlib from nltk.tokenize import TweetTokenizer from gensim import corpora import string from nltk.corpus import stopwords from six import iteritems import csv tokenizer = TweetTokenizer() def keep_ret...
9,862
Given the following text description, write Python code to implement the functionality described below step by step Description: Keras versus Poisonous Mushrooms This example demonstrates building a simple dense neural network using Keras. The example uses Agaricus Lepiota training data to detect poisonous mushrooms....
Python Code: from pandas import read_csv srooms_df = read_csv('../data/agaricus-lepiota.data.csv') srooms_df.head() Explanation: Keras versus Poisonous Mushrooms This example demonstrates building a simple dense neural network using Keras. The example uses Agaricus Lepiota training data to detect poisonous mushrooms. ...
9,863
Given the following text description, write Python code to implement the functionality described below step by step Description: Sommer 2017 HS 5 Step1: Die Bioscan GmbH plant ein System zur Zugangskontrolle. Dazu wurde bereits folgende Datenbank entwickelt und mit Testdaten gefüllt. a) Liste aller Gebäude mit deren ...
Python Code: %load_ext sql %sql mysql://steinam:steinam@localhost/sommer_2017 Explanation: Sommer 2017 HS 5 End of explanation %%sql select G.*, R.* from `gebaeude` G left join Raum R on G.`GebID` = R.`GebID` order by G.`Bezeichnung`, R.`Typ` Explanation: Die Bioscan GmbH plant ein System zur Zugangskontrolle. Dazu wur...
9,864
Given the following text description, write Python code to implement the functionality described below step by step Description: <a href="https Step1: DDSP Synths and Effects This notebook demonstrates the use of several of the Synths and Effects Processors in the DDSP library. While the core functions are also direc...
Python Code: # Copyright 2021 Google LLC. 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 required by applic...
9,865
Given the following text description, write Python code to implement the functionality described below step by step Description: 03 - Sequence Model Approach The more 'classical' approach to solving this problem Train a model that can take any number of 'steps' Makes a prediction on next step based on previous steps L...
Python Code: %matplotlib inline import pandas as pd import numpy as np from tensorflow.keras.models import Sequential from tensorflow.keras.layers import LSTM, Dense, LeakyReLU, Dropout, ReLU, GRU, TimeDistributed, Conv2D, MaxPooling2D, Flatten from tensorflow.keras.preprocessing.sequence import pad_sequences from tens...
9,866
Given the following text description, write Python code to implement the functionality described below step by step Description: ====================================================================== Time-frequency on simulated data (Multitaper vs. Morlet vs. Stockwell) ================================================...
Python Code: # Authors: Hari Bharadwaj <hari@nmr.mgh.harvard.edu> # Denis Engemann <denis.engemann@gmail.com> # Chris Holdgraf <choldgraf@berkeley.edu> # # License: BSD (3-clause) import numpy as np from matplotlib import pyplot as plt from mne import create_info, EpochsArray from mne.baseline import ...
9,867
Given the following text description, write Python code to implement the functionality described below step by step Description: Задание 1 Вывести 10 самых больших по размеру треков жанра ROCK и формата MPEG Step1: Задание 2 Вывести названия всех групп, их песен и названия их альбомов для всех треков жанра Рок, приоб...
Python Code: %%sql SELECT t FROM tracks t INNER JOIN genres g ON t.genreid = g.genreid INNER JOIN media_types m ON m.mediatypeid = t.mediatypeid ORDER BY t.bytes desc limit 10 Explanation: Задание 1 Вывести 10 самых больших по размеру треков жанра ROCK и формата MPEG End of explanation %%sql SELECT...
9,868
Given the following text description, write Python code to implement the functionality described below step by step Description: Tutorial for flexx.react - reactive programming Also see http Step1: First, we create two input signals Step2: Input signals can be called with an argument to set their value Step3: Now w...
Python Code: from flexx import react Explanation: Tutorial for flexx.react - reactive programming Also see http://flexx.readthedocs.org/en/latest/react/ Where classic event-driven programming is about reacting to things that happen, RP is about staying up to date with changing signals. Signals are objects that have a v...
9,869
Given the following text description, write Python code to implement the functionality described below step by step Description: Preamble Step1: Notebook Environment Step2: Example Step3: Closed-form KL divergence between diagonal Gaussians Step4: Monte Carlo estimation The KL divergence is an expectation of log d...
Python Code: %matplotlib notebook import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns from scipy.stats import norm from keras import backend as K from keras.layers import (Input, Activation, Dense, Lambda, Layer, add, multiply) from keras.models import...
9,870
Given the following text description, write Python code to implement the functionality described below step by step Description: Combining geosocial and financial data to understand retail performance Geosocial data is location-based social media data that can be interpreted and analyzed as part of any location-orient...
Python Code: import geopandas as gpd import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns from cartoframes.auth import set_default_credentials from cartoframes.data.observatory import * from cartoframes.viz import * from shapely import wkt pd.set_option('display.max_columns', Non...
9,871
Given the following text description, write Python code to implement the functionality described below step by step Description: png, jpeg와 SVG의 차이. 만약 scatter plot 같은 경우 scatter가 매우 많을 때에는 png보다 용량이 더 클 수 있다. Step1: scale Step2: cond number가 이상할 때(10000이 넘어갈 때). scale의 문제와 dependant 문제. 그래서 scale 과정을 거쳐서 1000 이하로 떨...
Python Code: # sns.pairplot(df_all, diag_kind="kde", kind="reg") # plt.show() sns.jointplot("RM", "MEDV", data=df) plt.show() import statsmodels.api as sm model = sm.OLS(df.ix[:, -1], df.ix[:, :-1]) result = model.fit() print(result.summary()) Explanation: png, jpeg와 SVG의 차이. 만약 scatter plot 같은 경우 scatter가 매우 많을 때에는 pn...
9,872
Given the following text description, write Python code to implement the functionality described below step by step Description: This notebook shows how to use an index file.<br/> This example uses the index file from the Mediterranean Sea region (INSITU_MED_NRT_OBSERVATIONS_013_035) corresponding to the latest data.<...
Python Code: indexfile = "datafiles/index_latest.txt" Explanation: This notebook shows how to use an index file.<br/> This example uses the index file from the Mediterranean Sea region (INSITU_MED_NRT_OBSERVATIONS_013_035) corresponding to the latest data.<br/> If you download the same file, the results will be slightl...
9,873
Given the following text description, write Python code to implement the functionality described below step by step Description: scipy.spatial scipy.spatial can compute triangulations, Voronoi diagrams, and convex hulls of a set of points, by leveraging the Qhull library. Moreover, it contains KDTree implementations f...
Python Code: %matplotlib inline import numpy as np from scipy.spatial import Delaunay, ConvexHull, Voronoi import matplotlib.pyplot as plt points = np.random.rand(30, 2) # 30 random points in 2-D tri = Delaunay(points) hull = ConvexHull(points) voronoi = Voronoi(points) print "Neighbour triangles\n",tri.neighbors[0:5...
9,874
Given the following text description, write Python code to implement the functionality described below step by step Description: Comparing PHOEBE 2 vs PHOEBE Legacy NOTE Step1: As always, let's do imports and initialize a logger and a new bundle. See Building a System for more details. Step2: Adding Datasets and Co...
Python Code: !pip install -I "phoebe>=2.1,<2.2" Explanation: Comparing PHOEBE 2 vs PHOEBE Legacy NOTE: PHOEBE 1.0 legacy is an alternate backend and is not installed with PHOEBE 2.0. In order to run this backend, you'll need to have PHOEBE 1.0 installed and manually build the python bindings in the phoebe-py directory...
9,875
Given the following text description, write Python code to implement the functionality described below step by step Description: New York University Applied Data Science 2016 Final Project Measuring household income under Redatam in CensusData 2. Merge Individual to Household Data Project Description Step1: DATA HAND...
Python Code: # helper functions import getEPH import categorize import createVariables import schoolYears import make_dummy import functionsForModels # libraries import pandas as pd import numpy as np from scipy import stats import statsmodels.api as sm import matplotlib.pyplot as plt import seaborn as sns from statsmo...
9,876
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Gathering system data Goals Step4: If you want to stream command output, use subprocess.Popen and check carefully subprocess documentation! Step7: Parsing /proc Linux /proc filesyst...
Python Code: import psutil import glob import sys import subprocess # # Our code is p3-ready # from __future__ import print_function, unicode_literals def grep(needle, fpath): A simple grep implementation goal: open() is iterable and doesn't need splitlines() goal: comprehension can filte...
9,877
Given the following text description, write Python code to implement the functionality described below step by step Description: Morse Code Neural Net I created a text file that has the entire alphabet of numerical morse code. Meaning, "." is represented by the number "0.5" and "-" is represented by "1.0". This neural...
Python Code: import NeuralNetImport as NN import numpy as np import NNpix as npx from IPython.display import Image Explanation: Morse Code Neural Net I created a text file that has the entire alphabet of numerical morse code. Meaning, "." is represented by the number "0.5" and "-" is represented by "1.0". This neural n...
9,878
Given the following text description, write Python code to implement the functionality described below step by step Description: Report counts of GO terms at various levels and depths Reports the number of GO terms at each level and depth. Level refers to the length of the shortest path from the top. Depth refer...
Python Code: # Get http://geneontology.org/ontology/go-basic.obo from goatools.base import download_go_basic_obo obo_fname = download_go_basic_obo() Explanation: Report counts of GO terms at various levels and depths Reports the number of GO terms at each level and depth. Level refers to the length of the shortest p...
9,879
Given the following text description, write Python code to implement the functionality described below step by step Description: Big Data Doesn't Exist The recent opinion piece Big Data Doesn't Exist on Tech Crunch by Slater Victoroff is an interesting discussion about the usefulness of data both big and small. Slate...
Python Code: %matplotlib inline import matplotlib.pyplot as plt import pandas as pd import numpy as np import ConfigParser import json import indicoio import requests import xmltodict from BeautifulSoup import BeautifulSoup import time import pickle propertiesFile = "indico.properties" cp = ConfigParser.ConfigParser() ...
9,880
Given the following text description, write Python code to implement the functionality described below step by step Description: <a href="https Step1: Filter <script type="text/javascript"> localStorage.setItem('language', 'language-py') </script> <table align="left" style="margin-right Step2: Examples In the follow...
Python Code: #@title Licensed under the Apache License, Version 2.0 (the "License") # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this fi...
9,881
Given the following text description, write Python code to implement the functionality described below step by step Description: <a href="https Step1: 2d embeddings Step2: 1d embeddings Step3: Clustering in 2d 1d embedding vs size of airline * find what is similar * what is an outlier Step4: Making results more st...
Python Code: !pip install -q tf-nightly-gpu-2.0-preview import tensorflow as tf print(tf.__version__) !curl -O https://raw.githubusercontent.com/jpatokal/openflights/master/data/routes.dat # pd.read_csv? import pandas as pd df = pd.read_csv('routes.dat', quotechar="'", sep=',', encoding='utf-8', header=None, na_values=...
9,882
Given the following text description, write Python code to implement the functionality described below step by step Description: 1. Descrição do Problema A empresa Amazon deseja obter um sistema inteligente para processar os comentários de seus clientes sobre os seus produtos, podendo classificar tais comentários dent...
Python Code: import pandas as pd import numpy as np import matplotlib.pyplot as plt Explanation: 1. Descrição do Problema A empresa Amazon deseja obter um sistema inteligente para processar os comentários de seus clientes sobre os seus produtos, podendo classificar tais comentários dentre as categorias: positivo ou neg...
9,883
Given the following text description, write Python code to implement the functionality described below step by step Description: Excercise - Functional Programming Q Step1: Ans
Python Code: names = ["Aalok", "Chandu", "Roshan", "Prashant", "Saurabh"] for i in range(len(names)): names[i] = hash(names[i]) print(names) Explanation: Excercise - Functional Programming Q: Try rewriting the code below as a map. It takes a list of real names and replaces them with code names produced using a mor...
9,884
Given the following text description, write Python code to implement the functionality described below step by step Description: &larr; Back to Index Onset Detection Automatic detection of musical events in an audio signal is one of the most fundamental tasks in music information retrieval. Here, we will show how to d...
Python Code: x, fs = librosa.load('simpleLoop.wav', sr=44100) print x.shape Explanation: &larr; Back to Index Onset Detection Automatic detection of musical events in an audio signal is one of the most fundamental tasks in music information retrieval. Here, we will show how to detect an onset, the start of a musical ev...
9,885
Given the following text description, write Python code to implement the functionality described below step by step Description: Lesson 38 Step1: This is the primary function of the webbrowser module, but it can be used as part of a script to improve web scraping. selenium is a more full featured web browser module. ...
Python Code: import webbrowser webbrowser.open('https://automatetheboringstuff.com') Explanation: Lesson 38: The Webbrowser Module The webbrowser module has tools to manage a webbrowser from Python. webbrowser.open() opens a new browser window at a url: End of explanation import webbrowser, sys, pyperclip sys.argv # Pa...
9,886
Given the following text description, write Python code to implement the functionality described below step by step Description: 03 PyTorch CPU to GPU copy Step1: Alloocate a PyTorch Tensor on the GPU
Python Code: % reset -f from __future__ import print_function from __future__ import division import math import numpy as np import matplotlib.pyplot as plt %matplotlib inline import torch import sys print('__Python VERSION:', sys.version) print('__pyTorch VERSION:', torch.__version__) print('__CUDA VERSION') from subp...
9,887
Given the following text description, write Python code to implement the functionality described below step by step Description: Input luminosity function Step1: Run the simulation, save the spectra Step2: Simulation outputs Step3: the table of simulated quasars, including redshift, luminosity, synthetic flux/mags ...
Python Code: M1450 = linspace(-30,-22,20) zz = arange(0.7,3.5,0.5) ple = bossqsos.BOSS_DR9_PLE() lede = bossqsos.BOSS_DR9_LEDE() for z in zz: if z<2.2: qlf = ple if z<2.2 else lede plot(M1450,qlf(M1450,z),label='z=%.1f'%z) legend(loc='lower left') xlim(-21.8,-30.2) xlabel("$M_{1450}$") ylabel("log Phi")...
9,888
Given the following text description, write Python code to implement the functionality described below step by step Description: Prepare catalogs Step1: Prioritize ``` x = base catalog on Dropbox ; CORRECT FOR EXTINCTION r = x.r - x.extinction_r i = x.i - x.extinction_i g = x.g - x.extinction_g ; DE...
Python Code: nmstoget = ('Dune', 'AnaK', 'Odyssey', 'Gilgamesh', 'OBrother', 'Narnia', 'Catch22') hosts_to_target = [h for h in hsd.values() if h.name in nmstoget] assert len(hosts_to_target)==len(nmstoget) new_targets = [hosts.NSAHost(145729), hosts.NSAHost(21709)] hosts_to_target.extend(new_targets) # now set to the ...
9,889
Given the following text description, write Python code to implement the functionality described below step by step Description: 检索,查询数据 这一节学习如何检索pandas数据。 Step1: Python和Numpy的索引操作符[]和属性操作符‘.’能够快速检索pandas数据。 然而,这两种方式的效率在pandas中可能不是最优的,我们推荐使用专门优化过的pandas数据检索方法。而这些方法则是本节要介绍的。 多种索引方式 pandas支持三种不同的索引方式: * .loc 是基本的基于labe...
Python Code: import numpy as np import pandas as pd Explanation: 检索,查询数据 这一节学习如何检索pandas数据。 End of explanation dates = pd.date_range('1/1/2000', periods=8) dates df = pd.DataFrame(np.random.randn(8,4), index=dates, columns=list('ABCD')) df panel = pd.Panel({'one':df, 'two':df-df.mean()}) panel Explanation: Python和Nump...
9,890
Given the following text description, write Python code to implement the functionality described below step by step Description: Titanic In this notebook, I explore the titanic data set provided by Kaggle, to try and predict survival rates. To process the data, certain missing values were replaced with medians or ave...
Python Code: %matplotlib inline import numpy as np import pandas as pd import sklearn from sklearn.ensemble import (RandomForestClassifier, RandomForestRegressor) from sklearn.linear_model import LogisticRegression from sklearn import svm from sklearn.learning_curve import validation_curve import sknn.mlp import matplo...
9,891
Given the following text description, write Python code to implement the functionality described below step by step Description: Estimating the effect of a Member Rewards program An example on how DoWhy can be used to estimate the effect of a subscription or a rewards program for customers. Suppose that a website has...
Python Code: # Creating some simulated data for our example import pandas as pd import numpy as np num_users = 10000 num_months = 12 signup_months = np.random.choice(np.arange(1, num_months), num_users) * np.random.randint(0,2, size=num_users) # signup_months == 0 means customer did not sign up df = pd.DataFrame({ ...
9,892
Given the following text description, write Python code to implement the functionality described below step by step Description: Vectorized Operations not necessary to write loops for element-by-element operations pandas' Series objects can be passed to MOST NumPy functions documentation Step1: add Series without loo...
Python Code: import pandas as pd import numpy as np my_dictionary = {'a' : 45., 'b' : -19.5, 'c' : 4444} my_series = pd.Series(my_dictionary) my_series Explanation: Vectorized Operations not necessary to write loops for element-by-element operations pandas' Series objects can be passed to MOST NumPy functions documenta...
9,893
Given the following text description, write Python code to implement the functionality described below step by step Description: automaton.has_bounded_lag Check if the transducer has bounded lag, i.e. that the difference of length between the input and output words is bounded, for every word accepted. It is a pre-cond...
Python Code: import vcsn ctx = vcsn.context("lat<lan_char(ab), lan_char(xy)>, b") ctx a = ctx.expression(r"'a,x''b,y'*'a,\e'").automaton() a Explanation: automaton.has_bounded_lag Check if the transducer has bounded lag, i.e. that the difference of length between the input and output words is bounded, for every word ac...
9,894
Given the following text description, write Python code to implement the functionality described below step by step Description: GlobalAveragePooling2D [pooling.GlobalAveragePooling2D.0] input 6x6x3, data_format='channels_last' Step1: [pooling.GlobalAveragePooling2D.1] input 3x6x6, data_format='channels_first' Step2:...
Python Code: data_in_shape = (6, 6, 3) L = GlobalAveragePooling2D(data_format='channels_last') layer_0 = Input(shape=data_in_shape) layer_1 = L(layer_0) model = Model(inputs=layer_0, outputs=layer_1) # set weights to random (use seed for reproducibility) np.random.seed(270) data_in = 2 * np.random.random(data_in_shape)...
9,895
Given the following text description, write Python code to implement the functionality described below step by step Description: Following on from Guide to the Sequential Model 10 May 2017 - WH Nixalo Getting started with the Keras Sequential model The Sequential model is a linear stack of layers. You can create a Seq...
Python Code: from keras.models import Sequential from keras.layers import Dense, Activation model = Sequential([Dense(32, input_shape=(784,)), Activation('relu'), Dense(10), Activation('softmax'),]) Explanation: Following on from Guide to the Sequential Model ...
9,896
Given the following text description, write Python code to implement the functionality described below step by step Description: Title Step1: Get The Data You can get the data on Kaggle's site. Step2: Data Cleaning Step3: Sex Here we convert the gender labels (male, female) into a dummy variable (1, 0). Step4: Emb...
Python Code: import pandas as pd import numpy as np from sklearn import preprocessing from sklearn.ensemble import RandomForestClassifier from sklearn.model_selection import GridSearchCV, cross_val_score import csv as csv Explanation: Title: Titanic Competition With Random Forest Slug: titanic_competition_with_random_f...
9,897
Given the following text description, write Python code to implement the functionality described below step by step Description: <table> <tr align=left><td><img align=left src="./images/CC-BY.png"> <td>Text provided under a Creative Commons Attribution license, CC-BY. All code is made available under the FSF-approve...
Python Code: %matplotlib inline import numpy as np import scipy.linalg as la import matplotlib.pyplot as plt import csv Explanation: <table> <tr align=left><td><img align=left src="./images/CC-BY.png"> <td>Text provided under a Creative Commons Attribution license, CC-BY. All code is made available under the FSF-appr...
9,898
Given the following text description, write Python code to implement the functionality described below step by step Description: 逻辑斯特回归示例 逻辑斯特回归 正则化后的逻辑斯特回归 Step1: 逻辑斯特回归 Step2: 逻辑斯特回归假设 $$ h_{\theta}(x) = g(\theta^{T}x)$$ $$ g(z)=\frac{1}{1+e^{−z}} $$ Step3: 其实scipy包里有一个函数可以完成一样的功能 Step4: 求偏导(梯度) $$ \frac{\delta ...
Python Code: import numpy as np import pandas as pd import seaborn as sns import matplotlib as mpl import matplotlib.pyplot as plt from scipy.optimize import minimize from sklearn.preprocessing import PolynomialFeatures pd.set_option('display.notebook_repr_html', False) pd.set_option('display.max_columns', None) pd.set...
9,899
Given the following text description, write Python code to implement the functionality described below step by step Description: Getting started with the Keras Sequential model The Sequential model is a linear stack of layers. Step1: Same neural network architecture as before, but now in keras Step2: Compilation Ste...
Python Code: # simulate data X, Y = backprop_make_classification() plt.scatter(X[:, 0], X[:, 1], c=Y.argmax(1)) Explanation: Getting started with the Keras Sequential model The Sequential model is a linear stack of layers. End of explanation model = Sequential() model.add(Dense(3, input_dim=2)) # input layer is implici...