Unnamed: 0 int64 0 16k | text_prompt stringlengths 110 62.1k | code_prompt stringlengths 37 152k |
|---|---|---|
3,100 | Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
I am trying to extract rows from a Pandas dataframe using a list of row names, but it can't be done. Here is an example | Problem:
import pandas as pd
import io
data = io.StringIO("""
rs alleles chrom pos strand assembly# center protLSID assayLSID
TP3 A/C 0 3 + NaN NaN NaN NaN
TP7 A/T 0 7 + NaN NaN NaN NaN
TP12 T/A 0 12 + NaN ... |
3,101 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Euler Equations
The Euler equations in primitive variable form, $q = (\rho, u, p)^\intercal$ appear as
Step1: The eigenvalues are the speeds at which information propagates with. SymPy ret... | Python Code:
from sympy.abc import rho
rho, u, c = symbols('rho u c')
A = Matrix([[u, rho, 0], [0, u, rho**-1], [0, c**2 * rho, u]])
A
Explanation: Euler Equations
The Euler equations in primitive variable form, $q = (\rho, u, p)^\intercal$ appear as:
$$q_t + A(q) q_x = 0$$
with the matrix $A(q)$:
$$A(q) = \left ( \beg... |
3,102 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<h1 align="center">Basic CFNCluster Setup</h1>
<h3 align="center">Author
Step1: 1. Install CFNCluster
Notice
Step2: 2. Upgrade CFNCluster
Step3: 3. Configure CFNCluster
To configure CFNCl... | Python Code:
import os
import sys
sys.path.append(os.getcwd().replace("notebooks", "cfncluster"))
## Input the AWS account access keys
aws_access_key_id = "/**aws_access_key_id**/"
aws_secret_access_key = "/**aws_secret_access_key**/"
## CFNCluster name
your_cluster_name = "cluster_name"
## The private key pair for ac... |
3,103 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
A notebook to test and demonstrate KernelSteinTest. This implements the kernelized Stein discrepancy test of Chwialkowski et al., 2016 and Liu et al., 2016 in ICML 2016.
Step1: Problem
Step... | Python Code:
%load_ext autoreload
%autoreload 2
%matplotlib inline
#%config InlineBackend.figure_format = 'svg'
#%config InlineBackend.figure_format = 'pdf'
import kgof
import kgof.data as data
import kgof.density as density
import kgof.goftest as gof
import kgof.kernel as ker
import kgof.util as util
import matplotlib... |
3,104 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Behavioral Cloning Notebook
Overview
This notebook contains project files for the Behavioral Cloning Project.
In this project, I use my knowledge on deep neural networks and convolutional ne... | Python Code:
import csv
from PIL import Image
import cv2
import numpy as np
import h5py
import os
from random import shuffle
import sklearn
Explanation: Behavioral Cloning Notebook
Overview
This notebook contains project files for the Behavioral Cloning Project.
In this project, I use my knowledge on deep neural networ... |
3,105 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
신경망 성능 개선
신경망의 예측 성능 및 수렴 성능을 개선하기 위해서는 다음과 같은 추가적인 고려를 해야 한다.
오차(목적) 함수 개선
Step1: 5나 10이 나오면 기울기값이 0이 나온다. 엄청 작게 나온다. (초록색 경우에). a값이 이렇게 나오면 weight update가 잘 안 되게 된다. 우리가 원하는 것은 반대다. a값이 크... | Python Code:
sigmoid = lambda x: 1/(1+np.exp(-x))
sigmoid_prime = lambda x: sigmoid(x)*(1-sigmoid(x))
xx = np.linspace(-10, 10, 1000)
plt.plot(xx, sigmoid(xx));
plt.plot(xx, sigmoid_prime(xx));
Explanation: 신경망 성능 개선
신경망의 예측 성능 및 수렴 성능을 개선하기 위해서는 다음과 같은 추가적인 고려를 해야 한다.
오차(목적) 함수 개선: cross-entropy cost function
정규화: reg... |
3,106 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Comparing the performance of our best model without modulation of the learning rate or momentum, deactivating the extensions.
Step1: So in the end it reaches almost the same log loss. I'm g... | Python Code:
import pylearn2.utils
import pylearn2.config
import theano
import neukrill_net.dense_dataset
import neukrill_net.utils
import numpy as np
%matplotlib inline
import matplotlib.pyplot as plt
import holoviews as hl
%load_ext holoviews.ipython
import sklearn.metrics
cd ..
settings = neukrill_net.utils.Settings... |
3,107 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Exercício 1-3
Step1: 2. Regressão linear
Vamos aplicar a regressão linear, usando o método gradiente descendente.<br>
Se não lembrar do método, volte para o Exercício 1-1<br>
Neste ponto, v... | Python Code:
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
# Criar um array com n números.
# Cada um desses números é um exemplo x
# Em seguida, estender os exemplos: x ---> (1,x)
N = 14
x = np.array([0.2, 0.5, 1, 1.1, 1.2, 1.8, 2, 4.3, 4.4, 5.7, 6.9, 7.5, 8, 8.2])
X = np.vstack(zip(np.ones(N),... |
3,108 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introduction to TensorFlow
TensorFlow is a deep learning framework that allows you to build neural networks more easily than by hand, and thus can speed up your deep learning development sig... | Python Code:
import math
import numpy as np
import h5py
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow.python.framework import ops
from tensorflow.examples.tutorials.mnist import input_data
%matplotlib inline
Explanation: Introduction to TensorFlow
TensorFlow is a deep learning framework that a... |
3,109 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
This notebook simulates an antidromic stimulus reaching a pool of motoneurons and a renshaw cell.
Pablo Alejandro
Step1: The antidromic stimulus at the PTN.
Step2: The spike times of each ... | Python Code:
import sys
sys.path.insert(0, '..')
import time
import matplotlib.pyplot as plt
%matplotlib notebook
plt.rcParams['figure.figsize']= 7,7
import numpy as np
from Configuration import Configuration
from MotorUnitPool import MotorUnitPool
from InterneuronPool import InterneuronPool
from SynapsesFactory import... |
3,110 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Classificação por Regras Pré-Definidas
O problema com o qual vamos lidar é o de classificar automaticamente elementos de um conjunto através de suas características mensuráveis. Trata-se, as... | Python Code:
%matplotlib inline
import numpy as np
from matplotlib import pyplot as plt
Explanation: Classificação por Regras Pré-Definidas
O problema com o qual vamos lidar é o de classificar automaticamente elementos de um conjunto através de suas características mensuráveis. Trata-se, assim, do problema de observar ... |
3,111 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Nonnegative Matrix Factorization In The Movielens Dataset
This example continues illustrating using pandas-munging capabilities in estimators building features that draw from several rows, t... | Python Code:
import os
from sklearn import base
import pandas as pd
import scipy as sp
import seaborn as sns
sns.set_style('whitegrid')
sns.despine()
import ibex
from ibex.sklearn import model_selection as pd_model_selection
from ibex.sklearn import decomposition as pd_decomposition
from ibex.sklearn import decompositi... |
3,112 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Convolutional Neural Networks
Project
Step1: <a id='step1'></a>
Step 1
Step2: Before using any of the face detectors, it is standard procedure to convert the images to grayscale. The dete... | Python Code:
import numpy as np
from glob import glob
# load filenames for human and dog images
human_files = np.array(glob("lfw/*/*"))
dog_files = np.array(glob("dogImages/*/*/*"))
# print number of images in each dataset
print('There are %d total human images.' % len(human_files))
print('There are %d total dog images... |
3,113 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
05 Scraping data with Requests and Beautiful Soup
To now, we've covered means of grabbing data that are formatted to grab. The term 'web scraping' refers to the messier means of pulling mate... | Python Code:
# Import the requests package; install if necessary
try:
import requests
except:
import pip
pip.main(['install','requests'])
import requests
# Import BeautifulSoup from the bs4 package; install bs4 if necessary
try:
from bs4 import BeautifulSoup
except:
import pip
pip.main(['ins... |
3,114 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Batch Normalization – Practice
Batch normalization is most useful when building deep neural networks. To demonstrate this, we'll create a convolutional neural network with 20 convolutional l... | Python Code:
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True, reshape=False)
Explanation: Batch Normalization – Practice
Batch normalization is most useful when building deep neural networks. To demonstrate this, we'll crea... |
3,115 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Variance Component Analysis
This notebook illustrates variance components analysis for two-level
nested and crossed designs.
Step1: Make the notebook reproducible
Step2: Nested analysis
In... | Python Code:
import numpy as np
import statsmodels.api as sm
from statsmodels.regression.mixed_linear_model import VCSpec
import pandas as pd
Explanation: Variance Component Analysis
This notebook illustrates variance components analysis for two-level
nested and crossed designs.
End of explanation
np.random.seed(3123)
... |
3,116 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
How to use the WFSGeojsonLayer class
This class provides WFS layers for ipyleaflet from services than avec geojson output capabilities
We first have to create the WFS connection and instanci... | Python Code:
from birdy import IpyleafletWFS
from ipyleaflet import Map
url = 'http://boreas.ouranos.ca/geoserver/wfs'
version = '2.0.0'
wfs_connection = IpyleafletWFS(url, version)
demo_map = Map(center=(46.42, -64.14), zoom=8)
demo_map
Explanation: How to use the WFSGeojsonLayer class
This class provides WFS layers f... |
3,117 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
확률 모형이란
데이터 분포 묘사의 문제점
기술 통계 등의 방법으로 자료의 분포를 기술하는 방법은 불확실하며 대략적인 정보만을 전달할 뿐이며 자세한 혹은 완벽한 정보를 전달하기 어렵다.
예를 들어 다음과 같이 1,000개의 데이터가 있다. 데이터 생성에는 SciPy의 확률 분포 명령을 이용하였다.
[[school_notebook
Step1:... | Python Code:
sp.random.seed(0)
x = sp.random.normal(size=1000)
Explanation: 확률 모형이란
데이터 분포 묘사의 문제점
기술 통계 등의 방법으로 자료의 분포를 기술하는 방법은 불확실하며 대략적인 정보만을 전달할 뿐이며 자세한 혹은 완벽한 정보를 전달하기 어렵다.
예를 들어 다음과 같이 1,000개의 데이터가 있다. 데이터 생성에는 SciPy의 확률 분포 명령을 이용하였다.
[[school_notebook:175522b819ae4645907179462dabc5d4]]
End of explanation
ns, bi... |
3,118 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Interact Exercise 6
Imports
Put the standard imports for Matplotlib, Numpy and the IPython widgets in the following cell.
Step1: Exploring the Fermi distribution
In quantum statistics, the ... | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
from IPython.display import Image
from IPython.html.widgets import interact, interactive, fixed
Explanation: Interact Exercise 6
Imports
Put the standard imports for Matplotlib, Numpy and the IPython widgets in the following cell.
End of... |
3,119 | 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', 'bcc', 'sandbox-2', 'atmos')
Explanation: ES-DOC CMIP6 Model Properties - Atmos
MIP Era: CMIP6
Institute: BCC
Source ID: SANDBOX-2
Topic: Atmos
Sub-Topics: Dynamical Core, Radiation, T... |
3,120 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Overview and Examples
A brief description of what linearsolve is for followed by examples.
What linearsolve Does
linearsolve defines a class - linearsolve.model - with several functions for ... | Python Code:
# Import numpy, pandas, linearsolve, matplotlib.pyplot
import numpy as np
import pandas as pd
import linearsolve as ls
import matplotlib.pyplot as plt
plt.style.use('classic')
%matplotlib inline
# Input model parameters
parameters = pd.Series(dtype=float)
parameters['alpha'] = .35
parameters['beta'] = 0.... |
3,121 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Appendix A
Step1: Baseline evaluation
For tuning the BM25 parameters, we're going to use just a match query per field, combined using a bool should query. This will search for query terms a... | Python Code:
%load_ext autoreload
%autoreload 2
import importlib
import os
import sys
from elasticsearch import Elasticsearch
from skopt.plots import plot_objective
# project library
sys.path.insert(0, os.path.abspath('..'))
import qopt
importlib.reload(qopt)
from qopt.notebooks import evaluate_mrr100_dev, optimize_bm2... |
3,122 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2022 The TensorFlow Authors.
Step1: Private Heavy Hitters
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https
Step3: Background
Step4: Si... | 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... |
3,123 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Invoer
We gaan dus proberen op te lossen
<img src=./examples/2x2b.png width = 120px></img>
Als eerste moeten we dit een manier bedenken om dit in te typen, op een manier de voor de ge... | Python Code:
# tekst kan je invoeren door met drie dubbele quotes te beginnen en eindigen
invoer =
3 . | 4 .
. 1 | . 3
----+----
2 3 | . .
1 . | . 2
print(invoer)
# in de variabele sudoku_invoer staan nu de volgende tekens. \n betekent nieuwe regel
invoer
Explanation: Invoer
We gaan dus proberen op te lossen
<img src... |
3,124 | Given the following text description, write Python code to implement the functionality described.
Description:
Find the Largest N digit perfect square number in Base B
Python3 implementation to find the largest N digit perfect square number in base B ; Function to find the largest N digit number ; Largest n - digit per... | Python Code:
import math
def nDigitPerfectSquares(n , b ) :
largest = pow(math . ceil(math . sqrt(pow(b , n ) ) ) - 1 , 2 )
print(largest )
N = 1
B = 8
nDigitPerfectSquares(N , B )
|
3,125 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Point cloud segmentation with PointNet
Author
Step1: Downloading Dataset
The ShapeNet dataset is an ongoing effort to establish a richly-annotated,
large-scale dataset of 3D shapes. ShapeNe... | Python Code:
import os
import json
import random
import numpy as np
import pandas as pd
from tqdm import tqdm
from glob import glob
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
import matplotlib.pyplot as plt
Explanation: Point cloud segmentation with PointNet
Author: Soumik ... |
3,126 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Tutorial
Step1: Introduction
In this tutorial, you will learn how to do statistical analysis of your simulation data.
This is an important topic, because the statistics of your data determi... | Python Code:
import numpy as np
%matplotlib inline
import matplotlib.pyplot as plt
plt.rcParams.update({'font.size': 18})
import sys
import logging
logging.basicConfig(level=logging.INFO, stream=sys.stdout)
np.random.seed(43)
def ar_1_process(n_samples, c, phi, eps):
'''
Generate a correlated random sequence wi... |
3,127 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<h1>Train Points Importer</h1>
<hr style="border
Step1: <span>
We want to have this data in a more standard format, a CSV file for instance. More like this way
Step2: <span>
<h2>Data clean... | Python Code:
!head -10 train_points_import_data/arduino_raw_data.txt
Explanation: <h1>Train Points Importer</h1>
<hr style="border: 1px solid #000;">
<span>
<h2>
Import Tool for transforming collected hits from Arduino serial port, to ATT readable hit format.
</h2>
<span>
<br>
</span>
<i>Import points from arduino form... |
3,128 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Test Data Prep
This page is meant to prepare test fixtures for use in hydrofunctions.
Table of Contents
Step1: Create sample NWIS responses to requests.
The cells below will generate the ou... | Python Code:
import hydrofunctions as hf
print("Hydrofunctions version: ", hf.__version__)
import numpy as np
print("Numpy version: ", np.__version__)
import pandas as pd
print("Pandas version: ", pd.__version__)
import requests
print("Requests version: ", requests.__version__)
import matplotlib as plt
%matplotlib inli... |
3,129 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Background
This notebook is an interactive tool for evaluating scoring methods for frame design.
Step1: We must first setup a sample environment with a frame and components.
Step2: Scoring... | Python Code:
import frame_methods
import engine_methods as em
import itertools
import pandas as pd
import matplotlib.pyplot as plt
from scipy.stats import norm
import numpy as np
from ipywidgets import interact, interactive, fixed, interact_manual
import ipywidgets as widgets
Explanation: Background
This notebook is an... |
3,130 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Taming math and physics using SymPy
Tutorial based on the No bullshit guide series of textbooks by Ivan Savov
Abstract
Most people consider math and physics to be scary
beasts from which it ... | Python Code:
from sympy import init_session
init_session()
Explanation: Taming math and physics using SymPy
Tutorial based on the No bullshit guide series of textbooks by Ivan Savov
Abstract
Most people consider math and physics to be scary
beasts from which it is best to keep one's distance. Computers,
however, can he... |
3,131 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Tant que ce n'est pas bien maîtrisé c'est ...
La Guerre des Fonctions
1) Autes fonctions particulières à corriger
2) Exercices de Simplification du code des fonctions
3) Quelques Exercices
... | Python Code:
def cube_positif( x ):
if abs( x*x*x >= 0.0):
return x*x*x
print("Erreur")
return
cube_positif(-4)
Explanation: Tant que ce n'est pas bien maîtrisé c'est ...
La Guerre des Fonctions
1) Autes fonctions particulières à corriger
2) Exercices de Simplification du code des fonctions
3) Quelq... |
3,132 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Search OOI ERDDAP for Pioneer Glider Data
Use ERDDAP's RESTful advanced search to try to find OOI Pioneer glider water temperatures from the OOI ERDDAP. Use case from Stace Beaulieu (sbeaul... | Python Code:
import pandas as pd
Explanation: Search OOI ERDDAP for Pioneer Glider Data
Use ERDDAP's RESTful advanced search to try to find OOI Pioneer glider water temperatures from the OOI ERDDAP. Use case from Stace Beaulieu (sbeaulieu@whoi.edu)
End of explanation
url = 'http://ooi-data.marine.rutgers.edu/erddap/se... |
3,133 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Background on projectors and projections
This tutorial provides background information on projectors and Signal Space
Projection (SSP), and covers loading and saving projectors, adding and r... | Python Code:
import os
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D # noqa
from scipy.linalg import svd
import mne
def setup_3d_axes():
ax = plt.axes(projection='3d')
ax.view_init(azim=-105, elev=20)
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('... |
3,134 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Сравнение метрик качества бинарной классификации
Programming Assignment
В этом задании мы разберемся, в чем состоит разница между разными метриками качества. Мы остановимся на задаче бинарно... | Python Code:
import numpy as np
from matplotlib import pyplot as plt
import seaborn
%matplotlib inline
Explanation: Сравнение метрик качества бинарной классификации
Programming Assignment
В этом задании мы разберемся, в чем состоит разница между разными метриками качества. Мы остановимся на задаче бинарной классификаци... |
3,135 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Homework #5
This homework presents a sophisticated scenario in which you must design a SQL schema, insert data into it, and issue queries against it.
The scenario
In the year 20XX, I have wo... | Python Code:
from bs4 import BeautifulSoup
from urllib.request import urlopen
html = urlopen("http://static.decontextualize.com/cats.html").read()
document = BeautifulSoup(html, "html.parser")
Explanation: Homework #5
This homework presents a sophisticated scenario in which you must design a SQL schema, insert data int... |
3,136 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Coregionalized Regression Model (vector-valued regression)
updated
Step1: For this example we will generate an artificial dataset.
Step2: Our two datasets look like this
Step3: We will al... | Python Code:
%pylab inline
import pylab as pb
pylab.ion()
import GPy
Explanation: Coregionalized Regression Model (vector-valued regression)
updated: 17th June 2015
by Ricardo Andrade-Pacheco
This tutorial will focus on the use and kernel selection of the $\color{firebrick}{\textbf{coregionalized regression}}$ model in... |
3,137 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Experimental Results from a Decision Tree based NER model
Decisions Trees, as opposed to other machine learning techniques such as SVM's and Neural Networks, provide a human-interpretable cl... | Python Code:
#python3 arff_translator.py [filename]
Explanation: Experimental Results from a Decision Tree based NER model
Decisions Trees, as opposed to other machine learning techniques such as SVM's and Neural Networks, provide a human-interpretable classification model. We will exploit this to both generate pretty ... |
3,138 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Gaussian Process Regression (in 1-D)
Gaussian processes belong to class of non-parametric regression models in machine learning. To try and develop an understanding of what is meant by "non-... | Python Code:
import matplotlib.image as mpimg
import pylab as plt
import numpy as np
%matplotlib inline
# Plot the (binned) photometric light curve
from MEarthphotometry import * # custom class
self = loadpickle('MEarthphot')
t, y, ey = self.bjdtrimbin, self.magtrimbin, self.emagtrimbin
# Plotting
fig = plt.figure(fi... |
3,139 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Tables to Networks, Networks to Tables
Networks can be represented in a tabular form in two ways
Step1: At this point, we have our stations and trips data loaded into memory.
How we constr... | Python Code:
# This block of code checks to make sure that a particular directory is present.
if "divvy_2013" not in os.listdir('datasets/'):
print('Unzip the divvy_2013.zip file in the datasets folder.')
stations = pd.read_csv('datasets/divvy_2013/Divvy_Stations_2013.csv', parse_dates=['online date'], index_col='i... |
3,140 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<font color='blue'>Data Science Academy - Python Fundamentos - Capítulo 7</font>
Download
Step1: Missão
Step2: Teste da Solução | Python Code:
# Versão da Linguagem Python
from platform import python_version
print('Versão da Linguagem Python Usada Neste Jupyter Notebook:', python_version())
Explanation: <font color='blue'>Data Science Academy - Python Fundamentos - Capítulo 7</font>
Download: http://github.com/dsacademybr
End of explanation
class... |
3,141 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Image Gradients
In this notebook we'll introduce the TinyImageNet dataset and a deep CNN that has been pretrained on this dataset. You will use this pretrained model to compute gradients wit... | Python Code:
# As usual, a bit of setup
import time, os, json
import numpy as np
import skimage.io
import matplotlib.pyplot as plt
from cs231n.classifiers.pretrained_cnn import PretrainedCNN
from cs231n.data_utils import load_tiny_imagenet
from cs231n.image_utils import blur_image, deprocess_image
%matplotlib inline
pl... |
3,142 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
+
Word Count Lab
Step2: (1b) Pluralize and test
Let's use a map() transformation to add the letter 's' to each string in the base RDD we just created. We'll define a Python function that ... | Python Code:
wordsList = ['cat', 'elephant', 'rat', 'rat', 'cat']
wordsRDD = sc.parallelize(wordsList, 4)
# Print out the type of wordsRDD
print type(wordsRDD)
Explanation: +
Word Count Lab: Building a word count application
This lab will build on the techniques covered in the Spark tutorial to develop a simple word c... |
3,143 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Business Question
Step1: The business question
Step2: Note On Correlation and Slope
Step3: Radio correlation
Step4: Newspaper correlation
Step5: All media correlation
Step6: Remarks u... | Python Code:
# necessary imports
from matplotlib import pyplot as plt
import pandas as pd
import numpy as np
%load_ext autoreload
%autoreload 2
import sys
sys.path.append("../lib_plot")
import scatter_boxplot as sbp
%matplotlib inline
import seaborn as sns
from scipy.stats.stats import pearsonr
from scipy import stats
... |
3,144 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Discussion 11
Step3: Understanding Gradient Descent
In order to better understand gradient descent, let's implement it to solve a familiar problem - least-squares linear regression. While w... | Python Code:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import patches, cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
from mpl_toolkits.mplot3d import Axes3D
%matplotlib inline
from IPython.display import display, Latex, Markdown
from ipywidgets import in... |
3,145 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
NS
$$h(t) \approx_0 \frac{16 \pi^2 G}{c^4 r}I \epsilon (\nu_0 + \dot{\nu}t)^2 cos(2\pi(\nu_0+\dot{\nu}t)t)$$
Step1: chirp | Python Code:
G = 6.67408*1e-11
c = 299792458
r = 2.4377e+20
I = 1e38
epsilon = 1e-4
nu0 = 1
nudot = -5e-10
cost = 16*math.pi**2*G/(c**4*r)*I*epsilon
print(cost)
nmesi = 9
tobs = nmesi*30*24*60*60
print(tobs)
tempi = numpy.linspace(0,10,100000)
leggeOraria = nu0+nudot*tempi
ampiezza = cost*numpy.power(leggeOraria,2)
ond... |
3,146 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<img src="http
Step1: Risk Factors
This sub-section models the single risk factors. We start with definition of the risk-neutral discounting object.
Step2: Three risk factors ares modeled
... | Python Code:
from dx import *
from pylab import plt
plt.style.use('seaborn')
Explanation: <img src="http://hilpisch.com/tpq_logo.png" alt="The Python Quants" width="45%" align="right" border="4">
Multi-Risk Derivatives Portfolios
The step from multi-risk derivatives instruments to multi-risk derivatives instrument port... |
3,147 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Land
MIP Era
Step1: Document Authors
Set document authors
Step2: Document Contributors
Specify document contributors
Step3: Document Publication
Specify do... | Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'ec-earth-consortium', 'sandbox-1', 'land')
Explanation: ES-DOC CMIP6 Model Properties - Land
MIP Era: CMIP6
Institute: EC-EARTH-CONSORTIUM
Source ID: SANDBOX-1
Topic: Land
Sub-Topics:... |
3,148 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2019 The TensorFlow Authors.
Step1: TensorFlow 2 quickstart for experts
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https
Step2: Load an... | 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... |
3,149 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Creating MNE's data structures from scratch
MNE provides mechanisms for creating various core objects directly from
NumPy arrays.
Step1: Creating
Step2: You can also supply more extensive... | Python Code:
import mne
import numpy as np
Explanation: Creating MNE's data structures from scratch
MNE provides mechanisms for creating various core objects directly from
NumPy arrays.
End of explanation
# Create some dummy metadata
n_channels = 32
sampling_rate = 200
info = mne.create_info(n_channels, sampling_rate)
... |
3,150 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
UFC Chicago Twitter Stream Topic Modeling
By Chris Tufts
This notebook uses Latent Dirichlet Allocation (LDA) to perform topic modeling on a stream of tweets collected during the UFC Chicago... | Python Code:
import pandas as pd
from pandas.tseries.resample import TimeGrouper
from pandas.tseries.offsets import DateOffset
import numpy as np
from langdetect import detect, lang_detect_exception
from nltk import FreqDist,WordNetLemmatizer
from nltk.corpus import stopwords
from gensim import corpora, models
import p... |
3,151 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Inferring Cluster Model Parameters from an X-ray Image
Forward modeling is always instructive
Step1: Spot the difference!
The data, $N_k$, now have a double circle around them, to remind us... | Python Code:
# import cluster_pgm
# cluster_pgm.inverse()
from IPython.display import Image
Image(filename="cluster_pgm_inverse.png")
Explanation: Inferring Cluster Model Parameters from an X-ray Image
Forward modeling is always instructive: we got a good sense of the parameters of our cluster + background model simply... |
3,152 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
CryoBLM BLEDP
2017-03-26
Display, extraction and analysis of the binary BLEDP format.
Also provides the possibility of directly writing out the analysis results.
Decoder class based on BLED... | Python Code:
import numpy as np
import logging
from time import time
from datetime import datetime
from os.path import join
from os import walk
%matplotlib notebook
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from itertools import cycle
Explanation: CryoBLM BLEDP
2017-03-26
Display, extraction and... |
3,153 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Lambert Scattering (irrad_method='horvat')
Setup
Let's first make sure we have the latest version of PHOEBE 2.4 installed (uncomment this line if running in an online notebook session such a... | Python Code:
#!pip install -I "phoebe>=2.4,<2.5"
Explanation: Lambert Scattering (irrad_method='horvat')
Setup
Let's first make sure we have the latest version of PHOEBE 2.4 installed (uncomment this line if running in an online notebook session such as colab).
End of explanation
import phoebe
from phoebe import u # un... |
3,154 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Explain PyTextRank
Step1: Create some text to use....
Step2: Then add PyTextRank into the spaCy pipeline...
Step3: Examine the results
Step4: Construct a list of the sentence boundaries ... | Python Code:
import warnings
warnings.filterwarnings("ignore")
import spacy
nlp = spacy.load("en_core_web_sm")
Explanation: Explain PyTextRank: extractive summarization
How does PyTextRank perform extractive summarization on a text document?
First we perform some basic housekeeping for Jupyter, then load spaCy with a l... |
3,155 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Load the default setting. This setting is identical to Example 6 except that this setting adds a filter in order to remove the error message.
Step1: Compare the results between standard AM1... | Python Code:
file = build_smarts_file(
**astmg_173_03_m
)
data = send_to_smarts(file)
plt.plot(data.iloc[:,0],data.iloc[:,1],hold=True)
plt.plot(data.iloc[:,0],data.iloc[:,4])
plt.show()
data.columns
Explanation: Load the default setting. This setting is identical to Example 6 except that this setting adds a fi... |
3,156 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<img style='float
Step1: Connect to server
Step2: <hr> Random points with default styling
Step3: <hr> Random small red points
Step4: <hr> Random points with all styling options
Step5: <... | Python Code:
from lightning import Lightning
from numpy import random, asarray, amin, concatenate, column_stack
from seaborn import color_palette
from sklearn import datasets
Explanation: <img style='float: left' src="http://lightning-viz.github.io/images/logo.png"> <br> <br> 3D scatter p... |
3,157 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Numpy Exercise 4
Imports
Step1: Complete graph Laplacian
In discrete mathematics a Graph is a set of vertices or nodes that are connected to each other by edges or lines. If those edges don... | Python Code:
import numpy as np
%matplotlib inline
import matplotlib.pyplot as plt
import seaborn as sns
Explanation: Numpy Exercise 4
Imports
End of explanation
import networkx as nx
K_5=nx.complete_graph(5)
nx.draw(K_5)
Explanation: Complete graph Laplacian
In discrete mathematics a Graph is a set of vertices or node... |
3,158 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Pumping test analysis of a constant-rate pumping test in an anisotropic unconfined aquifer
The description and data for this example are taken from the aqtesolve website.
Lohman (1972) pres... | Python Code:
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from scipy.optimize import fmin
from ttim import *
# problem definition
H = 39.4 * 0.3048 # thickness [meters]
xw, yw = 0, 0 # location well
xp, yp = 63 * 0.3048, 0 # Location piezometer [meter]
Qw = 1170 * 5.45 #... |
3,159 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Circular area-sink
Circular area-sink with radius 100 m, located at the origin.
Step1: Circular area-sink and well
Discharge of well is the same as total infiltration rate of the circular a... | Python Code:
N = 0.001
R = 100
ml = ModelMaq(kaq=5, z=[10, 0], Saq=2e-4, tmin=1e-3, tmax=1e4)
ca = CircAreaSink(ml, 0, 0, 100, tsandN=[(0, 0.001)])
ml.solve()
ml.xsection(-200, 200, 0, 0, t=[0.1, 1, 10], figsize=(12, 4), sstart=-200)
x = np.linspace(-200, 200, 200)
qx = np.zeros_like(x)
for t in [0.1, 1, 10]:
for i... |
3,160 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Multi-Armed Bandits
Imagine this scenario
Step3: Algorithm 1 - Epsilon Greedy
At each round $t = 1, 2, ...$ the Epsilon Greedy algorithm will
Step4: The decrease_const parameter in ... | Python Code:
def generate_bernoulli_bandit_data( n_simulations, K ):
generate simluate data, that represents success / trial data
Parameters
----------
n_simulations : int
the total number of turns in a simulation
K : int
the total number of arms
Returns
... |
3,161 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Text Classification with spaCy
This walkthrough is based on this spaCy tutorial.
Train a convolutional neural network text classifier on the
IMDB dataset, using the TextCategorizer component... | Python Code:
# Python >3.5
!pip install verta
!pip install spacy==2.1.6
!python -m spacy download en
Explanation: Text Classification with spaCy
This walkthrough is based on this spaCy tutorial.
Train a convolutional neural network text classifier on the
IMDB dataset, using the TextCategorizer component. The dataset wi... |
3,162 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
"Detection of anomalous tweets using supervising outlier techniques"
Importing the Dependencies and Loading the Data
Step1: Data Preparation
Data prepration with the available data. I made ... | Python Code:
import nltk
import pandas as pd
import numpy as np
data = pd.read_csv("original_train_data.csv", header = None,delimiter = "\t", quoting=3,names = ["Polarity","TextFeed"])
#Data Visualization
data.head()
Explanation: "Detection of anomalous tweets using supervising outlier techniques"
Importing the Depende... |
3,163 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Time Series Modeling
2017-04-28, Josh Montague
This is Part 2 of the "Time Series Modeling in Python" series.
In Part 1, we looked at data structures within the pandas library that make wor... | Python Code:
import copy
from IPython.display import Image
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import random
from sklearn.metrics import r2_score, mean_squared_error
%matplotlib inline
plt.rcParams["figure.figsize"] = (8,6)
# `unemploy.csv` is included in the repo - it's a small csv
!... |
3,164 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Basic Image Processing tutorial
Basic image data manipulation is introduced, using OpenCV library.
The sample image is obtained from PEXELS.
OpenCV is image processing library which supports... | Python Code:
import os
import matplotlib.pyplot as plt
import cv2
%matplotlib inline
def readRGBImage(imagepath):
image = cv2.imread(imagepath) # Height, Width, Channel
(major, minor, _) = cv2.__version__.split(".")
if major == '3':
# version 3 is used, need to convert
image = cv2.cvtColor(... |
3,165 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Loading Pre-Trained Models
In this tutorial, we'll use the squeezenet model to identify objects in images. The image location will pass in a URL to a photo or the location of a local file. T... | Python Code:
%matplotlib inline
from caffe2.proto import caffe2_pb2
import numpy as np
import skimage.io
import skimage.transform
from matplotlib import pyplot
import os
from caffe2.python import core, workspace, models
import urllib2
print("Required modules imported.")
# Configuration --- Change to your setup and pref... |
3,166 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Self-Driving Car Engineer Nanodegree
Deep Learning
Project
Step1: Step 1
Step2: Include an exploratory visualization of the dataset
Visualize the German Traffic Signs Dataset using the pic... | Python Code:
# Load pickled data
import pickle
# TODO: Fill this in based on where you saved the training and testing data
data_dir = "data/"
training_file = data_dir + "train.p"
validation_file = data_dir + "valid.p"
testing_file = data_dir + "test.p"
with open(training_file, mode='rb') as f:
train = pickle.load(f... |
3,167 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
title
Step1: 0. Open dataset and load package
This dataset examines the relationship between multitasking and working memory. Link here to original paper by Uncapher et al. 2016.
Step2: 1.... | Python Code:
# load packages we will be using for this lesson
import pandas as pd
Explanation: title: "Data Manipulation in Python"
subtitle: "CU Psych Scientific Computing Workshop"
weight: 1301
tags: ["core", "python"]
Goals of this lesson
Students will learn:
How to group and categorize data in Python
How to generat... |
3,168 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Similarity-based Learning
Similiarity-based approaches in machine learning come from the idea that the best way to make predictions is simply to look at what has worked in the past and predi... | Python Code:
import numpy as np
import math as ma
import matplotlib.pyplot as plt
%matplotlib inline
X = np.array([3.3, 1.2])
Y = np.array([2.1, -1.8])
plt.arrow(0,0,*X, head_width=0.2);
plt.arrow(0,0,*Y, head_width=0.2);
plt.xlim([0, 4]);
plt.ylim([-2,2]);
plt.show();
# Euclidean distance manually:
ma.sqrt(np.sum((X-Y... |
3,169 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Image Classification
In this project, you'll classify images from the CIFAR-10 dataset. The dataset consists of airplanes, dogs, cats, and other objects. You'll preprocess the images... | Python Code:
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
from urllib.request import urlretrieve
from os.path import isfile, isdir
from tqdm import tqdm
import problem_unittests as tests
import tarfile
cifar10_dataset_folder_path = 'cifar-10-batches-py'
class DLProgress(tqdm):
last_block = 0
def h... |
3,170 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Lab 4 - Convolutional Neural Network with MNIST
This lab corresponds to Module 4 of the "Deep Learning Explained" course. We assume that you have successfully Lab 1 to download the MNIST dat... | Python Code:
# Figure 1
Image(url= "http://3.bp.blogspot.com/_UpN7DfJA0j4/TJtUBWPk0SI/AAAAAAAAABY/oWPMtmqJn3k/s1600/mnist_originals.png", width=200, height=200)
Explanation: Lab 4 - Convolutional Neural Network with MNIST
This lab corresponds to Module 4 of the "Deep Learning Explained" course. We assume that you have ... |
3,171 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
TensorFlow Tutorial On Save & Restore Model
Introduction
This tutorial demonstrates how to save and restore the variables of a Neural Network. During optimization we save the variables of th... | Python Code:
from IPython.display import Image
Image('images/02_network_flowchart.png')
Explanation: TensorFlow Tutorial On Save & Restore Model
Introduction
This tutorial demonstrates how to save and restore the variables of a Neural Network. During optimization we save the variables of the neural network whenever its... |
3,172 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
TensorFlow Dataset API
Learning Objectives
1. Learn how to use tf.data to read data from memory
1. Learn how to use tf.data in a training loop
1. Learn how to use tf.data to read data from d... | Python Code:
# The json module is mainly used to convert the python dictionary above into a JSON string that can be written into a file
import json
# The math module in python provides some mathematical functions
import math
# The OS module in python provides functions for interacting with the operating system
import o... |
3,173 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Reconstruction de synonymes - énoncé
Ce notebook est plus un jeu. On récupère d'abord des synonymes via la base WOLF. On ne garde que les synonymes composé d'un seul mot. On prend ensuite un... | Python Code:
from jyquickhelper import add_notebook_menu
add_notebook_menu()
Explanation: Reconstruction de synonymes - énoncé
Ce notebook est plus un jeu. On récupère d'abord des synonymes via la base WOLF. On ne garde que les synonymes composé d'un seul mot. On prend ensuite un texte quelconque qu'on découpe en phras... |
3,174 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
机器学习工程师纳米学位
入门
项目 0
Step1: 从泰坦尼克号的数据样本中,我们可以看到船上每位旅客的特征
Survived:是否存活(0代表否,1代表是)
Pclass:社会阶级(1代表上层阶级,2代表中层阶级,3代表底层阶级)
Name:船上乘客的名字
Sex:船上乘客的性别
Age
Step3: 这个例子展示了如何将泰坦尼克号的 Survived 数据从 Data... | Python Code:
import numpy as np
import pandas as pd
# RMS Titanic data visualization code
# 数据可视化代码
from titanic_visualizations import survival_stats
from IPython.display import display
%matplotlib inline
# Load the dataset
# 加载数据集
in_file = 'titanic_data.csv'
full_data = pd.read_csv(in_file)
# Print the first few en... |
3,175 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Part 2
Step1: Import libraries
Step2: Configure GCP environment settings
Update the following variables to reflect the values for your GCP environment
Step3: Authenticate your GCP account... | Python Code:
!pip install -U -q apache-beam[gcp]
Explanation: Part 2: Process the item embedding data in BigQuery and export it to Cloud Storage
This notebook is the second of five notebooks that guide you through running the Real-time Item-to-item Recommendation with BigQuery ML Matrix Factorization and ScaNN solution... |
3,176 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2020 DeepMind Technologies Limited. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
Full license text
Step1: A (very) basic GAN for MNIST in J... | 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distr... |
3,177 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Computing In Context
Social Sciences Track
Lecture 3--text mining for real
Matthew L. Jones
like, with code and stuff
Step1: IMPORTANT
Step2: Let's get some text
Let's use the remarkable n... | Python Code:
%matplotlib inline
import pandas as pd
import matplotlib.pyplot as plt
import textmining_blackboxes as tm
Explanation: Computing In Context
Social Sciences Track
Lecture 3--text mining for real
Matthew L. Jones
like, with code and stuff
End of explanation
#see if package imported correctly
tm.icantbelieve(... |
3,178 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Corrupt known signal with point spread
The aim of this tutorial is to demonstrate how to put a known signal at a
desired location(s) in a
Step1: First, we set some parameters.
Step2: Load... | Python Code:
import os.path as op
import numpy as np
import mne
from mne.datasets import sample
from mne.minimum_norm import read_inverse_operator, apply_inverse
from mne.simulation import simulate_stc, simulate_evoked
Explanation: Corrupt known signal with point spread
The aim of this tutorial is to demonstrate how to... |
3,179 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Train policy
The training of the policy will take around 1h on GPU.
Step1: Generate and review frames from policy | Python Code:
iteration_num=300
hparams = trainer_lib.create_hparams("ppo_atari_base", "epochs_num={}".format(iteration_num+1))
ppo_dir = tempfile.mkdtemp(dir=data_dir, prefix="ppo_")
rl_trainer_lib.train(hparams, "stacked_pong", ppo_dir)
agent_policy_path = os.path.join(ppo_dir, "model{}.ckpt.index".format(iteration_nu... |
3,180 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Python Clustering with Scikit-learn
(C) 2017-2019 by Damir Cavar
Download
Step1: To use the K-means clustering algorithm from Scikit-learn, we import it and specify the number of clusters (... | Python Code:
import numpy
X = numpy.array([[1, 2], [1, 4], [1, 0], [4, 2], [4, 4], [4, 0]])
Explanation: Python Clustering with Scikit-learn
(C) 2017-2019 by Damir Cavar
Download: This and various other Jupyter notebooks are available from my GitHub repo.
License: Creative Commons Attribution-ShareAlike 4.0 Internation... |
3,181 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
APS 8
Entrega
Step1: b)A partir do cálculo da cdf, sabe-se que a probabilidade de um aluno ser aprovado nessa disciplina é igual a 67,98%.
Dataset para as questões de programação
Vamos trab... | Python Code:
from scipy import stats
Prob = 1-(stats.norm.cdf(5,loc=5.5,scale=1.07))
Prob
Explanation: APS 8
Entrega: 28/11 ao final do atendimento (17:15)
Questão 1
Assuma que $X$ seja uma variável aleatória contínua que descreve o preço de um multímetro digital em uma loja brasileira qualquer. Ainda, assuma que o pre... |
3,182 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
================================================================
Compute sparse inverse solution with mixed norm
Step1: Run solver
Step2: Plot dipole activations
Step3: Plot residual
Step... | Python Code:
# Author: Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr>
# Daniel Strohmeier <daniel.strohmeier@tu-ilmenau.de>
#
# License: BSD (3-clause)
import numpy as np
import mne
from mne.datasets import sample
from mne.inverse_sparse import mixed_norm, make_stc_from_dipoles
from mne.minimum_no... |
3,183 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Basic tour of the Bayesian Optimization package
This is a constrained global optimization package built upon bayesian inference and gaussian process, that attempts to find the maximum... | Python Code:
def black_box_function(x, y):
Function with unknown internals we wish to maximize.
This is just serving as an example, for all intents and
purposes think of the internals of this function, i.e.: the process
which generates its output values, as unknown.
return -x ** 2 - (y - 1) ** ... |
3,184 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Graded =11/11
Homework #4
These problem sets focus on list comprehensions, string operations and regular expressions.
Problem set #1
Step1: In the following cell, complete the code with an ... | Python Code:
numbers_str = '496,258,332,550,506,699,7,985,171,581,436,804,736,528,65,855,68,279,721,120'
Explanation: Graded =11/11
Homework #4
These problem sets focus on list comprehensions, string operations and regular expressions.
Problem set #1: List slices and list comprehensions
Let's start with some data. The ... |
3,185 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
General pandas Concepts
Step1: Now we’ve covered numpy the basis for pandas. We’ve covered some of the more advanced python concepts like list comprehensions and lambda functions. Let’s jum... | Python Code:
import sys
print(sys.version)
import numpy as np
print(np.__version__)
import pandas as pd
print(pd.__version__)
Explanation: General pandas Concepts
End of explanation
pd.Index
Explanation: Now we’ve covered numpy the basis for pandas. We’ve covered some of the more advanced python concepts like list comp... |
3,186 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
NumPy 배열 생성과 변형
NumPy의 자료형
NumPy의 ndarray클래스는 포함하는 모든 데이터가 같은 자료형(data type)이어야 한다. 또한 자료형 자체도 일반 파이썬에서 제공하는 것보다 훨씬 세분화되어 있다.
NumPy의 자료형은 dtype 이라는 인수로 지정한다. dtype 인수로 지정할 값은 다음 표에 보인것과 같은 d... | Python Code:
x = np.array([1, 2, 3])
x.dtype
x = np.array([1, 2, 3])
x.dtype #2.7과 3버전의 차이인가?
Explanation: NumPy 배열 생성과 변형
NumPy의 자료형
NumPy의 ndarray클래스는 포함하는 모든 데이터가 같은 자료형(data type)이어야 한다. 또한 자료형 자체도 일반 파이썬에서 제공하는 것보다 훨씬 세분화되어 있다.
NumPy의 자료형은 dtype 이라는 인수로 지정한다. dtype 인수로 지정할 값은 다음 표에 보인것과 같은 dtype 접두사로 시작하는 문자열... |
3,187 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
How to use different extra sources such as CCSN neutrino-driven winds
Prepared by Christian Ritter
Step1: AGB and massive star tables used
Step2: Setup
Step3: Default setup
Step4: Setup ... | Python Code:
%matplotlib nbagg
import matplotlib.pyplot as plt
import sys
import matplotlib
import numpy as np
from NuPyCEE import sygma as s
from NuPyCEE import omega as o
from NuPyCEE import read_yields as ry
Explanation: How to use different extra sources such as CCSN neutrino-driven winds
Prepared by Christian Ritt... |
3,188 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
There are many specialized packages for dealing with data analysis and statistical programming. One very important code that you will see in MATH1024, Introduction to Probability and Statist... | Python Code:
!head southampton_precip.txt
Explanation: There are many specialized packages for dealing with data analysis and statistical programming. One very important code that you will see in MATH1024, Introduction to Probability and Statistics, is R. A Python package for performing similar analysis of large data s... |
3,189 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Overfitting
By Evgenia "Jenny" Nitishinskaya and Delaney Granizo-Mackenzie. Algorithms by David Edwards.
Part of the Quantopian Lecture Series
Step1: When working with real data, there is u... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import statsmodels.api as sm
from statsmodels import regression
from scipy import poly1d
x = np.arange(10)
y = 2*np.random.randn(10) + x**2
xs = np.linspace(-0.25, 9.25, 200)
lin = np.polyfit(x, y, 1)
quad = np.polyfit(x, y, 2)
many = n... |
3,190 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
let us avaluate a function of 3 variables on relatively large mesh
Step1: isolevel can be changed from Python side
Step2: to avoid recentering one can disable camera auto fit
Step3: one c... | Python Code:
T = 1.618033988749895
from numpy import sin,cos,pi
r = 4.77
zmin,zmax = -r,r
xmin,xmax = -r,r
ymin,ymax = -r,r
Nx,Ny,Nz = 80,80,80
x = np.linspace(xmin,xmax,Nx)
y = np.linspace(ymin,ymax,Ny)
z = np.linspace(zmin,zmax,Nz)
x,y,z = np.meshgrid(x,y,z,indexing='ij')
%time p = 2 - (cos(x + T*y) + cos(x - T*y) + ... |
3,191 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Dask Tutorial Notebook
<hr>
Notebook Description
This notebook serves as an introduction to Dask, which is a software library that allows us to scale analyses to large datasets. This noteboo... | Python Code:
import sys
import os
sys.path.append(os.environ.get('NOTEBOOK_ROOT'))
from utils.data_cube_utilities.dc_display_map import display_map
from utils.data_cube_utilities.dask import create_local_dask_cluster
from datacube.utils.aws import configure_s3_access
configure_s3_access(requester_pays=True)
import data... |
3,192 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Quantile regression
This example page shows how to use statsmodels' QuantReg class to replicate parts of the analysis published in
Koenker, Roger and Kevin F. Hallock. "Quantile Regression"... | Python Code:
%matplotlib inline
import numpy as np
import pandas as pd
import statsmodels.api as sm
import statsmodels.formula.api as smf
import matplotlib.pyplot as plt
data = sm.datasets.engel.load_pandas().data
data.head()
Explanation: Quantile regression
This example page shows how to use statsmodels' QuantReg clas... |
3,193 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
7 - Sample Data Inheritance - The Microstructure Class
This sixth Notebook will introduce you to
Step2: This file is zipped in the package to reduce its size. We will have to unzip it to us... | Python Code:
from config import PYMICRO_EXAMPLES_DATA_DIR # import file directory path
import os
dataset_file = os.path.join(PYMICRO_EXAMPLES_DATA_DIR, 'example_microstructure') # test dataset file path
tar_file = os.path.join(PYMICRO_EXAMPLES_DATA_DIR, 'example_microstructure.tar.gz') # dataset archive path
Explanatio... |
3,194 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
A Python Tour of Data Science
Step1: 3.1 Facebook
There is two ways to scrape data from Facebook, you can choose one or combine them.
1. The low-level approach, sending HTTP requests and re... | Python Code:
# Number of posts / tweets to retrieve.
# Small value for development, then increase to collect final data.
n = 4000 # 20
Explanation: A Python Tour of Data Science: Data Acquisition & Exploration
Michaël Defferrard, PhD student, EPFL LTS2
1 Exercise: problem definition
Theme of the exercise: understand t... |
3,195 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Salvar y cargar en archivos de disco
NumPy puede salvar y recuperar datos desde archivos de disco en varios formatos
Step1: Salvar los datos en un archivo de texto
Step2: Recuperar los dat... | Python Code:
import numpy as np
a = np.random.randn(10,4)
a
Explanation: Salvar y cargar en archivos de disco
NumPy puede salvar y recuperar datos desde archivos de disco en varios formatos
End of explanation
# Esta estructura del ejemplo ocupa 1022 bytes en disco
np.savetxt('datosRandom.txt',a)
Explanation: Salvar los... |
3,196 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<img src="AW&H2015.tiff" style="float
Step1: We want to explore drawdown as a function of time
So, set up an array of times to evaluate, and loop over them. Also, we can specify a distance ... | Python Code:
# Problem 3.4, page 107 Anderson, Woessner and Hunt (2015)
# import Python libraries/functionality for use in this notebook
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
import scipy.special
import sys, os
from mpl_toolkits.axes_grid1 import make_axes_locatable
# return current work... |
3,197 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Language Translation
In this project, you’re going to take a peek into the realm of neural network machine translation. You’ll be training a sequence to sequence model on a dataset o... | Python Code:
DON'T MODIFY ANYTHING IN THIS CELL
import helper
import problem_unittests as tests
source_path = 'data/small_vocab_en'
target_path = 'data/small_vocab_fr'
source_text = helper.load_data(source_path)
target_text = helper.load_data(target_path)
Explanation: Language Translation
In this project, you’re going ... |
3,198 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Outputting a movie
In this brief example, we show how to create a movie of a seismic shot with SeisCL
Step1: We first create a constant velocity model, with one source in the middle
Step2: ... | Python Code:
%matplotlib inline
from SeisCL import SeisCL
import matplotlib.pyplot as plt
import numpy as np
Explanation: Outputting a movie
In this brief example, we show how to create a movie of a seismic shot with SeisCL
End of explanation
seis = SeisCL()
# Constants for the modeling
seis.ND = 2
N = 200
seis.N = np.... |
3,199 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Reading an NCEP BUFR data set
NCEP BUFR (Binary Universal Form for the Representation of meteorological data) can be read two ways
Step1: For the purposes of this demo I've made a local cop... | Python Code:
import matplotlib.pyplot as plt # graphics library
import numpy as np
import ncepbufr # python wrappers around BUFRLIB
Explanation: Reading an NCEP BUFR data set
NCEP BUFR (Binary Universal Form for the Representation of meteorological data) can be read two ways:
Fortran code with BUF... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.