Unnamed: 0
int64
0
16k
text_prompt
stringlengths
110
62.1k
code_prompt
stringlengths
37
152k
11,000
Given the following text description, write Python code to implement the functionality described below step by step Description: Práctica 3 - Dinámica de manipuladores En esta práctica nuestro objetivo será simular el comportamiento de un manipulador tipo PUMA, empecemos importando las liberrias necesarias Step1: Y c...
Python Code: from sympy.physics.mechanics import mechanics_printing mechanics_printing() from sympy import var, Function, pi var("l1:4") var("m1:4") var("g t") q1 = Function("q1")(t) q2 = Function("q2")(t) q3 = Function("q3")(t) Explanation: Práctica 3 - Dinámica de manipuladores En esta práctica nuestro objetivo será ...
11,001
Given the following text description, write Python code to implement the functionality described below step by step Description: these notes will not display in the slideshow interactive dashboard application rendered as a slideshow using ipywidgets plotly (express) voila reveal Step1: loading the iris dataset Step2:...
Python Code: import ipywidgets as widgets import plotly.graph_objs as go import plotly.express as px Explanation: these notes will not display in the slideshow interactive dashboard application rendered as a slideshow using ipywidgets plotly (express) voila reveal End of explanation iris = px.data.iris() iris.head() fi...
11,002
Given the following text description, write Python code to implement the functionality described below step by step Description: Data Both datasets are text collections from this site. TCP-ECCO (170mb uncompressed) can be downloaded here Lincoln (700kb uncompressed) can be downloaded here Step1: Intialize swhoosh in...
Python Code: def get_lincoln(): for filepath in sorted(glob.glob('Lincoln/*.txt')): with open(filepath, 'r', encoding='latin') as f: doc = f.read() yield {'filepath': filepath, 'doc': doc} def get_TCP(): for filepath in sorted(glob.glob('TCP-ECCO/*.txt')): with open(...
11,003
Given the following text description, write Python code to implement the functionality described below step by step Description: <h2 align="center">点击下列图标在线运行HanLP</h2> <div align="center"> <a href="https Step1: 加载模型 HanLP的工作流程是先加载模型,模型的标示符存储在hanlp.pretrained这个包中,按照NLP任务归类。 Step2: 调用hanlp.load进行加载,模型会自动下载到本地缓存。自...
Python Code: !pip install hanlp -U Explanation: <h2 align="center">点击下列图标在线运行HanLP</h2> <div align="center"> <a href="https://colab.research.google.com/github/hankcs/HanLP/blob/doc-zh/plugins/hanlp_demo/hanlp_demo/zh/tok_mtl.ipynb" target="_blank"><img src="https://colab.research.google.com/assets/colab-badge.svg" ...
11,004
Given the following text description, write Python code to implement the functionality described below step by step Description: Kernel hypothesis testing in Shogun Heiko Strathmann - heiko.strathmann@gmail.com - http Step1: Some Formal Basics (skip if you just want code examples) To set the context, we here briefly ...
Python Code: import os SHOGUN_DATA_DIR=os.getenv('SHOGUN_DATA_DIR', '../../../data') import shogun as sg import numpy as np import matplotlib.pyplot as plt %matplotlib inline Explanation: Kernel hypothesis testing in Shogun Heiko Strathmann - heiko.strathmann@gmail.com - http://github.com/karlnapf - http://herrstrathma...
11,005
Given the following text description, write Python code to implement the functionality described below step by step Description: Db2 Macros The %sql command also allows the use of macros. Macros are used to substitute text into SQL commands that you execute. Macros substitution is done before any SQL is executed. This...
Python Code: %run db2.ipynb Explanation: Db2 Macros The %sql command also allows the use of macros. Macros are used to substitute text into SQL commands that you execute. Macros substitution is done before any SQL is executed. This allows you to create macros that include commonly used SQL commands or parameters rather...
11,006
Given the following text description, write Python code to implement the functionality described below step by step Description: Boolean and None Objects Note Step1: To stay practical, it is important to understand that you won't be assigning True and False values to variables as much as you will be receiving them. W...
Python Code: # Declaring both Boolean values a = True b = False Explanation: Boolean and None Objects Note: Complete this lecture after finishing the "Comparison Operators" Section Booleans are objects that evaluate to either True or False. In turn, they represent the 1 and 0 "on and off" concept. Whether you're build...
11,007
Given the following text description, write Python code to implement the functionality described below step by step Description: Import the BigBang modules as needed. These should be in your Python environment if you've installed BigBang correctly. Step1: Also, let's import a number of other dependencies we'll use la...
Python Code: import bigbang.ingress.mailman as mailman import bigbang.analysis.graph as graph import bigbang.analysis.process as process from bigbang.parse import get_date from bigbang.archive import Archive import imp imp.reload(process) Explanation: Import the BigBang modules as needed. These should be in your Python...
11,008
Given the following text description, write Python code to implement the functionality described below step by step Description: 4.0 Numpy Advanced 4.1 Verifying the python version you are using Step1: At this point anything above python 3.5 should be ok. 4.2 Import numpy Step2: Notes Step3: Notes Step4: Notes Ste...
Python Code: import sys print(sys.version) Explanation: 4.0 Numpy Advanced 4.1 Verifying the python version you are using End of explanation import numpy as np np.__version__ import matplotlib as mpl from matplotlib import pyplot as plt mpl.__version__ Explanation: At this point anything above python 3.5 should be ok. ...
11,009
Given the following text description, write Python code to implement the functionality described below step by step Description: Python for Youth refer to last week's robotic session Under the hood, languages like Python program translate human language to something the machine can understand (instructions) Python is ...
Python Code: # First, let the player choose Rock, Paper or Scissors by typing the letter ‘r’, ‘p’ or ‘s’ # first create a prompt and explain input('what is your name?') # for python to do anything with the result we need to save it in a variable which we can name anything but this is informative player = input('...
11,010
Given the following text description, write Python code to implement the functionality described below step by step Description: Self-driving car Nanodegree - Term 1 Project 1 Step1: Loading data Step3: Include an exploratory visualization of the dataset I did not spend so much time on this. I first print out the di...
Python Code: # Load pickled data import pickle import pandas as pd import numpy as np import matplotlib.pyplot as plt import random # Visualizations will be shown in the notebook. %matplotlib inline import cv2 import glob import tensorflow as tf from tensorflow.contrib.layers import flatten from tensorflow.contrib.laye...
11,011
Given the following text description, write Python code to implement the functionality described below step by step Description: sequana_coverage test case example (Virus) This notebook creates the BED file provided in - https Step1: Download the genbank and genome reference Method1 Step2: Download the FastQ Step3:...
Python Code: %pylab inline matplotlib.rcParams['figure.figsize'] = [10,7] Explanation: sequana_coverage test case example (Virus) This notebook creates the BED file provided in - https://github.com/sequana/resources/tree/master/coverage and - https://www.synapse.org/#!Synapse:syn10638358/wiki/465309 WARNING: you need ...
11,012
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction Variables, arithmetic operators ~~~ + - * / ** % // ~~~ assignment ~~~ = ~~~ assign and increment ~~~ += ~~~ Step1: Flow Control, Loops Step2: Multiplication Table 2017-09-19...
Python Code: a = [1,2,5] b = [4,7,6] print('a =',a) print('b =',b) a = b print('a =',a) print('b =',b) b = [1,1,1] print('a =',a) print('b =',b) a = 2 b = 7.1 c = 4 d = a + b * c print(a**b) a = 7 b = 2 print(a//b) a = 5 # a = a + 2 a += 2 a -= 3 a *=4 a //= 3 print(a) x = -3 fx = 3*x**2 + 4*x - 7 print(x, fx) x = -2 f...
11,013
Given the following text description, write Python code to implement the functionality described below step by step Description: Setup conda install -y numpy conda install -y scipy conda install -y matplotlib conda install -y rasterio pip install lmdb conda install -y caffe conda install -y protobuf==3.0.0b3 pip insta...
Python Code: import logging import os import numpy as np import rasterio as rio import lmdb from caffe.proto.caffe_pb2 import Datum import caffe.io from rasterio._io import RasterReader from glob import glob sources =glob('/home/shared/srp/try2/*.tif') print len(sources) pos_regions = rasterio.open(r'/home/liux13/Deskt...
11,014
Given the following text description, write Python code to implement the functionality described below step by step Description: The 8-Queens Puzzle We represent solutions to the 8-queens puzzle as tuples of the form $$ (r_0, \cdots, r_7), $$ where $r_i$ is the row of the queen in column $i$. We start counting from $...
Python Code: start = () Explanation: The 8-Queens Puzzle We represent solutions to the 8-queens puzzle as tuples of the form $$ (r_0, \cdots, r_7), $$ where $r_i$ is the row of the queen in column $i$. We start counting from $0$ because this is the way it is done in Python. In general, states are defined as tuples of ...
11,015
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Goal Assessing the error in taxon abundances when using qPCR data + 16S sequence relative abundances to determine taxon proportional absolute abundances Init Step2: Making dataset St...
Python Code: %load_ext rpy2.ipython %%R library(ggplot2) library(dplyr) library(tidyr) def neg_binom_err(m, r, negs=False): Adding negative binomial distribuiton error, where variance scales more with the mean than a poisson distribution if (r < inf). Parameters ---------- m : float Mean val...
11,016
Given the following text description, write Python code to implement the functionality described below step by step Description: This notebook presents a working example of adjusting texts for multiple subplots, related to https Step1: With multiple subplots, run adjust_text for one subplot at a time
Python Code: %matplotlib inline import matplotlib.pyplot as plt # Matplotlib 2.0 shown here from adjustText import adjust_text import numpy as np import pandas as pd Explanation: This notebook presents a working example of adjusting texts for multiple subplots, related to https://github.com/Phlya/adjustText/issues/58 E...
11,017
Given the following text description, write Python code to implement the functionality described below step by step Description: Gaussian Mixture Models (GMM) are a kind of hybrid between a clustering estimator and a density estimator. Density estimator is an algorithm which takes a D-dimensional dataset and produces ...
Python Code: %matplotlib inline import matplotlib.pyplot as plt import seaborn as sns; sns.set() import numpy as np import pandas as pd Explanation: Gaussian Mixture Models (GMM) are a kind of hybrid between a clustering estimator and a density estimator. Density estimator is an algorithm which takes a D-dimensional da...
11,018
Given the following text description, write Python code to implement the functionality described below step by step Description: Removing particles from the simulation This tutorial shows the different ways to remove particles from a REBOUND simulation. Let us start by setting up a simple simulation with 10 bodies, an...
Python Code: import rebound import numpy as np sim = rebound.Simulation() sim.add(m=1., hash=0) for i in range(1,10): sim.add(a=i, hash=i) sim.move_to_com() print("Particle hashes:{0}".format([sim.particles[i].hash for i in range(sim.N)])) Explanation: Removing particles from the simulation This tutorial shows the ...
11,019
Given the following text description, write Python code to implement the functionality described below step by step Description: Achieving Generalization Testing and cross-validation Train-test split Step1: Cross validation Step3: Valid options are ['accuracy', 'adjusted_rand_score', 'average_precision', 'f1', 'f1_m...
Python Code: import pandas as pd from sklearn.datasets import load_boston boston = load_boston() dataset = pd.DataFrame(boston.data, columns=boston.feature_names) dataset['target'] = boston.target observations = len(dataset) variables = dataset.columns[:-1] X = dataset.ix[:,:-1] y = dataset['target'].values from sklea...
11,020
Given the following text description, write Python code to implement the functionality described below step by step Description: Python Course - Primer cas pràctic <img src="http Step1: I considerem una llista d'objectes que ha comprat un cert "client" Step2: Step 1 Step3: Segona versió - Ara com a mínim sap Python...
Python Code: prices = {'apple': 0.40, 'banana': 0.50, 'entrada_promocional': 10, 'entrada_simple': 17} Explanation: Python Course - Primer cas pràctic <img src="http://www.telecogresca.com/logo_mail.png"></img> Exercici fortament sintètic (En part de https://wiki.python.org/moin/SimplePrograms, en part collita pròpia) ...
11,021
Given the following text description, write Python code to implement the functionality described below step by step Description: Lemke-Howson Step1: Two-Player Games in Normal Form We are going to find Nash equilibria (pure or mixed action) of a Two-Player Game $g = (I, (A_i){i \in I}, (u_i){i \in I})$, where $I = {...
Python Code: import numpy as np import matplotlib.pyplot as plt import quantecon.game_theory as gt %matplotlib inline Explanation: Lemke-Howson: An Algorithm to Find Nash Equilibrium This notebook introduces the Lemke-Howson algorithm for finding a Nash equilibrium of a two-player normal form game. End of explanation d...
11,022
Given the following text description, write Python code to implement the functionality described below step by step Description: 'lc' Datasets and Options Setup Let's first make sure we have the latest version of PHOEBE 2.2 installed. (You can comment out this line if you don't use pip for your installation or don't w...
Python Code: !pip install -I "phoebe>=2.2,<2.3" Explanation: 'lc' Datasets and Options Setup Let's first make sure we have the latest version of PHOEBE 2.2 installed. (You can comment out this line if you don't use pip for your installation or don't want to update to the latest release). End of explanation %matplotlib ...
11,023
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Clean Raw Annotations Load raw annotations Step2: Make random and blocked samples disjoint Step3: Tidy is_harassment_or_attack column Step4: Remap aggression score Step5: Remove ...
Python Code: # v4_annotated user_blocked = [ 'annotated_onion_layer_5_rows_0_to_5000_raters_20', 'annotated_onion_layer_5_rows_0_to_10000', 'annotated_onion_layer_5_rows_0_to_10000_raters_3', 'annotated_onion_layer_5_rows_10000_...
11,024
Given the following text description, write Python code to implement the functionality described below step by step Description: pyPanair Tutorial#1 Rectangular Wing In this tutorial we will perform an analysis of a rectangular wing with a NACA0012 airfoil. A brief overview of the procedure is listed below Step1: 1.2...
Python Code: %matplotlib notebook from pyPanair.preprocess import wgs_creator delta_wing = wgs_creator.read_wgs("sample1.wgs") print(delta_wing._networks.keys()) delta_wing._networks["wing"].plot_wireframe(show_normvec=False, show_corners=False, show_edges=False) Explanation: pyPanair Tutorial#1 Rectangular Wing In thi...
11,025
Given the following text description, write Python code to implement the functionality described below step by step Description: This notebook presents how to perform maximum-likelihood parameter estimation for multiple neurons. The neurons depend on each other through a set of weights. Step1: Reading input-output d...
Python Code: import numpy as np import matplotlib.pyplot as plt import pandas as pd import random import csv %matplotlib inline import os import sys sys.path.append(os.path.join(os.getcwd(),'..')) sys.path.append(os.path.join(os.getcwd(),'..','code')) sys.path.append(os.path.join(os.getcwd(),'..','data')) import filter...
11,026
Given the following text description, write Python code to implement the functionality described below step by step Description: Reflection and Heating For a comparison between "Horvat" and "Wilson" methods in the "irad_method" parameter, see the tutorial on Lambert Scattering. Setup Let's first make sure we have the ...
Python Code: #!pip install -I "phoebe>=2.4,<2.5" Explanation: Reflection and Heating For a comparison between "Horvat" and "Wilson" methods in the "irad_method" parameter, see the tutorial on Lambert Scattering. Setup Let's first make sure we have the latest version of PHOEBE 2.4 installed (uncomment this line if runni...
11,027
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Exercise 1 Step2: You can use as input the sound files from the sounds directory, thus using a relative path to it. If you run the read_audio_samples() function using the piano.wav s...
Python Code: import sys import os import numpy as np # to use this notebook with colab uncomment the next line # !git clone https://github.com/MTG/sms-tools.git # and change the next line to sys.path.append('sms-tools/software/models/') sys.path.append('../software/models/') from utilFunctions import wavread, wavwrite ...
11,028
Given the following text description, write Python code to implement the functionality described below step by step Description: Will be focusing on LINEAR linear_0006 for now, until I better understand how they compare. Step1: Focusing on one of the periapse tables for now
Python Code: df = df[df.BIN_PATTERN_INDEX == 'LINEAR linear_0006'] # now can drop that column df = df.drop('BIN_PATTERN_INDEX', axis=1) bin_tables = df.BIN_TBL.value_counts() bin_tables for ind in bin_tables.index: print(ind) print(df[df.BIN_TBL==ind].orbit_segment.value_counts()) Explanation: Will be focusing ...
11,029
Given the following text problem statement, write Python code to implement the functionality described below in problem statement Problem: How does one convert a list of Z-scores from the Z-distribution (standard normal distribution, Gaussian distribution) to left-tailed p-values? Original data is sampled from X ~ N(mu...
Problem: import scipy.stats import numpy as np z_scores = [-3, -2, 0, 2, 2.5] mu = 3 sigma = 4 temp = np.array(z_scores) p_values = scipy.stats.norm.cdf(temp)
11,030
Given the following text description, write Python code to implement the functionality described below step by step Description: Chapter 11 Modeling and Simulation in Python Copyright 2021 Allen Downey License Step1: In this chapter, we develop a model of an epidemic as it spreads in a susceptible population, and use...
Python Code: # install Pint if necessary try: import pint except ImportError: !pip install pint # download modsim.py if necessary from os.path import exists filename = 'modsim.py' if not exists(filename): from urllib.request import urlretrieve url = 'https://raw.githubusercontent.com/AllenDowney/ModSim/...
11,031
Given the following text description, write Python code to implement the functionality described below step by step Description: MCMC Think Bayes, Second Edition Copyright 2020 Allen B. Downey License Step1: For most of this book we've been using grid methods to approximate posterior distributions. For models with on...
Python Code: # If we're running on Colab, install libraries import sys IN_COLAB = 'google.colab' in sys.modules if IN_COLAB: !pip install empiricaldist # Get utils.py from os.path import basename, exists def download(url): filename = basename(url) if not exists(filename): from urllib.request import ...
11,032
Given the following text description, write Python code to implement the functionality described below step by step Description: Using scipy iterative solvers The aim of this notebook is to show how the scipy.sparse.linalg module can be used to solve iteratively the Lippmann–Schwinger equation. The problem at hand is ...
Python Code: import h5py as h5 import matplotlib.pyplot as plt import numpy as np import janus import janus.material.elastic.linear.isotropic as material import janus.operators as operators import janus.fft.serial as fft import janus.green as green from scipy.sparse.linalg import cg, LinearOperator %matplotlib inline p...
11,033
Given the following text description, write Python code to implement the functionality described below step by step Description: Characteristics of Autonomous Market Makers Date Step1: From the Balancer whitepaper Step2: We can specify that swaps happen on some invariant surface $V(x,y)$ which allows us to replace t...
Python Code: from IPython.display import HTML # Hide code cells https://gist.github.com/uolter/970adfedf44962b47d32347d262fe9be def hide_code(): return HTML('''<script> code_show=true; function code_toggle() { if (code_show){ $("div.input").hide(); } else { $("div.input")....
11,034
Given the following text description, write Python code to implement the functionality described below step by step Description: The frequency of a Ricker wavelet We often use Ricker wavelets to model seismic, for example when making a synthetic seismogram with which to help tie a well. One simple way to guesstimate t...
Python Code: T, dt, f = 0.256, 0.001, 25 import bruges w, t = bruges.filters.ricker(T, dt, f, return_t=True) import scipy.signal f_W, W = scipy.signal.welch(w, fs=1/dt, nperseg=256) fig, axs = plt.subplots(figsize=(15,5), ncols=2) axs[0].plot(t, w) axs[0].set_xlabel("Time [s]") axs[1].plot(f_W[:25], W[:25], c="C1") axs...
11,035
Given the following text description, write Python code to implement the functionality described below step by step Description: <b>Step 1</b> Get the links of different app categories on iTunes. Step1: <b>Step2</b> Get the links for all popular apps of different catigories on iTunes. Step2: <b>Step3</b> Extract the...
Python Code: r = urllib.urlopen('https://itunes.apple.com/us/genre/ios-books/id6018?mt=8').read() soup = BeautifulSoup(r) print type(soup) all_categories = soup.find_all("div", class_="nav") category_url = all_categories[0].find_all(class_ = "top-level-genre") categories_url = pd.DataFrame() for itm in category_url: ...
11,036
Given the following text description, write Python code to implement the functionality described below step by step Description: Purpose The purpose of this notebook is to work out the code for how to combine and average tetrode pairs over brain areas over multiple sessions Step1: Make sure we can get the ripple-trig...
Python Code: import numpy as np import matplotlib.pyplot as plt import seaborn as sns import pandas as pd import xarray as xr from src.analysis import (decode_ripple_clusterless, detect_epoch_ripples, ripple_triggered_connectivity, connectivi...
11,037
Given the following text description, write Python code to implement the functionality described below step by step Description: Configuration Step1: Get the Trace Step2: FTrace Object Step3: Assertions Step4: Assertion Step5: Assertion Step6: Statistics Check if 95% of the temperature readings are below CONTROL...
Python Code: import trappy import numpy config = {} # TRAPpy Events config["THERMAL"] = trappy.thermal.Thermal config["OUT"] = trappy.cpu_power.CpuOutPower config["IN"] = trappy.cpu_power.CpuInPower config["PID"] = trappy.pid_controller.PIDController config["GOVERNOR"] = trappy.thermal.ThermalGovernor # Control Tempera...
11,038
Given the following text description, write Python code to implement the functionality described below step by step Description: 全局参数 Step1: 初始化权重 如果需要,会给权重加上L2 loss。为了在后面计算神经网络的总体loss的时候被用上,需要统一存到一个collection。 加载数据 使用cifa10_input来获取数据,这个文件来自tensorflow github,可以下载下来直接使用。如果使用distorted_input方法,那么得到的数据是经过增强处理的。会对图片随机做出切...
Python Code: max_steps = 3000 batch_size = 128 data_dir = 'data/cifar10/cifar-10-batches-bin/' model_dir = 'model/_cifar10_v2/' Explanation: 全局参数 End of explanation X_train, y_train = cifar10_input.distorted_inputs(data_dir, batch_size) X_test, y_test = cifar10_input.inputs(eval_data=True, data_dir=data_dir, batch_size...
11,039
Given the following text description, write Python code to implement the functionality described below step by step Description: Lecture 3 Step1: It's easy to determine the name of the variable; in this case, the name is $x$. It can be a bit more complicated to determine the type of the variable, as it depends on the...
Python Code: x = 2 Explanation: Lecture 3: Python Variables and Syntax CSCI 1360: Foundations for Informatics and Analytics Overview and Objectives In this lecture, we'll get into more detail on Python variables, as well as language syntax. By the end, you should be able to: Define variables of string and numerical typ...
11,040
Given the following text problem statement, write Python code to implement the functionality described below in problem statement Problem: use one hot encoding on the given dataset named 'onehotend_data.csv' on column 'town'
Python Code:: import pandas as pd from sklearn.preprocessing import OneHotEncoder from sklearn.compose import make_column_transformer ohe = OneHotEncoder() df = pd.read_csv('onehotend_data.csv') ohe.fit(df[['town']]) ct = make_column_transformer((OneHotEncoder(categories = ohe.categories_), ['town']), remainder = 'pass...
11,041
Given the following text description, write Python code to implement the functionality described below step by step Description: load in evaluation dataset sub-sample a large set of features calculate PCA and save out for loading in other places. Step1: How similar are PCs on 2 sub-samples of data? Step2: After comp...
Python Code: import numpy as np import matplotlib.pyplot as plt import seaborn import pandas as pd from sklearn.decomposition import PCA import pickle %matplotlib inline # load smaller user behavior dataset user_profile = pd.read_pickle('../data_user_view_buy/user_profile_items_nonnull_features_20_mins_5_views_v2_sampl...
11,042
Given the following text description, write Python code to implement the functionality described below step by step Description: Lecture 3 Warmup Write a function that simulates a dice roll every time the function is called. Step1: Rewrite your function to take in an int n and simulate n dice rolls. Write a function ...
Python Code: import random def dice(): return random.randint(1,6) def roll_dice(n): for i in range(n): print(dice()) roll_dice(5) Explanation: Lecture 3 Warmup Write a function that simulates a dice roll every time the function is called. End of explanation balls = ['r', 'r', 'b', 'b', 'b'] def...
11,043
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', ...
11,044
Given the following text description, write Python code to implement the functionality described below step by step Description: A Network Tour of Data Science &nbsp; &nbsp; &nbsp; Xavier Bresson, Winter 2016/17 Assignment 3 Step1: Goal The goal is to define with TensorFlow a vanilla recurrent neural network (RNN) m...
Python Code: # Import libraries import tensorflow as tf import numpy as np import collections import os # Load text data data = open(os.path.join('datasets', 'text_ass_6.txt'), 'r').read() # must be simple plain text file print('Text data:',data) chars = list(set(data)) print('\nSingle characters:',chars) data_len, voc...
11,045
Given the following text description, write Python code to implement the functionality described below step by step Description: Data Step1: Load dataframes Step2: 1. What are most popular categories? Step3: 2. What are the most common restaurant chains? Step4: 2a. Correlations in chain properties higher rating --...
Python Code: %matplotlib inline import matplotlib.pyplot as plt import numpy as np import pandas as pd import glob import os import scipy as sp from scipy import stats from tools.plt import color2d #from the 'srcole/tools' repo from matplotlib import cm Explanation: Data: 1000 restaurants for each city Cuisines: most p...
11,046
Given the following text description, write Python code to implement the functionality described below step by step Description: Catch that asteroid! Step1: First, we need to increase the timeout time to allow the download of data occur properly Step2: Two problems Step3: We first propagate Step4: And now we have ...
Python Code: import matplotlib.pyplot as plt plt.ion() from astropy import units as u from astropy.time import Time from astropy.utils.data import conf conf.dataurl conf.remote_timeout Explanation: Catch that asteroid! End of explanation conf.remote_timeout = 10000 from astropy.coordinates import solar_system_ephemeri...
11,047
Given the following text description, write Python code to implement the functionality described below step by step Description: WaveSolver - slider M. Lamoureux May 31, 2016. Pacific Insitute for the Mathematical Sciences Updated June 2017, to remove all reference to Bokeh, cuz it doesn't work now. (deprecated = brok...
Python Code: %matplotlib inline import numpy as np from matplotlib.pyplot import * Explanation: WaveSolver - slider M. Lamoureux May 31, 2016. Pacific Insitute for the Mathematical Sciences Updated June 2017, to remove all reference to Bokeh, cuz it doesn't work now. (deprecated = broken) (Bokeh = Brokehn) This code do...
11,048
Given the following text description, write Python code to implement the functionality described. Description: For a given string, flip lowercase characters to uppercase and uppercase to lowercase. This is how the function will work: flip_case('Hello') 'hELLO'
Python Code: def flip_case(string: str) -> str: return string.swapcase()
11,049
Given the following text description, write Python code to implement the functionality described below step by step Description: ES-DOC CMIP6 Model Properties - Atmos MIP Era Step1: Document Authors Set document authors Step2: Document Contributors Specify document contributors Step3: Document Publication Specify d...
Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'inm', 'inm-cm4-8', 'atmos') Explanation: ES-DOC CMIP6 Model Properties - Atmos MIP Era: CMIP6 Institute: INM Source ID: INM-CM4-8 Topic: Atmos Sub-Topics: Dynamical Core, Radiation, T...
11,050
Given the following text description, write Python code to implement the functionality described below step by step Description: Incrementally saving sampling progress Can I save intermediate MCMC results for long runs, to avoid catastrophic loss of samples? gully February 2016 In this notebook I explore how to save i...
Python Code: from emcee.sampler import Sampler def bogus_lnprob(p): return 1.0 samp = Sampler(3, bogus_lnprob) samp.run_mcmc( # Hit shift-tab... also peak at samp.sample(), etc... Explanation: Incrementally saving sampling progress Can I save intermediate MCMC results for long runs, to avoid catastrophic loss ...
11,051
Given the following text description, write Python code to implement the functionality described below step by step Description: Logistic Classfication https Step1: Hypothesis $$ H(X) = \frac {1} {1+e^{-W^T X}} $$ https Step2: Evaluation
Python Code: import tensorflow as tf import numpy as np xy = np.loadtxt('../data/logistic_data.txt',unpack=True, dtype='float32') x_data = xy[0:-1] y_data = xy[-1] Explanation: Logistic Classfication https://ko.wikipedia.org/wiki/%EB%A1%9C%EC%A7%80%EC%8A%A4%ED%8B%B1_%ED%9A%8C%EA%B7%80 End of explanation x_data = [ [1,2...
11,052
Given the following text description, write Python code to implement the functionality described below step by step Description: Lesson 3 Python Basic, Lesson 3, * v1.0, 2016 * v1.1, 2020.2,3,4, 6.13 edit by David Yi 本章内容要点 for 循环语句和 range() 函数 常用数据类型 字符串 字符串处理 思考 for 循环语句和 range() 函数 Python的循环语句主要是 for...in 循环,依次把 ...
Python Code: # 按照字符串进行迭代循环 s = 'abcdef' for i in s: print(i) # 按照列表进行循环,列表内容为字符 s = ['a', 'b', 'c'] for i in s: print(i) # 按照列列表进行循环,列表内容为数字 for i in range(3): print(i) Explanation: Lesson 3 Python Basic, Lesson 3, * v1.0, 2016 * v1.1, 2020.2,3,4, 6.13 edit by David Yi 本章内容要点 for 循环语句和 range() 函数 常用数据类...
11,053
Given the following text description, write Python code to implement the functionality described below step by step Description: A Simple Autoencoder We'll start off by building a simple autoencoder to compress the MNIST dataset. With autoencoders, we pass input data through an encoder that makes a compressed represen...
Python Code: %matplotlib inline import numpy as np import tensorflow as tf import matplotlib.pyplot as plt from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets('MNIST_data', validation_size=0) Explanation: A Simple Autoencoder We'll start off by building a simple autoencoder to c...
11,054
Given the following text description, write Python code to implement the functionality described below step by step Description: Basic of Machine Learning 1.Data Step1: Brodcasting Step2: nd array <-> Numpy Step3: Deal data with gpu Step4: Scala, Vector, Matrices, Tensors
Python Code: import mxnet as mx from mxnet import nd import numpy as np mx.random.seed(1) x = nd.empty((3, 4)) print(x) x = nd.ones((3, 4)) x y = nd.random_normal(0, 1, shape=(3, 4)) print y print y.shape print y.size x * y nd.exp(y) nd.dot(x, y.T) # Memory Host print "The current mem host y is {}".format(id(y)) y[:]...
11,055
Given the following text description, write Python code to implement the functionality described below step by step Description: ES-DOC CMIP6 Model Properties - Seaice MIP Era Step1: Document Authors Set document authors Step2: Document Contributors Specify document contributors Step3: Document Publication Specify ...
Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'mohc', 'hadgem3-gc31-mm', 'seaice') Explanation: ES-DOC CMIP6 Model Properties - Seaice MIP Era: CMIP6 Institute: MOHC Source ID: HADGEM3-GC31-MM Topic: Seaice Sub-Topics: Dynamics, T...
11,056
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2020 The OpenFermion Developers Step1: The Jordan-Wigner and Bravyi-Kitaev Transforms <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https S...
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...
11,057
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2020 Google LLC. Licensed under the Apache License, Version 2.0 (the "License"); Step1: Forward and Backward mode gradients in TFF <table class="tfo-notebook-buttons" align="left"...
Python Code: #@title Licensed under the Apache License, Version 2.0 (the "License"); { display-mode: "form" } # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in...
11,058
Given the following text description, write Python code to implement the functionality described below step by step Description: FDMS TME3 Kaggle How Much Did It Rain? II Florian Toque & Paul Willot Dear professor Denoyer... Warning This is an early version of our entry for the Kaggle challenge It's still very mes...
Python Code: # from __future__ import exam_success from __future__ import absolute_import from __future__ import print_function %matplotlib inline import sklearn import matplotlib.pyplot as plt import seaborn as sns import numpy as np import random import pandas as pd import scipy.stats as stats # Sk cheats from sklear...
11,059
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Train Models Train a logistic regression model with the engineered features Including LDA-based topic similarity, sentence position, sentence length, and readability metrics, I traine...
Python Code: import matplotlib.pyplot as plt import csv from textblob import TextBlob, Word import pandas as pd import sklearn import pickle import numpy as np import scipy from scipy import spatial import nltk.data from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer from sklearn.naive_bayes i...
11,060
Given the following text description, write Python code to implement the functionality described below step by step Description: This code shows an example for using the imported data from a modified .mat file into a artificial neural network and its training Step1: Importing preprocessing data Step2: Sorting out d...
Python Code: import numpy as np from sklearn.neural_network import MLPRegressor from sklearn import preprocessing from sklearn.cross_validation import train_test_split import matplotlib.pyplot as plt import matplotlib.patches as mpatches from sklearn.metrics import r2_score # in order to test the results from sklearn.g...
11,061
Given the following text description, write Python code to implement the functionality described below step by step Description: Keras deep neural network The structure of the network is the following Step1: Training Step2: Visualization
Python Code: import numpy as np import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split %matplotlib inline plt.rcParams['figure.figsize'] = (10.0, 8.0) # set default size of plots plt.rcParams['image.interpolation'] = 'nearest' plt.rcParams['image.cmap'] = 'gray' # Data generation obtained ...
11,062
Given the following text description, write Python code to implement the functionality described below step by step Description: Plotting phase tensors from a ModEM data file on a basemap In this example we will plot phase tensors from ModEM files. This example is a bit more complex than previous examples, as, unlike ...
Python Code: from mtpy.modeling.modem import PlotPTMaps import matplotlib.pyplot as plt import matplotlib.cm as cm import matplotlib as mpl from mpl_toolkits.basemap import Basemap from shapely.geometry import Polygon from descartes import PolygonPatch import numpy as np Explanation: Plotting phase tensors from a ModEM...
11,063
Given the following text description, write Python code to implement the functionality described below step by step Description: Pre-processing Step1: Read in tweets and add appropriate labels (sarcastic/genuine) Step2: Remove non-English tweets Step3: Feature Engineering ToUser - tweet references another user via ...
Python Code: import csv with open("processed_tweets/sarcastic_tweets.csv", 'r') as f: reader = csv.reader(f) linenumber = 1 try: for row in reader: linenumber += 1 except Exception as e: print (("Error line %d: %s %s" % (linenumber, str(type(e)), e))) Explanation: Pre-process...
11,064
Given the following text description, write Python code to implement the functionality described below step by step Description: Occupancy Detection Create a classification model to determine if a room is occupied or unoccupied based on environmental data. In class demo on May 5, 2018 Step1: Data Loading Load data i...
Python Code: %matplotlib notebook import os import csv import pickle import numpy as np import pandas as pd from datetime import datetime from sklearn.pipeline import Pipeline from sklearn.preprocessing import LabelEncoder from sklearn.feature_extraction import DictVectorizer from sklearn.base import BaseEstimator, Tr...
11,065
Given the following text description, write Python code to implement the functionality described below step by step Description: <a href="https Step1: Colab-only auth Step2: Config Step3: Linear Keras model [WORK REQUIRED] What do the columns do ? Familiarize yourself with these column types. numeric_col = fc.numer...
Python Code: import os, json, math import numpy as np import tensorflow as tf from tensorflow.python.feature_column import feature_column_v2 as fc # This will change when Keras FeatureColumn is final. from matplotlib import pyplot as plt print("Tensorflow version " + tf.__version__) tf.enable_eager_execution() #@title...
11,066
Given the following text description, write Python code to implement the functionality described below step by step Description: Using Feature Store Learning Objective In this notebook, you will learn how to Step1: Note Step2: Set your project ID Update YOUR-PROJECT-ID with your Project ID. If you don't know your pr...
Python Code: # Setup your dependencies import os # The Google Cloud Notebook product has specific requirements IS_GOOGLE_CLOUD_NOTEBOOK = os.path.exists("/opt/deeplearning/metadata/env_version") # Google Cloud Notebook requires dependencies to be installed with '--user' USER_FLAG = "" if IS_GOOGLE_CLOUD_NOTEBOOK: U...
11,067
Given the following text description, write Python code to implement the functionality described below step by step Description: MCMC & why 3d matters This example (although quite artificial) shows that viewing a posterior (ok, I have flat priors) in 3d can be quite useful. While the 2d projection may look quite 'bad'...
Python Code: !pip install emcee corner !pip show matplotlib import pylab import scipy.optimize as op import emcee import numpy as np %matplotlib inline # our 'blackbox' 3 parameter model which is highly degenerate def f_model(x, a, b, c): return x * np.sqrt(a**2 +b**2 + c**2) + a*x**2 + b*x**3 N = 100 a_true, b_tru...
11,068
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Success Prediction Predict success or fail with information given before project begins Features Step2: A. Percentage distribution Step3: B. Category Step4: Categories are classif...
Python Code: #load_data cf_df = pd.read_excel('cf_df.xlsx') #check feature number def check_number(feature): "feature : 'str' count = cf_df[feature].value_counts() return print(count) # success rate print('overall success'), print('=================='), success_percentage = cf_df['end_with_success'].value_c...
11,069
Given the following text description, write Python code to implement the functionality described below step by step Description: Modeling rent prices for the SF Bay Area This notebook will develop a predictive model for rent prices in the Bay Area using rental listings from Craigslist. Data Step1: Load and prepare d...
Python Code: import numpy as np import pandas as pd import os import math import matplotlib.pyplot as plt import seaborn as sns %matplotlib inline DATA_DIR = os.path.join('..','data','urbansim') Explanation: Modeling rent prices for the SF Bay Area This notebook will develop a predictive model for rent prices in the Ba...
11,070
Given the following text description, write Python code to implement the functionality described below step by step Description: Chapter 23 Modeling and Simulation in Python Copyright 2021 Allen Downey License Step1: Code from the previous chapter Step2: In the previous chapter we developed a model of the flight of ...
Python Code: # install Pint if necessary try: import pint except ImportError: !pip install pint # download modsim.py if necessary from os.path import exists filename = 'modsim.py' if not exists(filename): from urllib.request import urlretrieve url = 'https://raw.githubusercontent.com/AllenDowney/ModSim/...
11,071
Given the following text description, write Python code to implement the functionality described below step by step Description: CM360 Segmentology CM360 funnel analysis using Census data. License Copyright 2020 Google LLC, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file excep...
Python Code: !pip install git+https://github.com/google/starthinker Explanation: CM360 Segmentology CM360 funnel analysis using Census data. License Copyright 2020 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 ...
11,072
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2021 The TensorFlow Authors. Step1: <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https Step2: Sending Different Values Based On Client Da...
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...
11,073
Given the following text description, write Python code to implement the functionality described below step by step Description: Week 9 - Dataset preprocessing Before we utilize machine learning algorithms we must first prepare our dataset. This can often take a significant amount of time and can have a large impact o...
Python Code: import matplotlib.pyplot as plt import numpy as np import pandas as pd %matplotlib inline Explanation: Week 9 - Dataset preprocessing Before we utilize machine learning algorithms we must first prepare our dataset. This can often take a significant amount of time and can have a large impact on the performa...
11,074
Given the following text description, write Python code to implement the functionality described below step by step Description: Title Step1: Load Image As Greyscale Step2: Save Image
Python Code: # Load library import cv2 import numpy as np from matplotlib import pyplot as plt Explanation: Title: Save Images Slug: save_images Summary: How to save images using OpenCV in Python. Date: 2017-09-11 12:00 Category: Machine Learning Tags: Preprocessing Images Authors: Chris Albon Preliminaries End of...
11,075
Given the following text description, write Python code to implement the functionality described below step by step Description: Topic Modeling Amarigna _ Simple topic classifying LSTM model to test if it is possible to identify topics in Amharic text _ Step25: A small sample dataset to train and test the model Step2...
Python Code: from sklearn.datasets import fetch_20newsgroups from keras.preprocessing.text import Tokenizer from keras.preprocessing.sequence import pad_sequences import keras from keras.layers import Embedding, Dense, LSTM, GRU from keras.models import Sequential from sklearn.model_selection import train_test_split, S...
11,076
Given the following text description, write Python code to implement the functionality described below step by step Description: This IPython Notebook illustrates the use of the openmc.mgxs.Library class. The Library class is designed to automate the calculation of multi-group cross sections for use cases with one or ...
Python Code: import math import pickle from IPython.display import Image import matplotlib.pyplot as plt import numpy as np import openmc import openmc.mgxs from openmc.openmoc_compatible import get_openmoc_geometry import openmoc import openmoc.process from openmoc.materialize import load_openmc_mgxs_lib %matplotlib i...
11,077
Given the following text description, write Python code to implement the functionality described below step by step Description: Model Comparisons Comparing the DDM to other congitive models Step1: DDM vs Signal Detection Theory Comparing DDM to Signal Detection - does d' correlate with DDM parameters? Step2: d' dis...
Python Code: # Environment setup %matplotlib inline %cd /lang_dec # Imports import warnings; warnings.filterwarnings('ignore') import hddm import math import scipy import numpy as np import matplotlib.pyplot as plt import seaborn as sns import bayesian_bootstrap.bootstrap as bootstrap from utils import model_tools, sig...
11,078
Given the following text description, write Python code to implement the functionality described below step by step Description: Conversion of Objax models to Tensorflow This tutorial demonstrates how to export models from Objax to Tensorflow and then export them into SavedModel format. SavedModel format could be read...
Python Code: # install the latest version of Objax from github %pip --quiet install git+https://github.com/google/objax.git import math import random import tempfile import numpy as np import tensorflow as tf import objax from objax.zoo.wide_resnet import WideResNet Explanation: Conversion of Objax models to Tensorflow...
11,079
Given the following text description, write Python code to implement the functionality described below step by step Description: ES-DOC CMIP6 Model Properties - Ocean MIP Era Step1: Document Authors Set document authors Step2: Document Contributors Specify document contributors Step3: Document Publication Specify d...
Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'awi', 'sandbox-3', 'ocean') Explanation: ES-DOC CMIP6 Model Properties - Ocean MIP Era: CMIP6 Institute: AWI Source ID: SANDBOX-3 Topic: Ocean Sub-Topics: Timestepping Framework, Adve...
11,080
Given the following text description, write Python code to implement the functionality described below step by step Description: Part 1 Step1: Configure GCP environment settings Update the PROJECT_ID variable to reflect the ID of the Google Cloud project you are using to implement this solution. Step2: Authenticate ...
Python Code: from datetime import datetime import matplotlib.pyplot as plt import seaborn as sns from google.cloud import bigquery Explanation: Part 1: Learn item embeddings based on song co-occurrence This notebook is the first of five notebooks that guide you through running the Real-time Item-to-item Recommendation ...
11,081
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction In this micro-course, you'll learn all about pandas, the most popular Python library for data analysis. Along the way, you'll complete several hands-on exercises with real-world...
Python Code: import pandas as pd Explanation: Introduction In this micro-course, you'll learn all about pandas, the most popular Python library for data analysis. Along the way, you'll complete several hands-on exercises with real-world data. We recommend that you work on the exercises while reading the corresponding ...
11,082
Given the following text description, write Python code to implement the functionality described below step by step Description: Sampler statistics When checking for convergence or when debugging a badly behaving sampler, it is often helpful to take a closer look at what the sampler is doing. For this purpose some sam...
Python Code: import numpy as np import matplotlib.pyplot as plt import seaborn as sb import pandas as pd import pymc3 as pm %matplotlib inline Explanation: Sampler statistics When checking for convergence or when debugging a badly behaving sampler, it is often helpful to take a closer look at what the sampler is doing...
11,083
Given the following text description, write Python code to implement the functionality described below step by step Description: The first two consecutive numbers to have two distinct prime factors are Step1: Define an $n$-wise iterator over an iterator, inspired by the implementation of pairwise in the Itertools rec...
Python Code: %load_ext autoreload %autoreload 2 from common.utils import prime_factors from itertools import count, tee from six.moves import map, reduce, zip Explanation: The first two consecutive numbers to have two distinct prime factors are: $$ 14 = 2 × 7 \ 15 = 3 × 5 $$ The first three consecutive numbers to have ...
11,084
Given the following text description, write Python code to implement the functionality described below step by step Description: Image Reduction in Python Erik Tollerud (STScI) In this notebook we will walk through several of the basic steps required to do data reduction using Python and Astropy. This notebook is foc...
Python Code: import ccdproc ccdproc.__version__ import photutils photutils.__version__ Explanation: Image Reduction in Python Erik Tollerud (STScI) In this notebook we will walk through several of the basic steps required to do data reduction using Python and Astropy. This notebook is focused on "practical" (you decid...
11,085
Given the following text description, write Python code to implement the functionality described below step by step Description: Basic orienatation to ticdat, pandas and developing engines for Opalytics One of the advantages of Python is that it has "batteries included". That is to say, there is a rich set of librarie...
Python Code: from ticdat import TicDatFactory, freeze_me dataFactory = TicDatFactory ( categories = [["name"],["minNutrition", "maxNutrition"]], foods = [["name"],["cost"]], nutritionQuantities = [["food", "category"], ["qty"]]) Explanation: Basic orienatation to ticdat, pandas and developing engines fo...
11,086
Given the following text description, write Python code to implement the functionality described below step by step Description: Discretizando la ecuación de Schrödinger Autor Step1: Código que controla las simulaciones Step2: Rutinas que generan inicializan y generan la simulación Step3: Rutinas que conectan los c...
Python Code: import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation from IPython.display import HTML import ipywidgets as widgets from IPython.display import display L = 200 dx = 2. buttonrunsim=widgets.Button(description="Simulate") outwdt = widgets.Output() centropaquete = widgets...
11,087
Given the following text description, write Python code to implement the functionality described below step by step Description: Plotting This tutorial explains the high-level interface to plotting provided by the Bundle. You are of course always welcome to access arrays and plot manually. As of PHOEBE 2.1, PHOEBE us...
Python Code: !pip install -I "phoebe>=2.1,<2.2" Explanation: Plotting This tutorial explains the high-level interface to plotting provided by the Bundle. You are of course always welcome to access arrays and plot manually. As of PHOEBE 2.1, PHOEBE uses autofig as an intermediate layer for highend functionality to matp...
11,088
Given the following text description, write Python code to implement the functionality described below step by step Description: Title Step1: Create DataFrame Step2: Fit The Label Encoder Step3: View The Labels Step4: Transform Categories Into Integers Step5: Transform Integers Into Categories
Python Code: # Import required packages from sklearn import preprocessing import pandas as pd Explanation: Title: Convert Pandas Categorical Data For Scikit-Learn Slug: convert_pandas_categorical_column_into_integers_for_scikit-learn Summary: Convert Pandas Categorical Column Into Integers For Scikit-Learn Date: 2016-1...
11,089
Given the following text description, write Python code to implement the functionality described below step by step Description: Nexa Wall Street Columns Raw Data, Low Resolution vs High Resolution, NData Here we compare how well the LDA classifier works for both low resolution and high resolution classification when ...
Python Code: import numpy as np from sklearn import cross_validation from sklearn.discriminant_analysis import LinearDiscriminantAnalysis as LDA import h5py import matplotlib import matplotlib.pyplot as plt import seaborn as sns %matplotlib inline import sys sys.path.append("../") from aux.raw_images_columns_functions ...
11,090
Given the following text description, write Python code to implement the functionality described below step by step Description: Pandas pandas is an open source, BSD-licensed library providing high-performance, easy-to-use data structures and data analysis tools for the Python programming language. Pandas Website This...
Python Code: v = pd.Series(np.random.randn(5)) v Explanation: Pandas pandas is an open source, BSD-licensed library providing high-performance, easy-to-use data structures and data analysis tools for the Python programming language. Pandas Website This tutorial pulls from the Pandas website and the Handson-ML tutorial:...
11,091
Given the following text description, write Python code to implement the functionality described below step by step Description: Title Step1: Use Dictionary Comprehension
Python Code: Officers = {'Michael Mulligan': 'Red Army', 'Steven Johnson': 'Blue Army', 'Jessica Billars': 'Green Army', 'Sodoni Dogla': 'Purple Army', 'Chris Jefferson': 'Orange Army'} Officers Explanation: Title: Iterating Over Dictionary Keys Slug: iterating_over_dict...
11,092
Given the following text description, write Python code to implement the functionality described below step by step Description: Chapter 4 Step1: Pandas' data frame has some helpful methods for seeing which values are null Step2: Side note Step3: So we can quickly summarize the number of missing values for each fea...
Python Code: import pandas as pd from io import StringIO csv_data = '''A,B,C,D 1.0,2.0,3.0,4.0 5.0,6.0,,8.0 10.0,11.0,12.0,''' df = pd.read_csv(StringIO(csv_data)) df Explanation: Chapter 4: building good training sets Handling missing values Let's start by constructing a simple dataset with some missing values. End of...
11,093
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: PWC-Net-small model training (with cyclical learning rate schedule) In this notebook we Step2: TODO Step3: Pre-train on FlyingChairs+FlyingThings3DHalfRes mix Load the dataset Step4...
Python Code: pwcnet_train.ipynb PWC-Net model training. Written by Phil Ferriere Licensed under the MIT License (see LICENSE for details) Tensorboard: [win] tensorboard --logdir=E:\\repos\\tf-optflow\\tfoptflow\\pwcnet-sm-6-2-cyclic-chairsthingsmix [ubu] tensorboard --logdir=/media/EDrive/repos/tf-optflow/tfopt...
11,094
Given the following text description, write Python code to implement the functionality described below step by step Description: Matching Market This simple model consists of a buyer, a supplier, and a market. The buyer represents a group of customers whose willingness to pay for a single unit of the good is captured...
Python Code: %matplotlib inline import matplotlib.pyplot as plt import random as rnd import pandas as pd import numpy as np import time import datetime import calendar # fix what is missing with the datetime/time/calendar package def add_months(sourcedate,months): month = sourcedate.month - 1 + months year = in...
11,095
Given the following text description, write Python code to implement the functionality described below step by step Description: This script implements a Gradient Boosting Machine on the Titanic dataset. This is a boosting algorithm that will be using trees, and will be auto-selecting features to evaluate. Since we're...
Python Code: import numpy as np import pandas as pd titanic=pd.read_csv('./titanic_clean_data.csv') cols_to_norm=['Age','Fare'] col_norms=['Age_z','Fare_z'] titanic[col_norms]=titanic[cols_to_norm].apply(lambda x: (x-x.mean())/x.std()) titanic['cabin_clean']=(pd.notnull(titanic.Cabin)) from sklearn.cross_validation imp...
11,096
Given the following text description, write Python code to implement the functionality described below step by step Description: Manuscript plots This notebook creates the figures in Parviainen (2015, submitted to MNRAS). The figures show the calculation of quadratic limb darkening coefficients for three broadband fil...
Python Code: %pylab inline import seaborn as sb from matplotlib.patches import Ellipse from scipy.stats import chi2 from ldtk import LDPSetCreator, BoxcarFilter, TabulatedFilter AAOCW, AAPGW = 3.465, 7.087 rc(['xtick','ytick','axes'], labelsize=8) def eigsorted(cov): vals, vecs = np.linalg.eigh(cov) ord...
11,097
Given the following text problem statement, write Python code to implement the functionality described below in problem statement Problem: I'm using tensorflow 2.10.0.
Problem: import tensorflow as tf a = tf.constant([1,2,3]) b = tf.constant([4,5,6,7]) def g(a,b): tile_a = tf.tile(tf.expand_dims(a, 1), [1, tf.shape(b)[0]]) tile_a = tf.expand_dims(tile_a, 2) tile_b = tf.tile(tf.expand_dims(b, 0), [tf.shape(a)[0], 1]) tile_b = tf.expand_dims(tile_b, 2) cart = tf.con...
11,098
Given the following text description, write Python code to implement the functionality described below step by step Description: Numbers Python provide following builtins numeric data types Step1: NOTE Step2: Greater than (>) Step3: Less than or equal to (<=) Step4: greater_than_or_equal_to Step5: Equal To Step6:...
Python Code: # Converting real to integer print ('int(3.14) =', int(3.14)) print ('int(3.64) =', int(3.64)) print('int("22") =', int("22")) print('int("22.0") !=', int("22.0")) print("int(3+4j) =", int(3+4j)) # Converting integer to real print ('float(5) =', float(5)) print('int("22.0") ==', float("22.0")) print('int(f...
11,099
Given the following text description, write Python code to implement the functionality described below step by step Description: Programación lineal <img style="float Step1: 3.2 Mónica hace aretes y cadenitas de joyería. Es tan buena, que todo lo que hace lo vende. Le toma 30 minutos hacer un par de aretes y una hora...
Python Code: import numpy as np f = np.array([-1, -1]) A = np.array([[50, 24], [30, 33], [-1, 0], [0, -1]]) b = np.array([2400, 2100, -45, -5]) import pyomo_utilities x, obj = pyomo_utilities.linprog(f, A, b) x obj obj_real = x.sum()-50 obj_real.round(2) Explanation: Programación lineal <img style="float: right; margin...