markdown stringlengths 0 37k | code stringlengths 1 33.3k | path stringlengths 8 215 | repo_name stringlengths 6 77 | license stringclasses 15
values |
|---|---|---|---|---|
You can apply fancier functions than .sum(), e.g. let's compute the variance of each group: | a.reshape(4, 3).var(axis=-1) | taking_numpy_in_stride/Taking NumPy In Stride - Student Version.ipynb | jaimefrio/pydatabcn2017 | unlicense |
Exercise 6
Your turn to do a fancier reshaping: we will compute the average of a 2D array over non-overlapping rectangular patches:
Choose to small numbers m and n, e.g. 3 and 4.
Create a 2D array, with number of rows a multiple of one of those numbers, and number of columns a multiple of the other, e.g. 15 x 24.
Resh... | # Your code goes here | taking_numpy_in_stride/Taking NumPy In Stride - Student Version.ipynb | jaimefrio/pydatabcn2017 | unlicense |
Rearranging dimensions
Once we have a multidimensional array, rearranging the order of its dimensions is as simple as rearranging its .shape and .tuple attributes. You could do this with np.ndarray, but it would be a pain. NumPy has a bunch of functions for doing that, but they are all watered down versions of np.trans... | # Your code goes here | taking_numpy_in_stride/Taking NumPy In Stride - Student Version.ipynb | jaimefrio/pydatabcn2017 | unlicense |
Playing with strides
For the rest of the workshop we are going to dome some fancy tricks with strides, to create interesting views of an existing array.
Exercise 8
Create a function to extract the diagonal of a 2-D array, using the np.ndarray constructor. | # Your code goes here | taking_numpy_in_stride/Taking NumPy In Stride - Student Version.ipynb | jaimefrio/pydatabcn2017 | unlicense |
Exercise 9
Something very interesting happens when we set a stride to zero. Give that idea some thought and then:
Create two functions, stacked_column_vector and stacked_row_vector, that take a 1D array (the vector), and an integer n, and create a 2D view of the array that stack n copies of the vector, either as colum... | # Your code goes here | taking_numpy_in_stride/Taking NumPy In Stride - Student Version.ipynb | jaimefrio/pydatabcn2017 | unlicense |
Exercise 10
In the last exercise we used zero strides to reuse an item more than once in the resulting view. Let's try to build on that idea:
Write a function that takes a 1D array and a window integer value, and creates a 2D view of the array, each row a view through a sliding window of size window into the original ... | # Your code goes here | taking_numpy_in_stride/Taking NumPy In Stride - Student Version.ipynb | jaimefrio/pydatabcn2017 | unlicense |
Parting pro tip
NumPy's worst kept secret is the existence of a mostly undocumented, mostly hidden, as_strided function, that makes creating views with funny strides much easier (and also much more dangerous!) than using np.ndarray. Here's the available documentation: | from numpy.lib.stride_tricks import as_strided
np.info(as_strided) | taking_numpy_in_stride/Taking NumPy In Stride - Student Version.ipynb | jaimefrio/pydatabcn2017 | unlicense |
We're going to be building a model that recognizes these digits as 5, 0, and 4.
Imports and input data
We'll proceed in steps, beginning with importing and inspecting the MNIST data. This doesn't have anything to do with TensorFlow in particular -- we're just downloading the data archive. | import os
from six.moves.urllib.request import urlretrieve
SOURCE_URL = 'http://yann.lecun.com/exdb/mnist/'
WORK_DIRECTORY = "/tmp/mnist-data"
def maybe_download(filename):
"""A helper to download the data files if not present."""
if not os.path.exists(WORK_DIRECTORY):
os.mkdir(WORK_DIRECTORY)
fil... | tensorflow/tools/docker/notebooks/3_mnist_from_scratch.ipynb | HKUST-SING/tensorflow | apache-2.0 |
Working with the images
Now we have the files, but the format requires a bit of pre-processing before we can work with it. The data is gzipped, requiring us to decompress it. And, each of the images are grayscale-encoded with values from [0, 255]; we'll normalize these to [-0.5, 0.5].
Let's try to unpack the data using... | import gzip, binascii, struct, numpy
import matplotlib.pyplot as plt
with gzip.open(test_data_filename) as f:
# Print the header fields.
for field in ['magic number', 'image count', 'rows', 'columns']:
# struct.unpack reads the binary data provided by f.read.
# The format string '>i' decodes a ... | tensorflow/tools/docker/notebooks/3_mnist_from_scratch.ipynb | HKUST-SING/tensorflow | apache-2.0 |
The first 10 pixels are all 0 values. Not very interesting, but also unsurprising. We'd expect most of the pixel values to be the background color, 0.
We could print all 28 * 28 values, but what we really need to do to make sure we're reading our data properly is look at an image. | %matplotlib inline
# We'll show the image and its pixel value histogram side-by-side.
_, (ax1, ax2) = plt.subplots(1, 2)
# To interpret the values as a 28x28 image, we need to reshape
# the numpy array, which is one dimensional.
ax1.imshow(image.reshape(28, 28), cmap=plt.cm.Greys);
ax2.hist(image, bins=20, range=[0,... | tensorflow/tools/docker/notebooks/3_mnist_from_scratch.ipynb | HKUST-SING/tensorflow | apache-2.0 |
The large number of 0 values correspond to the background of the image, another large mass of value 255 is black, and a mix of grayscale transition values in between.
Both the image and histogram look sensible. But, it's good practice when training image models to normalize values to be centered around 0.
We'll do that... | # Let's convert the uint8 image to 32 bit floats and rescale
# the values to be centered around 0, between [-0.5, 0.5].
#
# We again plot the image and histogram to check that we
# haven't mangled the data.
scaled = image.astype(numpy.float32)
scaled = (scaled - (255 / 2.0)) / 255
_, (ax1, ax2) = plt.subplots(1, 2)... | tensorflow/tools/docker/notebooks/3_mnist_from_scratch.ipynb | HKUST-SING/tensorflow | apache-2.0 |
Great -- we've retained the correct image data while properly rescaling to the range [-0.5, 0.5].
Reading the labels
Let's next unpack the test label data. The format here is similar: a magic number followed by a count followed by the labels as uint8 values. In more detail:
[offset] [type] [value] [de... | with gzip.open(test_labels_filename) as f:
# Print the header fields.
for field in ['magic number', 'label count']:
print(field, struct.unpack('>i', f.read(4))[0])
print('First label:', struct.unpack('B', f.read(1))[0]) | tensorflow/tools/docker/notebooks/3_mnist_from_scratch.ipynb | HKUST-SING/tensorflow | apache-2.0 |
Indeed, the first label of the test set is 7.
Forming the training, testing, and validation data sets
Now that we understand how to read a single element, we can read a much larger set that we'll use for training, testing, and validation.
Image data
The code below is a generalization of our prototyping above that reads... | IMAGE_SIZE = 28
PIXEL_DEPTH = 255
def extract_data(filename, num_images):
"""Extract the images into a 4D tensor [image index, y, x, channels].
For MNIST data, the number of channels is always 1.
Values are rescaled from [0, 255] down to [-0.5, 0.5].
"""
print('Extracting', filename)
with g... | tensorflow/tools/docker/notebooks/3_mnist_from_scratch.ipynb | HKUST-SING/tensorflow | apache-2.0 |
A crucial difference here is how we reshape the array of pixel values. Instead of one image that's 28x28, we now have a set of 60,000 images, each one being 28x28. We also include a number of channels, which for grayscale images as we have here is 1.
Let's make sure we've got the reshaping parameters right by inspectin... | print('Training data shape', train_data.shape)
_, (ax1, ax2) = plt.subplots(1, 2)
ax1.imshow(train_data[0].reshape(28, 28), cmap=plt.cm.Greys);
ax2.imshow(train_data[1].reshape(28, 28), cmap=plt.cm.Greys); | tensorflow/tools/docker/notebooks/3_mnist_from_scratch.ipynb | HKUST-SING/tensorflow | apache-2.0 |
Looks good. Now we know how to index our full set of training and test images.
Label data
Let's move on to loading the full set of labels. As is typical in classification problems, we'll convert our input labels into a 1-hot encoding over a length 10 vector corresponding to 10 digits. The vector [0, 1, 0, 0, 0, 0, 0, 0... | NUM_LABELS = 10
def extract_labels(filename, num_images):
"""Extract the labels into a 1-hot matrix [image index, label index]."""
print('Extracting', filename)
with gzip.open(filename) as bytestream:
# Skip the magic number and count; we know these values.
bytestream.read(8)
buf = ... | tensorflow/tools/docker/notebooks/3_mnist_from_scratch.ipynb | HKUST-SING/tensorflow | apache-2.0 |
As with our image data, we'll double-check that our 1-hot encoding of the first few values matches our expectations. | print('Training labels shape', train_labels.shape)
print('First label vector', train_labels[0])
print('Second label vector', train_labels[1]) | tensorflow/tools/docker/notebooks/3_mnist_from_scratch.ipynb | HKUST-SING/tensorflow | apache-2.0 |
The 1-hot encoding looks reasonable.
Segmenting data into training, test, and validation
The final step in preparing our data is to split it into three sets: training, test, and validation. This isn't the format of the original data set, so we'll take a small slice of the training data and treat that as our validation ... | VALIDATION_SIZE = 5000
validation_data = train_data[:VALIDATION_SIZE, :, :, :]
validation_labels = train_labels[:VALIDATION_SIZE]
train_data = train_data[VALIDATION_SIZE:, :, :, :]
train_labels = train_labels[VALIDATION_SIZE:]
train_size = train_labels.shape[0]
print('Validation shape', validation_data.shape)
print(... | tensorflow/tools/docker/notebooks/3_mnist_from_scratch.ipynb | HKUST-SING/tensorflow | apache-2.0 |
Defining the model
Now that we've prepared our data, we're ready to define our model.
The comments describe the architecture, which fairly typical of models that process image data. The raw input passes through several convolution and max pooling layers with rectified linear activations before several fully connected l... | import tensorflow as tf
# We'll bundle groups of examples during training for efficiency.
# This defines the size of the batch.
BATCH_SIZE = 60
# We have only one channel in our grayscale images.
NUM_CHANNELS = 1
# The random seed that defines initialization.
SEED = 42
# This is where training samples and labels are ... | tensorflow/tools/docker/notebooks/3_mnist_from_scratch.ipynb | HKUST-SING/tensorflow | apache-2.0 |
Now that we've defined the variables to be trained, we're ready to wire them together into a TensorFlow graph.
We'll define a helper to do this, model, which will return copies of the graph suitable for training and testing. Note the train argument, which controls whether or not dropout is used in the hidden layer. (We... | def model(data, train=False):
"""The Model definition."""
# 2D convolution, with 'SAME' padding (i.e. the output feature map has
# the same size as the input). Note that {strides} is a 4D array whose
# shape matches the data layout: [image index, y, x, depth].
conv = tf.nn.conv2d(data,
... | tensorflow/tools/docker/notebooks/3_mnist_from_scratch.ipynb | HKUST-SING/tensorflow | apache-2.0 |
Having defined the basic structure of the graph, we're ready to stamp out multiple copies for training, testing, and validation.
Here, we'll do some customizations depending on which graph we're constructing. train_prediction holds the training graph, for which we use cross-entropy loss and weight regularization. We'll... | # Training computation: logits + cross-entropy loss.
logits = model(train_data_node, True)
loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(
labels=train_labels_node, logits=logits))
# L2 regularization for the fully connected parameters.
regularizers = (tf.nn.l2_loss(fc1_weights) + tf.nn.l2_loss(fc1_bi... | tensorflow/tools/docker/notebooks/3_mnist_from_scratch.ipynb | HKUST-SING/tensorflow | apache-2.0 |
Training and visualizing results
Now that we have the training, test, and validation graphs, we're ready to actually go through the training loop and periodically evaluate loss and error.
All of these operations take place in the context of a session. In Python, we'd write something like:
with tf.Session() as s:
...t... | # Create a new interactive session that we'll use in
# subsequent code cells.
s = tf.InteractiveSession()
# Use our newly created session as the default for
# subsequent operations.
s.as_default()
# Initialize all the variables we defined above.
tf.global_variables_initializer().run() | tensorflow/tools/docker/notebooks/3_mnist_from_scratch.ipynb | HKUST-SING/tensorflow | apache-2.0 |
Now we're ready to perform operations on the graph. Let's start with one round of training. We're going to organize our training steps into batches for efficiency; i.e., training using a small set of examples at each step rather than a single example. | BATCH_SIZE = 60
# Grab the first BATCH_SIZE examples and labels.
batch_data = train_data[:BATCH_SIZE, :, :, :]
batch_labels = train_labels[:BATCH_SIZE]
# This dictionary maps the batch data (as a numpy array) to the
# node in the graph it should be fed to.
feed_dict = {train_data_node: batch_data,
train_... | tensorflow/tools/docker/notebooks/3_mnist_from_scratch.ipynb | HKUST-SING/tensorflow | apache-2.0 |
Let's take a look at the predictions. How did we do? Recall that the output will be probabilities over the possible classes, so let's look at those probabilities. | print(predictions[0]) | tensorflow/tools/docker/notebooks/3_mnist_from_scratch.ipynb | HKUST-SING/tensorflow | apache-2.0 |
As expected without training, the predictions are all noise. Let's write a scoring function that picks the class with the maximum probability and compares with the example's label. We'll start by converting the probability vectors returned by the softmax into predictions we can match against the labels. | # The highest probability in the first entry.
print('First prediction', numpy.argmax(predictions[0]))
# But, predictions is actually a list of BATCH_SIZE probability vectors.
print(predictions.shape)
# So, we'll take the highest probability for each vector.
print('All predictions', numpy.argmax(predictions, 1)) | tensorflow/tools/docker/notebooks/3_mnist_from_scratch.ipynb | HKUST-SING/tensorflow | apache-2.0 |
Next, we can do the same thing for our labels -- using argmax to convert our 1-hot encoding into a digit class. | print('Batch labels', numpy.argmax(batch_labels, 1)) | tensorflow/tools/docker/notebooks/3_mnist_from_scratch.ipynb | HKUST-SING/tensorflow | apache-2.0 |
Now we can compare the predicted and label classes to compute the error rate and confusion matrix for this batch. | correct = numpy.sum(numpy.argmax(predictions, 1) == numpy.argmax(batch_labels, 1))
total = predictions.shape[0]
print(float(correct) / float(total))
confusions = numpy.zeros([10, 10], numpy.float32)
bundled = zip(numpy.argmax(predictions, 1), numpy.argmax(batch_labels, 1))
for predicted, actual in bundled:
confusio... | tensorflow/tools/docker/notebooks/3_mnist_from_scratch.ipynb | HKUST-SING/tensorflow | apache-2.0 |
Now let's wrap this up into our scoring function. | def error_rate(predictions, labels):
"""Return the error rate and confusions."""
correct = numpy.sum(numpy.argmax(predictions, 1) == numpy.argmax(labels, 1))
total = predictions.shape[0]
error = 100.0 - (100 * float(correct) / float(total))
confusions = numpy.zeros([10, 10], numpy.float32)
bun... | tensorflow/tools/docker/notebooks/3_mnist_from_scratch.ipynb | HKUST-SING/tensorflow | apache-2.0 |
We'll need to train for some time to actually see useful predicted values. Let's define a loop that will go through our data. We'll print the loss and error periodically.
Here, we want to iterate over the entire data set rather than just the first batch, so we'll need to slice the data to that end.
(One pass through ou... | # Train over the first 1/4th of our training set.
steps = train_size // BATCH_SIZE
for step in range(steps):
# Compute the offset of the current minibatch in the data.
# Note that we could use better randomization across epochs.
offset = (step * BATCH_SIZE) % (train_size - BATCH_SIZE)
batch_data = train... | tensorflow/tools/docker/notebooks/3_mnist_from_scratch.ipynb | HKUST-SING/tensorflow | apache-2.0 |
The error seems to have gone down. Let's evaluate the results using the test set.
To help identify rare mispredictions, we'll include the raw count of each (prediction, label) pair in the confusion matrix. | test_error, confusions = error_rate(test_prediction.eval(), test_labels)
print('Test error: %.1f%%' % test_error)
plt.xlabel('Actual')
plt.ylabel('Predicted')
plt.grid(False)
plt.xticks(numpy.arange(NUM_LABELS))
plt.yticks(numpy.arange(NUM_LABELS))
plt.imshow(confusions, cmap=plt.cm.jet, interpolation='nearest');
for... | tensorflow/tools/docker/notebooks/3_mnist_from_scratch.ipynb | HKUST-SING/tensorflow | apache-2.0 |
We can see here that we're mostly accurate, with some errors you might expect, e.g., '9' is often confused as '4'.
Let's do another sanity check to make sure this matches roughly the distribution of our test set, e.g., it seems like we have fewer '5' values. | plt.xticks(numpy.arange(NUM_LABELS))
plt.hist(numpy.argmax(test_labels, 1)); | tensorflow/tools/docker/notebooks/3_mnist_from_scratch.ipynb | HKUST-SING/tensorflow | apache-2.0 |
Setting Up S3 Access Using Boto
We'll use boto to access the S3 bucket. Below, we'll set the bucket ID and create a resource to access it.
Note that although the bucket is public, boto requires the presence of an AWS access key and secret key to use a s3 resource. To request data anonymously, we'll use a low-level clie... | era5_bucket = 'era5-pds'
# AWS access / secret keys required
# s3 = boto3.resource('s3')
# bucket = s3.Bucket(era5_bucket)
# No AWS keys required
client = boto3.client('s3', config=botocore.client.Config(signature_version=botocore.UNSIGNED)) | aws/era5-s3-via-boto.ipynb | planet-os/notebooks | mit |
ERA5 Data Structure on S3
The ERA5 data is chunked into distinct NetCDF files per variable, each containing a month of hourly data. These files are organized in the S3 bucket by year, month, and variable name.
The data is structured as follows:
/{year}/{month}/main.nc
/data/{var1}.nc
... | paginator = client.get_paginator('list_objects')
result = paginator.paginate(Bucket=era5_bucket, Delimiter='/')
for prefix in result.search('CommonPrefixes'):
print(prefix.get('Prefix')) | aws/era5-s3-via-boto.ipynb | planet-os/notebooks | mit |
Let's take a look at the objects available for a specific month using boto's list_objects_v2 method. | keys = []
date = datetime.date(2018,1,1) # update to desired date
prefix = date.strftime('%Y/%m/')
response = client.list_objects_v2(Bucket=era5_bucket, Prefix=prefix)
response_meta = response.get('ResponseMetadata')
if response_meta.get('HTTPStatusCode') == 200:
contents = response.get('Contents')
if content... | aws/era5-s3-via-boto.ipynb | planet-os/notebooks | mit |
Downloading Files
Let's download main.nc file for that month and use xarray to inspect the metadata relating to the data files. | metadata_file = 'main.nc'
metadata_key = prefix + metadata_file
client.download_file(era5_bucket, metadata_key, metadata_file)
ds_meta = xr.open_dataset('main.nc', decode_times=False)
ds_meta.info() | aws/era5-s3-via-boto.ipynb | planet-os/notebooks | mit |
Now let's acquire data for a single variable over the course of a month. Let's download air temperature for August of 2017 and open the NetCDF file using xarray.
Note that the cell below may take some time to execute, depending on your connection speed. Most of the variable files are roughly 1 GB in size. | # select date and variable of interest
date = datetime.date(2017,8,1)
var = 'air_temperature_at_2_metres'
# file path patterns for remote S3 objects and corresponding local file
s3_data_ptrn = '{year}/{month}/data/{var}.nc'
data_file_ptrn = '{year}{month}_{var}.nc'
year = date.strftime('%Y')
month = date.strftime('%m... | aws/era5-s3-via-boto.ipynb | planet-os/notebooks | mit |
The ds.info output above shows us that there are three dimensions to the data: lat, lon, and time0; and one data variable: air_temperature_at_2_metres. Let's inspect the coordinate values to see what they look like... | ds.coords.values() | aws/era5-s3-via-boto.ipynb | planet-os/notebooks | mit |
In the coordinate values, we can see that longitude is expressed as degrees east, ranging from 0 to 359.718 degrees. Latitude is expressed as degrees north, ranging from -89.784874 to 89.784874. And finally the time0 coordinate, ranging from 2017-08-01T07:00:00Z to 2017-09-01T06:00:00Z.
As mentioned above, due to the f... | # location coordinates
locs = [
{'name': 'santa_monica', 'lon': -118.496245, 'lat': 34.010341},
{'name': 'tallinn', 'lon': 24.753574, 'lat': 59.436962},
{'name': 'honolulu', 'lon': -157.835938, 'lat': 21.290014},
{'name': 'cape_town', 'lon': 18.423300, 'lat': -33.918861},
{'name': 'dubai', 'lon': 55... | aws/era5-s3-via-boto.ipynb | planet-os/notebooks | mit |
Convert Units and Create a Dataframe
Temperature data in the ERA5 dataset uses Kelvin. Let's convert it to something more meaningful. I've chosen to use Fahrenheit, because as a U.S. citizen (and stubborn metric holdout) Celcius still feels foreign to me ;-)
While we're at it, let's also convert the dataset to a pandas... | def kelvin_to_celcius(t):
return t - 273.15
def kelvin_to_fahrenheit(t):
return t * 9/5 - 459.67
ds_locs_f = ds_locs.apply(kelvin_to_fahrenheit)
df_f = ds_locs_f.to_dataframe()
df_f.describe() | aws/era5-s3-via-boto.ipynb | planet-os/notebooks | mit |
Show Me Some Charts!
Finally, let's plot the temperature data for each of the locations over the period. The first plot displays the hourly temperature for each location over the month.
The second plot is a box plot. A box plot is a method for graphically depicting groups of numerical data through their quartiles. The ... | # readability please
plt.rcParams.update({'font.size': 16})
ax = df_f.plot(figsize=(18, 10), title="ERA5 Air Temperature at 2 Meters", grid=1)
ax.set(xlabel='Date', ylabel='Air Temperature (deg F)')
plt.show()
ax = df_f.plot.box(figsize=(18, 10))
ax.set(xlabel='Location', ylabel='Air Temperature (deg F)')
plt.show() | aws/era5-s3-via-boto.ipynb | planet-os/notebooks | mit |
Спецсимволы
Для задания в строке особых символов (например переводов строк или табуляций) в Python используются специальный последовательности, вроде \n для перевода строки или \t для символа табуляции: | s = "Эта строка\nсостоит из двух строк"
print(s)
s = "А в этой\tстроке\nиспользуются\tсимволы табуляции"
print(s) | crash-course/strings.ipynb | citxx/sis-python | mit |
Такой же синтаксис используетя для задания кавычек в строке: | s1 = "Это \"строка\" с кавычками."
s2 = 'И "это" тоже.'
s3 = 'С одинарными Кавычками \'\' всё работает также.'
print(s1, s2, s3)
print("Если надо задать обратный слэш \\, то его надо просто удвоить: '\\\\'") | crash-course/strings.ipynb | citxx/sis-python | mit |
Операции со строками
Сложение
Строки можно складывать. В этом случае они просто припишутся друг к другу. По-умному это называется конкатенацией. | greeting = "Привет"
exclamation = "!!!"
print(greeting + exclamation) | crash-course/strings.ipynb | citxx/sis-python | mit |
Повторение
Можно умножать на целое число, чтобы повторить строку нужное число раз. | print("I will write in Python with style!\n" * 10)
print(3 * "Really\n") | crash-course/strings.ipynb | citxx/sis-python | mit |
Индексация
Получить символ на заданной позиции можно также, как и в C++ или Pascal. Индекасация начинается с 0. | s = "Это моя строка"
print(s[0], s[1], s[2]) | crash-course/strings.ipynb | citxx/sis-python | mit |
Но нельзя поменять отдельный символ. Это сделано для того, чтобы более логично и эффективно реализовать некоторые возможности Python. | s = "Вы не можете изменить символы этой строки"
s[0] = "Т" | crash-course/strings.ipynb | citxx/sis-python | mit |
Перевод: ОшибкаТипа: объект 'str' не поддерживает присваивание элементов
Можно указывать отрицательные индексы, тогда нумерация происходит с конца. | s = "Строка"
print(s[-1], "=", s[5])
print(s[-2], "=", s[4])
print(s[-3], "=", s[3])
print(s[-4], "=", s[2])
print(s[-5], "=", s[1])
print(s[-6], "=", s[0]) | crash-course/strings.ipynb | citxx/sis-python | mit |
Длина строки | s = "Для получения длины используется функция len"
print(len(s)) | crash-course/strings.ipynb | citxx/sis-python | mit |
Проверка наличия подстроки
Проверить наличие или отсутствие в строке подстроки или символа можно с помощью операций in и not in. | vowels = "аеёиоуыэюя"
c = "ы"
if c in vowels:
print(c, "- гласная")
else:
print(c, "- согласная")
s = "Python - лучший из неторопливых языков :)"
print("Python" in s)
print("C++" in s) | crash-course/strings.ipynb | citxx/sis-python | mit |
Кодировка символов
В памяти компьютера каждый символ хранится как число. Соответствие между символом и числом называется кодировкой.
Самая простая кодировка для латинских букв, цифр и часто используемых символов — ASCII. Она задаёт коды (числа) для 128 символов и используется в Python для представления этих символов.
К... | # Код любого символа можно получить с помощью функции ord
print(ord("a"))
# Можно пользоваться тем, что коды чисел, маленьких латинских букв и больших латинских букв идут подряд.
print("Цифры:", ord("0"), ord("1"), ord("2"), ord("3"), "...", ord("8"), ord("9"))
print("Маленькие буквы:", ord("a"), ord("b"), ord("c"), o... | crash-course/strings.ipynb | citxx/sis-python | mit |
Символ по коду | # Для получение символа по коду используется функция chr
print(chr(100)) | crash-course/strings.ipynb | citxx/sis-python | mit |
ASCII | # Этот код выводит всю таблицу ASCII
for code in range(128):
print('chr(' + str(code) + ') =', repr(chr(code))) | crash-course/strings.ipynb | citxx/sis-python | mit |
读取数据,去掉不用的数据 | if __name__ == '__main__':
# parser = set_arguments()
# cmd_args = parser.parse_args()
print('{} START'.format(time.strftime(TIME_FORMAT)))
fd = codecs.open(DEFAULT_FIN, 'r', 'utf-8')
fw = codecs.open( DEFAULT_FOUT, 'w', 'utf-8')
reg = re.compile('〖(.*)〗')
start_flag = False
for line in ... | PrepareData.ipynb | seth2000/chinesepoem | mit |
分词实验
DEFAULT_FOUT = os.path.join(DATA_FOLDER, 'poem.txt')
thu1 = thulac.thulac(seg_only=True) #只进行分词,不进行词性标注
text = thu1.cut("我爱北京天安门", text=True) #进行一句话分词
print(text)
thu1 = thulac.thulac(seg_only=True) #只进行分词,不进行词性标注
thu1.cut_f(DEFAULT_FOUT, outp) #对input.txt文件内容进行分词,输出到output.txt | print('{} START'.format(time.strftime(TIME_FORMAT)))
import thulac
DEFAULT_Segment = os.path.join(DATA_FOLDER, 'wordsegment.txt')
fd = codecs.open(DEFAULT_FOUT, 'r', 'utf-8')
fw = codecs.open(DEFAULT_Segment, 'w', 'utf-8')
thu1 = thulac.thulac(seg_only=True) #只进行分词,不进行词性标注
for line in fd:
#print(line)
f... | PrepareData.ipynb | seth2000/chinesepoem | mit |
分词不是很成功,我们转向直接用汉字字符来代替分段,我们保留标点符号 | print('{} START'.format(time.strftime(TIME_FORMAT)))
DEFAULT_FOUT = os.path.join(DATA_FOLDER, 'poem.txt')
DEFAULT_charSegment = os.path.join(DATA_FOLDER, 'Charactersegment.txt')
fd = codecs.open(DEFAULT_FOUT, 'r', 'utf-8')
fw = codecs.open(DEFAULT_charSegment, 'w', 'utf-8')
start_flag = False
for line in fd:
if ... | PrepareData.ipynb | seth2000/chinesepoem | mit |
把汉字转成拼音 | from pypinyin import pinyin | PrepareData.ipynb | seth2000/chinesepoem | mit |
Importing some modules (libraries) and giving them short names such as np and plt. You will find that most users will use these common ones. | import numpy as np
import matplotlib.pyplot as plt | notebooks/04-plotting.ipynb | teuben/astr288p | mit |
It might be tempting to import a module in a blank namespace, to make for "more readable code" like the following example:
from math import *
s2 = sqrt(2)
but the danger of this is that importing multiple modules in blank namespace can make some invisible, plus obfuscates the code where the function came from. So i... | x = 0.5*np.arange(20)
y = x*x*0.1
z = np.sqrt(x)*3
plt.plot(x,y,'o-',label='y')
plt.plot(x,z,'*--',label='z')
plt.title("$x^2$ and $\sqrt{x}$")
#plt.legend(loc='best')
plt.legend()
plt.xlabel('X axis')
plt.ylabel('Y axis')
#plt.xscale('log')
#plt.yscale('log')
#plt.savefig('sample1.png')
| notebooks/04-plotting.ipynb | teuben/astr288p | mit |
Scatter plot | plt.scatter(x,y,s=40.0,c='r',label='y')
plt.scatter(x,z,s=20.0,c='g',label='z')
plt.legend(loc='best')
plt.show() | notebooks/04-plotting.ipynb | teuben/astr288p | mit |
Multi planel plots| | fig = plt.figure()
fig1 = fig.add_subplot(121)
fig1.scatter(x,z,s=20.0,c='g',label='z')
fig2 = fig.add_subplot(122)
fig2.scatter(x,y,s=40.0,c='r',label='y'); | notebooks/04-plotting.ipynb | teuben/astr288p | mit |
Histogram | n = 100000
mean = 4.0
disp = 2.0
bins = 32
g = np.random.normal(mean,disp,n)
p = np.random.poisson(mean,n)
gh=plt.hist(g,bins)
ph=plt.hist(p,bins)
plt.hist([g,p],bins) | notebooks/04-plotting.ipynb | teuben/astr288p | mit |
Los sistemas mas sencillos a estudiar en oscilaciones son el sistema masa-resorte y el péndulo simple.
<div>
<img style="float: left; margin: 0px 0px 15px 15px;" src="https://upload.wikimedia.org/wikipedia/commons/7/76/Pendulum.jpg" width="150px" height="50px" />
<img style="float: right; margin: 15px 15px 15px 15px;"... | %matplotlib inline | Modulo1/.ipynb_checkpoints/Clase4_OsciladorArmonico-checkpoint.ipynb | EricChiquitoG/Simulacion2017 | mit |
_Esta es la librería con todas las instrucciones para realizar gráficos. _ | import matplotlib.pyplot as plt
import matplotlib as mpl
label_size = 14
mpl.rcParams['xtick.labelsize'] = label_size
mpl.rcParams['ytick.labelsize'] = label_size | Modulo1/.ipynb_checkpoints/Clase4_OsciladorArmonico-checkpoint.ipynb | EricChiquitoG/Simulacion2017 | mit |
Y esta es la librería con todas las funciones matemáticas necesarias. | import numpy as np
# Definición de funciones a graficar
A, B, w0 = .5, .1, .5 # Parámetros
t = np.linspace(0, 50, 100) # Creamos vector de tiempo de 0 a 50 con 100 puntos
x = A*np.cos(w0*t)+B*np.sin(w0*t) # Función de posición
dx = w0*(-A*np.sin(w0*t)+B*np... | Modulo1/.ipynb_checkpoints/Clase4_OsciladorArmonico-checkpoint.ipynb | EricChiquitoG/Simulacion2017 | mit |
Y si consideramos un conjunto de frecuencias de oscilación, entonces | frecuencias = np.array([.1, .2 , .5, .6]) # Vector de diferentes frecuencias
plt.figure(figsize = (7, 4)) # Ventana de gráfica con tamaño
# Graficamos para cada frecuencia
for w0 in frecuencias:
x = A*np.cos(w0*t)+B*np.sin(w0*t)
plt.plot(t, x, '*-')
plt.xlabel('$t$', fontsize = 16) ... | Modulo1/.ipynb_checkpoints/Clase4_OsciladorArmonico-checkpoint.ipynb | EricChiquitoG/Simulacion2017 | mit |
Estos colores, son el default de matplotlib, sin embargo existe otra librería dedicada, entre otras cosas, a la presentación de gráficos. | import seaborn as sns
sns.set(style='ticks', palette='Set2')
frecuencias = np.array([.1, .2 , .5, .6])
plt.figure(figsize = (7, 4))
for w0 in frecuencias:
x = A*np.cos(w0*t)+B*np.sin(w0*t)
plt.plot(t, x, 'o-',
label = '$\omega_0 = %s$'%w0) # Etiqueta cada gráfica con frecuencia correspondiente ... | Modulo1/.ipynb_checkpoints/Clase4_OsciladorArmonico-checkpoint.ipynb | EricChiquitoG/Simulacion2017 | mit |
Si queremos tener manipular un poco mas las cosas, hacemos uso de lo siguiente: | from ipywidgets import *
def masa_resorte(t = 0):
A, B, w0 = .5, .1, .5 # Parámetros
x = A*np.cos(w0*t)+B*np.sin(w0*t) # Función de posición
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.plot(x, [0], 'ko', ms = 10)
ax.set_xlim(xmin = -0.6, x... | Modulo1/.ipynb_checkpoints/Clase4_OsciladorArmonico-checkpoint.ipynb | EricChiquitoG/Simulacion2017 | mit |
La opción de arriba generalmente será lenta, así que lo recomendable es usar interact_manual. | def masa_resorte(t = 0):
A, B, w0 = .5, .1, .5 # Parámetros
x = A*np.cos(w0*t)+B*np.sin(w0*t) # Función de posición
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.plot(x, [0], 'ko', ms = 10)
ax.set_xlim(xmin = -0.6, xmax = .6)
ax.axvline(x... | Modulo1/.ipynb_checkpoints/Clase4_OsciladorArmonico-checkpoint.ipynb | EricChiquitoG/Simulacion2017 | mit |
Péndulo simple
Ahora, si fijamos nuestra atención al movimiento de un péndulo simple (oscilaciones pequeñas), la ecuación diferencial a resolver tiene la misma forma:
\begin{equation}
\frac{d^2 \theta}{dt^2} + \omega_{0}^{2}\, \theta = 0, \quad\mbox{donde}\quad \omega_{0}^2 = \frac{g}{l}.
\end{equation}
La diferencia m... | # Podemos definir una función que nos entregue theta dados los parámetros y el tiempo
def theta_t(a, b, g, l, t):
omega_0 = np.sqrt(g/l)
return a * np.cos(omega_0 * t) + b * np.sin(omega_0 * t)
# Hacemos un gráfico interactivo del péndulo
def pendulo_simple(t = 0):
fig = plt.figure(figsize = (5,5))
a... | Modulo1/.ipynb_checkpoints/Clase4_OsciladorArmonico-checkpoint.ipynb | EricChiquitoG/Simulacion2017 | mit |
Condiciones iniciales
Realmente lo que se tiene que resolver es,
\begin{equation}
\theta(t) = \theta(0) \cos(\omega_{0} t) + \frac{\dot{\theta}(0)}{\omega_{0}} \sin(\omega_{0} t)
\end{equation}
Actividad. Modificar el programa anterior para incorporar las condiciones iniciales. | # Solución:
def theta_t():
return
def pendulo_simple(t = 0):
fig = plt.figure(figsize = (5,5))
ax = fig.add_subplot(1, 1, 1)
x = 2 * np.sin(theta_t( , t))
y = - 2 * np.cos(theta_t(, t))
ax.plot(x, y, 'ko', ms = 10)
ax.plot([0], [0], 'rD')
ax.plot([0, x ], [0, y], 'k-', lw = 1)
... | Modulo1/.ipynb_checkpoints/Clase4_OsciladorArmonico-checkpoint.ipynb | EricChiquitoG/Simulacion2017 | mit |
Plano fase $(x, \frac{dx}{dt})$
La posición y velocidad para el sistema masa-resorte se escriben como:
\begin{align}
x(t) &= x(0) \cos(\omega_{o} t) + \frac{\dot{x}(0)}{\omega_{0}} \sin(\omega_{o} t)\
\dot{x}(t) &= -\omega_{0}x(0) \sin(\omega_{0} t) + \dot{x}(0)\cos(\omega_{0}t)]
\end{align} | k = 3 #constante elástica [N]/[m]
m = 1 # [kg]
omega_0 = np.sqrt(k/m)
x_0 = .5
dx_0 = .1
t = np.linspace(0, 50, 300)
x_t = x_0 *np.cos(omega_0 *t) + (dx_0/omega_0) * np.sin(omega_0 *t)
dx_t = -omega_0 * x_0 * np.sin(omega_0 * t) + dx_0 * np.cos(omega_0 * t)
plt.figure(figsize = (7, 4))
plt.plot(t, x_t, label = '$... | Modulo1/.ipynb_checkpoints/Clase4_OsciladorArmonico-checkpoint.ipynb | EricChiquitoG/Simulacion2017 | mit |
Multiples condiciones iniciales | k = 3 #constante elástica [N]/[m]
m = 1 # [kg]
omega_0 = np.sqrt(k/m)
t = np.linspace(0, 50, 50)
x_0s = np.array([.7, .5, .25, .1])
dx_0s = np.array([.2, .1, .05, .01])
cmaps = np.array(['viridis', 'inferno', 'magma', 'plasma'])
plt.figure(figsize = (6, 6))
for indx, x_0 in enumerate(x_0s):
x_t = x_0 *np.cos(o... | Modulo1/.ipynb_checkpoints/Clase4_OsciladorArmonico-checkpoint.ipynb | EricChiquitoG/Simulacion2017 | mit |
Problem Statement: You have just been hired as an AI expert by the French Football Corporation. They would like you to recommend positions where France's goal keeper should kick the ball so that the French team's players can then hit it with their head.
<img src="images/field_kiank.png" style="width:600px;height:350px... | train_X, train_Y, test_X, test_Y = load_2D_dataset() | deep-learnining-specialization/2. improving deep neural networks/week1/Regularization.ipynb | diegocavalca/Studies | cc0-1.0 |
Each dot corresponds to a position on the football field where a football player has hit the ball with his/her head after the French goal keeper has shot the ball from the left side of the football field.
- If the dot is blue, it means the French player managed to hit the ball with his/her head
- If the dot is red, it ... | def model(X, Y, learning_rate = 0.3, num_iterations = 30000, print_cost = True, lambd = 0, keep_prob = 1):
"""
Implements a three-layer neural network: LINEAR->RELU->LINEAR->RELU->LINEAR->SIGMOID.
Arguments:
X -- input data, of shape (input size, number of examples)
Y -- true "label" vector (1 ... | deep-learnining-specialization/2. improving deep neural networks/week1/Regularization.ipynb | diegocavalca/Studies | cc0-1.0 |
Let's train the model without any regularization, and observe the accuracy on the train/test sets. | parameters = model(train_X, train_Y)
print ("On the training set:")
predictions_train = predict(train_X, train_Y, parameters)
print ("On the test set:")
predictions_test = predict(test_X, test_Y, parameters) | deep-learnining-specialization/2. improving deep neural networks/week1/Regularization.ipynb | diegocavalca/Studies | cc0-1.0 |
The train accuracy is 94.8% while the test accuracy is 91.5%. This is the baseline model (you will observe the impact of regularization on this model). Run the following code to plot the decision boundary of your model. | plt.title("Model without regularization")
axes = plt.gca()
axes.set_xlim([-0.75,0.40])
axes.set_ylim([-0.75,0.65])
plot_decision_boundary(lambda x: predict_dec(parameters, x.T), train_X, train_Y) | deep-learnining-specialization/2. improving deep neural networks/week1/Regularization.ipynb | diegocavalca/Studies | cc0-1.0 |
The non-regularized model is obviously overfitting the training set. It is fitting the noisy points! Lets now look at two techniques to reduce overfitting.
2 - L2 Regularization
The standard way to avoid overfitting is called L2 regularization. It consists of appropriately modifying your cost function, from:
$$J = -\fr... | # GRADED FUNCTION: compute_cost_with_regularization
def compute_cost_with_regularization(A3, Y, parameters, lambd):
"""
Implement the cost function with L2 regularization. See formula (2) above.
Arguments:
A3 -- post-activation, output of forward propagation, of shape (output size, number of examp... | deep-learnining-specialization/2. improving deep neural networks/week1/Regularization.ipynb | diegocavalca/Studies | cc0-1.0 |
Expected Output:
<table>
<tr>
<td>
**cost**
</td>
<td>
1.78648594516
</td>
</tr>
</table>
Of course, because you changed the cost, you have to change backward propagation as well! All the gradients have to be computed with respect to this new cost.
Exercise: Implement the chang... | # GRADED FUNCTION: backward_propagation_with_regularization
def backward_propagation_with_regularization(X, Y, cache, lambd):
"""
Implements the backward propagation of our baseline model to which we added an L2 regularization.
Arguments:
X -- input dataset, of shape (input size, number of example... | deep-learnining-specialization/2. improving deep neural networks/week1/Regularization.ipynb | diegocavalca/Studies | cc0-1.0 |
Expected Output:
<table>
<tr>
<td>
**dW1**
</td>
<td>
[[-0.25604646 0.12298827 -0.28297129]
[-0.17706303 0.34536094 -0.4410571 ]]
</td>
</tr>
<tr>
<td>
**dW2**
</td>
<td>
[[ 0.79276486 0.85133918]
[-0.0957219 -0.01720463]
[-0.13100772 -0.03750433]]... | parameters = model(train_X, train_Y, lambd = 0.7)
print ("On the train set:")
predictions_train = predict(train_X, train_Y, parameters)
print ("On the test set:")
predictions_test = predict(test_X, test_Y, parameters) | deep-learnining-specialization/2. improving deep neural networks/week1/Regularization.ipynb | diegocavalca/Studies | cc0-1.0 |
Congrats, the test set accuracy increased to 93%. You have saved the French football team!
You are not overfitting the training data anymore. Let's plot the decision boundary. | plt.title("Model with L2-regularization")
axes = plt.gca()
axes.set_xlim([-0.75,0.40])
axes.set_ylim([-0.75,0.65])
plot_decision_boundary(lambda x: predict_dec(parameters, x.T), train_X, train_Y) | deep-learnining-specialization/2. improving deep neural networks/week1/Regularization.ipynb | diegocavalca/Studies | cc0-1.0 |
Observations:
- The value of $\lambda$ is a hyperparameter that you can tune using a dev set.
- L2 regularization makes your decision boundary smoother. If $\lambda$ is too large, it is also possible to "oversmooth", resulting in a model with high bias.
What is L2-regularization actually doing?:
L2-regularization relie... | # GRADED FUNCTION: forward_propagation_with_dropout
def forward_propagation_with_dropout(X, parameters, keep_prob = 0.5):
"""
Implements the forward propagation: LINEAR -> RELU + DROPOUT -> LINEAR -> RELU + DROPOUT -> LINEAR -> SIGMOID.
Arguments:
X -- input dataset, of shape (2, number of example... | deep-learnining-specialization/2. improving deep neural networks/week1/Regularization.ipynb | diegocavalca/Studies | cc0-1.0 |
Expected Output:
<table>
<tr>
<td>
**A3**
</td>
<td>
[[ 0.36974721 0.00305176 0.04565099 0.49683389 0.36974721]]
</td>
</tr>
</table>
3.2 - Backward propagation with dropout
Exercise: Implement the backward propagation with dropout. As before, you are training a 3 layer netw... | # GRADED FUNCTION: backward_propagation_with_dropout
def backward_propagation_with_dropout(X, Y, cache, keep_prob):
"""
Implements the backward propagation of our baseline model to which we added dropout.
Arguments:
X -- input dataset, of shape (2, number of examples)
Y -- "true" labels vector... | deep-learnining-specialization/2. improving deep neural networks/week1/Regularization.ipynb | diegocavalca/Studies | cc0-1.0 |
Expected Output:
<table>
<tr>
<td>
**dA1**
</td>
<td>
[[ 0.36544439 0. -0.00188233 0. -0.17408748]
[ 0.65515713 0. -0.00337459 0. -0. ]]
</td>
</tr>
<tr>
<td>
**dA2**
</td>
<td>
[[ 0.58180856 0. -0.00... | parameters = model(train_X, train_Y, keep_prob = 0.86, learning_rate = 0.3)
print ("On the train set:")
predictions_train = predict(train_X, train_Y, parameters)
print ("On the test set:")
predictions_test = predict(test_X, test_Y, parameters) | deep-learnining-specialization/2. improving deep neural networks/week1/Regularization.ipynb | diegocavalca/Studies | cc0-1.0 |
Dropout works great! The test accuracy has increased again (to 95%)! Your model is not overfitting the training set and does a great job on the test set. The French football team will be forever grateful to you!
Run the code below to plot the decision boundary. | plt.title("Model with dropout")
axes = plt.gca()
axes.set_xlim([-0.75,0.40])
axes.set_ylim([-0.75,0.65])
plot_decision_boundary(lambda x: predict_dec(parameters, x.T), train_X, train_Y) | deep-learnining-specialization/2. improving deep neural networks/week1/Regularization.ipynb | diegocavalca/Studies | cc0-1.0 |
Create Local File Space | mydatafolder = os.environ['PWD'] + '/' + 'my_team_name_data_folder'
# THIS DISABLES HOST KEY CHECKING! Should be okay for our temporary running machines though.
cnopts = pysftp.CnOpts()
cnopts.hostkeys = None
#Get this from your Nimbix machine (or other cloud service provider!)
hostname='NAE-xxxx.jarvice.com'
userna... | tutorials/General_move_data_to_from_Nimbix_Cloud.ipynb | setiQuest/ML4SETI | apache-2.0 |
PUT a file
If you follow the Step 3 tutorial, you will have created some zip files containing the PNGs. These will be located in your my_team_name_data_folder/zipfiles/ directory. | with pysftp.Connection(hostname, username=username, password=password, cnopts=cnopts) as sftp:
sftp.put(mydatafolder + '/zipfiles/classification_6_noise.zip') # upload file to remote | tutorials/General_move_data_to_from_Nimbix_Cloud.ipynb | setiQuest/ML4SETI | apache-2.0 |
GET a file
First, I define a separate location to hold files I get from remote. | fromnimbixfolder = mydatafolder + '/fromnimbix'
if os.path.exists(fromnimbixfolder) is False:
os.makedirs(fromnimbixfolder)
with pysftp.Connection(hostname, username=username, password=password, cnopts=cnopts) as sftp:
with pysftp.cd(fromnimbixfolder):
sftp.get('test.csv') #data in local HOME space
... | tutorials/General_move_data_to_from_Nimbix_Cloud.ipynb | setiQuest/ML4SETI | apache-2.0 |
Variables and data types
Here we go! we've written our first line of code... But I guess we want to do something a little more interesting, right? Well, for a start, we might want to use Python to execute some operation (say: sum two numbers like 2 and 3) and process the result to print it on the screen, process it, an... | result = 2 + 3
#now we print the result
print(result)
# by the way, I'm a comment. I'm not executed
# every line of code following the sign # is ignored:
# print("I'm line n. 3: do you see me?")
# see? You don't see me...
print("I'm line nr. 5 and you DO see me!") | participants_notebooks/Sunoikisis - Named Entity Extraction 1a-GB.ipynb | mromanello/SunoikisisDC_NER | gpl-3.0 |
That's it! As easy as that (yes, in some programming languages you have to create or declare the variable first and then use it to fill the shoebox; in Python, you go ahead and simply use it!)
Now, what do you think we will get when we execute the following code? | result + 5 | participants_notebooks/Sunoikisis - Named Entity Extraction 1a-GB.ipynb | mromanello/SunoikisisDC_NER | gpl-3.0 |
What types of values can we put into a variable? What goes into the shoebox? We can start by the members of this list:
Integers (-1,0,1,2,3,4...)
Strings ("Hello", "s", "Wolfgang Amadeus Mozart", "I am the α and the ω!"...)
floats (3.14159; 2.71828...)
Booleans (True, False)
If you're not sure what type of value you'... | type("I am the α and the ω!")
type(2.7182818284590452353602874713527)
type(True)
result = "hello"
type(result) | participants_notebooks/Sunoikisis - Named Entity Extraction 1a-GB.ipynb | mromanello/SunoikisisDC_NER | gpl-3.0 |
You declare strings with single ('') or double ("") quote: it's totally indifferent! But now two questions:
1. what happens if you forget the quotes?
2. what happens if you put quotes around a number? | hello = "goodbye"
print(hello)
print("hello")
type("2") | participants_notebooks/Sunoikisis - Named Entity Extraction 1a-GB.ipynb | mromanello/SunoikisisDC_NER | gpl-3.0 |
String, integer, float... Why is that so important? Well, try to sum two strings and see what happens... | "2" + "3"
#probably you wanted this...
int("2") + int("3") | participants_notebooks/Sunoikisis - Named Entity Extraction 1a-GB.ipynb | mromanello/SunoikisisDC_NER | gpl-3.0 |
But if we are working with strings, then the "+" sign is used to concatenate the strings: | a = "interesting!"
print("not very " + a) | participants_notebooks/Sunoikisis - Named Entity Extraction 1a-GB.ipynb | mromanello/SunoikisisDC_NER | gpl-3.0 |
Lists and dictionaries
Lists and dictionaries are two very useful types to store whole collections of data | beatles = ["John", "Paul", "George", "Ringo"]
type(beatles)
# dictionaries collections of key : value pairs
beatles_dictionary = { "john" : "John Lennon" ,
"paul" : "Paul McCartney",
"george" : "George Harrison",
"ringo" : "Ringo Starr"}
type(beatles_di... | participants_notebooks/Sunoikisis - Named Entity Extraction 1a-GB.ipynb | mromanello/SunoikisisDC_NER | gpl-3.0 |
(there are also other types of collection, like Tuples and Sets, but we won't talk about them now; read the links if you're interested!)
Items in list are accessible using their index. Do remember that indexing starts from 0! | print(beatles[0])
#indexes can be negative!
beatles[-1] | participants_notebooks/Sunoikisis - Named Entity Extraction 1a-GB.ipynb | mromanello/SunoikisisDC_NER | gpl-3.0 |
Dictionaries are collections of key : value pairs. You access the value using the key as index | beatles_dictionary["john"]
beatles_dictionary[0] | participants_notebooks/Sunoikisis - Named Entity Extraction 1a-GB.ipynb | mromanello/SunoikisisDC_NER | gpl-3.0 |
There are a bunch of methods that you can apply to list to work with them.
You can append items at the end of a list | beatles.append("Billy Preston")
beatles | participants_notebooks/Sunoikisis - Named Entity Extraction 1a-GB.ipynb | mromanello/SunoikisisDC_NER | gpl-3.0 |
You can learn the index of an item | beatles.index("George") | participants_notebooks/Sunoikisis - Named Entity Extraction 1a-GB.ipynb | mromanello/SunoikisisDC_NER | gpl-3.0 |
You can insert elements at a predefinite index: | beatles.insert(0, "Pete Best")
print(beatles.index("George"))
beatles | participants_notebooks/Sunoikisis - Named Entity Extraction 1a-GB.ipynb | mromanello/SunoikisisDC_NER | gpl-3.0 |
But most importantly, you can slice lists, producing sub-lists by specifying the range of indexes you want: | beatles[1:5] | participants_notebooks/Sunoikisis - Named Entity Extraction 1a-GB.ipynb | mromanello/SunoikisisDC_NER | gpl-3.0 |
Do you notice something strange? Yes, the limit index is not inclusive (i.e. item beatles[5] is not included) | beatles[5] | participants_notebooks/Sunoikisis - Named Entity Extraction 1a-GB.ipynb | mromanello/SunoikisisDC_NER | gpl-3.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.