markdown stringlengths 0 37k | code stringlengths 1 33.3k | path stringlengths 8 215 | repo_name stringlengths 6 77 | license stringclasses 15
values |
|---|---|---|---|---|
Nicely formatted results
IPython notebooks allow you to display nicely formatted results, such as plots and tables, directly in
the notebook. You'll learn how to use the following libraries later on in this course, but for now here's a
preview of what IPython notebook can do. | # If you run this cell, you should see the values displayed as a table.
# Pandas is a software library for data manipulation and analysis. You'll learn to use it later in this course.
import pandas as pd
df = pd.DataFrame({'a': [2, 4, 6, 8], 'b': [1, 3, 5, 7]})
df
# If you run this cell, you should see a scatter plo... | ipython_notebook_tutorial.ipynb | tsavo-sevenoaks/garth | gpl-3.0 |
Creating cells
To create a new code cell, click "Insert > Insert Cell [Above or Below]". A code cell will automatically be created.
To create a new markdown cell, first follow the process above to create a code cell, then change the type from "Code" to "Markdown" using the dropdown next to the run, stop, and restart bu... | class_name = "BRUCE Woodley Intro to Data Analysis"
message = class_name + " is awesome!"
message | ipython_notebook_tutorial.ipynb | tsavo-sevenoaks/garth | gpl-3.0 |
Once you've run all three cells, try modifying the first one to set class_name to your name, rather than "Intro to Data Analysis", so you can print that you are awesome. Then rerun the first and third cells without rerunning the second.
You should have seen that the third cell still printed "Intro to Data Analysis is ... | import unicodecsv
with open("enrollments.csv","rb") as filein :
line = unicodecsv.DictReader(filein)
print("type(line) \t",type(line))
enrollments = list(line)
print enrollments[0]
import unicodecsv
with open("daily_engagement.csv","rb") as filein :
line = unicodecsv.DictReader(filein)
... | ipython_notebook_tutorial.ipynb | tsavo-sevenoaks/garth | gpl-3.0 |
Fixing Data Types. | # Fixing Data Types.
# Hit shift + enter or use the run button to run this cell and see the results
from datetime import datetime as dt
# Takes a date as a string, and returns a Python datetime object.
# If there is no date given, returns None
def parse_date(date):
if date == '':
return None
else:
... | ipython_notebook_tutorial.ipynb | tsavo-sevenoaks/garth | gpl-3.0 |
Line with Gaussian noise
Write a function named random_line that creates x and y data for a line with y direction random noise that has a normal distribution $N(0,\sigma^2)$:
$$
y = m x + b + N(0,\sigma^2)
$$
Be careful about the sigma=0.0 case. | def random_line(m, b, sigma, size=10):
"""Create a line y = m*x + b + N(0,sigma**2) between x=[-1.0,1.0]
Parameters
----------
m : float
The slope of the line.
b : float
The y-intercept of the line.
sigma : float
The standard deviation of the y direction normal distr... | assignments/assignment05/InteractEx04.ipynb | SJSlavin/phys202-2015-work | mit |
Write a function named plot_random_line that takes the same arguments as random_line and creates a random line using random_line and then plots the x and y points using Matplotlib's scatter function:
Make the marker color settable through a color keyword argument with a default of red.
Display the range $x=[-1.1,1.1]$... | def ticks_out(ax):
"""Move the ticks to the outside of the box."""
ax.get_xaxis().set_tick_params(direction='out', width=1, which='both')
ax.get_yaxis().set_tick_params(direction='out', width=1, which='both')
def plot_random_line(m, b, sigma, size=10, color='red'):
"""Plot a random line with slope m, i... | assignments/assignment05/InteractEx04.ipynb | SJSlavin/phys202-2015-work | mit |
Use interact to explore the plot_random_line function using:
m: a float valued slider from -10.0 to 10.0 with steps of 0.1.
b: a float valued slider from -5.0 to 5.0 with steps of 0.1.
sigma: a float valued slider from 0.0 to 5.0 with steps of 0.01.
size: an int valued slider from 10 to 100 with steps of 10.
color: a ... | # YOUR CODE HERE
interact(plot_random_line, m=(-10.0, 10.0, 0.1), b=(-5.0, 5.0, 0.1), sigma = (0.0, 5.0, 0.01), size = (10, 100, 10), color = ["green", "red", "blue"])
#### assert True # use this cell to grade the plot_random_line interact | assignments/assignment05/InteractEx04.ipynb | SJSlavin/phys202-2015-work | mit |
Supongamos que esta curva representa a una función cuyo máximo buscamos, y supongamos que el eje x representa parámetros de los que la función depende. | x = np.linspace(0,50,500)
y = np.sin(x) * np.sin(x/17)
plt.figure(None, figsize=(10,5))
plt.ylim(-1.1, 1.1)
plt.plot(x,y) | Teoria III - Exploracion-Explotacion.ipynb | AeroPython/Taller-PyConEs-2015 | mit |
Supongamos que con un algoritmo hemos encontrado un punto alto, pero que corresponde a un óptimo local, por ejemplo: | plt.figure(None, figsize=(10,5))
plt.ylim(-1.1, 1.1)
plt.plot(x,y)
plt.plot([21,21],[0,1],'r--')
plt.plot(21, 0.75, 'ko') | Teoria III - Exploracion-Explotacion.ipynb | AeroPython/Taller-PyConEs-2015 | mit |
El dilema Exploración-Explotación hace referencia a a dos fuerzas contrapuestas que necesitamos equilibrar cuidadosamente cuando usemos estos tipos de algoritmos.
La Exploración se refiere a buscar soluciones alejadas de lo que tenemos, abrir nuestro abanico de búsqueda.
Nos permite escapar de máximos locales y encont... | # EJEMPLO DE RESULTADO CON DEMASIADA EXPLORACIÓN: NO SE ENCUENTRA NADA
x2 = np.array([7,8,12,28,31,35,40,49])
y2 = np.sin(x2) * np.sin(x2/17)
plt.figure(None, figsize=(10,5))
plt.ylim(-1.1, 1.1)
plt.plot(x,y)
plt.plot([21,21],[0,1],'r--')
plt.plot(21, 0.75, 'ko')
plt.plot(x2, y2, 'go')
# EJEMPLO DE RESULTADO CO... | Teoria III - Exploracion-Explotacion.ipynb | AeroPython/Taller-PyConEs-2015 | mit |
Este tipo de estrategias se modulan mediante todos los parámetros de los algoritmos, pero quizás el parámetro que más claramente influye en este equilibrio es el de la mutación en los algoritmos genéticos: Reduciendo el índice de mutación potenciaremos la explotación, mientras que si lo aumentamos, potenciamos la explo... | #Usaremos el paquete en el ejercicio del laberinto
import Ejercicios.Laberinto.laberinto.laberinto as lab
ag = lab.ag | Teoria III - Exploracion-Explotacion.ipynb | AeroPython/Taller-PyConEs-2015 | mit |
Supongamos que tenemos el siguiente laberinto, al que accedemos por la izquierda y que queremos resolver: | mapa1 = lab.Map()
mapa1.draw_tablero() | Teoria III - Exploracion-Explotacion.ipynb | AeroPython/Taller-PyConEs-2015 | mit |
En el ejercicio se detalla más el proceso, llamemos aquí simplemente al algoritmo genético que lo resuelve: | mapa1 = lab.Map()
lab.avanzar(mapa1)
lab.draw_all(mapa1) | Teoria III - Exploracion-Explotacion.ipynb | AeroPython/Taller-PyConEs-2015 | mit |
Lo más probable es que hayas obtenido una solución o un camino cerrado en un bucle. Puedes ejecutar la celda superior varias veces para hecerte una idea aproximada de con qué frecuencia aparece cada situación. Pero, ¿por qué aparecen estos bucles?
Examinemos qué aspecto tiene una solución:
Cada casilla contiene una fle... | mapa1.list_caminos[0].draw_directions()
mapa1.list_caminos[0].draw_path(0.7) | Teoria III - Exploracion-Explotacion.ipynb | AeroPython/Taller-PyConEs-2015 | mit |
La respuesta a por qué se forman bucles está en cómo se define la función de fitness o puntuación de cada camino:
Se recorren 50 casillas, intentando seguir el camino que determinan las flechas
Cada vez que se choca con una pared, o que se vuelve a la casilla anterior (por ejemplo, si dos flechas se apuntan mutuamente... | mapa1 = lab.Map(veneno=1)
lab.avanzar(mapa1)
lab.draw_all(mapa1) | Teoria III - Exploracion-Explotacion.ipynb | AeroPython/Taller-PyConEs-2015 | mit |
Prueba e ejecutarlo varias veces. ¿Notas si ha cambiado la cantidad de bucles?
Por último, veamos que ocurre si potenciamos la exploración demasiado: | mapa1 = lab.Map(veneno=100)
lab.avanzar(mapa1)
lab.draw_all(mapa1) | Teoria III - Exploracion-Explotacion.ipynb | AeroPython/Taller-PyConEs-2015 | mit |
MaxPooling1D
[pooling.MaxPooling1D.0] input 6x6, pool_size=2, strides=None, padding='valid' | data_in_shape = (6, 6)
L = MaxPooling1D(pool_size=2, strides=None, padding='valid')
layer_0 = Input(shape=data_in_shape)
layer_1 = L(layer_0)
model = Model(inputs=layer_0, outputs=layer_1)
# set weights to random (use seed for reproducibility)
np.random.seed(250)
data_in = 2 * np.random.random(data_in_shape) - 1
resu... | notebooks/layers/pooling/MaxPooling1D.ipynb | transcranial/keras-js | mit |
[pooling.MaxPooling1D.1] input 6x6, pool_size=2, strides=1, padding='valid' | data_in_shape = (6, 6)
L = MaxPooling1D(pool_size=2, strides=1, padding='valid')
layer_0 = Input(shape=data_in_shape)
layer_1 = L(layer_0)
model = Model(inputs=layer_0, outputs=layer_1)
# set weights to random (use seed for reproducibility)
np.random.seed(251)
data_in = 2 * np.random.random(data_in_shape) - 1
result ... | notebooks/layers/pooling/MaxPooling1D.ipynb | transcranial/keras-js | mit |
[pooling.MaxPooling1D.2] input 6x6, pool_size=2, strides=3, padding='valid' | data_in_shape = (6, 6)
L = MaxPooling1D(pool_size=2, strides=3, padding='valid')
layer_0 = Input(shape=data_in_shape)
layer_1 = L(layer_0)
model = Model(inputs=layer_0, outputs=layer_1)
# set weights to random (use seed for reproducibility)
np.random.seed(252)
data_in = 2 * np.random.random(data_in_shape) - 1
result ... | notebooks/layers/pooling/MaxPooling1D.ipynb | transcranial/keras-js | mit |
[pooling.MaxPooling1D.3] input 6x6, pool_size=2, strides=None, padding='same' | data_in_shape = (6, 6)
L = MaxPooling1D(pool_size=2, strides=None, padding='same')
layer_0 = Input(shape=data_in_shape)
layer_1 = L(layer_0)
model = Model(inputs=layer_0, outputs=layer_1)
# set weights to random (use seed for reproducibility)
np.random.seed(253)
data_in = 2 * np.random.random(data_in_shape) - 1
resul... | notebooks/layers/pooling/MaxPooling1D.ipynb | transcranial/keras-js | mit |
[pooling.MaxPooling1D.4] input 6x6, pool_size=2, strides=1, padding='same' | data_in_shape = (6, 6)
L = MaxPooling1D(pool_size=2, strides=1, padding='same')
layer_0 = Input(shape=data_in_shape)
layer_1 = L(layer_0)
model = Model(inputs=layer_0, outputs=layer_1)
# set weights to random (use seed for reproducibility)
np.random.seed(254)
data_in = 2 * np.random.random(data_in_shape) - 1
result =... | notebooks/layers/pooling/MaxPooling1D.ipynb | transcranial/keras-js | mit |
[pooling.MaxPooling1D.5] input 6x6, pool_size=2, strides=3, padding='same' | data_in_shape = (6, 6)
L = MaxPooling1D(pool_size=2, strides=3, padding='same')
layer_0 = Input(shape=data_in_shape)
layer_1 = L(layer_0)
model = Model(inputs=layer_0, outputs=layer_1)
# set weights to random (use seed for reproducibility)
np.random.seed(255)
data_in = 2 * np.random.random(data_in_shape) - 1
result =... | notebooks/layers/pooling/MaxPooling1D.ipynb | transcranial/keras-js | mit |
[pooling.MaxPooling1D.6] input 6x6, pool_size=3, strides=None, padding='valid' | data_in_shape = (6, 6)
L = MaxPooling1D(pool_size=3, strides=None, padding='valid')
layer_0 = Input(shape=data_in_shape)
layer_1 = L(layer_0)
model = Model(inputs=layer_0, outputs=layer_1)
# set weights to random (use seed for reproducibility)
np.random.seed(256)
data_in = 2 * np.random.random(data_in_shape) - 1
resu... | notebooks/layers/pooling/MaxPooling1D.ipynb | transcranial/keras-js | mit |
[pooling.MaxPooling1D.7] input 7x7, pool_size=3, strides=1, padding='same' | data_in_shape = (7, 7)
L = MaxPooling1D(pool_size=3, strides=1, padding='same')
layer_0 = Input(shape=data_in_shape)
layer_1 = L(layer_0)
model = Model(inputs=layer_0, outputs=layer_1)
# set weights to random (use seed for reproducibility)
np.random.seed(257)
data_in = 2 * np.random.random(data_in_shape) - 1
result =... | notebooks/layers/pooling/MaxPooling1D.ipynb | transcranial/keras-js | mit |
[pooling.MaxPooling1D.8] input 7x7, pool_size=3, strides=3, padding='same' | data_in_shape = (7, 7)
L = MaxPooling1D(pool_size=3, strides=3, padding='same')
layer_0 = Input(shape=data_in_shape)
layer_1 = L(layer_0)
model = Model(inputs=layer_0, outputs=layer_1)
# set weights to random (use seed for reproducibility)
np.random.seed(258)
data_in = 2 * np.random.random(data_in_shape) - 1
result =... | notebooks/layers/pooling/MaxPooling1D.ipynb | transcranial/keras-js | mit |
export for Keras.js tests | import os
filename = '../../../test/data/layers/pooling/MaxPooling1D.json'
if not os.path.exists(os.path.dirname(filename)):
os.makedirs(os.path.dirname(filename))
with open(filename, 'w') as f:
json.dump(DATA, f)
print(json.dumps(DATA)) | notebooks/layers/pooling/MaxPooling1D.ipynb | transcranial/keras-js | mit |
Step 0 - hyperparams
vocab_size is all the potential words you could have (classification for translation case)
and max sequence length are the SAME thing
decoder RNN hidden units are usually same size as encoder RNN hidden units in translation but for our case it does not seem really to be a relationship there but we ... | input_len = 60
target_len = 30
batch_size = 50
with_EOS = False
csv_in = '../price_history_03_seq_start_suddens_trimmed.csv' | 04_time_series_prediction/.ipynb_checkpoints/30_price_history_dataset_per_mobile_phone-arima-checkpoint.ipynb | pligor/predicting-future-product-prices | agpl-3.0 |
Actual Run | data_path = '../../../../Dropbox/data'
ph_data_path = data_path + '/price_history'
assert path.isdir(ph_data_path)
npz_full = ph_data_path + '/price_history_per_mobile_phone.npz'
#dataset_gen = PriceHistoryDatasetPerMobilePhone(random_state=random_state)
dic = np.load(npz_full)
dic.keys()[:10] | 04_time_series_prediction/.ipynb_checkpoints/30_price_history_dataset_per_mobile_phone-arima-checkpoint.ipynb | pligor/predicting-future-product-prices | agpl-3.0 |
Arima | parameters = OrderedDict([
('p_auto_regression_order', range(6)), #0-5
('d_integration_level', range(3)), #0-2
('q_moving_average', range(6)), #0-5
])
cart = cartesian_coord(*parameters.values())
cart.shape
cur_key = dic.keys()[0]
cur_key
cur_sku = dic[cur_key][()]
cur_sku.keys()
train_mat = cur_sku['tr... | 04_time_series_prediction/.ipynb_checkpoints/30_price_history_dataset_per_mobile_phone-arima-checkpoint.ipynb | pligor/predicting-future-product-prices | agpl-3.0 |
Testing with easy mode on | %%time
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
ae = ArimaEstimator(p_auto_regression_order=best_params[0],
d_integration_level=best_params[1],
q_moving_average=best_params[2],
easy_mode=True)
score = ae.fit(tes... | 04_time_series_prediction/.ipynb_checkpoints/30_price_history_dataset_per_mobile_phone-arima-checkpoint.ipynb | pligor/predicting-future-product-prices | agpl-3.0 |
Testing with easy mode off | %%time
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
ae = ArimaEstimator(p_auto_regression_order=best_params[0],
d_integration_level=best_params[1],
q_moving_average=best_params[2],
easy_mode=False)
score = ae.fit(te... | 04_time_series_prediction/.ipynb_checkpoints/30_price_history_dataset_per_mobile_phone-arima-checkpoint.ipynb | pligor/predicting-future-product-prices | agpl-3.0 |
Conclusion
If you are training in easy mode then what you get at the end is that the model only cares for the previous value in order to do its predictions and this makes it much easier for everybody but in reality we might not have advantage
Trying | args = np.argsort(filtered_arr[:, 1])
args
filtered_arr[args[:10], 0]
%%time
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
ae = ArimaEstimator(p_auto_regression_order=4,
d_integration_level=1,
q_moving_average=3,
easy_... | 04_time_series_prediction/.ipynb_checkpoints/30_price_history_dataset_per_mobile_phone-arima-checkpoint.ipynb | pligor/predicting-future-product-prices | agpl-3.0 |
All tests | from arima.arima_testing import ArimaTesting
best_params, target_len, npz_full
%%time
keys, scores, preds = ArimaTesting.full_testing(best_params=best_params, target_len=target_len,
npz_full=npz_full)
# render graphs here
score_arr = np.array(scores)
np.mean(scor... | 04_time_series_prediction/.ipynb_checkpoints/30_price_history_dataset_per_mobile_phone-arima-checkpoint.ipynb | pligor/predicting-future-product-prices | agpl-3.0 |
Test on Mock | main('/path/to/data/directory', 10000) | notebooks/Bootstrap_Analysis.ipynb | cavestruz/StrongCNN | mit |
Test on SLACS | main('/path/to/data/directory', 10000) | notebooks/Bootstrap_Analysis.ipynb | cavestruz/StrongCNN | mit |
Test on SLACS separating out different bands | main('/path/to/data/directory', 10000, bands=['435', '814']) | notebooks/Bootstrap_Analysis.ipynb | cavestruz/StrongCNN | mit |
Below I'm plotting an example image from the MNIST dataset. These are 28x28 grayscale images of handwritten digits. | img = mnist.train.images[2]
plt.imshow(img.reshape((28, 28)), cmap='Greys_r') | autoencoder/Simple_Autoencoder_Solution.ipynb | Lstyle1/Deep_learning_projects | mit |
We'll train an autoencoder with these images by flattening them into 784 length vectors. The images from this dataset are already normalized such that the values are between 0 and 1. Let's start by building basically the simplest autoencoder with a single ReLU hidden layer. This layer will be used as the compressed rep... | # Size of the encoding layer (the hidden layer)
encoding_dim = 32
image_size = mnist.train.images.shape[1]
inputs_ = tf.placeholder(tf.float32, (None, image_size), name='inputs')
targets_ = tf.placeholder(tf.float32, (None, image_size), name='targets')
# Output of hidden layer
encoded = tf.layers.dense(inputs_, enco... | autoencoder/Simple_Autoencoder_Solution.ipynb | Lstyle1/Deep_learning_projects | mit |
Training | # Create the session
sess = tf.Session() | autoencoder/Simple_Autoencoder_Solution.ipynb | Lstyle1/Deep_learning_projects | mit |
Here I'll write a bit of code to train the network. I'm not too interested in validation here, so I'll just monitor the training loss and the test loss afterwards.
Calling mnist.train.next_batch(batch_size) will return a tuple of (images, labels). We're not concerned with the labels here, we just need the images. Othe... | epochs = 20
batch_size = 200
sess.run(tf.global_variables_initializer())
for e in range(epochs):
for ii in range(mnist.train.num_examples//batch_size):
batch = mnist.train.next_batch(batch_size)
feed = {inputs_: batch[0], targets_: batch[0]}
batch_cost, _ = sess.run([cost, opt], feed_dict=fe... | autoencoder/Simple_Autoencoder_Solution.ipynb | Lstyle1/Deep_learning_projects | mit |
Checking out the results
Below I've plotted some of the test images along with their reconstructions. For the most part these look pretty good except for some blurriness in some parts. | fig, axes = plt.subplots(nrows=2, ncols=10, sharex=True, sharey=True, figsize=(20,4))
in_imgs = mnist.test.images[:10]
reconstructed, compressed = sess.run([decoded, encoded], feed_dict={inputs_: in_imgs})
for images, row in zip([in_imgs, reconstructed], axes):
for img, ax in zip(images, row):
ax.imshow(im... | autoencoder/Simple_Autoencoder_Solution.ipynb | Lstyle1/Deep_learning_projects | mit |
Question 2: WHERE Statements
Write a Python function get_coeffs that returns an array of 7 coefficients.
The function should take in two parameters: 1.) species_name and 2.) temp_range, an indicator variable ('low' or 'high') to indicate whether the coefficients should come from the low or high temperature range.
... | def get_coeffs(species_name, temp_range):
if temp_range=="low":
function = '''SELECT coeff_1,coeff_2,coeff_3,coeff_4,coeff_5,coeff_6,coeff_7 FROM low WHERE species_name=?'''
coeffs=cursor.execute(function,(species_name)).fetchone()
else:
function = '''SELECT coeff_1,coeff_2,coeff_3,co... | homeworks/HW10/HW10.ipynb | crystalzhaizhai/cs207_yi_zhai | mit |
Question 3: JOIN STATEMENTS
Create a table named ALL_TEMPS that has the following columns:
SPECIES_NAME
TEMP_LOW
TEMP_HIGH
This table should be created by joining the tables LOW and HIGH on the value SPECIES_NAME.
Write a Python function get_range that returns the range of temperatures for a given species_name.
The... | def get_range(species_name):
function = '''SELECT tlow FROM low WHERE species_name=?'''
temp_low=cursor.execute(function, (species_name,)).fetchall()[0]
function = '''SELECT thigh FROM high WHERE species_name=?'''
temp_high=cursor.execute(function,(species_name,)).fetchall()[0]
return (temp_lo... | homeworks/HW10/HW10.ipynb | crystalzhaizhai/cs207_yi_zhai | mit |
Load amazon review dataset | products = graphlab.SFrame('amazon_baby.gl/') | ml-classification/week-6/module-9-precision-recall-assignment-blank.ipynb | zomansud/coursera | mit |
Extract word counts and sentiments
As in the first assignment of this course, we compute the word counts for individual words and extract positive and negative sentiments from ratings. To summarize, we perform the following:
Remove punctuation.
Remove reviews with "neutral" sentiment (rating 3).
Set reviews with ratin... | def remove_punctuation(text):
import string
return text.translate(None, string.punctuation)
# Remove punctuation.
review_clean = products['review'].apply(remove_punctuation)
# Count words
products['word_count'] = graphlab.text_analytics.count_words(review_clean)
# Drop neutral sentiment reviews.
products = ... | ml-classification/week-6/module-9-precision-recall-assignment-blank.ipynb | zomansud/coursera | mit |
Now, let's remember what the dataset looks like by taking a quick peek: | products | ml-classification/week-6/module-9-precision-recall-assignment-blank.ipynb | zomansud/coursera | mit |
Split data into training and test sets
We split the data into a 80-20 split where 80% is in the training set and 20% is in the test set. | train_data, test_data = products.random_split(.8, seed=1) | ml-classification/week-6/module-9-precision-recall-assignment-blank.ipynb | zomansud/coursera | mit |
Train a logistic regression classifier
We will now train a logistic regression classifier with sentiment as the target and word_count as the features. We will set validation_set=None to make sure everyone gets exactly the same results.
Remember, even though we now know how to implement logistic regression, we will us... | model = graphlab.logistic_classifier.create(train_data, target='sentiment',
features=['word_count'],
validation_set=None) | ml-classification/week-6/module-9-precision-recall-assignment-blank.ipynb | zomansud/coursera | mit |
Model Evaluation
We will explore the advanced model evaluation concepts that were discussed in the lectures.
Accuracy
One performance metric we will use for our more advanced exploration is accuracy, which we have seen many times in past assignments. Recall that the accuracy is given by
$$
\mbox{accuracy} = \frac{\mbo... | accuracy= model.evaluate(test_data, metric='accuracy')['accuracy']
print "Test Accuracy: %s" % accuracy | ml-classification/week-6/module-9-precision-recall-assignment-blank.ipynb | zomansud/coursera | mit |
Baseline: Majority class prediction
Recall from an earlier assignment that we used the majority class classifier as a baseline (i.e reference) model for a point of comparison with a more sophisticated classifier. The majority classifier model predicts the majority class for all data points.
Typically, a good model sho... | baseline = len(test_data[test_data['sentiment'] == 1])/len(test_data)
print "Baseline accuracy (majority class classifier): %s" % baseline | ml-classification/week-6/module-9-precision-recall-assignment-blank.ipynb | zomansud/coursera | mit |
Quiz Question: Using accuracy as the evaluation metric, was our logistic regression model better than the baseline (majority class classifier)?
Confusion Matrix
The accuracy, while convenient, does not tell the whole story. For a fuller picture, we turn to the confusion matrix. In the case of binary classification, the... | confusion_matrix = model.evaluate(test_data, metric='confusion_matrix')['confusion_matrix']
confusion_matrix | ml-classification/week-6/module-9-precision-recall-assignment-blank.ipynb | zomansud/coursera | mit |
Quiz Question: How many predicted values in the test set are false positives? | round(1443 / (26689 + 1443 ), 2) | ml-classification/week-6/module-9-precision-recall-assignment-blank.ipynb | zomansud/coursera | mit |
Computing the cost of mistakes
Put yourself in the shoes of a manufacturer that sells a baby product on Amazon.com and you want to monitor your product's reviews in order to respond to complaints. Even a few negative reviews may generate a lot of bad publicity about the product. So you don't want to miss any reviews w... | 100*1443 + 1*1406 | ml-classification/week-6/module-9-precision-recall-assignment-blank.ipynb | zomansud/coursera | mit |
Precision and Recall
You may not have exact dollar amounts for each kind of mistake. Instead, you may simply prefer to reduce the percentage of false positives to be less than, say, 3.5% of all positive predictions. This is where precision comes in:
$$
[\text{precision}] = \frac{[\text{# positive data points with posit... | precision = model.evaluate(test_data, metric='precision')['precision']
print "Precision on test data: %s" % precision | ml-classification/week-6/module-9-precision-recall-assignment-blank.ipynb | zomansud/coursera | mit |
Quiz Question: Out of all reviews in the test set that are predicted to be positive, what fraction of them are false positives? (Round to the second decimal place e.g. 0.25) | round(1 - precision, 2) | ml-classification/week-6/module-9-precision-recall-assignment-blank.ipynb | zomansud/coursera | mit |
Quiz Question: Based on what we learned in lecture, if we wanted to reduce this fraction of false positives to be below 3.5%, we would: (see the quiz)
A complementary metric is recall, which measures the ratio between the number of true positives and that of (ground-truth) positive reviews:
$$
[\text{recall}] = \frac{[... | recall = model.evaluate(test_data, metric='recall')['recall']
print "Recall on test data: %s" % recall | ml-classification/week-6/module-9-precision-recall-assignment-blank.ipynb | zomansud/coursera | mit |
Quiz Question: What fraction of the positive reviews in the test_set were correctly predicted as positive by the classifier?
Quiz Question: What is the recall value for a classifier that predicts +1 for all data points in the test_data?
Precision-recall tradeoff
In this part, we will explore the trade-off between preci... | def apply_threshold(probabilities, threshold):
### YOUR CODE GOES HERE
# +1 if >= threshold and -1 otherwise.
return probabilities.apply(lambda x: +1 if x >= threshold else -1) | ml-classification/week-6/module-9-precision-recall-assignment-blank.ipynb | zomansud/coursera | mit |
Run prediction with output_type='probability' to get the list of probability values. Then use thresholds set at 0.5 (default) and 0.9 to make predictions from these probability values. | probabilities = model.predict(test_data, output_type='probability')
predictions_with_default_threshold = apply_threshold(probabilities, 0.5)
predictions_with_high_threshold = apply_threshold(probabilities, 0.9)
print "Number of positive predicted reviews (threshold = 0.5): %s" % (predictions_with_default_threshold == ... | ml-classification/week-6/module-9-precision-recall-assignment-blank.ipynb | zomansud/coursera | mit |
Quiz Question: What happens to the number of positive predicted reviews as the threshold increased from 0.5 to 0.9?
Exploring the associated precision and recall as the threshold varies
By changing the probability threshold, it is possible to influence precision and recall. We can explore this as follows: | # Threshold = 0.5
precision_with_default_threshold = graphlab.evaluation.precision(test_data['sentiment'],
predictions_with_default_threshold)
recall_with_default_threshold = graphlab.evaluation.recall(test_data['sentiment'],
predictions_w... | ml-classification/week-6/module-9-precision-recall-assignment-blank.ipynb | zomansud/coursera | mit |
Quiz Question (variant 1): Does the precision increase with a higher threshold?
Quiz Question (variant 2): Does the recall increase with a higher threshold?
Precision-recall curve
Now, we will explore various different values of tresholds, compute the precision and recall scores, and then plot the precision-recall curv... | threshold_values = np.linspace(0.5, 1, num=100)
print threshold_values | ml-classification/week-6/module-9-precision-recall-assignment-blank.ipynb | zomansud/coursera | mit |
For each of the values of threshold, we compute the precision and recall scores. | precision_all = []
recall_all = []
probabilities = model.predict(test_data, output_type='probability')
for threshold in threshold_values:
predictions = apply_threshold(probabilities, threshold)
precision = graphlab.evaluation.precision(test_data['sentiment'], predictions)
recall = graphlab.evaluation.... | ml-classification/week-6/module-9-precision-recall-assignment-blank.ipynb | zomansud/coursera | mit |
Now, let's plot the precision-recall curve to visualize the precision-recall tradeoff as we vary the threshold. | import matplotlib.pyplot as plt
%matplotlib inline
def plot_pr_curve(precision, recall, title):
plt.rcParams['figure.figsize'] = 7, 5
plt.locator_params(axis = 'x', nbins = 5)
plt.plot(precision, recall, 'b-', linewidth=4.0, color = '#B0017F')
plt.title(title)
plt.xlabel('Precision')
plt.ylabel... | ml-classification/week-6/module-9-precision-recall-assignment-blank.ipynb | zomansud/coursera | mit |
Quiz Question: Among all the threshold values tried, what is the smallest threshold value that achieves a precision of 96.5% or better? Round your answer to 3 decimal places. | for i, p in enumerate(precision_all):
print str(i) + " -> " + str(p)
round(threshold_values[67], 3) | ml-classification/week-6/module-9-precision-recall-assignment-blank.ipynb | zomansud/coursera | mit |
Quiz Question: Using threshold = 0.98, how many false negatives do we get on the test_data? (Hint: You may use the graphlab.evaluation.confusion_matrix function implemented in GraphLab Create.) | predictions_with_98_threshold = apply_threshold(probabilities, 0.98)
cm = graphlab.evaluation.confusion_matrix(test_data['sentiment'],
predictions_with_98_threshold)
cm | ml-classification/week-6/module-9-precision-recall-assignment-blank.ipynb | zomansud/coursera | mit |
This is the number of false negatives (i.e the number of reviews to look at when not needed) that we have to deal with using this classifier.
Evaluating specific search terms
So far, we looked at the number of false positives for the entire test set. In this section, let's select reviews using a specific search term an... | baby_reviews = test_data[test_data['name'].apply(lambda x: 'baby' in x.lower())] | ml-classification/week-6/module-9-precision-recall-assignment-blank.ipynb | zomansud/coursera | mit |
Now, let's predict the probability of classifying these reviews as positive: | probabilities = model.predict(baby_reviews, output_type='probability') | ml-classification/week-6/module-9-precision-recall-assignment-blank.ipynb | zomansud/coursera | mit |
Let's plot the precision-recall curve for the baby_reviews dataset.
First, let's consider the following threshold_values ranging from 0.5 to 1: | threshold_values = np.linspace(0.5, 1, num=100) | ml-classification/week-6/module-9-precision-recall-assignment-blank.ipynb | zomansud/coursera | mit |
Second, as we did above, let's compute precision and recall for each value in threshold_values on the baby_reviews dataset. Complete the code block below. | precision_all = []
recall_all = []
for threshold in threshold_values:
# Make predictions. Use the `apply_threshold` function
## YOUR CODE HERE
predictions = apply_threshold(probabilities, threshold)
# Calculate the precision.
# YOUR CODE HERE
precision = graphlab.evaluation.precision(ba... | ml-classification/week-6/module-9-precision-recall-assignment-blank.ipynb | zomansud/coursera | mit |
Quiz Question: Among all the threshold values tried, what is the smallest threshold value that achieves a precision of 96.5% or better for the reviews of data in baby_reviews? Round your answer to 3 decimal places. | round(threshold_values[72], 3)
for i, p in enumerate(precision_all):
print str(i) + " -> " + str(p) | ml-classification/week-6/module-9-precision-recall-assignment-blank.ipynb | zomansud/coursera | mit |
Quiz Question: Is this threshold value smaller or larger than the threshold used for the entire dataset to achieve the same specified precision of 96.5%?
Finally, let's plot the precision recall curve. | plot_pr_curve(precision_all, recall_all, "Precision-Recall (Baby)") | ml-classification/week-6/module-9-precision-recall-assignment-blank.ipynb | zomansud/coursera | mit |
Now we define the domain of the function to optimize as usual. | mixed_domain =[{'name': 'var1', 'type': 'continuous', 'domain': (-5,5),'dimensionality': 3},
{'name': 'var2', 'type': 'discrete', 'domain': (3,8,10)},
{'name': 'var3', 'type': 'categorical', 'domain': (0,1,2)},
{'name': 'var4', 'type': 'continuous', 'domain': (-1,2)}]
myBop... | manual/GPyOpt_context.ipynb | SheffieldML/GPyOpt | bsd-3-clause |
Now, we run the optimization for 20 iterations or a maximum of 60 seconds and we show the convergence plots. | max_iter = 2 ## maximum number of iterations
max_time = 60 ## maximum allowed time
eps = 0 ## tolerance, max distance between consicutive evaluations. | manual/GPyOpt_context.ipynb | SheffieldML/GPyOpt | bsd-3-clause |
To set a context, we just need to create a dicctionary with the variables to fix and pass it to the Bayesian ottimization object when running the optimization. Note that, everytime we run new iterations we can set other variables to be the context. Note that for variables in which the dimaensionality has been specified... | myBopt.run_optimization(max_iter,eps=eps)
myBopt.run_optimization(max_iter,eps=eps,context = {'var1_1':.3, 'var1_2':0.4})
myBopt.run_optimization(max_iter,eps=eps,context = {'var1_1':0, 'var3':2})
myBopt.run_optimization(max_iter,eps=eps,context = {'var1_1':0, 'var2':3},)
myBopt.run_optimization(max_iter,eps=eps,contex... | manual/GPyOpt_context.ipynb | SheffieldML/GPyOpt | bsd-3-clause |
We can now visualize the results | np.round(myBopt.X,2) | manual/GPyOpt_context.ipynb | SheffieldML/GPyOpt | bsd-3-clause |
Import matplotlib.pyplot as plt and set %matplotlib inline if you are using the jupyter notebook. What command do you use if you aren't using the jupyter notebook? | import matplotlib.pyplot as plt
%matplotlib inline | data-science/learning/ud2/Part 1 Exercise Solutions/Matplotlib Exercises .ipynb | therealAJ/python-sandbox | gpl-3.0 |
Exercise 1
Follow along with these steps:
* Create a figure object called fig using plt.figure()
* Use add_axes to add an axis to the figure canvas at [0,0,1,1]. Call this new axis ax.
* Plot (x,y) on that axes and set the labels and titles to match the plot below: | fig = plt.figure()
ax = fig.add_axes([0,0,1,1])
ax.plot(x,y)
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_title('title') | data-science/learning/ud2/Part 1 Exercise Solutions/Matplotlib Exercises .ipynb | therealAJ/python-sandbox | gpl-3.0 |
Exercise 2
Create a figure object and put two axes on it, ax1 and ax2. Located at [0,0,1,1] and [0.2,0.5,.2,.2] respectively. | fig = plt.figure()
ax1 = fig.add_axes([0,0,1,1])
ax2 = fig.add_axes([0.2,0.5,0.2,0.2]) | data-science/learning/ud2/Part 1 Exercise Solutions/Matplotlib Exercises .ipynb | therealAJ/python-sandbox | gpl-3.0 |
Now plot (x,y) on both axes. And call your figure object to show it. | ax1.plot(x,y,color='black')
ax2.plot(x,y,color='red')
fig | data-science/learning/ud2/Part 1 Exercise Solutions/Matplotlib Exercises .ipynb | therealAJ/python-sandbox | gpl-3.0 |
Exercise 3
Create the plot below by adding two axes to a figure object at [0,0,1,1] and [0.2,0.5,.4,.4] | fig = plt.figure()
ax1 = fig.add_axes([0,0,1,1])
ax2 = fig.add_axes([0.2,0.5,0.4,0.4])
#Large
ax1.set_xlabel('x')
ax1.set_ylabel('z')
ax1.plot(x,z)
#Inserted
ax2.set_xlabel('x')
ax2.set_ylabel('y')
ax2.set_title('zoom')
ax2.plot(x,y)
ax2.set_xlim(left=20,right=22)
ax2.set_ylim(bottom=30,top=50)
| data-science/learning/ud2/Part 1 Exercise Solutions/Matplotlib Exercises .ipynb | therealAJ/python-sandbox | gpl-3.0 |
Now use x,y, and z arrays to recreate the plot below. Notice the xlimits and y limits on the inserted plot:
Exercise 4
Use plt.subplots(nrows=1, ncols=2) to create the plot below. | fig,axes = plt.subplots(1,2)
axes[0].plot(x,y,lw=3,ls='--')
axes[1].plot(x,z,color='r',lw=4) | data-science/learning/ud2/Part 1 Exercise Solutions/Matplotlib Exercises .ipynb | therealAJ/python-sandbox | gpl-3.0 |
Now plot (x,y) and (x,z) on the axes. Play around with the linewidth and style
See if you can resize the plot by adding the figsize() argument in plt.subplots() are copying and pasting your previous code. | fig,axes = plt.subplots(1,2,figsize=(12,2))
axes[0].plot(x,y,lw=3,ls='--')
axes[1].plot(x,z,color='r',lw=4) | data-science/learning/ud2/Part 1 Exercise Solutions/Matplotlib Exercises .ipynb | therealAJ/python-sandbox | gpl-3.0 |
Init SparkContext | from zoo.common.nncontext import init_spark_on_local, init_spark_on_yarn
import numpy as np
import os
hadoop_conf_dir = os.environ.get('HADOOP_CONF_DIR')
if hadoop_conf_dir:
sc = init_spark_on_yarn(
hadoop_conf=hadoop_conf_dir,
conda_name=os.environ.get("ZOO_CONDA_NAME", "zoo"), # The name of the created c... | apps/ray/parameter_server/sharded_parameter_server.ipynb | intel-analytics/analytics-zoo | apache-2.0 |
파이썬 기본 자료형
문제
실수(부동소수점)를 하나 입력받아, 그 숫자를 반지름으로 하는 원의 면적과 둘레의 길이를 튜플로 리턴하는 함수 circle_radius를 구현하는 코드를 작성하라,
```
.
```
문자열 자료형
아래 사이트는 커피 콩의 현재 시세를 보여준다.
http://beans-r-us.appspot.com/prices.html
위 사이트의 내용을 html 소스코드로 보면 다음과 같으며, 검색된 시간의 커피콩의 가격은
Current price of coffee beans 문장이 담겨 있는 줄에 명시되어 있다.
```html
<html><head><... | odd_1000 = [x**2 for x in range(0, 1000) if x % 2 == 1]
# 리스트의 처음 다섯 개 항목
odd_1000[:5] | ref_materials/exams/2017/A02/midterm-a02.ipynb | liganega/Gongsu-DataSci | gpl-3.0 |
문제
0부터 1000까지의 숫자들 중에서 홀수이면서 7의 배수인 숫자들의 리스트를 조건제시법으로 생성하는 코드를 작성하라.
```
.
```
모범답안: | odd_3x7 = [x for x in range(0, 1000) if x % 2 == 1 and x % 7 == 0]
# 리스트의 처음 다섯 개 항목
odd_3x7[:5] | ref_materials/exams/2017/A02/midterm-a02.ipynb | liganega/Gongsu-DataSci | gpl-3.0 |
문제
0부터 1000까지의 숫자들 중에서 홀수이면서 7의 배수인 숫자들을 제곱하여 1을 더한 값들의 리스트를 조건제시법으로 생성하는 코드를 작성하라.
힌트: 아래와 같이 정의된 함수를 활용한다.
$$f(x) = x^2 + 1$$
```
.```
견본답안: | def square_plus1(x):
return x**2 + 1
odd_3x7_spl = [square_plus1(x) for x in odd_3x7]
# 리스트의 처음 다섯 개 항목
odd_3x7_spl[:5] | ref_materials/exams/2017/A02/midterm-a02.ipynb | liganega/Gongsu-DataSci | gpl-3.0 |
csv 파일 읽어들이기
'Seoul_pop2.csv' 파일에는 아래 내용이 저장되어 있다"
```csv
1949년부터 2010년 사이의 서울과 수도권 인구 증가율(%)
구간,서울,수도권
1949-1955,9.12,-5.83
1955-1960,55.88,32.22
1960-1966,55.12,32.76
1966-1970,45.66,28.76
1970-1975,24.51,22.93
1975-1980,21.38,21.69
1980-1985,15.27,18.99
1985-1990,10.15,17.53
1990-1995,-3.64,8.54
1995-2000,-3.55,5.4... | import csv
with open('Seoul_pop2.csv', 'rb') as f:
reader = csv.reader(f)
for row in reader:
if len(row) == 0 or row[0][0] == '#':
continue
else:
print(row) | ref_materials/exams/2017/A02/midterm-a02.ipynb | liganega/Gongsu-DataSci | gpl-3.0 |
문제
위 코드에서 5번 째 줄을 아래와 같이 하면 오류 발생한다.
if row[0][0] == '#' or len(row) == 0:
이유를 간단하게 설명하라.
```
.
```
넘파이 활용 기초 1
넘파이 어레이를 생성하는 방법은 몇 개의 기본적인 함수를 이용하면 된다.
np.arange()
np.zeros()
np.ones()
np.diag()
예제: | np.arange(3, 10, 3)
np.zeros((2,3))
np.ones((2,))
np.diag([1, 2, 3, 4])
np.ones((3,3)) * 2 | ref_materials/exams/2017/A02/midterm-a02.ipynb | liganega/Gongsu-DataSci | gpl-3.0 |
문제
아래 모양의 어레이를 생성하는 코드를 작성하라.
단, 언급된 네 개의 함수들만 사용해야 하며, 수동으로 생성된 리스트나 어레이는 허용되지 않는다.
$$\left [ \begin{matrix} 2 & 0 & 0 \ 0 & 2 & 0 \ 0 & 0 & 2 \end{matrix} \right ]$$
```
.
```
견본답안: | np.diag(np.ones((3,))*2) | ref_materials/exams/2017/A02/midterm-a02.ipynb | liganega/Gongsu-DataSci | gpl-3.0 |
문제
아래 모양의 어레이를 생성하는 코드를 작성하라.
단, 언급된 네 개의 함수만 사용해야 하며, 수동으로 생성된 리스트나 어레이는 허용되지 않는다.
$$\left [ \begin{matrix} 2 & 0 & 0 \ 0 & 4 & 0 \ 0 & 0 & 6 \end{matrix} \right ]$$
```
.
```
견본답안: | np.diag(np.arange(2, 7, 2)) | ref_materials/exams/2017/A02/midterm-a02.ipynb | liganega/Gongsu-DataSci | gpl-3.0 |
넘파이의 linspace() 함수 활용
numpy 모듈의 linspace() 함수는 지정된 구간을 정해진 크기로 일정하게 쪼개는 어래이를 생성한다.
예를 들어, 0부터 3사이의 구간을 균등하게 30개로 쪼개고자 하면 아래와 같이 실행하면 된다. | xs = np.linspace(0, 3, 30)
xs | ref_materials/exams/2017/A02/midterm-a02.ipynb | liganega/Gongsu-DataSci | gpl-3.0 |
문제
0부터 1사이의 구간을 균등하게 10개로 쪼개어 각 항목을 제곱하는 코드를 작성하라.
```
.
```
견본답안: | np.linspace(0,1, 10) ** 2 | ref_materials/exams/2017/A02/midterm-a02.ipynb | liganega/Gongsu-DataSci | gpl-3.0 |
넘파이 활용 기초 2
population.txt 파일은 1900년부터 1920년까지 캐나다 북부지역에서 서식한 산토끼(hare)와 스라소니(lynx)의 숫자,
그리고 채소인 당근(carrot)의 재배숫자를 아래 내용으로 순수 텍스트 데이터로 담고 있다.
```
year hare lynx carrot
1900 30e3 4e3 48300
1901 47.2e3 6.1e3 48200
1902 70.2e3 9.8e3 41500
1903 77.4e3 35.2e3 38200
1904 36.3e3 ... | data = np.loadtxt('populations.txt')
year, hares, lynxes, carrots = data.T | ref_materials/exams/2017/A02/midterm-a02.ipynb | liganega/Gongsu-DataSci | gpl-3.0 |
문제
위 코드에서 np.loadtxt 함수의 작동방식을 간단하게 설명하라.
```
.
```
문제
위 코드에서 data.T에 대해 간단하게 설명하라.
```
.
```
아래 코드는 토끼, 스라소니, 당근 각각의 개체수의 연도별 변화를 선그래프로 보여주도록 하는 코드이다. | plt.axes([0.2, 0.1, 0.5, 0.8])
plt.plot(year, hares, year, lynxes, year, carrots)
plt.legend(('Hare', 'Lynx', 'Carrot'), loc=(1.05, 0.5)) | ref_materials/exams/2017/A02/midterm-a02.ipynb | liganega/Gongsu-DataSci | gpl-3.0 |
Obtain Analytics Raster
Identify road feed feature for download
We want to download the most recent feature from the feed for road detection in Kirazli, Turkey. | # This ID is for a subscription for monthly road detection in Kirazli, Turkey
SUBSCRIPTION_ID = 'f184516c-b948-406f-b257-deaa66c3f38a'
results = analytics_client.list_collection_features(SUBSCRIPTION_ID).get()
features = results['features']
print('{} features in collection'.format(len(features)))
# sort features by a... | jupyter-notebooks/analytics-snippets/roads_as_vector.ipynb | planetlabs/notebooks | apache-2.0 |
Download Quad Raster | RESOURCE_TYPE = 'target-quad'
def create_save_dir(root_dir='data'):
save_dir = root_dir
if not os.path.isdir(save_dir):
os.makedirs(save_dir)
return save_dir
dest = 'data'
create_save_dir(dest) | jupyter-notebooks/analytics-snippets/roads_as_vector.ipynb | planetlabs/notebooks | apache-2.0 |
We want to save each all of the images in one directory. But all of the images for a single target quad have the same name, L15_{target_quad_id}. We use the function write_to_file to save the image, and that function pulls the name from the resource name attribute, which we can't set. So, we are going to make a new obj... | from planet.api.models import Body
from planet.api.utils import write_to_file
def download_feature(feature, subscription_id, resource_type, dest=dest):
print('{}: acquired {}'.format(feature['id'], get_date(feature)))
resource = analytics_client.get_associated_resource_for_analytic_feature(subscription_id,
... | jupyter-notebooks/analytics-snippets/roads_as_vector.ipynb | planetlabs/notebooks | apache-2.0 |
Visualize Roads Image
The output of the analytics road detection is a boolean image where road pixels are given a value of True and non-road pixels are given a value of False. | def _open(filename, factor=1):
with rasterio.open(filename) as dataset:
height = int(dataset.height / factor)
width = int(dataset.width / factor)
data = dataset.read(
out_shape=(dataset.count, height, width)
)
return data
def open_bool(filename, factor=1):
data =... | jupyter-notebooks/analytics-snippets/roads_as_vector.ipynb | planetlabs/notebooks | apache-2.0 |
Convert Roads to Vector Features
GDAL Command-Line Interface (CLI)
GDAL provides a python script that can be run via the CLI. It is quite easy to run and fast, though it doesn't allow for some of the convenient pixel-space filtering and processing that rasterio provides and we will use later on. | gdal_output_filename = os.path.join('data', 'test_gdal.shp')
!gdal_polygonize.py $filename $gdal_output_filename | jupyter-notebooks/analytics-snippets/roads_as_vector.ipynb | planetlabs/notebooks | apache-2.0 |
Rasterio - no filtering
In this section we use rasterio to convert the binary roads raster into a vector dataset. The vectors are written to disk as a shapefile. The shapefile can be imported into geospatial programs such as QGIS or ArcGIS for visualization and further processing.
This is basic conversion to vector sha... | def roads_as_vectors(filename):
with rasterio.open(filename) as dataset:
roads = dataset.read(1)
road_mask = roads == 255 # mask non-road pixels
# transforms roads features to image crs
road_shapes = rfeatures.shapes(roads, mask=road_mask, connectivity=8, transform=dataset.transfor... | jupyter-notebooks/analytics-snippets/roads_as_vector.ipynb | planetlabs/notebooks | apache-2.0 |
Rasterio - Filtering and Simplifying
In this section, we use shapely to filter the road vectors by size and simplify them so we don't have a million pixel edges. | def roads_as_vectors_with_filtering(filename, min_pixel_size=5):
with rasterio.open(filename) as dataset:
roads = dataset.read(1)
road_mask = roads == 255 # mask non-road pixels
# we skip transform on vectorization so we can perform filtering in pixel space
road_shapes = rfeatures.... | jupyter-notebooks/analytics-snippets/roads_as_vector.ipynb | planetlabs/notebooks | apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.