Unnamed: 0
int64
0
16k
text_prompt
stringlengths
110
62.1k
code_prompt
stringlengths
37
152k
10,000
Given the following text description, write Python code to implement the functionality described below step by step Description: The ELS matching procedure This practical is based on the concepts introduced for optimising electrical contacts in photovoltaic cells. The procedure was published in [J. Mater. Chem. C (201...
Python Code: %%bash cd Electronic/ python scan_energies.py -h Explanation: The ELS matching procedure This practical is based on the concepts introduced for optimising electrical contacts in photovoltaic cells. The procedure was published in [J. Mater. Chem. C (2016)]((http://pubs.rsc.org/en/content/articlehtml/2016/tc...
10,001
Given the following text description, write Python code to implement the functionality described below step by step Description: Sklearn sklearn.datasets документация Step1: Генерация выборок Способы генерации данных Step2: datasets.make_classification Step3: "Игрушечные" наборы данных Наборы данных Step4: Визуали...
Python Code: from sklearn import datasets %pylab inline Explanation: Sklearn sklearn.datasets документация: http://scikit-learn.org/stable/datasets/ End of explanation circles = datasets.make_circles() print "features: {}".format(circles[0][:10]) print "target: {}".format(circles[1][:10]) from matplotlib.colors import ...
10,002
Given the following text description, write Python code to implement the functionality described below step by step Description: <div class="alert alert-block alert-info" style="margin-top Step1: <a id="ref0"></a> <h2 align=center>What is Convolution?</h2> Convolution is a linear operation similar to a linear equatio...
Python Code: import torch import torch.nn as nn import matplotlib.pyplot as plt import numpy as np from scipy import ndimage, misc Explanation: <div class="alert alert-block alert-info" style="margin-top: 20px"> <a href="http://cocl.us/pytorch_link_top"><img src = "http://cocl.us/Pytorch_top" width = 950, align = "ce...
10,003
Given the following text description, write Python code to implement the functionality described below step by step Description: Learning to speak like Alice A generative character based language model is created by training an RNN on the text of Alice in Wonderland. Setup Imports Step1: Read input Step2: Build voca...
Python Code: from __future__ import division, print_function from keras.layers.recurrent import SimpleRNN from keras.models import Sequential from keras.layers import Dense, Activation from keras.utils.visualize_util import plot import numpy as np %matplotlib inline Explanation: Learning to speak like Alice A generativ...
10,004
Given the following text description, write Python code to implement the functionality described below step by step Description: Extract Landmarks Data in Melbourne from Wikipedia Interactively <a id=toc> Extract landmarks data Step1: URL for the landmarks in the Melbourne city centre. Step3: Extract POI coordinates...
Python Code: %matplotlib inline import requests, re, os from bs4 import BeautifulSoup from bs4.element import Tag import pandas as pd import numpy as np import matplotlib.pyplot as plt import lxml from fastkml import kml, styles from shapely.geometry import Point Explanation: Extract Landmarks Data in Melbourne from Wi...
10,005
Given the following text description, write Python code to implement the functionality described below step by step Description: Visualization 1 Step1: Scatter plots Learn how to use Matplotlib's plt.scatter function to make a 2d scatter plot. Generate random data using np.random.randn. Style the markers (color, size...
Python Code: %matplotlib inline import matplotlib.pyplot as plt import numpy as np Explanation: Visualization 1: Matplotlib Basics Exercises End of explanation # This assignment wasn't graded for some reason, having a 0.0/0.0 score. Resubmitting the assignment for grading on this one # as well as on the Theory and Prac...
10,006
Given the following text description, write Python code to implement the functionality described below step by step Description: Word embeddings Import various modules that we need for this notebook (now using Keras 1.0.0) Step1: Load the MNIST dataset, flatten the images, convert the class labels, and scale the data...
Python Code: %pylab inline import copy import numpy as np import pandas as pd import matplotlib.pyplot as plt from keras.datasets import imdb, reuters from keras.models import Sequential from keras.layers.core import Dense, Dropout, Activation, Flatten from keras.optimizers import SGD, RMSprop from keras.utils import n...
10,007
Given the following text description, write Python code to implement the functionality described below step by step Description: Load and Split Kaggle Data Step1: Build baseline text classification model in Sklearn Step2: This is about as good as the best Kagglers report they did. Step3: Score Random Wikipedia Use...
Python Code: data_filename = '../data/train.csv' data_df = pd.read_csv(data_filename) corpus = data_df['Comment'] labels = data_df['Insult'] train_corpus, test_corpus, train_labels, test_labels = \ sklearn.cross_validation.train_test_split(corpus, labels, test_size=0.33) Explanation: Load and Split Kaggle Data End of...
10,008
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction to Pandas pandas is a Python package providing fast, flexible, and expressive data structures designed to work with relational or labeled data both. It is a fundamental high-lev...
Python Code: from IPython.core.display import HTML HTML("<iframe src=http://pandas.pydata.org width=800 height=350></iframe>") %matplotlib inline import pandas as pd import numpy as np # Set some Pandas options pd.set_option('html', False) pd.set_option('max_columns', 30) pd.set_option('max_rows', 20) Explanation: Intr...
10,009
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2020 The TensorFlow Authors. Step1: 高级自动微分 <table class="tfo-notebook-buttons" align="left"> <td><a target="_blank" href="https Step2: 控制梯度记录 在自动微分指南中,您已了解构建梯度计算时如何控制条带监视变量和张量。...
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...
10,010
Given the following text description, write Python code to implement the functionality described below step by step Description: Digit Recognizer Import Libraries Step1: Loading Data Step2: Plotting images and their class values Step3: Viewing shape and content of data Step4: Flattening images The neural-network t...
Python Code: import numpy as np import pandas as pd import matplotlib.pyplot as plt %matplotlib inline from keras.utils import np_utils from keras.datasets import mnist # for Multi-layer Perceptron (MLP) model from keras.models import Sequential from keras.layers import Dense # for Convolutional Neural Network (CNN) mo...
10,011
Given the following text description, write Python code to implement the functionality described below step by step Description: 基本的登陆 Step1: sending cookie Step2: Re-direction 302 means the URL has been redirected to some other location. We could use allow_redirects=False to disable this feature. Step3: time out S...
Python Code: url='http://httpbin.org' req=requests.get(url+'/basic-auth/user/passwd',auth=('user','passwd')) print(req.text) print(req.url) print(req.status_code) import json payload={'some':'data'} headers={'Content-Type':'application/json','Authorization':'some token'} req=requests.post(url+'/post',data=json.dumps(pa...
10,012
Given the following text description, write Python code to implement the functionality described below step by step Description: tacotron2 Step1: Run tacotron2 Step2: speech contains the raw waveform and sampling rate, which can be played back. Step3: You can also plot the waveform.
Python Code: %tensorflow_version 1.x !pip3 install --quiet ml4a Explanation: tacotron2: Text-to-speech synthesis Generates speech audio from a text string. See the original code and paper. Set up ml4a and enable GPU If you don't already have ml4a installed, or you are opening this in Colab, first enable GPU (Runtime > ...
10,013
Given the following text description, write Python code to implement the functionality described below step by step Description: Manual sanity checks for the formula and text within mmrd.tex Check fitting formula by hand, and compare with raw data Step1: Load data file that contains QNM amplitudes from fitting algori...
Python Code: %matplotlib inline from numpy import exp,sqrt,log,linspace,pi,sin import kerr from os import system import matplotlib as mpl from matplotlib.pyplot import * mpl.rcParams['lines.linewidth'] = 2 mpl.rcParams['font.family'] = 'serif' mpl.rcParams['font.size'] = 12 mpl.rcParams['axes.labelsize'] = 20 mpl.rcPar...
10,014
Given the following text description, write Python code to implement the functionality described below step by step Description: Encontro 05 Step1: Configurando a biblioteca Step2: O objetivo desta atividade é realizar $24$ simulações de centralidade diferentes, para avaliar o desempenho de medidas clássicas em rela...
Python Code: import sys sys.path.append('..') import socnet as sn Explanation: Encontro 05: Simulação de Centralidades Importando a biblioteca: End of explanation sn.node_size = 10 sn.edge_width = 1 sn.edge_color = (192, 192, 192) sn.node_label_position = 'top center' Explanation: Configurando a biblioteca: End of expl...
10,015
Given the following text description, write Python code to implement the functionality described below step by step Description: Exercise 3 We're going to switch gears a little and talk about the astrophysical part of Astrophysical Machine Learning. This exercise will have you examine two different forms of data. The ...
Python Code: from astropy.io import fits as fits fitsimage=fits.open('filename.fits') image=np.flipud(fitsimage[0].data) Explanation: Exercise 3 We're going to switch gears a little and talk about the astrophysical part of Astrophysical Machine Learning. This exercise will have you examine two different forms of data. ...
10,016
Given the following text description, write Python code to implement the functionality described below step by step Description: 6b Calculate binned gradient-network overlap This file works out the average z-score inside a gradient percentile area written by Jan Freyberg for the Brainhack 2017 Project_ This should rep...
Python Code: % matplotlib inline from __future__ import print_function import nibabel as nib from nilearn.image import resample_img import matplotlib.pyplot as plt import numpy as np import pandas as pd import os import os.path # The following are a progress bar, these are not strictly necessary: from ipywidgets impor...
10,017
Given the following text description, write Python code to implement the functionality described below step by step Description: Model Evaluation Pipeline and Feature Unions It is always a good decision to make your code as readable as possible. Not only so that others can pick it up and use it easily, but so that yo...
Python Code: import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns %matplotlib inline from sklearn.base import BaseEstimator, TransformerMixin from sklearn.utils import resample from sklearn.preprocessing import PolynomialFeatures, StandardScaler, LabelEncoder, OneHotEncoder from ...
10,018
Given the following text description, write Python code to implement the functionality described below step by step Description: This note book gives the trend of a single word in single mailing list. Step1: You'll need to download some resources for NLTK (the natural language toolkit) in order to do the kind of proc...
Python Code: %matplotlib inline from bigbang.archive import Archive import bigbang.parse as parse import bigbang.graph as graph import bigbang.mailman as mailman import bigbang.process as process import networkx as nx import matplotlib.pyplot as plt import pandas as pd from pprint import pprint as pp import pytz import...
10,019
Given the following text description, write Python code to implement the functionality described below step by step Description: The goal of punk is to make available sime wrappers for a variety of machine learning pipelines. The pipelines are termed primitves and each primitive is designed with a functional programmi...
Python Code: import punk help(punk) %matplotlib inline import matplotlib.pyplot as plt import pandas as pd import numpy as np from sklearn import datasets from sklearn.preprocessing import StandardScaler from sklearn.model_selection import train_test_split from punk import feature_select...
10,020
Given the following text description, write Python code to implement the functionality described below step by step Description: Cross Spectra This tutorial shows how to make and manipulate a cross spectrum of two light curves using Stingray. Step1: 1. Create two light curves There are two ways to make Lightcurve obj...
Python Code: import numpy as np from stingray import Lightcurve, Crossspectrum, AveragedCrossspectrum import matplotlib.pyplot as plt import matplotlib.font_manager as font_manager %matplotlib inline font_prop = font_manager.FontProperties(size=16) Explanation: Cross Spectra This tutorial shows how to make and manipula...
10,021
Given the following text description, write Python code to implement the functionality described below step by step Description: Import necessary libraries Step1: K-means clustering Example adapted from here. Load dataset Step2: Define and train model Step3: Extract the labels and the cluster centers Step4: Plot t...
Python Code: import numpy as np from scipy import ndimage from time import time from sklearn import datasets, manifold from sklearn.cluster import KMeans, AgglomerativeClustering from sklearn.mixture import GMM from sklearn.cross_validation import StratifiedKFold import matplotlib.pyplot as plt import matplotlib as mpl...
10,022
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2018 The TensorFlow Probability Authors. Licensed under the Apache License, Version 2.0 (the "License"); Step1: TensorFlow Distributions Step2: Basic Univariate Distributions Let...
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...
10,023
Given the following text description, write Python code to implement the functionality described below step by step Description: Ensemble Learning <!-- new sections --> <!-- Ensemble learning --> <!-- - Machine Learning Flach, Ch.11 --> <!-- - Machine Learning Mohri, pp.135- --> <!-- - Data Mining Witten, Ch. 8 --> St...
Python Code: from IPython.display import Image Image('../../../python_for_probability_statistics_and_machine_learning.jpg') from pprint import pprint import textwrap import sys, re def displ(x): if x is None: return print ("\n".join(textwrap.wrap(repr(x).replace(' ',''),width=80))) sys.displayhook=displ Explanat...
10,024
Given the following text description, write Python code to implement the functionality described below step by step Description: Construct the metadata just based on the headers Step1: Add the frame types as we've always done Step2: Find the unique configurations. The unique configurations are found by matching dat...
Python Code: fitstbl = PypeItMetaData('keck_lris_red', file_list=file_list, background_index=True) Explanation: Construct the metadata just based on the headers End of explanation _ = fitstbl.get_frame_types(flag_unknown=True) Explanation: Add the frame types as we've always done End of explanation cfgs = fitstbl.uniqu...
10,025
Given the following text description, write Python code to implement the functionality described below step by step Description: Import required packages Step1: Download and Prep NASA's Turbofan Engine Degradation Simulation (PHM08 Challenge) Data Set Step2: Read training data into a DataFrame. Step3: Create traini...
Python Code: import os import matplotlib.pyplot as plt import pandas as pd import swat # SAS Viya Python interface %matplotlib inline Explanation: Import required packages End of explanation DATA_URL = 'https://ti.arc.nasa.gov/m/project/prognostic-repository/Challenge_Data.zip' DATA_DIR = '.' train_tsv = os.path.join...
10,026
Given the following text description, write Python code to implement the functionality described below step by step Description: LAB 5a Step1: Import necessary libraries. Step2: Set environment variables. Set environment variables so that we can use them throughout the entire lab. We will be using our project name f...
Python Code: !sudo chown -R jupyter:jupyter /home/jupyter/training-data-analyst !pip3 install cloudml-hypertune Explanation: LAB 5a: Training Keras model on Cloud AI Platform Learning Objectives Setup up the environment Create trainer module's task.py to hold hyperparameter argparsing code Create trainer module's mode...
10,027
Given the following text description, write Python code to implement the functionality described below step by step Description: Using a random forest for demographic model selection In Schrider and Kern (2017) we give a toy example of demographic model selection via supervised machine learning in Figure Box 1. Follow...
Python Code: #untar and compile ms and sample_stats !tar zxf ms.tar.gz; cd msdir; gcc -o ms ms.c streec.c rand1.c -lm; gcc -o sample_stats sample_stats.c tajd.c -lm #I get three compiler warnings from ms, but everything should be fine #now I'll just move the programs into the current working dir !mv msdir/ms . ; mv msd...
10,028
Given the following text description, write Python code to implement the functionality described below step by step Description: 06 - Data Preparation and Advanced Model Evaluation by Alejandro Correa Bahnsen version 0.2, May 2016 Part of the class Machine Learning for Security Informatics This notebook is licensed un...
Python Code: import pandas as pd import zipfile with zipfile.ZipFile('../datasets/titanic.csv.zip', 'r') as z: f = z.open('titanic.csv') titanic = pd.read_csv(f, sep=',', index_col=0) titanic.head() # check for missing values titanic.isnull().sum() Explanation: 06 - Data Preparation and Advanced Model Evaluatio...
10,029
Given the following text description, write Python code to implement the functionality described below step by step Description: Chapter 12 Step1: If you want to create a tuple with a single value, add a comma (,) after the value, but don’t add parenthesis You can also use the built in function tuple Step2: Most lis...
Python Code: a_tuple = ( 'a', 'b', 'c', 'd', 'e' ) a_tuple = 'a', 'b', 'c', 'd', 'e' a_tuple = 'a', type( a_tuple ) Explanation: Chapter 12: Tuples Contents - Tuples are immutable - Tuple assignment - Tuples as return values - Variable-length argument tuples - Lists and tuples - Dictionaries and tuples - Comparing tupl...
10,030
Given the following text description, write Python code to implement the functionality described below step by step Description: Name Data preparation using SparkSQL on YARN with Cloud Dataproc Label Cloud Dataproc, GCP, Cloud Storage, YARN, SparkSQL, Kubeflow, pipelines, components Summary A Kubeflow Pipeline compo...
Python Code: %%capture --no-stderr KFP_PACKAGE = 'https://storage.googleapis.com/ml-pipeline/release/0.1.14/kfp.tar.gz' !pip3 install $KFP_PACKAGE --upgrade Explanation: Name Data preparation using SparkSQL on YARN with Cloud Dataproc Label Cloud Dataproc, GCP, Cloud Storage, YARN, SparkSQL, Kubeflow, pipelines, compo...
10,031
Given the following text description, write Python code to implement the functionality described below step by step Description: Q 5.1 Step1: (a) The squared reconstruction error vs iteration number. Step2: (b) Let us say that the number of assignments for a mean is the number of points assigned to that mean. Plot t...
Python Code: km_16 = KMeans(k=16, train_X=X_train, train_y=y_train, pca_obj=pca_training, max_iter = 500, test_X=X_test, test_y=y_test, verbose=False) km_16.run() Explanation: Q 5.1: k = 16, MNIST data transformed by first 50 PCA components. End of explanation km_16_rec...
10,032
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction We're going to improve the tweet_enricher.py script from Gnip-Analysis-Pipeline. We'll make a simplified version and create variations that improve it in various ways. To enric...
Python Code: DT_FORMAT_STR = "%Y-%m-%dT%H:%M:%S.%f" def stream_of_tweets(n=10): # generator function to generate sequential tweets for i in range(n): time.sleep(0.01) tweet = { 'body':'I am tweet #' + str(i), 'postedTime':datetime.datetime.now().strftime(DT_FORMAT_STR) ...
10,033
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 ...
10,034
Given the following text description, write Python code to implement the functionality described below step by step Description: Data Management In this guide you will learn how to load different data files into DataFrames and how to interact with the CARTO platform to upload DataFrames into tables and download tables...
Python Code: from geopandas import read_file gdf = read_file('https://libs.cartocdn.com/cartoframes/samples/starbucks_brooklyn_geocoded.geojson') gdf.head() Explanation: Data Management In this guide you will learn how to load different data files into DataFrames and how to interact with the CARTO platform to upload Da...
10,035
Given the following text description, write Python code to implement the functionality described below step by step Description: Compile and deploy the TFX pipeline to Kubeflow Pipelines This notebook is the second of two notebooks that guide you through automating the Real-time Item-to-item Recommendation with BigQue...
Python Code: %load_ext autoreload %autoreload 2 !pip install -q -U kfp Explanation: Compile and deploy the TFX pipeline to Kubeflow Pipelines This notebook is the second of two notebooks that guide you through automating the Real-time Item-to-item Recommendation with BigQuery ML Matrix Factorization and ScaNN solution ...
10,036
Given the following text description, write Python code to implement the functionality described below step by step Description: Reading and writing files Step1: It says that the file is opened, reminds the filename and indicates that it is in mode 'r', which means 'read' You can call specific functions on an object ...
Python Code: # We can create a file object and store it inside a variable. # you can see objects as a different type of data f=open("awanode-farmlab-2017-08-14.txt") print(f) Explanation: Reading and writing files End of explanation f=open("awanode-farmlab-2017-08-14.txt") # The read() function reads the content of a f...
10,037
Given the following text description, write Python code to implement the functionality described below step by step Description: XML example and exercise study examples of accessing nodes in XML tree structure work on exercise to be completed and submitted reference Step1: XML example for details about tree travers...
Python Code: from xml.etree import ElementTree as ET import pandas as pd Explanation: XML example and exercise study examples of accessing nodes in XML tree structure work on exercise to be completed and submitted reference: https://docs.python.org/2.7/library/xml.etree.elementtree.html data source: http://www.dbis.i...
10,038
Given the following text description, write Python code to implement the functionality described below step by step Description: Title Step1: Create dataframe Step2: Make plot
Python Code: %matplotlib inline import pandas as pd import matplotlib.pyplot as plt import numpy as np Explanation: Title: Back To Back Bar Plot In MatPlotLib Slug: matplotlib_back_to_back_bar_plot Summary: Back To Back Bar Plot In MatPlotLib Date: 2016-05-01 12:00 Category: Python Tags: Data Visualization Authors: Chr...
10,039
Given the following text description, write Python code to implement the functionality described below step by step Description: Chem 30324, Spring 2020, Homework 7 Due March 27, 2020 Variations on the hydrogen atom Step1: So the normalized 1s wavefunction is $\tilde{R}_{10}(r) = \frac{2}{\sqrt[4]{\pi}} 2^{\frac{3}{4...
Python Code: import sympy as sy import numpy as np from sympy import * r = Symbol('r') I = integrate(exp(-2*r**2)*r**2,(r,0,+oo)) C = sqrt(1/I) print(latex(simplify(C))) Explanation: Chem 30324, Spring 2020, Homework 7 Due March 27, 2020 Variations on the hydrogen atom: The variational principle guarantees that the exp...
10,040
Given the following text description, write Python code to implement the functionality described below step by step Description: Populate local MDCS instance with student data and metadata Import MDCS API tool module Step1: Host and user information Step2: List of file prefixes for micrograph images and XML metadata...
Python Code: import mdcs Explanation: Populate local MDCS instance with student data and metadata Import MDCS API tool module End of explanation user='admin' pswd='admin' host='http://127.0.0.1:8000' template_name='DiffusionDemo' Explanation: Host and user information End of explanation name_list=[ "GE-DiffusionCou...
10,041
Given the following text description, write Python code to implement the functionality described below step by step Description: Rational approximations of 𝝿 The fractions 22/7 and 355/113 are good approximations of pi. Let's find more. Step1: Spoiler alert Step2: We'll need to go to larger and larger denominators ...
Python Code: from math import pi pi Explanation: Rational approximations of 𝝿 The fractions 22/7 and 355/113 are good approximations of pi. Let's find more. End of explanation pi.as_integer_ratio() f"{884279719003555/281474976710656:0.48f}" Explanation: Spoiler alert: Who knew that Python floats have this handy method...
10,042
Given the following text description, write Python code to implement the functionality described below step by step Description: <a href="https Step1: Chapter 19 - More about Natural Language Processing Tools (spaCy) Text data is unstructured. But if you want to extract information from text, then you often need to p...
Python Code: %%capture !wget https://github.com/cltl/python-for-text-analysis/raw/master/zips/Data.zip !wget https://github.com/cltl/python-for-text-analysis/raw/master/zips/images.zip !wget https://github.com/cltl/python-for-text-analysis/raw/master/zips/Extra_Material.zip !unzip Data.zip -d ../ !unzip images.zip -d ....
10,043
Given the following text description, write Python code to implement the functionality described below step by step Description: Prepare data so the format is as compatible with the 2018 data as possible Step1: Examine response rates per day Step2: The high spike seen on 1/13/20 aligns with the time when the surve...
Python Code: survey_data = prepare_2019.get_df( "contribex-survey-2019.csv" ) Explanation: Prepare data so the format is as compatible with the 2018 data as possible End of explanation ( p9.ggplot(survey_data, p9.aes(x="date_taken")) + p9.geom_bar() + p9.theme(axis_text_x=p9.element_text(angle=45, ha="r...
10,044
Given the following text description, write Python code to implement the functionality described below step by step Description: Analysis of a run with constraints, and a run without I have made a little analysis to test our ability to date a tree with node order constraints. I use the following tree Step1: Then I wi...
Python Code: import sys from ete3 import Tree, TreeStyle, NodeStyle import numpy as np import pandas as pd import matplotlib.pyplot as plt import math import scipy import re t = Tree("(((a:0.1,b:0.1):0.2, (c:0.2,d:0.2):0.1):0.6, ((e:0.4,f:0.4):0.3, (g:0.5,h:0.5):0.2):0.2);") ts = TreeStyle() ts.min_leaf_separation= 0 t...
10,045
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...
10,046
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', 'mohc', 'hadgem3-gc31-mm', 'aerosol') Explanation: ES-DOC CMIP6 Model Properties - Aerosol MIP Era: CMIP6 Institute: MOHC Source ID: HADGEM3-GC31-MM Topic: Aerosol Sub-Topics: Transpor...
10,047
Given the following text description, write Python code to implement the functionality described below step by step Description: Step2: Jupyter Notebook backend demo This example shows how vispy's low-level gloo interface can be used to display a WebGL canvas in a notebook. By default, vispy will detect that it is bei...
Python Code: import numpy as np import vispy import vispy.gloo as gloo from vispy import app from vispy.util.transforms import perspective, translate, rotate # load the vispy bindings manually for the notebook which enables webGL # %load_ext vispy n = 100 a_position = np.random.uniform(-1, 1, (n, 3)).astype(np.float32)...
10,048
Given the following text description, write Python code to implement the functionality described below step by step Description: Read data Step1: Target variable Step2: Target variable is Survived. Quality metric Your score is the percentage of passengers you correctly predict. That means - accuracy. Model One varia...
Python Code: train_df = pd.read_csv('../input/train.csv') test_df = pd.read_csv('../input/test.csv') all_df = train_df.append(test_df) all_df['is_test'] = all_df.Survived.isnull() all_df.index = all_df.Survived del all_df['Survived'] all_df.head() Explanation: Read data End of explanation train_df.describe() Explanatio...
10,049
Given the following text description, write Python code to implement the functionality described below step by step Description: Part 3 Step1: Applying the Rotation Let's try out our function, using it to derive the heptagon edges from the P1-P0 edge, and drawing the result, using the original "render" function that ...
Python Code: # load the definitions from the previous notebooks %run DrawingTheHeptagon.py r = sigma-rho s = rho-1 t = one-rho # the __sub__ function requires a HeptagonNumber on the left, so "1-rho" won't work u = rho-1 def rotate(v) : x, y = v return ( r*x + t*y, s*x + u*y ) def plusv( v1, v2 ) : h1, h2 =...
10,050
Given the following text description, write Python code to implement the functionality described below step by step Description: Vertex AI Step1: Install the latest GA version of google-cloud-storage library as well. Step2: Restart the kernel Once you've installed the additional packages, you need to restart the not...
Python Code: import os # Google Cloud Notebook if os.path.exists("/opt/deeplearning/metadata/env_version"): USER_FLAG = "--user" else: USER_FLAG = "" ! pip3 install --upgrade google-cloud-aiplatform $USER_FLAG Explanation: Vertex AI: Vertex AI Migration: Custom Scikit-Learn model with pre-built training contain...
10,051
Given the following text description, write Python code to implement the functionality described below step by step Description: Modeling and Simulation in Python Case study. Copyright 2017 Allen Downey License Step1: Unrolling Let's simulate a kitten unrolling toilet paper. As reference material, see this video. Th...
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...
10,052
Given the following text description, write Python code to implement the functionality described below step by step Description: Managing kubernetes objects using common resource operations with the python client Some of these operations include; create_xxxx Step1: Load config from default location. Step2: Create A...
Python Code: from kubernetes import client, config Explanation: Managing kubernetes objects using common resource operations with the python client Some of these operations include; create_xxxx : create a resource object. Ex create_namespaced_pod and create_namespaced_deployment, for creation of pods and deployments re...
10,053
Given the following text description, write Python code to implement the functionality described below step by step Description: GPyOpt Step1: In this example we will optimize the 2D Six-Hump Camel function (available in GPyOpt). We will assume that exact evaluations of the function are observed. The explicit form of...
Python Code: %pylab inline import GPyOpt import GPy import numpy as np Explanation: GPyOpt: Bayesian Optimization with fixed constraints Written by Javier Gonzalez, University of Sheffield. Reference Manual index Last updated Friday, 11 March 2016. In this notebook we will learn how to solve optimization problems with ...
10,054
Given the following text description, write Python code to implement the functionality described below step by step Description: Deep Convolutional GANs In this notebook, you'll build a GAN using convolutional layers in the generator and discriminator. This is called a Deep Convolutional GAN, or DCGAN for short. The D...
Python Code: %matplotlib inline import pickle as pkl import matplotlib.pyplot as plt import numpy as np from scipy.io import loadmat import tensorflow as tf !mkdir data Explanation: Deep Convolutional GANs In this notebook, you'll build a GAN using convolutional layers in the generator and discriminator. This is called...
10,055
Given the following text description, write Python code to implement the functionality described below step by step Description: LDA/QDA on height/weight data We're asked to fit a Linear Discriminant Analysis (LDA) and Quadratic Discriminant Analysis (QDA) model to the height/weight data and compute the the misclassif...
Python Code: %matplotlib inline import numpy as np import pandas as pd import matplotlib.pyplot as plt from matplotlib.colors import ListedColormap # benchmark sklearn implementations, these are much faster from sklearn.discriminant_analysis import LinearDiscriminantAnalysis from sklearn.discriminant_analysis import Qu...
10,056
Given the following text description, write Python code to implement the functionality described below step by step Description: Two Moons Normalizing Flow Using Distrax + Haiku Neural Spline Flow based off of distrax documentation for a flow. Code to load 2 moons example dataset sourced from Chris Waites's jax-flows ...
Python Code: !pip install -qq -U dm-haiku distrax optax import matplotlib.pyplot as plt from IPython.display import clear_output from sklearn import datasets, preprocessing try: import distrax except ModuleNotFoundError: %pip install -qq distrax import distrax import jax import jax.numpy as jnp import numpy...
10,057
Given the following text description, write Python code to implement the functionality described below step by step Description: Idea Using the vmstat command line utility to quickly determine the root cause of performance problems. Step1: Data Input In this version, we use a helper library that I've built to read in...
Python Code: %less ../datasets/vmstat_loadtest.log Explanation: Idea Using the vmstat command line utility to quickly determine the root cause of performance problems. End of explanation from ozapfdis.linux import vmstat stats = vmstat.read_logfile("../datasets/vmstat_loadtest.log") stats.head() Explanation: Data Input...
10,058
Given the following text description, write Python code to implement the functionality described below step by step Description: Olfaction Model Demo This notebook illustrates how to run a Neurokernel-based model of part of the fruit fly's antennal lobe. Background The early olfactory system in Drosophila consists of ...
Python Code: %cd -q ~/neurokernel/examples/olfaction/data %run gen_olf_input.py %run create_olf_gexf.py Explanation: Olfaction Model Demo This notebook illustrates how to run a Neurokernel-based model of part of the fruit fly's antennal lobe. Background The early olfactory system in Drosophila consists of two antennal ...
10,059
Given the following text description, write Python code to implement the functionality described below step by step Description: Data reduction for paleomagnetic data aboard the JOIDES Resolution This notebook is for people wanting to download and manipulate data from an IODP Expedition using data in the LIMS Online R...
Python Code: # import a bunch of packages for use in the notebook import pmagpy.pmag as pmag # a bunch of PmagPy modules import pmagpy.pmagplotlib as pmagplotlib import pmagpy.ipmag as ipmag import pmagpy.contribution_builder as cb from pmagpy import convert_2_magic as convert # conversion scripts for many lab formats ...
10,060
Given the following text description, write Python code to implement the functionality described below step by step Description: 확률론적 선형 회귀 모형 OLS(Ordinary Least Square) 방법을 사용하면 데이터에 대한 확률론적인 가정없이도 최적의 가중치를 계산할 수 있다. 그러나 이 경우에는 계산한 가중치가 어느 정도의 신뢰도 또는 안정성을 가지는지 확인할 수 있는 방법이 없다. 이를 확인하고자 하는 시도 중의 하나가 부트스트래핑(bootstrappi...
Python Code: from sklearn.datasets import make_regression X0, y, coef = make_regression(n_samples=100, n_features=1, noise=20, coef=True, random_state=0) dfX0 = pd.DataFrame(X0, columns=["X1"]) dfX = sm.add_constant(dfX0) dfy = pd.DataFrame(y, columns=["y"]) model = sm.OLS(dfy, dfX) result = model.fit() print(result.pa...
10,061
Given the following text description, write Python code to implement the functionality described below step by step Description: <div style="text-align Step1: <a id="ref3"></a> Building a Graph As we said before, TensorFlow works as a graph computational model. Let's create our first graph. To create two source opera...
Python Code: import tensorflow as tf Explanation: <div style="text-align:center"><img src = "https://www.tensorflow.org/_static/images/tensorflow/logo.png"></div> <a id="ref2"></a> How does TensorFlow work? TensorFlow defines computations as Graphs, and these are made with operations (also know as “ops”). So, when we w...
10,062
Given the following text description, write Python code to implement the functionality described below step by step Description: Week 1 Tutorial GitHub Workflow and Goals for the Class Getting Started Ideally, you have already work through the Getting Started page on the course GitHub repository. You will need a compu...
Python Code: class SolutionMissingError(Exception): def __init__(self): Exception.__init__(self,"You need to complete the solution for this code to work!") def REPLACE_WITH_YOUR_SOLUTION(): raise SolutionMissingError REMOVE_THIS_LINE = REPLACE_WITH_YOUR_SOLUTION Explanation: Week 1 Tutorial GitHub Workf...
10,063
Given the following text description, write Python code to implement the functionality described below step by step Description: Content and Objective Show result of LS estimator for polynomials Step1: Parameters Step2: Do LS Estimation Step3: Plotting
Python Code: # importing import numpy as np import matplotlib.pyplot as plt import matplotlib # showing figures inline %matplotlib inline # plotting options font = {'size' : 30} plt.rc('font', **font) plt.rc('text', usetex=True) matplotlib.rc('figure', figsize=(30, 15) ) Explanation: Content and Objective Show resul...
10,064
Given the following text description, write Python code to implement the functionality described below step by step Description: matplotlib 学习手册 整理和学习 matplotlib 的基本知识点和使用方法 参考 matplotlib org Matplotlib 教程 IPython 以及 pylab 模式 IPython 是 Python 的一个增强版本。它在下列方面有所增强:命名输入输出、使用系统命令(shell commands)、排错(debug)能力。我们在命令行终端给 IPyth...
Python Code: # 导入 matplotlib 的所有内容(nympy 可以用 np 这个名字来使用) from pylab import * # 创建一个 8 * 6 点(point)的图,并设置分辨率为 80 figure(figsize=(8,6), dpi=80) # 创建一个新的 1 * 1 的子图,接下来的图样绘制在其中的第 1 块(也是唯一的一块) subplot(1,1,1) X = np.linspace(-np.pi, np.pi, 256,endpoint=True) C,S = np.cos(X), np.sin(X) # 绘制余弦曲线,使用蓝色的、连续的、宽度为 1 (像素)的线条 plot(X,...
10,065
Given the following text description, write Python code to implement the functionality described below step by step Description: Preparation of the reference genome Usually NGS reads are mapped against a reference genome containing only the assembled chromosomes, and not the remaining contigs. And this methodology is ...
Python Code: species = 'Mus_musculus' taxid = '10090' assembly = 'GRCm38.p6' genbank = 'GCF_000001635.26' Explanation: Preparation of the reference genome Usually NGS reads are mapped against a reference genome containing only the assembled chromosomes, and not the remaining contigs. And this methodology is perfec...
10,066
Given the following text description, write Python code to implement the functionality described below step by step Description: GP Regression with a Spectral Mixture Kernel Introduction This example shows how to use a SpectralMixtureKernel module on an ExactGP model. This module is designed for When you want to use e...
Python Code: import math import torch import gpytorch from matplotlib import pyplot as plt %matplotlib inline %load_ext autoreload %autoreload 2 Explanation: GP Regression with a Spectral Mixture Kernel Introduction This example shows how to use a SpectralMixtureKernel module on an ExactGP model. This module is designe...
10,067
Given the following text description, write Python code to implement the functionality described below step by step Description: Facetted subgrids We can split the image (facetting), and we can split the grid (subgrids) and do a lot of operations separately. This works out relatively straightforwardly. However, can we...
Python Code: %matplotlib inline from matplotlib import pylab import matplotlib.patches as patches import matplotlib.path as path from ipywidgets import interact import numpy import sys import random import itertools import time import scipy.special import math pylab.rcParams['figure.figsize'] = 16, 10 pylab.rcParams['i...
10,068
Given the following text description, write Python code to implement the functionality described below step by step Description: Test the Retrieval Latency of Approximate vs Exact Matching Step1: Exact Matching Step2: Approximate Matching (ScaNN)
Python Code: import tensorflow as tf import time PROJECT_ID = 'ksalama-cloudml' BUCKET = 'ksalama-cloudml' INDEX_DIR = f'gs://{BUCKET}/bqml/scann_index' BQML_MODEL_DIR = f'gs://{BUCKET}/bqml/item_matching_model' LOOKUP_MODEL_DIR = f'gs://{BUCKET}/bqml/embedding_lookup_model' songs = { '2114406': 'Metallica: Nothing...
10,069
Given the following text description, write Python code to implement the functionality described below step by step Description: In this post, we are going to construct a unit conversion table in python. The table will have columns for meters (m), centimeter (cm), and inches (in). We will start off with a list of valu...
Python Code: meters = [0, 10, 20, 30, 40, 50] meters centimeters = meters*0.01 centimeters Explanation: In this post, we are going to construct a unit conversion table in python. The table will have columns for meters (m), centimeter (cm), and inches (in). We will start off with a list of values that will be our meter ...
10,070
Given the following text description, write Python code to implement the functionality described below step by step Description: From raw data to dSPM on SPM Faces dataset Runs a full pipeline using MNE-Python Step1: Load and filter data, set up epochs Step2: Visualize fields on MEG helmet Step3: Look at the whiten...
Python Code: # Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr> # Denis Engemann <denis.engemann@gmail.com> # # License: BSD-3-Clause import matplotlib.pyplot as plt import mne from mne.datasets import spm_face from mne.preprocessing import ICA, create_eog_epochs from mne import io, combine_evoked fro...
10,071
Given the following text description, write Python code to implement the functionality described below step by step Description: Paris Saclay Center for Data Science Titanic RAMP Step1: Exploratory data analysis Loading the data Step2: The original training data frame has 891 rows. In the starting kit, we give you a...
Python Code: %matplotlib inline import os import glob import numpy as np from scipy import io import matplotlib.pyplot as plt import pandas as pd from rampwf.utils.importing import import_module_from_source Explanation: Paris Saclay Center for Data Science Titanic RAMP: survival prediction of Titanic passengers Benoit ...
10,072
Given the following text description, write Python code to implement the functionality described below step by step Description: Bundle setup Step1: We will set the pblum mode to dataset-scaled for estimators and optimizers, to avoid having to add pblum to the fitted parameters or adjusting it manually. We will also ...
Python Code: lc = np.loadtxt('data/lc.V.data') rv1 = np.loadtxt('data/rv1.data') rv2 = np.loadtxt('data/rv2.data') b = phoebe.default_binary() b.add_dataset('lc', times = lc[:,0], fluxes=lc[:,1], sigmas=lc[:,2], passband='Johnson:V') b.add_dataset('rv', passband='Johnson:V') b['times@rv@primary'], b['rvs@rv@primary'], ...
10,073
Given the following text description, write Python code to implement the functionality described below step by step Description: Burgers' equation Step1: In this chapter, we study a simple scalar nonlinear conservation law Step2: Notice that at first $q$ remains single-valued for every $x$. However, after some time ...
Python Code: %matplotlib inline %config InlineBackend.figure_format = 'svg' from ipywidgets import interact from ipywidgets import widgets from ipywidgets import FloatSlider, fixed from exact_solvers import burgers from exact_solvers import burgers_demos from IPython.display import HTML Explanation: Burgers' equation E...
10,074
Given the following text description, write Python code to implement the functionality described below step by step Description: Comparing 2 Stacks of Catalogues Environment Step1: Need more packages? Step2: Main() Run legacy-zeropoints-qa.py like this "python legacy-zeropoints-qa.py" to analyze everything. See bel...
Python Code: import sys print sys.executable # Hack!, this avoids messing with NERSC's config file for jupyter hub sys.path.append('/global/homes/k/kaylanb/repos/astrometry.net') sys.path.append('/global/homes/k/kaylanb/repos/tractor') sys.path print sys.path Explanation: Comparing 2 Stacks of Catalogues Environment: a...
10,075
Given the following text description, write Python code to implement the functionality described below step by step Description: Convolutional Autoencoder Sticking with the MNIST dataset, let's improve our autoencoder's performance using convolutional layers. Again, loading modules and the data. Step1: Network Archit...
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) img = mnist.train.images[2] plt.imshow(img.reshape((28, 28)), cmap='Greys_r') Explanati...
10,076
Given the following text description, write Python code to implement the functionality described below step by step Description: Quick Intro to Keras Functional API Preamble Step1: Step 2
Python Code: # let's load MNIST data as we did in the exercise on MNIST with FC Nets # %load ../solutions/sol_52.py Explanation: Quick Intro to Keras Functional API Preamble: All models (layers) are callables ```python from keras.layers import Input, Dense from keras.models import Model this returns a tensor inputs = I...
10,077
Given the following text description, write Python code to implement the functionality described below step by step Description: This script checks if all the ROI atlases in functional space have all the ROIs Step1: As seen from histogram most of the corrupted ROIs are in cerebellum. Therefore I have chosen to consid...
Python Code: import numpy as np import nibabel as nib atlas_path = '/home1/varunk/results_again_again/ABIDE1_Preprocess_Datasink/atlas_paths/atlas_file_list.npy' atlas_files = np.load(atlas_path) atlas_files[41] in_file = atlas_files[40] atlas_values_list = nib.load(in_file).get_data().ravel() universe = set(np.arange(...
10,078
Given the following text description, write Python code to implement the functionality described below step by step Description: Whoosh Step1: Means the sound made by something that is moving quickly Whoosh, so fast and easy that even a lawyer could manage it What is Whoosh? Whoosh is a library of classes and functio...
Python Code: from IPython.display import Image Image(filename='files/screenshot.png') from IPython.display import Image Image(filename='files/whoosh.jpg') Explanation: Whoosh: a fast pure-Python search engine library Pydata Madrid 2016.04.10 Who am I? Claudia Guirao Fernández @claudiaguirao Background: Double degre...
10,079
Given the following text description, write Python code to implement the functionality described below step by step Description: Chapter 7 Regularization for Deep Learning the best fitting model is a large model that has been regularized appropriately. 7.1 Parameter Norm Penalties \begin{equation} \tilde{J}(\theta...
Python Code: show_image("fig7_2.png") Explanation: Chapter 7 Regularization for Deep Learning the best fitting model is a large model that has been regularized appropriately. 7.1 Parameter Norm Penalties \begin{equation} \tilde{J}(\theta; X, y) = J(\theta; X, y) + \alpha \Omega(\theta) \end{equation} where $\Omega(...
10,080
Given the following text description, write Python code to implement the functionality described below step by step Description: Les tables concernant l'âge et le sexe Output Step1: Les tables concernant le statut d'actif.ve Output Step2: Les tables concernant le statut d'actif.ve occupée Taux de chômage trimestrie...
Python Code: pd.read_csv("data/demographie/pop_age_sexe_2016.csv").head() Explanation: Les tables concernant l'âge et le sexe Output : pop_age_sexe_2016.csv Input : Table générée à partir de pop-1janvier-fe.xls (https://www.insee.fr/fr/statistiques/1892086) Source : Insee, estimations de population (résultats provisoi...
10,081
Given the following text description, write Python code to implement the functionality described below step by step Description: <!--BOOK_INFORMATION--> <a href="https Step1: Although the original images consisted of 92 x 112 pixel images, the version available through scikit-learn contains images downscaled to 64 x ...
Python Code: from sklearn.datasets import fetch_olivetti_faces dataset = fetch_olivetti_faces() X = dataset.data y = dataset.target Explanation: <!--BOOK_INFORMATION--> <a href="https://www.packtpub.com/big-data-and-business-intelligence/machine-learning-opencv" target="_blank"><img align="left" src="data/cover.jpg" st...
10,082
Given the following text description, write Python code to implement the functionality described below step by step Description: Repeated measures ANOVA on source data with spatio-temporal clustering This example illustrates how to make use of the clustering functions for arbitrary, self-defined contrasts beyond stand...
Python Code: # Authors: Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr> # Eric Larson <larson.eric.d@gmail.com> # Denis Engemannn <denis.engemann@gmail.com> # # License: BSD (3-clause) import os.path as op import numpy as np from numpy.random import randn import matplotlib.pyplot as plt i...
10,083
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Classification 2 Step2: Exercise 7.2 Show that a classifier $\hat y_i = \text{sign}(\beta^\top x_i)$ is defined by a separating hyperplane. Assume that $\beta \in \mathbb R^{p+1}$ a...
Python Code: def lm_sim(N = 100): simulate a binary response and two predictors X1 = (np.random.randn(N*2)).reshape((N,2)) + np.array([2,3]) X0 = (np.random.randn(N*2)).reshape((N,2)) + np.array([.5,1.5]) y = - np.ones(N*2) y[:N]=1 X = np.vstack((X1,X0)) return X, y, X0, X1 X_sim,y_sim,X0,X1...
10,084
Given the following text description, write Python code to implement the functionality described below step by step Description: Getting started - a single particle In this tutorial, we'll simulate the stochastic dynamics of a single nanoparticle. We model clusters of nanoparticles using the magpy.Model class. In this...
Python Code: import magpy as mp Explanation: Getting started - a single particle In this tutorial, we'll simulate the stochastic dynamics of a single nanoparticle. We model clusters of nanoparticles using the magpy.Model class. In this case we only have a single particle in our cluster. The first step is to import magp...
10,085
Given the following text description, write Python code to implement the functionality described below step by step Description: <!--BOOK_INFORMATION--> <img align="left" style="padding-right Step1: The plt interface is what we will use most often, as we shall see throughout this chapter. Setting Styles We will use t...
Python Code: import matplotlib as mpl import matplotlib.pyplot as plt Explanation: <!--BOOK_INFORMATION--> <img align="left" style="padding-right:10px;" src="figures/PDSH-cover-small.png"> This notebook contains an excerpt from the Python Data Science Handbook by Jake VanderPlas; the content is available on GitHub. The...
10,086
Given the following text description, write Python code to implement the functionality described below step by step Description: 人生苦短,我用python python第四课 课程安排 1、numpy 2、pandas 3、matplotlib numpy 数组跟列表,列表可以存储任意类型的数据,而数组只能存储一种类型数据 Step1: 从原有列表转换为数组 Step2: 生成数组 Step3: random Step4: 范围取值 Step5: | Data type | Descr...
Python Code: import array a = array.array('i', range(10)) # 数据类型必须统一 a[1] = 's' a import numpy as np Explanation: 人生苦短,我用python python第四课 课程安排 1、numpy 2、pandas 3、matplotlib numpy 数组跟列表,列表可以存储任意类型的数据,而数组只能存储一种类型数据 End of explanation a_list = list(range(10)) b = np.array(a_list) type(b) Explanation: 从原有列表转换为数组 End of exp...
10,087
Given the following text description, write Python code to implement the functionality described below step by step Description: We covered a lot of information today and I'd like you to practice developing classification trees on your own. For each exercise, work through the problem, determine the result, and provide...
Python Code: import pandas as pd %matplotlib inline from sklearn import datasets from pandas.tools.plotting import scatter_matrix import matplotlib.pyplot as plt from sklearn import tree iris = datasets.load_iris() x = iris.data[:,2:] y = iris.target plt.figure(2, figsize=(8, 6)) plt.scatter(x[:, 0], x[:, 1], c=y, c...
10,088
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...
10,089
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2018 The TensorFlow Authors. Step1: 과대적합과 과소적합 <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https Step2: IMDB 데이터셋 다운로드 이전 노트북에서처럼 임베딩을 사...
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...
10,090
Given the following text description, write Python code to implement the functionality described below step by step Description: W6 Lab Assignment Deep dive into Histogram and boxplot. Step1: Histogram Let's revisit the table from the class | Hours | Frequency | |-------|-----------| | 0-1 | 4,300 | | 1-3 | 6...
Python Code: import matplotlib.pyplot as plt import numpy as np import seaborn as sns import pandas as pd sns.set_style('white') %matplotlib inline Explanation: W6 Lab Assignment Deep dive into Histogram and boxplot. End of explanation bins = [0, 1, 3, 5, 10, 24] data = {0.5: 4300, 2: 6900, 4: 4900, 7: 2000, 15: 2100}...
10,091
Given the following text description, write Python code to implement the functionality described below step by step Description: GeoNet FDSN webservice with Obspy demo - Event Service This demo introduces some simple code that requests data using GeoNet's FDSN webservices and the obspy module in python. This notebook ...
Python Code: from obspy import UTCDateTime from obspy.clients.fdsn import Client as FDSN_Client from obspy import read_inventory Explanation: GeoNet FDSN webservice with Obspy demo - Event Service This demo introduces some simple code that requests data using GeoNet's FDSN webservices and the obspy module in python. Th...
10,092
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction This notebook is an analysis of the Crowdflower labels of 10,000 revisions of Wikipedia talk pages by users who have been blocked for personal harassment. These revisions are ch...
Python Code: %matplotlib inline from __future__ import division import pandas as pd import numpy as np import matplotlib.pyplot as plt import time import datetime from scipy import stats import warnings warnings.filterwarnings('ignore') pd.set_option('display.max_colwidth', 1000) # Download data from google drive (Resp...
10,093
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Validation and Verification of the 25mm collimator simulation, GP3, PhSF Here we provide code and output which verifies and validates the 25mm collimator simulation. We're using simul...
Python Code: import math import matplotlib import numpy as np import matplotlib.pyplot as plt import BEAMphsf import beam_loader import H1Dn import H1Du import ListTable %matplotlib inline def cm2mm(value): converts cm to mm return value*10.0 Explanation: Validation and Verification of the 25mm collim...
10,094
Given the following text description, write Python code to implement the functionality described below step by step Description: Setup the environment Step1: Do the work to do the plotting Step2: Print yields and plot all the templates $B_s \to D_s^- \mu^+ \nu_{\mu} $ Step3: Print yields and plot all the templates...
Python Code: import sys sys.path.append('../../FourVector') sys.path.append('../project') from FourVector import FourVector from ThreeVector import ThreeVector from FutureColliderTools import SmearVertex, GetCorrectedMass, GetMissingMass2, GetQ2 from FutureColliderDataLoader import LoadData_KMuNu, LoadData_DsMuNu from ...
10,095
Given the following text description, write Python code to implement the functionality described below step by step Description: Here, we transform some strings to lowercase. This is because there are duplicate entries in the dataset which in both upper and lower. This increases redundancy Step1: There is still alot ...
Python Code: cleandata1['SOC_NAME'].value_counts() Explanation: Here, we transform some strings to lowercase. This is because there are duplicate entries in the dataset which in both upper and lower. This increases redundancy End of explanation cleandata1['SOC_NAME'].value_counts().count() Explanation: There is still a...
10,096
Given the following text description, write Python code to implement the functionality described below step by step Description: 2/1/17 FEProblemBase Step1: Jacobian calculations related to deviatoric stress tensor ($\hat{\tau}$) and rate of strain tensor ($\hat{\epsilon}$) Note that the total stress tensor ($\hat{\s...
Python Code: import sympy as sp sxx, sxy, syx, syy, nx, ny = sp.var('sxx sxy syx syy nx ny') s = sp.Matrix([[sxx, sxy],[syx, syy]]) n = sp.Matrix([nx, ny]) s*n prod = n.transpose()*s*n prod2 = n.transpose()*(s*n) print(prod) print(prod2) print(prod==prod2) prod.shape sp.expand(prod) == sp.expand(prod2) lhs = n.transpos...
10,097
Given the following text description, write Python code to implement the functionality described below step by step Description: 适配器模式(Adapter pattern)是一种结构型设计模式,帮助我们实现两个不兼容接口之间的兼容。 首先,解释一下不兼容接口的真正含义。如果我们希望把一个老组件用于一个新系统中,或者把一个新组件用于一个老系统中,不对代码进行任何修改两者就能够通信的情况很少见。但又并非总是能修改代码,或因为我们无法访问这些代码(例如,组件以外部库的方式提供),或因为修改代码本身就不切实际。...
Python Code: import os class Dog(object): def __init__(self): self.name = "Dog" def bark(self): return "woof!" class Cat(object): def __init__(self): self.name = "Cat" def meow(self): return "meow!" class Human(object): def __init__(self): self.name = "Human" ...
10,098
Given the following text description, write Python code to implement the functionality described below step by step Description: Hdf5 File format Vaex uses hdf5 (Hierarchical Data Format) for storing data. You can think of hdf5 files as being a file system, where the 'files' contain N-dimensional arrays, or think of i...
Python Code: import h5py import numpy as np h5file = h5py.File("/Users/users/breddels/src/vaex/data/helmi-dezeeuw-2000-10p.hdf5", "r") FeH = h5file["/data/FeH"] # FeH is your regular numpy array (with some extras) print("mean FeH", np.mean(FeH), "length", len(FeH)) Explanation: Hdf5 File format Vaex uses hdf5 (Hierarch...
10,099
Given the following text description, write Python code to implement the functionality described below step by step Description: Customer Churn Credits Step1: We'll be keeping the statistical model pretty simple for this example so the feature space is almost unchanged from what you see above. The following code simp...
Python Code: from __future__ import division import pandas as pd import numpy as np import matplotlib.pyplot as plt import json from sklearn.cross_validation import KFold from sklearn.preprocessing import StandardScaler from sklearn.cross_validation import train_test_split from sklearn.svm import SVC from sklearn.ensem...