Unnamed: 0
int64
0
16k
text_prompt
stringlengths
110
62.1k
code_prompt
stringlengths
37
152k
15,200
Given the following text description, write Python code to implement the functionality described below step by step Description: ES-DOC CMIP6 Model Properties - Aerosol 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', 'dwd', 'sandbox-2', 'aerosol') Explanation: ES-DOC CMIP6 Model Properties - Aerosol MIP Era: CMIP6 Institute: DWD Source ID: SANDBOX-2 Topic: Aerosol Sub-Topics: Transport, Emissions, ...
15,201
Given the following text description, write Python code to implement the functionality described below step by step Description: Layers of the Earth Students will analyze the following information and answer questions a long the way in order to learn the different layers of the earth. Through BBC's website (provided b...
Python Code: import pandas as pd import numpy as np %matplotlib inline import matplotlib as mpl import matplotlib.pyplot as plt # Read in data that will be used for answering some of the questions below data = pd.read_csv("./significant_month.csv") # Observe the first 5 rows of the data provided below data.head(4) Expl...
15,202
Given the following text description, write Python code to implement the functionality described below step by step Description: Homework 2 Step1: If you get an error stating that database "homework2" does not exist, make sure that you followed the instructions above exactly. If necessary, drop the database you creat...
Python Code: import pg8000 conn = pg8000.connect(database="homework2") Explanation: Homework 2: Working with SQL (Data and Databases 2016) This homework assignment takes the form of an IPython Notebook. There are a number of exercises below, with notebook cells that need to be completed in order to meet particular crit...
15,203
Given the following text description, write Python code to implement the functionality described below step by step Description: 基于词向量的英汉翻译——“火炬上的深度学习"下第一次作业 在这个作业中,你需要半独立地完成一个英文到中文的单词翻译器 本文件是集智AI学园http Step1: 第一步:加载词向量 首先,让我们加载别人已经在大型语料库上训练好的词向量 Step2: 第二步:可视化同一组意思词在两种不同语言的词向量中的相互位置关系 Step3: 结论:可以看出,中文的一、二、等数字彼此之间...
Python Code: # 加载必要的程序包 # PyTorch的程序包 import torch from torch.autograd import Variable import torch.nn as nn import torch.nn.functional as F import torch.optim as optim # 数值运算和绘图的程序包 import numpy as np import matplotlib.pyplot as plt import matplotlib # 加载机器学习的软件包,主要为了词向量的二维可视化 from sklearn.decomposition import PCA #加载...
15,204
Given the following text description, write Python code to implement the functionality described below step by step Description: Notebook 3 Step2: Download the sequence data Sequence data for this study are archived on the NCBI sequence read archive (SRA). Below I read in SraRunTable.txt for this project which contai...
Python Code: ### Notebook 3 ### Data set 3 (American oaks) ### Authors: Eaton et al. (2015) ### Data Location: NCBI SRA SRP055977 Explanation: Notebook 3: This is an IPython notebook. Most of the code is composed of bash scripts, indicated by %%bash at the top of the cell, otherwise it is IPython code. This notebook in...
15,205
Given the following text description, write Python code to implement the functionality described below step by step Description: Pipeline Cleaning confounds We first created the confound matrix according to Smith et al. (2015). The confound variables are motion (Jenkinson), sex, and age. We also created squared confou...
Python Code: import copy import os, sys import numpy as np import pandas as pd import joblib os.chdir('../') # loa my modules from src.utils import load_pkl from src.file_io import save_output from src.models import nested_kfold_cv_scca, clean_confound, permutate_scca from src.visualise import set_text_size, show_resul...
15,206
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Lecture 3 Step2: <p class='alert alert-success'> Solve the questions in green blocks. Save the file as ME249-Lecture-3-YOURNAME.ipynb and change YOURNAME in the bottom cell. Send me ...
Python Code: %matplotlib inline # plots graphs within the notebook %config InlineBackend.figure_format='svg' # not sure what this does, may be default images to svg format from IPython.display import Image from IPython.core.display import HTML def header(text): raw_html = '<h4>' + str(text) + '</h4>' return ra...
15,207
Given the following text description, write Python code to implement the functionality described below step by step Description: <a href='http Step1: Load the data As a first step we will load a large dataset using dask. If you have followed the setup instructions you will have downloaded a large CSV containing 12 mi...
Python Code: import pandas as pd import holoviews as hv import dask.dataframe as dd import datashader as ds import geoviews as gv from holoviews.operation.datashader import datashade, aggregate hv.extension('bokeh') Explanation: <a href='http://www.holoviews.org'><img src="assets/hv+bk.png" alt="HV+BK logos" width="40%...
15,208
Given the following text description, write Python code to implement the functionality described below step by step Description: Lecture 12 Step1: That's everything we need for a working function! Let's walk through it. Step2: def keyword Step3: Other notes on functions You can define functions (as we did just befo...
Python Code: def our_function(): pass Explanation: Lecture 12: Functions CBIO (CSCI) 4835/6835: Introduction to Computational Biology Overview and Objectives In this lecture, we'll introduce the concept of functions, critical abstractions in nearly every modern programming language. Functions are important for abst...
15,209
Given the following text description, write Python code to implement the functionality described below step by step Description: 1. Prepare Problem a) Load libraries Step1: b) Load dataset Download customer account data from Wiley's website, RetailMart.xlsx Step2: The 'Pregnant' column can only take on one of two (i...
Python Code: import pandas as pd import numpy as np from pandas.tools.plotting import scatter_matrix from matplotlib import pyplot as plt from sklearn.model_selection import train_test_split from sklearn.model_selection import KFold from sklearn.model_selection import cross_val_score from sklearn.metrics import classif...
15,210
Given the following text description, write Python code to implement the functionality described below step by step Description: Same tweet belongs to multiple datasets Step1: Merge URL types Step2: Add location states df_merged_meta_cats.u_location.value_counts().to_csv("USER_LOCATIONS.txt", sep="\t", encoding='utf...
Python Code: df_merged_meta.t_id.value_counts().head() df_merged_meta[df_merged_meta.t_id == 700042121877835776][["topic_name"]] df_merged_meta.t_id.value_counts()[df_merged_meta.t_id.value_counts() > 1] df_merged_meta[df_merged_meta.t_id == 792354716521009152].T df_merged_meta["is_controversial"] = df_merged_meta.topi...
15,211
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction History of Machine Learning The field of machine learning has its roots in Artificial intelligence (AI), which started in 1950 with the seminal paper Computing Machinery and Int...
Python Code: from IPython.display import YouTubeVideo YouTubeVideo('sXx-PpEBR7k') Explanation: Introduction History of Machine Learning The field of machine learning has its roots in Artificial intelligence (AI), which started in 1950 with the seminal paper Computing Machinery and Intelligence. In this paper, Alan Turi...
15,212
Given the following text description, write Python code to implement the functionality described below step by step Description: Load TensorFlow Go to Edit->Notebook settings to confirm you have a GPU accelerated kernel. Step1: Set up FFN code and sample data Colab already provides most of the dependencies. Step2: R...
Python Code: %tensorflow_version 1.x import tensorflow as tf print(tf.__version__) # Silence deprecation warnings for now. tf.logging.set_verbosity(tf.logging.ERROR) device_name = tf.test.gpu_device_name() if device_name != '/device:GPU:0': print('GPU device not found') gpu = False else: print('Found GPU at: {}'....
15,213
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Dropout Dropout [1] is a technique for regularizing neural networks by randomly setting some features to zero during the forward pass. In this exercise you will implement a dropout la...
Python Code: # As usual, a bit of setup import time import numpy as np import matplotlib.pyplot as plt from cs231n.classifiers.fc_net import * from cs231n.data_utils import get_CIFAR10_data from cs231n.gradient_check import eval_numerical_gradient, eval_numerical_gradient_array from cs231n.solver import Solver %matplot...
15,214
Given the following text description, write Python code to implement the functionality described below step by step Description: Chapter 3 - Strings This notebook uses code snippets and explanations from this course. In this notebook, we will focus on the datatype strings. The first thing you learned was printing a si...
Python Code: # Here are some strings: string_1 = "Hello, world!" string_2 = 'I ❤️ cheese' # If you are using Python 2, your computer will not like this. string_3 = '1,2,3,4,5,6,7,8,9' Explanation: Chapter 3 - Strings This notebook uses code snippets and explanations from this course. In this notebook, we will focu...
15,215
Given the following text description, write Python code to implement the functionality described below step by step Description: <table width="100%" border="0"> <tr> <td><img src="./images/ing.png" alt="" align="left" /></td> <td><img src="./images/ucv.png" alt="" align="center" height="100" width="100" /></...
Python Code: import numpy as np from numba import njit arr2d = np.arange(20 * 30, dtype=float).reshape(20,30) %%timeit np.sum(arr2d) def py_sum(arr): M, N = arr.shape sum = 0.0 for i in range(M): for j in range(N): sum += arr[i,j] return sum %%timeit py_sum(arr2d) fast_sum = njit(py_...
15,216
Given the following text description, write Python code to implement the functionality described below step by step Description: Parse Json Step1: 載入原始 RAW Data Step2: 利用 LXML Parser 來分析文章結構 Step3: 取出 Image Src 的列表 Step4: 統計 Image Src 的列表 Step5: 請使用 reduceByKey , sortBy 來計算出 img src 排行榜 請參照以下文件 [http
Python Code: def parseRaw(json_map): url = json_map['url'] content = json_map['html'] return (url,content) Explanation: Parse Json End of explanation import json import pprint pp = pprint.PrettyPrinter(indent=2) path = "./pixnet.txt" all_content = sc.textFile(path).map(json.loads).map(parseRaw) Explanation:...
15,217
Given the following text description, write Python code to implement the functionality described below step by step Description: Basic Python Syntax In this exercise, you will work through some simple blocks of code so you learn the essentials of the Python language syntax. For each of the code blocks below, read the...
Python Code: 1 + 1 2 * 4 (2 * 4) - 2 4 ** 2 # Raise a number to a power 16 / 4 15 / 4 2.5 * 2.0 15.0 / 4 Explanation: Basic Python Syntax In this exercise, you will work through some simple blocks of code so you learn the essentials of the Python language syntax. For each of the code blocks below, read the code before...
15,218
Given the following text description, write Python code to implement the functionality described below step by step Description: Meta-Analysis in statsmodels Statsmodels include basic methods for meta-analysis. This notebook illustrates the current usage. Status Step1: Example Step2: estimate effect size standardize...
Python Code: %matplotlib inline import numpy as np import pandas as pd from scipy import stats, optimize from statsmodels.regression.linear_model import WLS from statsmodels.genmod.generalized_linear_model import GLM from statsmodels.stats.meta_analysis import ( effectsize_smd, effectsize_2proportions, combine_effe...
15,219
Given the following text description, write Python code to implement the functionality described below step by step Description: Concrete Slump Test - UCI Analysis of the <a href="https Step1: Univariate Analysis Step2: Correlation With the Target Columns Step3: Correlation between Features Step4: Bivariate Analys...
Python Code: import numpy as np import pandas as pd %pylab inline pylab.style.use('ggplot') import seaborn as sns data = pd.read_csv('concrete_slump.csv') data = data.drop('No', axis=1) data.head() Explanation: Concrete Slump Test - UCI Analysis of the <a href="https://archive.ics.uci.edu/ml/datasets/Concrete+Slump+Tes...
15,220
Given the following text description, write Python code to implement the functionality described below step by step Description: 5. Additional Statistics Functions Step1: Bootstrap Comparisons Step2: TOST Equivalence Tests
Python Code: # Import numpy and set random number generator import numpy as np np.random.seed(10) # Import stats functions from pymer4.stats import perm_test # Generate two samples of data: X (M~2, SD~10, N=100) and Y (M~2.5, SD~1, N=100) x = np.random.normal(loc=2, size=100) y = np.random.normal(loc=2.5, size=100) # B...
15,221
Given the following text description, write Python code to implement the functionality described below step by step Description: Multivariable regression Imports and setup Step1: Load Data We are going to use daily gas, electricity and water consumption data and weather data. Because we don't want to overload the wea...
Python Code: import os import pandas as pd from opengrid.library import houseprint, caching, regression from opengrid import config c = config.Config() import matplotlib.pyplot as plt plt.style.use('ggplot') %matplotlib inline plt.rcParams['figure.figsize'] = 16,8 # Create houseprint from saved file, if not available, ...
15,222
Given the following text description, write Python code to implement the functionality described below step by step Description: Title Step1: Create Some Data Step2: Create An Operation To Execute On The Data Step3: Traditional Approach Step4: Parallelism Approach
Python Code: from multiprocessing import Pool from multiprocessing.dummy import Pool as ThreadPool Explanation: Title: Parallel Processing Slug: parallel_processing Summary: Lightweight Parallel Processing in Python. Date: 2016-01-23 12:00 Category: Python Tags: Basics Authors: Chris Albon This tutorial is inspi...
15,223
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Extract curves into striplogs Sometimes you'd like to summarize or otherwise extract curve data (e.g. wireline log data) into a striplog (e.g. one that represents formations). We'll s...
Python Code: data = Comp Formation,Depth A,100 B,200 C,250 D,400 E,600 Explanation: Extract curves into striplogs Sometimes you'd like to summarize or otherwise extract curve data (e.g. wireline log data) into a striplog (e.g. one that represents formations). We'll start by making some fake CSV text — we'll make 5 form...
15,224
Given the following text description, write Python code to implement the functionality described below step by step Description: Facies classification using Machine Learning LA Team Submission 5 ## Lukas Mosser, Alfredo De la Fuente In this approach for solving the facies classfication problem ( https Step1: Data Pre...
Python Code: %%sh pip install pandas pip install scikit-learn pip install tpot from __future__ import print_function import numpy as np %matplotlib inline import pandas as pd import matplotlib.pyplot as plt from sklearn.model_selection import cross_val_score from sklearn.model_selection import KFold , StratifiedKFold f...
15,225
Given the following text description, write Python code to implement the functionality described below step by step Description: EDA Step1: Counting Named Entities Here is my count_entities function. The idea is to count the total mentions of a person or a place in an article's body or title and save them as columns ...
Python Code: import articledata import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import operator data = pd.read_pickle('/Users/teresaborcuch/capstone_project/notebooks/pickled_data.pkl') Explanation: EDA: Named Entity Recognition Named entity recognition is the process of identifing particular ...
15,226
Given the following text description, write Python code to implement the functionality described below step by step Description: Modeling and Simulation in Python Comparison of the penny models from Chapters 1, 20, and 21 Copyright 2018 Allen Downey License Step1: With air resistance Next we'll add air resistance usi...
Python Code: # Configure Jupyter so figures appear in the notebook %matplotlib inline # Configure Jupyter to display the assigned value after an assignment %config InteractiveShell.ast_node_interactivity='last_expr_or_assign' # import functions from the modsim.py module from modsim import * Explanation: Modeling and Si...
15,227
Given the following text description, write Python code to implement the functionality described below step by step Description: $ \newcommand\HH{\mathbf{H}} \newcommand\SO{\mathbf{S}} \newcommand\Scat{\boldsymbol\Gamma} \newcommand\ket[1]{|#1\rangle} \newcommand\bra[1]{\langle#1|} \newcommand\set[1]{{#1}} \newcommand...
Python Code: C60 = sisl.Geometry.read('C60.xyz') # Calculate the nearest neighbour distance dist = C60.distance(R=5) C60.atom.atom[0] = sisl.Atom(6, R=dist[0] + 0.01) print(C60) Explanation: $ \newcommand\HH{\mathbf{H}} \newcommand\SO{\mathbf{S}} \newcommand\Scat{\boldsymbol\Gamma} \newcommand\ket[1]{|#1\rangle} \newco...
15,228
Given the following text description, write Python code to implement the functionality described below step by step Description: ReadCSV Read the csv file with acceloremeter information. Convert the data in file to numpy array and then plot it. Step1: Open the CSV file and transform to an array. Also get number of sa...
Python Code: import csv import numpy as np import matplotlib.pyplot as plt Explanation: ReadCSV Read the csv file with acceloremeter information. Convert the data in file to numpy array and then plot it. End of explanation with open('../dataset/PhysicsToolboxSuite/walk_normal_hand_001.csv', 'rb') as csvfile: data_r...
15,229
Given the following text description, write Python code to implement the functionality described below step by step Description: NumPy NumPy is a Linear Algebra Library for Python. NumPy’s main object is the homogeneous multidimensional array. It is a table of elements (usually numbers), all of the same type, indexed ...
Python Code: import numpy as np a = [1,2,3] a b = np.array(a) b np.arange(1, 10) np.arange(1, 10, 2) Explanation: NumPy NumPy is a Linear Algebra Library for Python. NumPy’s main object is the homogeneous multidimensional array. It is a table of elements (usually numbers), all of the same type, indexed by a tuple of p...
15,230
Given the following text description, write Python code to implement the functionality described below step by step Description: <a id='Urbanization_Using_NDBI_top'></a> Urbanization Using NDBI <hr> Background Among the many urbanization indices, the Normalized Difference Built-Up Index (NDBI) is one of the most commo...
Python Code: import sys import os sys.path.append(os.environ.get('NOTEBOOK_ROOT')) import matplotlib.pyplot as plt import xarray as xr from utils.data_cube_utilities.dc_display_map import display_map from utils.data_cube_utilities.dc_rgb import rgb from utils.data_cube_utilities.urbanization import NDBI from utils.data...
15,231
Given the following text description, write Python code to implement the functionality described below step by step Description: Lab 4 - Tensorflow ANN for regression In this lab we will use Tensorflow to build an Artificial Neuron Network (ANN) for a regression task. As opposed to the low-level implementation from th...
Python Code: %matplotlib inline import math import random import seaborn as sns import matplotlib.pyplot as plt import pandas as pd from sklearn.datasets import load_boston import numpy as np import tensorflow as tf sns.set(style="ticks", color_codes=True) Explanation: Lab 4 - Tensorflow ANN for regression In this lab ...
15,232
Given the following text description, write Python code to implement the functionality described below step by step Description: 第8章 機械学習の適用1 - 感情分析 https Step1: 8.2 BoWモデルの紹介 BoW(Bag-of-Words) ドキュメントの集合全体から、たとえば単語という一意なトークン(token)からなる語彙(vocabulary)を作成する 各ドキュメントでの各単語の出現回数を含んだ特徴ベクトルを構築する 疎ベクトル(sparse vector) 8.2.1 単語を...
Python Code: # Added version check for recent scikit-learn 0.18 checks from distutils.version import LooseVersion as Version from sklearn import __version__ as sklearn_version # データを読み込む import pyprind import pandas as pd import os pbar = pyprind.ProgBar(50000) labels = {'pos': 1, 'neg': 0} df = pd.DataFrame() for set ...
15,233
Given the following text description, write Python code to implement the functionality described below step by step Description: Visualizing epoched data This tutorial shows how to plot epoched data as time series, how to plot the spectral density of epoched data, how to plot epochs as an imagemap, and how to plot the...
Python Code: import os import mne sample_data_folder = mne.datasets.sample.data_path() sample_data_raw_file = os.path.join(sample_data_folder, 'MEG', 'sample', 'sample_audvis_raw.fif') raw = mne.io.read_raw_fif(sample_data_raw_file, verbose=False).crop(tmax=120) Explanation: Visualiz...
15,234
Given the following text description, write Python code to implement the functionality described below step by step Description: This notebook applies different regression methods to the finalized dataset in search of the best regression model. Data Ingestion and Wrangling Step1: Lasso Regression Lasso regression is...
Python Code: import pandas as pd import numpy as np import matplotlib.pyplot as plt %matplotlib inline dataset_1min = pd.read_csv('dataset-1min.csv') print(dataset_1min.shape) dataset_1min.head(3) # Delete duplicate rows in the dataset dataset_1min = dataset_1min.drop_duplicates() print(dataset_1min.shape) dataset_1min...
15,235
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...
15,236
Given the following text description, write Python code to implement the functionality described below step by step Description: Visualize Raw data Step1: The visualization module ( Step2: The channels are color coded by channel type. Generally MEG channels are colored in different shades of blue, whereas EEG channe...
Python Code: import os.path as op import numpy as np import mne data_path = op.join(mne.datasets.sample.data_path(), 'MEG', 'sample') raw = mne.io.read_raw_fif(op.join(data_path, 'sample_audvis_raw.fif'), preload=True) raw.set_eeg_reference('average', projection=True) # set EEG average refere...
15,237
Given the following text description, write Python code to implement the functionality described below step by step Description: <center><h2>Scale your pandas workflows by changing one line of code</h2> Exercise 3 Step1: Concept for exercise Step2: Speed improvements If we were to try and replicate this functionalit...
Python Code: import modin.pandas as pd import pandas import numpy as np import time frame_data = np.random.randint(0, 100, size=(2**18, 2**8)) df = pd.DataFrame(frame_data).add_prefix("col") pandas_df = pandas.DataFrame(frame_data).add_prefix("col") modin_start = time.time() print(df.mask(df < 50)) modin_end = time.tim...
15,238
Given the following text description, write Python code to implement the functionality described below step by step Description: Calcul symbolique en Python Step1: Introduction Ce notebook est la traduction française du cours sur SymPy disponible entre autre sur Wakari avec quelques modifications et compléments notam...
Python Code: %matplotlib inline Explanation: Calcul symbolique en Python End of explanation from sympy import * Explanation: Introduction Ce notebook est la traduction française du cours sur SymPy disponible entre autre sur Wakari avec quelques modifications et compléments notamment pour la résolution d'équations diffé...
15,239
Given the following text description, write Python code to implement the functionality described below step by step Description: Recommendation Engine In this tutorial we are going to build a simple recommender system using collaborative filtering. You'll be learning about the popular data analysis package pandas alon...
Python Code: import numpy as np import pandas as pd import sklearn.metrics.pairwise Explanation: Recommendation Engine In this tutorial we are going to build a simple recommender system using collaborative filtering. You'll be learning about the popular data analysis package pandas along the way. 1. The import statemen...
15,240
Given the following text description, write Python code to implement the functionality described below step by step Description: San Francisco Crime Modeling Go here for the details on the Kaggle competition Predictive Goal Step1: Load the dataset from the prepared Parquet file Step2: Step 1 Step3: Thus, our machin...
Python Code: sc sc.setLogLevel('INFO') Explanation: San Francisco Crime Modeling Go here for the details on the Kaggle competition Predictive Goal: "Given time and location, you must predict the category of crime that occurred." Data profiling contained in a separate notebook ("SanFranCrime.ipynb") End of explanation ...
15,241
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', 'dwd', 'sandbox-1', 'atmos') Explanation: ES-DOC CMIP6 Model Properties - Atmos MIP Era: CMIP6 Institute: DWD Source ID: SANDBOX-1 Topic: Atmos Sub-Topics: Dynamical Core, Radiation, T...
15,242
Given the following text description, write Python code to implement the functionality described below step by step Description: Plotting is an essential skill for Engineers. Plots can reveal trends in data and outliers. Plots are a way to visually communicate results with your engineering team, supervisors and custom...
Python Code: import matplotlib.pyplot as plt import numpy as np # if using a jupyter notebook %matplotlib inline Explanation: Plotting is an essential skill for Engineers. Plots can reveal trends in data and outliers. Plots are a way to visually communicate results with your engineering team, supervisors and custom...
15,243
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: word2vec <img src="http Step2: Check for understanding <br> <details><summary> How many dimensions are data represented in? </summary> <br> There are 2 dimensions. </details> <br> ...
Python Code: corpus = The man and woman meet each other ... They become king and queen ... They got old and stop talking to each other. Instead, they read books and magazines ... import matplotlib.pyplot as plt import numpy as np %matplotlib inline # Let's hand assign the words to vectors im...
15,244
Given the following text description, write Python code to implement the functionality described below step by step Description: Day 18 Pre-class assignment Goals for today's pre-class assignment In this pre-class assignment, you are going to learn how to Step1: Question 1 Step2: Question 2
Python Code: from IPython.display import YouTubeVideo # WATCH THE VIDEO IN FULL-SCREEN MODE YouTubeVideo("JXJQYpgFAyc",width=640,height=360) # Numerical integration Explanation: Day 18 Pre-class assignment Goals for today's pre-class assignment In this pre-class assignment, you are going to learn how to: Numerically ...
15,245
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2019 The TensorFlow Authors. Step1: Using DTensors with Keras <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https Step2: Next, import tens...
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...
15,246
Given the following text description, write Python code to implement the functionality described below step by step Description: Python Basics with Numpy (optional assignment) Welcome to your first assignment. This exercise gives you a brief introduction to Python. Even if you've used Python before, this will help fam...
Python Code: ### START CODE HERE ### (≈ 1 line of code) test = "Hello World" ### END CODE HERE ### print ("test: " + test) Explanation: Python Basics with Numpy (optional assignment) Welcome to your first assignment. This exercise gives you a brief introduction to Python. Even if you've used Python before, this will he...
15,247
Given the following text description, write Python code to implement the functionality described below step by step Description: Semidefinite Relaxation of AC Optimal Power Flow Problems This notebook demonstrates the use of semidefinite relaxation techniques for AC optimal power flow (ACOPF) problems. A description o...
Python Code: import json, re import requests testcases = {} clist = [] # Retrieve list of MATPOWER test cases response = requests.get('https://api.github.com/repos/MATPOWER/matpower/contents/data') clist += json.loads(response.text) # Retrieve list of pglib-opf test cases response = requests.get('https://api.github.com...
15,248
Given the following text problem statement, write Python code to implement the functionality described below in problem statement Problem: Train-Test Splitting with Stratification using Scikit-Learn
Python Code:: from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.4, random_state=101, ...
15,249
Given the following text description, write Python code to implement the functionality described below step by step Description: HAC variance estimation Use two data files FwdSpot1.dat and FwdSpot3.dat. The former contains monthly spot and 1-month forward exchange rates, the latter monthly spot and 3-month forward exc...
Python Code: import pandas as pd import numpy as np import matplotlib.pylab as plt import seaborn as sns import datetime as dt from numpy.linalg import inv, lstsq from scipy.stats import chi2 # For inline pictures %matplotlib inline # For nicer output of Pandas dataframes pd.set_option('float_format', '{:8.2f}'.format)...
15,250
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', 'inpe', 'besm-2-7', 'atmos') Explanation: ES-DOC CMIP6 Model Properties - Atmos MIP Era: CMIP6 Institute: INPE Source ID: BESM-2-7 Topic: Atmos Sub-Topics: Dynamical Core, Radiation, T...
15,251
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Two-Level Step2: We'll just check that the pulse area is what we want. Step3: Solve the Problem Step4: Plot Output Step5: Analysis The $2 \pi$ sech pulse passes through, slowed bu...
Python Code: import numpy as np SECH_FWHM_CONV = 1./2.6339157938 t_width = 1.0*SECH_FWHM_CONV # [τ] print('t_width', t_width) mb_solve_json = { "atom": { "fields": [ { "coupled_levels": [[0, 1]], "rabi_freq_t_args": { "n_pi": 2.0, "centre": 0.0, "width": %f ...
15,252
Given the following text description, write Python code to implement the functionality described below step by step Description: DEM analysis Load site using shapely Step1: Load digital elevation model Step2: Reproject the site to coords of dem for sampling elevation Step3: Get site elevation Step4: Not integrated...
Python Code: with open ('inputs/site.geojson') as f: js = json.load(f) s = shape(js['features'][0]['geometry']) s Explanation: DEM analysis Load site using shapely End of explanation dem = gdal.Open('inputs/dem/filled.tif') Explanation: Load digital elevation model End of explanation site = ogr.Geometry(ogr.wkbPoin...
15,253
Given the following text description, write Python code to implement the functionality described below step by step Description: ES-DOC CMIP6 Model Properties - Toplevel MIP Era Step1: Document Authors Set document authors Step2: Document Contributors Specify document contributors Step3: Document Publication Specif...
Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'mpi-m', 'icon-esm-lr', 'toplevel') Explanation: ES-DOC CMIP6 Model Properties - Toplevel MIP Era: CMIP6 Institute: MPI-M Source ID: ICON-ESM-LR Sub-Topics: Radiative Forcings. Proper...
15,254
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: <a id='top'></a> Demonstration of the filters available in scipy.signal This notebook is not intended to replace the SciPy reference guide but to serve only as a one stop shop for the...
Python Code: # IPython magic commands %matplotlib inline # Python standard library import sys import os.path # 3rd party modules import numpy as np import scipy as sp import matplotlib as mpl from scipy import signal import matplotlib.pyplot as plt print(sys.version) for module in (np, sp, mpl): print('{:.<15}{}'.f...
15,255
Given the following text description, write Python code to implement the functionality described below step by step Description: ApJdataFrames Hernandez2014 Title Step1: Table 4 - Low Resolution Analysis
Python Code: %pylab inline import seaborn as sns sns.set_context("notebook", font_scale=1.5) import warnings warnings.filterwarnings("ignore") from astropy.io import ascii Explanation: ApJdataFrames Hernandez2014 Title: A SPECTROSCOPIC CENSUS IN YOUNG STELLAR REGIONS: THE σ ORIONIS CLUSTER Authors: Jesus Hernandez, Nur...
15,256
Given the following text description, write Python code to implement the functionality described below step by step Description: Ввод/Вывод в ipython notebook Пользовательский ввод осуществляется использованием конструкции input Step1: Вывод одной переменной Для вывода одной переменной на блок достаточно написать имя...
Python Code: a = input("Enter new name:") Explanation: Ввод/Вывод в ipython notebook Пользовательский ввод осуществляется использованием конструкции input End of explanation a Explanation: Вывод одной переменной Для вывода одной переменной на блок достаточно написать имя этой переменной End of explanation b = input("En...
15,257
Given the following text description, write Python code to implement the functionality described below step by step Description: Summary Notes taken to help for the first project for the Deep Learning Foundations Nanodegree course dellivered by Udacity. My Github repo for this project can be found here Step1: Change ...
Python Code: %run ../../../code/version_check.py Explanation: Summary Notes taken to help for the first project for the Deep Learning Foundations Nanodegree course dellivered by Udacity. My Github repo for this project can be found here: adriantorrie/udacity_dlfnd_project_1 Table of Contents Neural network Output Formu...
15,258
Given the following text description, write Python code to implement the functionality described below step by step Description: Handwritten Number Recognition with TFLearn and MNIST In this notebook, we'll be building a neural network that recognizes handwritten numbers 0-9. This kind of neural network is used in a ...
Python Code: # Import Numpy, TensorFlow, TFLearn, and MNIST data import numpy as np import tensorflow as tf import tflearn import tflearn.datasets.mnist as mnist Explanation: Handwritten Number Recognition with TFLearn and MNIST In this notebook, we'll be building a neural network that recognizes handwritten numbers 0-...
15,259
Given the following text description, write Python code to implement the functionality described below step by step Description: Mapping utilities and options This notebook illustrate how to map SuperDARN radars and FoVs Step1: Plot all radars in AACGM coordinates Be patient, this takes a few seconds (so many radars,...
Python Code: %pylab inline from davitpy.pydarn.radar import * from davitpy.pydarn.plotting import * from davitpy.utils import * import datetime as dt Explanation: Mapping utilities and options This notebook illustrate how to map SuperDARN radars and FoVs End of explanation figure(figsize=(15,10)) # Plot map subplot(121...
15,260
Given the following text description, write Python code to implement the functionality described below step by step Description: 통계적 사고 (2판) 연습문제 (thinkstats2.com, think-stat.xwmooc.org)<br> Allen Downey / 이광춘(xwMOOC) Step1: 연습문제 5.1 BRFSS 데이터셋에서 (5.4절 참조), 신장 분포는 대략 남성에 대해 모수 µ = 178 cm, σ = 7.7cm을 갖는 정규분포이며, 여성에 대해...
Python Code: %matplotlib inline %run chap06soln.py Explanation: 통계적 사고 (2판) 연습문제 (thinkstats2.com, think-stat.xwmooc.org)<br> Allen Downey / 이광춘(xwMOOC) End of explanation import scipy.stats Explanation: 연습문제 5.1 BRFSS 데이터셋에서 (5.4절 참조), 신장 분포는 대략 남성에 대해 모수 µ = 178 cm, σ = 7.7cm을 갖는 정규분포이며, 여성에 대해서 µ = 163 cm, σ = 7.3 c...
15,261
Given the following text description, write Python code to implement the functionality described below step by step Description: CTA 1DC background energy distribution This is my attempt to understand the background event energy distribution for CTA 1DC simulated data. See https Step1: Actual distribution of events W...
Python Code: %matplotlib inline import matplotlib.pyplot as plt import matplotlib.colors as colors import numpy as np from astropy.table import Table, vstack from gammapy.data import DataStore # Parameters used throughout this notebook CTADATA = '/Users/deil/work/cta-dc/data/1dc/1dc/' irf_name = 'South_z20_50h' n_obs =...
15,262
Given the following text description, write Python code to implement the functionality described below step by step Description: Doc2Vec Tutorial on the Lee Dataset Step1: What is it? Doc2Vec is an NLP tool for representing documents as a vector and is a generalizing of the Word2Vec method. This tutorial will serve a...
Python Code: import gensim import os import collections import random Explanation: Doc2Vec Tutorial on the Lee Dataset End of explanation # Set file names for train and test data test_data_dir = '{}'.format(os.sep).join([gensim.__path__[0], 'test', 'test_data']) lee_train_file = test_data_dir + os.sep + 'lee_background...
15,263
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction to the Mandelbrot Set First, a boring example A sequence of numbers can be defined by a map. For example, consider the simple map $$f Step1: Interesting! To explore this more, ...
Python Code: def f(x, c): return x**2 + c x = 0.0 for i in range(10): print(i, x) x = f(x, 1) x = 0.0 for i in range(10): print(i, x) x = f(x, -1) x = 0.0 for i in range(10): print(i, x) x = f(x, 0.1) Explanation: Introduction to the Mandelbrot Set First, a boring example A sequence of numbe...
15,264
Given the following text description, write Python code to implement the functionality described below step by step Description: 3D Plots, in Python (Easy version, without the "np" and "plt" namespaces.) We first load in the toolboxes for numerical python and plotting. Note the "import * " command will bring in the f...
Python Code: %matplotlib inline from numpy import * from matplotlib.pyplot import * from mpl_toolkits.mplot3d import Axes3D Explanation: 3D Plots, in Python (Easy version, without the "np" and "plt" namespaces.) We first load in the toolboxes for numerical python and plotting. Note the "import * " command will bring i...
15,265
Given the following text description, write Python code to implement the functionality described below step by step Description: Deep Dream Deep Dream, or Inceptionism, was introduced by Google in this blogpost. Deep Dream is an algorithm that optimizes an input image so that it maximizes its activations in certain la...
Python Code: import matplotlib.pyplot as plt %matplotlib inline from keras.applications import vgg16 from keras.layers import Input from dream import * Explanation: Deep Dream Deep Dream, or Inceptionism, was introduced by Google in this blogpost. Deep Dream is an algorithm that optimizes an input image so that it ma...
15,266
Given the following text problem statement, write Python code to implement the functionality described below in problem statement Problem: I want to use a logical index to slice a torch tensor. Which means, I want to select the columns that get a '1' in the logical index.
Problem: import numpy as np import pandas as pd import torch A_logical, B = load_data() C = B[:, A_logical.bool()]
15,267
Given the following text description, write Python code to implement the functionality described below step by step Description: Content under Creative Commons Attribution license CC-BY 4.0, code under BSD 3-Clause License © 2018 parts of this notebook are from this Jupyter notebook by Heiner Igel (@heinerigel), Lion ...
Python Code: # Execute this cell to load the notebook's style sheet, then ignore it from IPython.core.display import HTML css_file = '../style/custom.css' HTML(open(css_file, "r").read()) Explanation: Content under Creative Commons Attribution license CC-BY 4.0, code under BSD 3-Clause License © 2018 parts of this note...
15,268
Given the following text description, write Python code to implement the functionality described below step by step Description: Custom Keras Layer Idea Step1: AntiRectifier Layer Step2: Parametrs and Settings Step3: Data Preparation Step4: Model with Custom Layer Step5: Excercise Compare with an equivalent netwo...
Python Code: from keras.models import Sequential from keras.layers import Dense, Dropout, Layer, Activation from keras.datasets import mnist from keras import backend as K from keras.utils import np_utils Explanation: Custom Keras Layer Idea: We build a custom activation layer called Antirectifier, which modifies the s...
15,269
Given the following text description, write Python code to implement the functionality described below step by step Description: Minist 예제 Minist 예제를 살펴봅시다. 사실 minist 예제는 3장 다룬 기초적인 Neural Networw와 거의 동일 합니다. 단지, 입력 DataLoader를 사용하여 Minist dataset를 이용하는 부분만 차이가 나고, 데이터량이 많아서 시간이 좀 많이 걸리는 부분입니다. 입력 DataLoader를 이용하는...
Python Code: %matplotlib inline Explanation: Minist 예제 Minist 예제를 살펴봅시다. 사실 minist 예제는 3장 다룬 기초적인 Neural Networw와 거의 동일 합니다. 단지, 입력 DataLoader를 사용하여 Minist dataset를 이용하는 부분만 차이가 나고, 데이터량이 많아서 시간이 좀 많이 걸리는 부분입니다. 입력 DataLoader를 이용하는 것은 4장에서 잠시 다루었기 때문에, 시간을 줄이기 위해서 cuda gpu를 사용하는 부분을 추가했습니다. 입력변수와 network상의 변수의 tor...
15,270
Given the following text description, write Python code to implement the functionality described below step by step Description: <a href="https Step1: Entrada de Dados Step2: Executar comandos Linux Step3: Instalar biblioteca Step4: Saída de dados ricas Step5: Utilizando a ajuda integrada Use a tecla tab para exe...
Python Code: print('Olá seja bem vindo!!') Explanation: <a href="https://colab.research.google.com/github/cavalcantetreinamentos/curso_python/blob/master/Primeiros_passos_Google_Colab.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> Aprendendo Google ...
15,271
Given the following text description, write Python code to implement the functionality described below step by step Description: GRADEV Step2: Gap robust allan deviation comparison Compute the GRADEV of a white phase noise. Compares two different scenarios. 1) The original data and 2) ADEV estimate with gap robust AD...
Python Code: %matplotlib inline import pylab as plt import numpy as np import allantools Explanation: GRADEV: gap robust allan deviation Notebook setup & package imports End of explanation def example1(): Compute the GRADEV of a white phase noise. Compares two different scenarios. 1) The original data and...
15,272
Given the following text description, write Python code to implement the functionality described below step by step Description: Interact Exercise 5 Imports Put the standard imports for Matplotlib, Numpy and the IPython widgets in the following cell. Step2: Interact with SVG display SVG is a simple way of drawing vec...
Python Code: %matplotlib inline import matplotlib.pyplot as plt import numpy as np from IPython.html.widgets import interact, interactive, fixed from IPython.display import display, SVG Explanation: Interact Exercise 5 Imports Put the standard imports for Matplotlib, Numpy and the IPython widgets in the following cell....
15,273
Given the following text description, write Python code to implement the functionality described below step by step Description: Gaussian Process (GP) smoothing This example deals with the case when we want to smooth the observed data points $(x_i, y_i)$ of some 1-dimensional function $y=f(x)$, by finding the new valu...
Python Code: %pylab inline figsize(12, 6); import numpy as np import scipy.stats as stats x = np.linspace(0, 50, 100) y = (np.exp(1.0 + np.power(x, 0.5) - np.exp(x/15.0)) + np.random.normal(scale=1.0, size=x.shape)) plot(x, y); xlabel("x"); ylabel("y"); title("Observed Data"); Explanation: Gaussian Process (GP) s...
15,274
Given the following text description, write Python code to implement the functionality described below step by step Description: Algorithms Exercise 2 Imports Step2: Peak finding Write a function find_peaks that finds and returns the indices of the local maxima in a sequence. Your function should Step3: Here is a st...
Python Code: %matplotlib inline from matplotlib import pyplot as plt import seaborn as sns import numpy as np Explanation: Algorithms Exercise 2 Imports End of explanation def find_peaks(a): Find the indices of the local maxima in a sequence. #empty list and make the parameter into an array empty = [] ...
15,275
Given the following text description, write Python code to implement the functionality described below step by step Description: Decision Tree Classification Create entry points to spark Step1: Decision tree classification with pyspark Import data Step2: Process categorical columns The following code does three thin...
Python Code: from pyspark import SparkContext sc = SparkContext(master = 'local') from pyspark.sql import SparkSession spark = SparkSession.builder \ .appName("Python Spark SQL basic example") \ .config("spark.some.config.option", "some-value") \ .getOrCreate() Explanation: Decision Tree C...
15,276
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2018 Google LLC. Step1: Visualizing objective functions by interpolating in randomly drawn directions Motivation Useful visualizations of high dimensional objective functions are ...
Python Code: # 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 # distribute...
15,277
Given the following text description, write Python code to implement the functionality described below step by step Description: Exercici de navegació <span title="Roomba navigating around furniture"><img src="img/roomba.jpg" align="right" width=200></span> Un robot mòbil com el Roomba de la imatge ha d'evitar xocar a...
Python Code: from functions import connect, touch, forward, backward, left, right, stop, disconnect, next_notebook from time import sleep connect() Explanation: Exercici de navegació <span title="Roomba navigating around furniture"><img src="img/roomba.jpg" align="right" width=200></span> Un robot mòbil com el Roomba d...
15,278
Given the following text description, write Python code to implement the functionality described below step by step Description: Fast Sign Adversary Generation Example This notebook demos finds adversary examples using MXNet Gluon and taking advantage of the gradient information [1] Goodfellow, Ian J., Jonathon Shlens...
Python Code: %matplotlib inline import mxnet as mx import numpy as np import matplotlib.pyplot as plt import matplotlib.cm as cm from mxnet import gluon Explanation: Fast Sign Adversary Generation Example This notebook demos finds adversary examples using MXNet Gluon and taking advantage of the gradient information [1]...
15,279
Given the following text description, write Python code to implement the functionality described below step by step Description: 기말고사 예비 문제집 Step1: 문제 1 아래 모양의 2차원 어레이를 작성하라. 단, 항목들을 일일이 입력하는 방식은 사용할 수 없다. $$\left [ \begin{matrix} 1 & 6 & 11 \ 2 & 7 & 12 \ 3 & 8 & 13 \ 4 & 9 & 14 \ 5 & 10 & 15 \end{matrix} ...
Python Code: import numpy as np Explanation: 기말고사 예비 문제집 End of explanation a = np.arange(1, 16).reshape(3, 5).T a np.arange(1, 6)[:, np.newaxis] + np.arange(0, 11, 5) Explanation: 문제 1 아래 모양의 2차원 어레이를 작성하라. 단, 항목들을 일일이 입력하는 방식은 사용할 수 없다. $$\left [ \begin{matrix} 1 & 6 & 11 \ 2 & 7 & 12 \ 3 & 8 & 13 \ 4 & 9 & ...
15,280
Given the following text description, write Python code to implement the functionality described below step by step Description: &larr; Back to Index Spectral Features in Essentia For classification, we're going to be using new features in our arsenal Step1: This value is normalized between 0 and 1. If 0, then the ce...
Python Code: spectrum = ess.Spectrum() centroid = ess.Centroid() x = essentia.array(scipy.randn(1024)) X = spectrum(x) spectral_centroid = centroid(X) print spectral_centroid Explanation: &larr; Back to Index Spectral Features in Essentia For classification, we're going to be using new features in our arsenal: spectral...
15,281
Given the following text description, write Python code to implement the functionality described below step by step Description: Spatial Data Overview of today's topics Step1: 1. Loading a shapefile or GeoPackage Step2: 2. Loading a CSV file Often, you won't have a shapefile or GeoPackage (which is explicitly spatia...
Python Code: import ast import contextily as cx import folium import geopandas as gpd import matplotlib.pyplot as plt import numpy as np import pandas as pd import rasterio import rasterio.features Explanation: Spatial Data Overview of today's topics: Working with shapefiles, GeoPackages, CSV files, and rasters Project...
15,282
Given the following text description, write Python code to implement the functionality described below step by step Description: Some sources Step1: Run model Step2: Questions Step3: Now let's look at the variations of the respective clusters, nmf topic and epithets Question Step4: Visualize topic clusters Step5: ...
Python Code: import datetime as dt import os import time from cltk.corpus.greek.tlg.parse_tlg_indices import get_epithet_index from cltk.corpus.greek.tlg.parse_tlg_indices import get_epithets from cltk.corpus.greek.tlg.parse_tlg_indices import select_authors_by_epithet from cltk.corpus.greek.tlg.parse_tlg_indices impor...
15,283
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction Step1: If you remember, at the beginning of this book, we saw a quote from John Quackenbush that essentially said that the reason a graph is interesting is because of its edges...
Python Code: from IPython.display import YouTubeVideo YouTubeVideo(id="3DWSRCbPPJs", width="100%") Explanation: Introduction End of explanation from nams import load_data as cf G = cf.load_physicians_network() Explanation: If you remember, at the beginning of this book, we saw a quote from John Quackenbush that essenti...
15,284
Given the following text description, write Python code to implement the functionality described below step by step Description: Import facility data and NERC labels Step1: Read NERC shapefile and merge with geo_df Step2: Merge NERC labels into the facility df Step3: Filter out data older than 2014 to reduce size S...
Python Code: path = os.path.join('Data storage', 'Facility gen fuels and CO2 2017-05-25.zip') facility_df = pd.read_csv(path, parse_dates=['datetime']) facility_df.head() facility_df.dropna(inplace=True, subset=['lat', 'lon']) cols = ['lat', 'lon', 'plant id', 'year'] small_facility = facility_df.loc[:, cols].drop_dupl...
15,285
Given the following text description, write Python code to implement the functionality described below step by step Description: How Bias Enters a Model This notebook is a simple demonstration of how bias with respect an attribute can get encoded into a model, even if the labels are perfectly accurate and the model is...
Python Code: %matplotlib inline from IPython.display import display, Markdown, Latex import numpy as np import sklearn import matplotlib import matplotlib.pylab as plt import sklearn.linear_model import seaborn import scipy.special seaborn.set(rc={"figure.figsize": (8, 6)}, font_scale=1.5) Explanation: How Bias Enters ...
15,286
Given the following text description, write Python code to implement the functionality described below step by step Description: Compute MNE inverse solution on evoked data with a mixed source space Create a mixed source space and compute an MNE inverse solution on an evoked dataset. Step1: Set up our source space Li...
Python Code: # Author: Annalisa Pascarella <a.pascarella@iac.cnr.it> # # License: BSD (3-clause) import os.path as op import matplotlib.pyplot as plt from nilearn import plotting import mne from mne.minimum_norm import make_inverse_operator, apply_inverse # Set dir data_path = mne.datasets.sample.data_path() subject = ...
15,287
Given the following text description, write Python code to implement the functionality described below step by step Description: Content-based recommender using Deep Structured Semantic Model An example of how to build a Deep Structured Semantic Model (DSSM) for incorporating complex content-based features into a reco...
Python Code: import warnings import mxnet as mx from mxnet import gluon, nd, autograd, sym import numpy as np from sklearn.random_projection import johnson_lindenstrauss_min_dim # Define some constants max_user = int(1e5) title_vocab_size = int(3e4) query_vocab_size = int(3e4) num_samples = int(1e4) hidden_units = 128 ...
15,288
Given the following text description, write Python code to implement the functionality described below step by step Description: Solución de ecuaciones diferenciales Dada la siguiente ecuación diferencial Step1: Ejercicio Crea codigo para una iteración mas con estos mismos parametros y despliega el resultado. Step2: ...
Python Code: x0 = 1 Δt = 1 # Para escribir simbolos griegos como Δ, tan solo tienes que escribir su nombre # precedido de una diagonal (\Delta) y teclear tabulador una vez F = lambda x : -x x1 = x0 + F(x0)*Δt x1 x2 = x1 + F(x1)*Δt x2 Explanation: Solución de ecuaciones diferenciales Dada la siguiente ecuación diferenc...
15,289
Given the following text description, write Python code to implement the functionality described below step by step Description: Review from the previous lecture In yesterday's Lecture 2, you learned how to use the numpy module, how to make your own functions, and how to import and export data. Below is a quick review...
Python Code: import numpy as np Explanation: Review from the previous lecture In yesterday's Lecture 2, you learned how to use the numpy module, how to make your own functions, and how to import and export data. Below is a quick review before we move on to Lecture 3. Remember, to use the numpy module, first it must be ...
15,290
Given the following text description, write Python code to implement the functionality described below step by step Description: Homework #1 This notebook contains the first homework for this class, and is due on Sunday, January 31st, 2016 at 11 Step1: Section 2
Python Code: # write any code you need here! # Create additional cells if you need them by using the # 'Insert' menu at the top of the browser window. Explanation: Homework #1 This notebook contains the first homework for this class, and is due on Sunday, January 31st, 2016 at 11:59 p.m.. Please make sure to get st...
15,291
Given the following text description, write Python code to implement the functionality described below step by step Description: Clustering Astronomical Sources The objective of this hands-on activity is to cluster a set of candidate sources from the Zwicky Transient Facility's (ZTF) image subtraction pipeline. All c...
Python Code: %matplotlib inline import numpy as np import matplotlib.pyplot as plt import glob import os from time import time from matplotlib.pyplot import imshow from matplotlib.image import imread from sklearn.cluster import KMeans from sklearn.preprocessing import MinMaxScaler, StandardScaler from sklearn import me...
15,292
Given the following text description, write Python code to implement the functionality described below step by step Description: Name Competition with Gradient Boosting This code is provided as supplementary material of the lecture Machine Learning and Optimization in Communications (MLOC).<br> This code illustrates *...
Python Code: import numpy as np import string from sklearn.ensemble import GradientBoostingClassifier Explanation: Name Competition with Gradient Boosting This code is provided as supplementary material of the lecture Machine Learning and Optimization in Communications (MLOC).<br> This code illustrates * The use of a g...
15,293
Given the following text description, write Python code to implement the functionality described below step by step Description: Executed Step1: Load software and filenames definitions Step2: Data folder Step3: List of data files Step4: Data load Initial loading of the data Step5: Laser alternation selection At t...
Python Code: ph_sel_name = "Dex" data_id = "12d" # ph_sel_name = "all-ph" # data_id = "7d" Explanation: Executed: Mon Mar 27 11:35:46 2017 Duration: 8 seconds. usALEX-5samples - Template This notebook is executed through 8-spots paper analysis. For a direct execution, uncomment the cell below. End of explanation from f...
15,294
Given the following text description, write Python code to implement the functionality described below step by step Description: Say Hello Recipe template for say hello. License Copyright 2020 Google LLC, Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance wit...
Python Code: !pip install git+https://github.com/google/starthinker Explanation: Say Hello Recipe template for say hello. 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 a copy of the Licen...
15,295
Given the following text description, write Python code to implement the functionality described below step by step Description: Deriving a Point-Spread Function in a Crowded Field following Appendix III of Peter Stetson's User's Manual for DAOPHOT II Using pydaophot form astwro python package All italic text here hav...
Python Code: from astwro.sampledata import fits_image frame = fits_image() Explanation: Deriving a Point-Spread Function in a Crowded Field following Appendix III of Peter Stetson's User's Manual for DAOPHOT II Using pydaophot form astwro python package All italic text here have been taken from Stetson's manual. The on...
15,296
Given the following text description, write Python code to implement the functionality described below step by step Description: Visualization of pre-generated images. This is a notebook to load and display pre-generated images used in parameter exploration. Step1: Now we need to build a function that takes distance,...
Python Code: import numpy as np import matplotlib.pyplot as plt import matplotlib as mpl import matplotlib.image as mpimg # Widgets library from ipywidgets import interact %matplotlib inline # We need to load all the files here # Load the file folder = '../results/' name = 'parameter_swep_SLM-0.00-0.00-10.00.png' file_...
15,297
Given the following text description, write Python code to implement the functionality described below step by step Description: Sentiment analysis with TFLearn In this notebook, we'll continue Andrew Trask's work by building a network for sentiment analysis on the movie review data. Instead of a network written with ...
Python Code: import pandas as pd import numpy as np import tensorflow as tf import tflearn from tflearn.data_utils import to_categorical Explanation: Sentiment analysis with TFLearn In this notebook, we'll continue Andrew Trask's work by building a network for sentiment analysis on the movie review data. Instead of a n...
15,298
Given the following text description, write Python code to implement the functionality described below step by step Description: Run all the cells below to make sure everything is working and ready to go. All cells should run without error. Test Matplotlib and Plotting Step1: Test OpenCV Step2: Test TensorFlow Step3...
Python Code: import matplotlib.pyplot as plt import matplotlib.image as mpimg import numpy as np %matplotlib inline img = mpimg.imread('test.jpg') plt.imshow(img) Explanation: Run all the cells below to make sure everything is working and ready to go. All cells should run without error. Test Matplotlib and Plotting End...
15,299
Given the following text description, write Python code to implement the functionality described below step by step Description: Custom finite difference coefficients in Devito Introduction When taking the numerical derivative of a function in Devito, the default behaviour is for 'standard' finite difference weights (...
Python Code: import numpy as np import sympy as sp from devito import Grid, TimeFunction # Create our grid (computational domain) Lx = 10 Ly = Lx Nx = 11 Ny = Nx dx = Lx/(Nx-1) dy = dx grid = Grid(shape=(Nx,Ny), extent=(Lx,Ly)) # Define u(x,y,t) on this grid u = TimeFunction(name='u', grid=grid, time_order=2, space_ord...