markdown
stringlengths 0
1.02M
| code
stringlengths 0
832k
| output
stringlengths 0
1.02M
| license
stringlengths 3
36
| path
stringlengths 6
265
| repo_name
stringlengths 6
127
|
---|---|---|---|---|---|
Load the Model with the Best Validation Loss | model.load_weights('saved_models/weights.best.from_scratch.hdf5') | _____no_output_____ | MIT | dog_app.ipynb | theCydonian/Dog-App |
Test the ModelTry out your model on the test dataset of dog images. Ensure that your test accuracy is greater than 1%. | # get index of predicted dog breed for each image in test set
dog_breed_predictions = [np.argmax(model.predict(np.expand_dims(tensor, axis=0))) for tensor in test_tensors]
# report test accuracy
test_accuracy = 100*np.sum(np.array(dog_breed_predictions)==np.argmax(test_targets, axis=1))/len(dog_breed_predictions)
print('Test accuracy: %.4f%%' % test_accuracy) | Test accuracy: 6.0000%
| MIT | dog_app.ipynb | theCydonian/Dog-App |
--- Step 4: Use a CNN to Classify Dog BreedsTo reduce training time without sacrificing accuracy, we show you how to train a CNN using transfer learning. In the following step, you will get a chance to use transfer learning to train your own CNN. Obtain Bottleneck Features | bottleneck_features = np.load('bottleneck_features/DogVGG16Data.npz')
train_VGG16 = bottleneck_features['train']
valid_VGG16 = bottleneck_features['valid']
test_VGG16 = bottleneck_features['test'] | _____no_output_____ | MIT | dog_app.ipynb | theCydonian/Dog-App |
Model ArchitectureThe model uses the the pre-trained VGG-16 model as a fixed feature extractor, where the last convolutional output of VGG-16 is fed as input to our model. We only add a global average pooling layer and a fully connected layer, where the latter contains one node for each dog category and is equipped with a softmax. | VGG16_model = Sequential()
VGG16_model.add(GlobalAveragePooling2D(input_shape=train_VGG16.shape[1:]))
VGG16_model.add(Dense(133, activation='softmax'))
VGG16_model.summary() | _____no_output_____ | MIT | dog_app.ipynb | theCydonian/Dog-App |
Compile the Model | VGG16_model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy']) | _____no_output_____ | MIT | dog_app.ipynb | theCydonian/Dog-App |
Train the Model | checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.VGG16.hdf5',
verbose=1, save_best_only=True)
VGG16_model.fit(train_VGG16, train_targets,
validation_data=(valid_VGG16, valid_targets),
epochs=20, batch_size=20, callbacks=[checkpointer], verbose=1) | Train on 6680 samples, validate on 835 samples
Epoch 1/20
6680/6680 [==============================] - 89s 13ms/step - loss: 11.8201 - acc: 0.1313 - val_loss: 10.1389 - val_acc: 0.2240
Epoch 00001: val_loss improved from inf to 10.13894, saving model to saved_models/weights.best.VGG16.hdf5
Epoch 2/20
6680/6680 [==============================] - 10s 2ms/step - loss: 9.2538 - acc: 0.3043 - val_loss: 8.9575 - val_acc: 0.3222
Epoch 00002: val_loss improved from 10.13894 to 8.95749, saving model to saved_models/weights.best.VGG16.hdf5
Epoch 3/20
6680/6680 [==============================] - 10s 2ms/step - loss: 8.4209 - acc: 0.3877 - val_loss: 8.6163 - val_acc: 0.3557
Epoch 00003: val_loss improved from 8.95749 to 8.61632, saving model to saved_models/weights.best.VGG16.hdf5
Epoch 4/20
6680/6680 [==============================] - 10s 2ms/step - loss: 8.0421 - acc: 0.4325 - val_loss: 8.2879 - val_acc: 0.3772
Epoch 00004: val_loss improved from 8.61632 to 8.28791, saving model to saved_models/weights.best.VGG16.hdf5
Epoch 5/20
6680/6680 [==============================] - 12s 2ms/step - loss: 7.7844 - acc: 0.4624 - val_loss: 8.1717 - val_acc: 0.4048
Epoch 00005: val_loss improved from 8.28791 to 8.17172, saving model to saved_models/weights.best.VGG16.hdf5
Epoch 6/20
6680/6680 [==============================] - 11s 2ms/step - loss: 7.6280 - acc: 0.4835 - val_loss: 8.0697 - val_acc: 0.4096
Epoch 00006: val_loss improved from 8.17172 to 8.06973, saving model to saved_models/weights.best.VGG16.hdf5
Epoch 7/20
6680/6680 [==============================] - 11s 2ms/step - loss: 7.4649 - acc: 0.5015 - val_loss: 8.0886 - val_acc: 0.4096
Epoch 00007: val_loss did not improve from 8.06973
Epoch 8/20
6680/6680 [==============================] - 11s 2ms/step - loss: 7.3254 - acc: 0.5120 - val_loss: 7.9434 - val_acc: 0.4168
Epoch 00008: val_loss improved from 8.06973 to 7.94338, saving model to saved_models/weights.best.VGG16.hdf5
Epoch 9/20
6680/6680 [==============================] - 10s 2ms/step - loss: 7.1596 - acc: 0.5250 - val_loss: 7.7321 - val_acc: 0.4240
Epoch 00009: val_loss improved from 7.94338 to 7.73213, saving model to saved_models/weights.best.VGG16.hdf5
Epoch 10/20
6680/6680 [==============================] - 10s 2ms/step - loss: 6.9381 - acc: 0.5419 - val_loss: 7.5836 - val_acc: 0.4395
Epoch 00010: val_loss improved from 7.73213 to 7.58365, saving model to saved_models/weights.best.VGG16.hdf5
Epoch 11/20
6680/6680 [==============================] - 10s 2ms/step - loss: 6.7472 - acc: 0.5557 - val_loss: 7.4644 - val_acc: 0.4467
Epoch 00011: val_loss improved from 7.58365 to 7.46442, saving model to saved_models/weights.best.VGG16.hdf5
Epoch 12/20
6680/6680 [==============================] - 10s 2ms/step - loss: 6.6441 - acc: 0.5686 - val_loss: 7.3440 - val_acc: 0.4491
Epoch 00012: val_loss improved from 7.46442 to 7.34403, saving model to saved_models/weights.best.VGG16.hdf5
Epoch 13/20
6680/6680 [==============================] - 10s 2ms/step - loss: 6.5786 - acc: 0.5749 - val_loss: 7.2727 - val_acc: 0.4635
Epoch 00013: val_loss improved from 7.34403 to 7.27274, saving model to saved_models/weights.best.VGG16.hdf5
Epoch 14/20
6680/6680 [==============================] - 11s 2ms/step - loss: 6.3946 - acc: 0.5844 - val_loss: 7.2446 - val_acc: 0.4611
Epoch 00014: val_loss improved from 7.27274 to 7.24463, saving model to saved_models/weights.best.VGG16.hdf5
Epoch 15/20
6680/6680 [==============================] - 11s 2ms/step - loss: 6.2405 - acc: 0.5940 - val_loss: 7.1072 - val_acc: 0.4695
Epoch 00015: val_loss improved from 7.24463 to 7.10718, saving model to saved_models/weights.best.VGG16.hdf5
Epoch 16/20
6680/6680 [==============================] - 11s 2ms/step - loss: 6.1987 - acc: 0.6039 - val_loss: 7.0344 - val_acc: 0.4754
Epoch 00016: val_loss improved from 7.10718 to 7.03437, saving model to saved_models/weights.best.VGG16.hdf5
Epoch 17/20
6680/6680 [==============================] - 10s 2ms/step - loss: 6.1235 - acc: 0.6072 - val_loss: 6.9543 - val_acc: 0.4754
Epoch 00017: val_loss improved from 7.03437 to 6.95427, saving model to saved_models/weights.best.VGG16.hdf5
Epoch 18/20
6680/6680 [==============================] - 11s 2ms/step - loss: 6.0022 - acc: 0.6138 - val_loss: 6.8999 - val_acc: 0.4754
Epoch 00018: val_loss improved from 6.95427 to 6.89992, saving model to saved_models/weights.best.VGG16.hdf5
Epoch 19/20
6680/6680 [==============================] - 10s 2ms/step - loss: 5.8735 - acc: 0.6213 - val_loss: 6.7769 - val_acc: 0.4826
Epoch 00019: val_loss improved from 6.89992 to 6.77690, saving model to saved_models/weights.best.VGG16.hdf5
Epoch 20/20
6680/6680 [==============================] - 10s 2ms/step - loss: 5.7552 - acc: 0.6341 - val_loss: 6.6512 - val_acc: 0.5018
Epoch 00020: val_loss improved from 6.77690 to 6.65119, saving model to saved_models/weights.best.VGG16.hdf5
| MIT | dog_app.ipynb | theCydonian/Dog-App |
Load the Model with the Best Validation Loss | VGG16_model.load_weights('saved_models/weights.best.VGG16.hdf5') | _____no_output_____ | MIT | dog_app.ipynb | theCydonian/Dog-App |
Test the ModelNow, we can use the CNN to test how well it identifies breed within our test dataset of dog images. We print the test accuracy below. | # get index of predicted dog breed for each image in test set
VGG16_predictions = [np.argmax(VGG16_model.predict(np.expand_dims(feature, axis=0))) for feature in test_VGG16]
# report test accuracy
test_accuracy = 100*np.sum(np.array(VGG16_predictions)==np.argmax(test_targets, axis=1))/len(VGG16_predictions)
print('Test accuracy: %.4f%%' % test_accuracy) | Test accuracy: 48.0000%
| MIT | dog_app.ipynb | theCydonian/Dog-App |
Predict Dog Breed with the Model | from extract_bottleneck_features import *
def VGG16_predict_breed(img_path):
# extract bottleneck features
bottleneck_feature = extract_VGG16(path_to_tensor(img_path))
# obtain predicted vector
predicted_vector = VGG16_model.predict(bottleneck_feature)
# return dog breed that is predicted by the model
return dog_names[np.argmax(predicted_vector)] | _____no_output_____ | MIT | dog_app.ipynb | theCydonian/Dog-App |
--- Step 5: Create a CNN to Classify Dog Breeds (using Transfer Learning)You will now use transfer learning to create a CNN that can identify dog breed from images. Your CNN must attain at least 60% accuracy on the test set.In Step 4, we used transfer learning to create a CNN using VGG-16 bottleneck features. In this section, you must use the bottleneck features from a different pre-trained model. To make things easier for you, we have pre-computed the features for all of the networks that are currently available in Keras:- [VGG-19](https://s3-us-west-1.amazonaws.com/udacity-aind/dog-project/DogVGG19Data.npz) bottleneck features- [ResNet-50](https://s3-us-west-1.amazonaws.com/udacity-aind/dog-project/DogResnet50Data.npz) bottleneck features- [Inception](https://s3-us-west-1.amazonaws.com/udacity-aind/dog-project/DogInceptionV3Data.npz) bottleneck features- [Xception](https://s3-us-west-1.amazonaws.com/udacity-aind/dog-project/DogXceptionData.npz) bottleneck featuresThe files are encoded as such: Dog{network}Data.npz where `{network}`, in the above filename, can be one of `VGG19`, `Resnet50`, `InceptionV3`, or `Xception`. Pick one of the above architectures, download the corresponding bottleneck features, and store the downloaded file in the `bottleneck_features/` folder in the repository. (IMPLEMENTATION) Obtain Bottleneck FeaturesIn the code block below, extract the bottleneck features corresponding to the train, test, and validation sets by running the following: bottleneck_features = np.load('bottleneck_features/Dog{network}Data.npz') train_{network} = bottleneck_features['train'] valid_{network} = bottleneck_features['valid'] test_{network} = bottleneck_features['test'] | bottleneck_features_VGG19 = np.load('bottleneck_features/DogVGG19Data.npz')
train_VGG19 = bottleneck_features_VGG19['train']
valid_VGG19 = bottleneck_features_VGG19['valid']
test_VGG19 = bottleneck_features_VGG19['test'] | _____no_output_____ | MIT | dog_app.ipynb | theCydonian/Dog-App |
(IMPLEMENTATION) Model ArchitectureCreate a CNN to classify dog breed. At the end of your code cell block, summarize the layers of your model by executing the line: .summary() __Question 5:__ Outline the steps you took to get to your final CNN architecture and your reasoning at each step. Describe why you think the architecture is suitable for the current problem.__Answer:__ I started with a relu and a tanh hidden layer with a couple of dropouts between them. This gave decent performance(low 70%s). I them proceeded to increase complexity while managing overfitting with the dropout layers. After many tests, I was able to break 80% accuracy. Switching to sgd optimizer also helped. I might try to improve it in the future.Final accuracy: 81.0000% | VGG19_model = Sequential()
VGG19_model.add(GlobalAveragePooling2D(input_shape=train_VGG19.shape[1:]))
VGG19_model.add(Dense(760, activation="relu"))
VGG19_model.add(Dropout(0.5))
VGG19_model.add(Dense(256, activation="tanh"))
VGG19_model.add(Dropout(0.4))
VGG19_model.add(Dense(133, activation="softmax"))
VGG19_model.summary() | _________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
global_average_pooling2d_1 ( (None, 512) 0
_________________________________________________________________
dense_4 (Dense) (None, 760) 389880
_________________________________________________________________
dropout_5 (Dropout) (None, 760) 0
_________________________________________________________________
dense_5 (Dense) (None, 256) 194816
_________________________________________________________________
dropout_6 (Dropout) (None, 256) 0
_________________________________________________________________
dense_6 (Dense) (None, 133) 34181
=================================================================
Total params: 618,877
Trainable params: 618,877
Non-trainable params: 0
_________________________________________________________________
| MIT | dog_app.ipynb | theCydonian/Dog-App |
(IMPLEMENTATION) Compile the Model | VGG19_model.compile(loss='categorical_crossentropy', optimizer='sgd', metrics=['accuracy']) | _____no_output_____ | MIT | dog_app.ipynb | theCydonian/Dog-App |
(IMPLEMENTATION) Train the ModelTrain your model in the code cell below. Use model checkpointing to save the model that attains the best validation loss. You are welcome to [augment the training data](https://blog.keras.io/building-powerful-image-classification-models-using-very-little-data.html), but this is not a requirement. | from keras.callbacks import ModelCheckpoint
checkpoint = ModelCheckpoint(filepath='saved_models/weights.best.VGG19.hdf5', verbose=1, save_best_only=True)
VGG19_model.fit(train_VGG19, train_targets, validation_data=(valid_VGG19, valid_targets), epochs=50, batch_size=20, callbacks=[checkpoint], verbose=1)
# high number of epochs for manual stop | _____no_output_____ | MIT | dog_app.ipynb | theCydonian/Dog-App |
(IMPLEMENTATION) Load the Model with the Best Validation Loss | VGG19_model.load_weights('saved_models/weights.best.VGG19.hdf5') | _____no_output_____ | MIT | dog_app.ipynb | theCydonian/Dog-App |
(IMPLEMENTATION) Test the ModelTry out your model on the test dataset of dog images. Ensure that your test accuracy is greater than 60%. | # get index of predicted dog breed for each image in test set
VGG19_predictions = [np.argmax(VGG19_model.predict(np.expand_dims(feature, axis=0))) for feature in test_VGG19]
# report test accuracy
test_accuracy = 100*np.sum(np.array(VGG19_predictions)==np.argmax(test_targets, axis=1))/len(VGG19_predictions)
print('Test accuracy: %.4f%%' % test_accuracy) | Test accuracy: 81.0000%
| MIT | dog_app.ipynb | theCydonian/Dog-App |
(IMPLEMENTATION) Predict Dog Breed with the ModelWrite a function that takes an image path as input and returns the dog breed (`Affenpinscher`, `Afghan_hound`, etc) that is predicted by your model. Similar to the analogous function in Step 5, your function should have three steps:1. Extract the bottleneck features corresponding to the chosen CNN model.2. Supply the bottleneck features as input to the model to return the predicted vector. Note that the argmax of this prediction vector gives the index of the predicted dog breed.3. Use the `dog_names` array defined in Step 0 of this notebook to return the corresponding breed.The functions to extract the bottleneck features can be found in `extract_bottleneck_features.py`, and they have been imported in an earlier code cell. To obtain the bottleneck features corresponding to your chosen CNN architecture, you need to use the function extract_{network} where `{network}`, in the above filename, should be one of `VGG19`, `Resnet50`, `InceptionV3`, or `Xception`. | import extract_bottleneck_features
def getBreed(path):
# extract bottleneck features
bottleneck_feature = extract_bottleneck_features.extract_VGG19(path_to_tensor(path))
# obtain predicted vector
predicted_vector = VGG19_model.predict(bottleneck_feature)
# return dog breed that is predicted by the model
return dog_names[np.argmax(predicted_vector)]
print getBreed("/Users/Luke_MacBook/Downloads/dog-project/dogImages/train/023.Bernese_mountain_dog/Bernese_mountain_dog_01619.jpg") | Bernese_mountain_dog
| MIT | dog_app.ipynb | theCydonian/Dog-App |
--- Step 6: Write your AlgorithmWrite an algorithm that accepts a file path to an image and first determines whether the image contains a human, dog, or neither. Then,- if a __dog__ is detected in the image, return the predicted breed.- if a __human__ is detected in the image, return the resembling dog breed.- if __neither__ is detected in the image, provide output that indicates an error.You are welcome to write your own functions for detecting humans and dogs in images, but feel free to use the `face_detector` and `dog_detector` functions developed above. You are __required__ to use your CNN from Step 5 to predict dog breed. Some sample output for our algorithm is provided below, but feel free to design your own user experience! (IMPLEMENTATION) Write your Algorithm | def printImg(path):
img = cv2.imread(path)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
cv_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
# display the image, along with bounding box
plt.imshow(cv_rgb)
plt.show()
def whatIs(path, error_mode):
dog = dog_detector(path)
human = face_detector(path)
if not dog and not human:
if error_mode == "terminate":
raise ValueError("Neither Human nor Dog Detected. Please input a new image")
elif error_mode == "continue":
print "Neither Human nor Dog Detected."
return None
if dog:
return "dog"
else:
return "human"
def finalAlg(path, error_mode = 'terminate'):
if error_mode is not "terminate" and error_mode is not "continue":
raise ValueError("error_mode can only be set to terminate or continue") # "continue" just prints and does not raise error
entity_type = whatIs(path, error_mode)
if entity_type == "dog":
print "Whats up Dog!"
printImg(path)
print("You are a...")
print(str(getBreed(path)))
print("\n")
elif entity_type == "human":
print "Hello, Human!"
printImg(path)
print("You look like a...")
print(str(getBreed(path)))
print("\n")
else:
print "Hello!"
printImg(path)
print("You look like a...")
print(str(getBreed(path)))
print("\n") | _____no_output_____ | MIT | dog_app.ipynb | theCydonian/Dog-App |
--- Step 7: Test Your AlgorithmIn this section, you will take your new algorithm for a spin! What kind of dog does the algorithm think that __you__ look like? If you have a dog, does it predict your dog's breed accurately? If you have a cat, does it mistakenly think that your cat is a dog? (IMPLEMENTATION) Test Your Algorithm on Sample Images!Test your algorithm at least six images on your computer. Feel free to use any images you like. Use at least two human and two dog images. __Question 6:__ Is the output better than you expected :) ? Or worse :( ? Provide at least three possible points of improvement for your algorithm.__Answer:__ Much better. For dogs, it is fairly accurate, and for humans, I can clearly see similar features between humans and the dogs they were identified as.I could potentially improve the algorithm by leveraging both dog and human checks for greater accurracy.I could also add camera input to make it more usable.Finally, I could potentially eliminate more overfitting to get a more accurate mode. | # doqs
finalAlg("dogImages/test/002.Afghan_hound/Afghan_hound_00151.jpg")
finalAlg("dogImages/train/023.Bernese_mountain_dog/Bernese_mountain_dog_01619.jpg")
finalAlg("dogImages/train/080.Greater_swiss_mountain_dog/Greater_swiss_mountain_dog_05466.jpg")
# humans
finalAlg("lfw/Aaron_Guiel/Aaron_Guiel_0001.jpg")
finalAlg("lfw/Will_Ferrell/Will_Ferrell_0001.jpg")
# other
finalAlg("weirdPics/KingDedede.jpg", error_mode="continue")
finalAlg("weirdPics/furry.jpg", error_mode="continue") | Whats up Dog!
| MIT | dog_app.ipynb | theCydonian/Dog-App |
Advanced features in Rasteriohttps://gist.github.com/sgillies/7e5cd548110a5b4d45ac1a1d93cb17a3[Rasterio](https://mapbox.github.io/rasterio/) is an open source Python package that wraps [GDAL](http://www.gdal.org/) in idiomatic Python functions and classes.The last pre-release of Rasterio has five advanced features that are useful for developing cloud-native applications.1. Quick overviews of GeoTIFFs in the cloud2. Quick subsets of GeoTIFFs in the cloud3. Lazy warping of GeoTIFFs in the cloud4. Formatted files in RAM5. Datasets in zipped streamsPlease note these features already exist in the latest version of the GDAL library. What Rasterio does, for the first time, is make them into solid Python patterns.This notebook is a demonstration of these patterns. Notebook requirementsThis notebook uses f-strings and requires Python 3.6. It will probably work with other Python 3 versions if the f-strings are replaced by `str.format()` calls. My team has switched to Python 3.6 this year and we're glad we did.I recommend that you run this notebook in an isolated Python environment. My preference is for one created with venv. Install the latest pre-release of Rasterio with its S3-related extras.```python3.6 -m venv rasterio-advanced-featuressource rasterio-advanced-features/bin/activate(rasterio-advanced-features) $ pip install --pre rasterio[s3](rasterio-advanced-features) $ pip install mercantile jupyter```If you're a conda user, do the following.```conda create -n rasterio-advanced-features python=3.6 boto3 jupyterconda install -c conda-forge mercantileconda install -c conda-forge/label/dev rasterio```You will need an AWS account and credentials to run the scripts in this notebook. An AWS account is free and doesn't take long to set up: https://aws.amazon.com/account/. Rasterio documentationThis notebook glosses over basic usage of Rasterio and discusses several advanced usage patterns. Please consult the documentation of the Rasterio package for help with basic usage: https://mapbox.github.io/rasterio/. Quick tour of the AWS Landsat PDSWe're going to use the [AWS Landsat PDS](https://aws.amazon.com/public-datasets/landsat/) as a source of data for this notebook. From the site:> Landsat 8 data is available for anyone to use via Amazon S3. All Landsat 8 scenes are available from the start of imagery capture. All new Landsat 8 scenes are made available each day, often within hours of production.> The Landsat program is a joint effort of the U.S. Geological Survey and NASA. First launched in 1972, the Landsat series of satellites has produced the longest, continuous record of Earth’s land surface as seen from space. NASA is in charge of developing remote-sensing instruments and spacecraft, launching the satellites, and validating their performance. USGS develops the associated ground systems, then takes ownership and operates the satellites, as well as managing data reception, archiving, and distribution. Since late 2008, Landsat data have been made available to all users free of charge. Carefully calibrated Landsat imagery provides the U.S. and the world with a long-term, consistent inventory of vitally important global resources.AWS has made Landsat 8 data freely available on Amazon S3 so that anyone can use our on-demand computing resources to perform analysis and create new products without needing to worry about the cost of storing Landsat data or the time required to download it.> Landsat data is in AWS S3 bucket named *landsat-pds* and is organzied by *path*, *row*, and *scene*. The scene id also has the path and row encoded in it. If you know the scene you're interested in – by searching the USGS Earth Explorer site, or via James Bridle's [Landsat Tumblr](http://laaaaaaandsat.tumblr.com/) – you can extract the path and row and construct an AWS S3 prefix that lets you find all the objects associated with that scene using boto3. If you don't have AWS credentials set in your environment, you can set them in the block below. If you, delete the block. Be careful to remove your credentials from the notebook before sharing it with anyone else. | %env AWS_ACCESS_KEY_ID= AWS_SECRET_ACCESS_KEY= | env: AWS_ACCESS_KEY_ID=AWS_SECRET_ACCESS_KEY=
| MIT | examples/rasterio.ipynb | sackh/python-geospatial |
In the script below we will use the AWS boto3 module to examine the structure of the Landsat Public Dataset. `LC08_L1TP_139045_20170304_20170316_01_T1` is a Landsat scene ID with a standard pattern. | import re
scene = 'LC08_L1TP_139045_20170304_20170316_01_T1'
path, row = re.match(r'LC08_L1TP_(\d{3})(\d{3})', scene).groups()
prefix = f'c1/L8/{path}/{row}/{scene}'
import boto3
for objsum in boto3.resource('s3').Bucket('landsat-pds').objects.filter(Prefix=prefix):
print(objsum.bucket_name, objsum.key, objsum.size) | landsat-pds c1/L8/139/045/LC08_L1TP_139045_20170304_20170316_01_T1/LC08_L1TP_139045_20170304_20170316_01_T1_ANG.txt 117122
landsat-pds c1/L8/139/045/LC08_L1TP_139045_20170304_20170316_01_T1/LC08_L1TP_139045_20170304_20170316_01_T1_B1.TIF 50091654
landsat-pds c1/L8/139/045/LC08_L1TP_139045_20170304_20170316_01_T1/LC08_L1TP_139045_20170304_20170316_01_T1_B1.TIF.ovr 6454401
landsat-pds c1/L8/139/045/LC08_L1TP_139045_20170304_20170316_01_T1/LC08_L1TP_139045_20170304_20170316_01_T1_B10.TIF 48758134
landsat-pds c1/L8/139/045/LC08_L1TP_139045_20170304_20170316_01_T1/LC08_L1TP_139045_20170304_20170316_01_T1_B10.TIF.ovr 7379918
landsat-pds c1/L8/139/045/LC08_L1TP_139045_20170304_20170316_01_T1/LC08_L1TP_139045_20170304_20170316_01_T1_B10_wrk.IMD 11597
landsat-pds c1/L8/139/045/LC08_L1TP_139045_20170304_20170316_01_T1/LC08_L1TP_139045_20170304_20170316_01_T1_B11.TIF 46753150
landsat-pds c1/L8/139/045/LC08_L1TP_139045_20170304_20170316_01_T1/LC08_L1TP_139045_20170304_20170316_01_T1_B11.TIF.ovr 7202288
landsat-pds c1/L8/139/045/LC08_L1TP_139045_20170304_20170316_01_T1/LC08_L1TP_139045_20170304_20170316_01_T1_B11_wrk.IMD 11597
landsat-pds c1/L8/139/045/LC08_L1TP_139045_20170304_20170316_01_T1/LC08_L1TP_139045_20170304_20170316_01_T1_B1_wrk.IMD 11597
landsat-pds c1/L8/139/045/LC08_L1TP_139045_20170304_20170316_01_T1/LC08_L1TP_139045_20170304_20170316_01_T1_B2.TIF 51415509
landsat-pds c1/L8/139/045/LC08_L1TP_139045_20170304_20170316_01_T1/LC08_L1TP_139045_20170304_20170316_01_T1_B2.TIF.ovr 6776630
landsat-pds c1/L8/139/045/LC08_L1TP_139045_20170304_20170316_01_T1/LC08_L1TP_139045_20170304_20170316_01_T1_B2_wrk.IMD 11597
landsat-pds c1/L8/139/045/LC08_L1TP_139045_20170304_20170316_01_T1/LC08_L1TP_139045_20170304_20170316_01_T1_B3.TIF 55266974
landsat-pds c1/L8/139/045/LC08_L1TP_139045_20170304_20170316_01_T1/LC08_L1TP_139045_20170304_20170316_01_T1_B3.TIF.ovr 7207728
landsat-pds c1/L8/139/045/LC08_L1TP_139045_20170304_20170316_01_T1/LC08_L1TP_139045_20170304_20170316_01_T1_B3_wrk.IMD 11597
landsat-pds c1/L8/139/045/LC08_L1TP_139045_20170304_20170316_01_T1/LC08_L1TP_139045_20170304_20170316_01_T1_B4.TIF 59330924
landsat-pds c1/L8/139/045/LC08_L1TP_139045_20170304_20170316_01_T1/LC08_L1TP_139045_20170304_20170316_01_T1_B4.TIF.ovr 7682022
landsat-pds c1/L8/139/045/LC08_L1TP_139045_20170304_20170316_01_T1/LC08_L1TP_139045_20170304_20170316_01_T1_B4_wrk.IMD 11597
landsat-pds c1/L8/139/045/LC08_L1TP_139045_20170304_20170316_01_T1/LC08_L1TP_139045_20170304_20170316_01_T1_B5.TIF 63037553
landsat-pds c1/L8/139/045/LC08_L1TP_139045_20170304_20170316_01_T1/LC08_L1TP_139045_20170304_20170316_01_T1_B5.TIF.ovr 8033890
landsat-pds c1/L8/139/045/LC08_L1TP_139045_20170304_20170316_01_T1/LC08_L1TP_139045_20170304_20170316_01_T1_B5_wrk.IMD 11597
landsat-pds c1/L8/139/045/LC08_L1TP_139045_20170304_20170316_01_T1/LC08_L1TP_139045_20170304_20170316_01_T1_B6.TIF 65134525
landsat-pds c1/L8/139/045/LC08_L1TP_139045_20170304_20170316_01_T1/LC08_L1TP_139045_20170304_20170316_01_T1_B6.TIF.ovr 8283172
landsat-pds c1/L8/139/045/LC08_L1TP_139045_20170304_20170316_01_T1/LC08_L1TP_139045_20170304_20170316_01_T1_B6_wrk.IMD 11597
landsat-pds c1/L8/139/045/LC08_L1TP_139045_20170304_20170316_01_T1/LC08_L1TP_139045_20170304_20170316_01_T1_B7.TIF 64089521
landsat-pds c1/L8/139/045/LC08_L1TP_139045_20170304_20170316_01_T1/LC08_L1TP_139045_20170304_20170316_01_T1_B7.TIF.ovr 8161327
landsat-pds c1/L8/139/045/LC08_L1TP_139045_20170304_20170316_01_T1/LC08_L1TP_139045_20170304_20170316_01_T1_B7_wrk.IMD 11597
landsat-pds c1/L8/139/045/LC08_L1TP_139045_20170304_20170316_01_T1/LC08_L1TP_139045_20170304_20170316_01_T1_B8.TIF 229147981
landsat-pds c1/L8/139/045/LC08_L1TP_139045_20170304_20170316_01_T1/LC08_L1TP_139045_20170304_20170316_01_T1_B8.TIF.ovr 28702520
landsat-pds c1/L8/139/045/LC08_L1TP_139045_20170304_20170316_01_T1/LC08_L1TP_139045_20170304_20170316_01_T1_B8_wrk.IMD 11597
landsat-pds c1/L8/139/045/LC08_L1TP_139045_20170304_20170316_01_T1/LC08_L1TP_139045_20170304_20170316_01_T1_B9.TIF 38573789
landsat-pds c1/L8/139/045/LC08_L1TP_139045_20170304_20170316_01_T1/LC08_L1TP_139045_20170304_20170316_01_T1_B9.TIF.ovr 3510656
landsat-pds c1/L8/139/045/LC08_L1TP_139045_20170304_20170316_01_T1/LC08_L1TP_139045_20170304_20170316_01_T1_B9_wrk.IMD 11597
landsat-pds c1/L8/139/045/LC08_L1TP_139045_20170304_20170316_01_T1/LC08_L1TP_139045_20170304_20170316_01_T1_BQA.TIF 1921058
landsat-pds c1/L8/139/045/LC08_L1TP_139045_20170304_20170316_01_T1/LC08_L1TP_139045_20170304_20170316_01_T1_BQA.TIF.ovr 367874
landsat-pds c1/L8/139/045/LC08_L1TP_139045_20170304_20170316_01_T1/LC08_L1TP_139045_20170304_20170316_01_T1_BQA_wrk.IMD 11597
landsat-pds c1/L8/139/045/LC08_L1TP_139045_20170304_20170316_01_T1/LC08_L1TP_139045_20170304_20170316_01_T1_MTL.json 10565
landsat-pds c1/L8/139/045/LC08_L1TP_139045_20170304_20170316_01_T1/LC08_L1TP_139045_20170304_20170316_01_T1_MTL.txt 8695
landsat-pds c1/L8/139/045/LC08_L1TP_139045_20170304_20170316_01_T1/LC08_L1TP_139045_20170304_20170316_01_T1_thumb_large.jpg 148845
landsat-pds c1/L8/139/045/LC08_L1TP_139045_20170304_20170316_01_T1/LC08_L1TP_139045_20170304_20170316_01_T1_thumb_small.jpg 8090
landsat-pds c1/L8/139/045/LC08_L1TP_139045_20170304_20170316_01_T1/index.html 5391
| MIT | examples/rasterio.ipynb | sackh/python-geospatial |
There's a web browser in GDALEach of the .TIF files in the landsat-pds bucket is a georeferenced raster dataset formatted as a [cloud optimized GeoTIFF](https://trac.osgeo.org/gdal/wiki/CloudOptimizedGeoTIFF). A GeoTIFF is a TIFF with extra tags specifying spatial reference systems and coordinates and can be accompanied by reduced-resolution .ovr files as well as other auxiliary files.There is a browser in the latest version of GDAL that can navigate these TIFFs and auxiliary files like a web browser navigates linked HTML documents. HTTP and the GeoTIFF format replace specialized geospatial raster services like [WCS](http://www.opengeospatial.org/standards/wcs) in the workflow presented in this notebook.By using GDAL's browser, Rasterio can open and query cloud-optimized GeoTIFFs *without* prior download. Quick overviews of GeoTIFFsRasterio affords us quickly-generated overviews of Landsat PDS GeoTIFFs. In the script below we will open a GeoTIFF stored on S3 (and identified by an AWS CLI style 's3://' URI), read a 10:1 overview of its data as a Numpy ndarray, and display the array. Note that we use no temporary file to do so.The S3 object with the name ending in `B4.TIF` corresponds to the red band of the Landsat imager. | import rasterio
with rasterio.open(f's3://landsat-pds/{prefix}/{scene}_B4.TIF') as src:
arr = src.read(out_shape=(src.height//10, src.width//10))
%matplotlib inline
from matplotlib import pyplot as plt
plt.imshow(arr[0])
plt.show() | _____no_output_____ | MIT | examples/rasterio.ipynb | sackh/python-geospatial |
A look backstageNot only is there a web browser in a Rasterio dataset object, it's a sophisticated web brower that uses HTTP range requests to download the least number of bytes required to execute `src.read()` with the given parameters. With a little extra configuration we can see exactly how few bytes.We will read and display a 10:1 overview as we did for band 4. The S3 object in the listing above with the name ending in `B5.TIF` corresponds to the near-infrared (NIR) band of the Landsat imager.The little extra configuration needed is to use a rasterio environment with `CPL_CURL_VERBOSE=True` as the context for opening and reading a Landsat PDS GeoTIFF. | with rasterio.Env(CPL_CURL_VERBOSE=True):
with rasterio.open(f's3://landsat-pds/{prefix}/{scene}_B5.TIF') as src:
arr = src.read(out_shape=(src.height//10, src.width//10))
plt.imshow(arr[0])
plt.show() | _____no_output_____ | MIT | examples/rasterio.ipynb | sackh/python-geospatial |
Within a `rasterio.Env` context with `CPL_CURL_VERBOSE=True`, the GDAL functions called by `rasterio.open()` and `src.read()` will print HTTP request and response details as you would see if you used `curl -v`.A dissected transcript follows. In the transcript, we can see that 5 HTTP requests are made to display the 10:1 overview image of band 5.First we see the request GDAL makes for only the first 16384 (2^14) bytes of the 63 MB B5.TIF GeoTIFF file.Please note: I've removed sensitive headers from the transcript. Yours will be different.```* Couldn't find host landsat-pds.s3.amazonaws.com in the .netrc file; using defaults* Connection 1 seems to be dead!* Closing connection 1* Trying 52.218.160.34...* TCP_NODELAY set* Connected to landsat-pds.s3.amazonaws.com (52.218.160.34) port 443 (2)* SSL re-using session ID* TLS 1.2 connection using TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256* Server certificate: *.s3.amazonaws.com* Server certificate: DigiCert Baltimore CA-2 G2* Server certificate: Baltimore CyberTrust Root> GET /c1/L8/139/045/LC08_L1TP_139045_20170304_20170316_01_T1/LC08_L1TP_139045_20170304_20170316_01_T1_B5.TIF HTTP/1.1Host: landsat-pds.s3.amazonaws.comRange: bytes=0-16383Accept: */*< HTTP/1.1 206 Partial Content< Date: Thu, 07 Dec 2017 17:02:07 GMT< Last-Modified: Sat, 29 Apr 2017 11:24:24 GMT< ETag: "8dfaba5cd40136c31959b411038760ab"< Accept-Ranges: bytes< Content-Range: bytes 0-16383/63037553< Content-Type: image/tiff< Content-Length: 16384< Server: AmazonS3<* Connection 2 to host landsat-pds.s3.amazonaws.com left intact```At this point you could get the `profile` attribute of the dataset object we've named `src` and GDAL wouldn't need to download any more bytes to provide the dataset metadata. Thanks to the the TIFF format's consolidation of metadata in the head of the file and [HTTP range requests](https://tools.ietf.org/html/rfc7233), we only need to read 0.03% of the file to know its dimensions, data type, spatial extent, and coordinate reference system.Calling `src.read()` triggers 3 more HTTP requests by GDAL. The third is for the first 16384 (2^14) bytes of the 8 MB .ovr file that GDAL discovered when it fetched the directory listing. In our case, the array returned by ``src.read()`` will come entirely from the .ovr file. For a reference on GeoTIFF overviews, see http://www.gdal.org/frmt_gtiff.html.```* Couldn't find host landsat-pds.s3.amazonaws.com in the .netrc file; using defaults* Found bundle for host landsat-pds.s3.amazonaws.com: 0x109a5a9a0 [can pipeline]* Re-using existing connection! (2) with host landsat-pds.s3.amazonaws.com* Connected to landsat-pds.s3.amazonaws.com (52.218.160.34) port 443 (2)> GET /c1/L8/139/045/LC08_L1TP_139045_20170304_20170316_01_T1/LC08_L1TP_139045_20170304_20170316_01_T1_B5.TIF.ovr HTTP/1.1Host: landsat-pds.s3.amazonaws.comRange: bytes=0-16383Accept: */*< HTTP/1.1 206 Partial Content< Date: Thu, 07 Dec 2017 17:02:07 GMT< Last-Modified: Sat, 29 Apr 2017 11:23:56 GMT< ETag: "d6777167ccd6141537b5e9d71abdcfeb"< Accept-Ranges: bytes< Content-Range: bytes 0-16383/8033890< Content-Type: application/octet-stream< Content-Length: 16384< Server: AmazonS3<* Connection 2 to host landsat-pds.s3.amazonaws.com left intact```The fourth and fifth requests are for overview imagery stored near the tail of the .ovr file, as you can see in the request and response `Content-Range` headers.```* Couldn't find host landsat-pds.s3.amazonaws.com in the .netrc file; using defaults* Found bundle for host landsat-pds.s3.amazonaws.com: 0x109a5a9a0 [can pipeline]* Re-using existing connection! (2) with host landsat-pds.s3.amazonaws.com* Connected to landsat-pds.s3.amazonaws.com (52.218.160.34) port 443 (2)> GET /c1/L8/139/045/LC08_L1TP_139045_20170304_20170316_01_T1/LC08_L1TP_139045_20170304_20170316_01_T1_B5.TIF.ovr HTTP/1.1Host: landsat-pds.s3.amazonaws.comRange: bytes=7110656-7438335Accept: */*< HTTP/1.1 206 Partial Content< Date: Thu, 07 Dec 2017 17:02:07 GMT< Last-Modified: Sat, 29 Apr 2017 11:23:56 GMT< ETag: "d6777167ccd6141537b5e9d71abdcfeb"< Accept-Ranges: bytes< Content-Range: bytes 7110656-7438335/8033890< Content-Type: application/octet-stream< Content-Length: 327680< Server: AmazonS3<* Connection 2 to host landsat-pds.s3.amazonaws.com left intact* Couldn't find host landsat-pds.s3.amazonaws.com in the .netrc file; using defaults* Found bundle for host landsat-pds.s3.amazonaws.com: 0x109a5a9a0 [can pipeline]* Re-using existing connection! (2) with host landsat-pds.s3.amazonaws.com* Connected to landsat-pds.s3.amazonaws.com (52.218.160.34) port 443 (2)> GET /c1/L8/139/045/LC08_L1TP_139045_20170304_20170316_01_T1/LC08_L1TP_139045_20170304_20170316_01_T1_B5.TIF.ovr HTTP/1.1Host: landsat-pds.s3.amazonaws.comRange: bytes=7438336-8033889Accept: */*< HTTP/1.1 206 Partial Content< Date: Thu, 07 Dec 2017 17:02:07 GMT< Last-Modified: Sat, 29 Apr 2017 11:23:56 GMT< ETag: "d6777167ccd6141537b5e9d71abdcfeb"< Accept-Ranges: bytes< Content-Range: bytes 7438336-8033889/8033890< Content-Type: application/octet-stream< Content-Length: 595554< Server: AmazonS3<* Connection 2 to host landsat-pds.s3.amazonaws.com left intact```We got a 10:1 overview of one band of one Landsat scene and downloaded only 1/9th of its .ovr file – which is itself only about 1/8th of the target file. Quick subsets of GeoTIFFsHaving seen how GeoTIFF overviews work in the cloud, let's look at access to full resolution subsets of imagery.Here we'll read imagery from a random block of the GeoTIFF. Please note that blocks near the south and east edges of the GeoTIFF may be smaller than 512 x 512 pixels. | import random
with rasterio.Env(CPL_CURL_VERBOSE=True):
with rasterio.open(f's3://landsat-pds/{prefix}/{scene}_B5.TIF') as src:
ij, window = random.choice(list(src.block_windows()))
print(ij, window)
arr = src.read(window=window)
plt.imshow(arr[0])
plt.show() | (5, 7) Window(col_off=3584, row_off=2560, width=512, height=512)
| MIT | examples/rasterio.ipynb | sackh/python-geospatial |
Backstage againHere is the transcript.```* Hostname landsat-pds.s3.amazonaws.com was found in DNS cache* Trying 52.218.208.122...* TCP_NODELAY set* Connected to landsat-pds.s3.amazonaws.com (52.218.208.122) port 443 (5)* SSL re-using session ID* TLS 1.2 connection using TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256* Server certificate: *.s3.amazonaws.com* Server certificate: DigiCert Baltimore CA-2 G2* Server certificate: Baltimore CyberTrust Root> GET /c1/L8/139/045/LC08_L1TP_139045_20170304_20170316_01_T1/LC08_L1TP_139045_20170304_20170316_01_T1_B5.TIF HTTP/1.1Host: landsat-pds.s3.amazonaws.comRange: bytes=44646400-44957695Accept: */*< HTTP/1.1 206 Partial Content< Date: Thu, 07 Dec 2017 18:17:20 GMT< Last-Modified: Sat, 29 Apr 2017 11:24:24 GMT< ETag: "8dfaba5cd40136c31959b411038760ab"< Accept-Ranges: bytes< Content-Range: bytes 44646400-44957695/63037553< Content-Type: image/tiff< Content-Length: 311296< Server: AmazonS3<* Connection 5 to host landsat-pds.s3.amazonaws.com left intact```We've downloaded only 311 KB (every block of the GeoTIFF is DEFLATE compressed) of a 63 MB file to get that piece of data.GDAL's GeoTIFF browser caches the data in the fetched byte ranges, so you may not see any curl transcripts from subsequent requests. Finer control of caching will be a feature of GDAL 2.3 and future version of Rasterio. Lazy warping: WarpedVRTThe Landsat PDS data is georeferenced using the [Universal Transverse Mercator (UTM) system](https://en.wikipedia.org/wiki/Universal_Transverse_Mercator_coordinate_system). To use it in another system such as Web Mercator (also known as 'epsg:3857', as in Google Maps, Mapbox, etc.) it must be reprojected or *warped*.Rasterio has an abstraction for reprojection that also does not require prior download of the GeoTIFF file and, as with the previously discussed patterns, fetches the least number of bytes required to fill the reading window.In the script below we fetch imagery from the B5.TIF (georeferenced to UTM Zone 45) that intersects with the zoom level 11 Web Mercator tile at the center of the GeoTIFF. We will use functions from the mercantile module to get the bounds of the that tile. | import mercantile
from rasterio.vrt import WarpedVRT
with rasterio.open(f's3://landsat-pds/{prefix}/{scene}_B5.TIF') as src:
lng, lat = src.lnglat()
tile = mercantile.tile(lng, lat, 11)
merc_bounds = mercantile.xy_bounds(tile)
with WarpedVRT(src, dst_crs='epsg:3857') as vrt:
window = vrt.window(*merc_bounds)
arr_transform = vrt.window_transform(window)
arr = vrt.read(window=window)
plt.imshow(arr[0])
plt.show() | _____no_output_____ | MIT | examples/rasterio.ipynb | sackh/python-geospatial |
Formatted files in RAM: MemoryFileRaster data processing often involves temporary files. For example, in making a set of Web Mercator tiles from a differently projected raster dataset we may use a temporary GeoTIFF dataset to hold the result of a warp operation and then transform this into a JPEG, PNG, or WebP for use on the web.Python has a `NamedTemporaryFile` class in its `tempfile` module that is well suited for this task. It has a visible name in the filesystem, which GDAL requires, and is automatically cleaned up when no longer used. Its usage a raster-processing program is something like we see in the script below. | from tempfile import NamedTemporaryFile
count, height, width = arr.shape
dtype = arr.dtype
with NamedTemporaryFile() as temp:
with rasterio.open(temp.name, 'w', driver='GTiff', dtype=dtype,
count=count, height=height, width=width,
transform=arr_transform) as dst:
dst.write(arr)
temp_bytes = temp.read() | _____no_output_____ | MIT | examples/rasterio.ipynb | sackh/python-geospatial |
We can see an indicator that we have a TIFF file in `temp` if we print the first few bytes. | print(temp_bytes[:20]) | b'II*\x00\x08\x00\x00\x00\r\x00\x00\x01\x03\x00\x01\x00\x00\x00\\\x02'
| MIT | examples/rasterio.ipynb | sackh/python-geospatial |
Let’s say you want to write a program like this that will run on a computer with a very limited filesystem or no filesystem at all. Python has an in-memory binary file-like class, `io.BytesIO`, but, unlike `NamedTemporaryFile`, instances of `BytesIO` lack the name GDAL needs to access data. To solve this problem, Rasterio provides a new class, `io.MemoryFile`, a drop-in replacement for Python’s `NamedTemporaryFile` which keeps its bytes in a virtual file in an in-memory filesystem that GDAL can access, not on disk.The usage of `MemoryFile` is modeled after Python’s `zipfile.ZipFile` class. `MemoryFile.open` returns a dataset object, just as `rasterio.open` does. | from rasterio.io import MemoryFile
with MemoryFile() as temp:
with temp.open(driver='GTiff', dtype=dtype,
count=count, height=height, width=width,
transform=arr_transform) as dst:
dst.write(arr)
png_bytes = temp.read()
print(temp_bytes[:20]) | b'II*\x00\x08\x00\x00\x00\r\x00\x00\x01\x03\x00\x01\x00\x00\x00\\\x02'
| MIT | examples/rasterio.ipynb | sackh/python-geospatial |
A `MemoryFile` can also be used to access datasets contained in a stream of bytes. | with MemoryFile(temp_bytes) as temp:
with temp.open() as src:
print(src.profile) | {'driver': 'GTiff', 'dtype': 'uint16', 'nodata': None, 'width': 604, 'height': 604, 'count': 1, 'crs': None, 'transform': Affine(32.374971311808814, 0.0, 9666532.345057327,
0.0, -32.374971311808814, 2485120.663606849), 'tiled': False, 'interleave': 'band'}
| MIT | examples/rasterio.ipynb | sackh/python-geospatial |
Below is an example of downloading an entire Landsat PDS GeoTIFF to a stream of bytes and then opening the stream of bytes. | from io import BytesIO
f's3://landsat-pds/{prefix}/{scene}_B4.TIF'
s3 = boto3.resource('s3')
bucket = s3.Bucket('landsat-pds')
obj = bucket.Object(f'{prefix}/{scene}_B4.TIF')
with BytesIO() as temp:
obj.download_fileobj(temp)
temp.seek(0)
with MemoryFile(temp) as memfile:
with memfile.open() as src:
print(src.profile) | {'driver': 'GTiff', 'dtype': 'uint16', 'nodata': None, 'width': 7611, 'height': 7771, 'count': 1, 'crs': CRS({'init': 'epsg:32645'}), 'transform': Affine(30.0, 0.0, 382185.0,
0.0, -30.0, 2512515.0), 'blockxsize': 512, 'blockysize': 512, 'tiled': True, 'compress': 'deflate', 'interleave': 'band'}
| MIT | examples/rasterio.ipynb | sackh/python-geospatial |
Zip files in memoryRasterio can read datasets within zipped streams of bytes. Zipfiles are commonly used in the GIS domain to package legacy multi-file formats like shapefiles (a shapefile is actually an ensemble of .shp, .dbf, .shx, .prj, and other files) or virtual raster files (VRT) and the rasters they reference.Below we'll fetch a VRT and JPEG pair from the Rasterio GitHub repo and package them in an in-memory zip file to simulate a zip file such as one that a server might accept as an upload. | import io
import zipfile
import requests
temp = io.BytesIO()
with zipfile.ZipFile(temp, 'w') as pkg:
res = requests.get('https://raw.githubusercontent.com/mapbox/rasterio/master/tests/data/389225main_sw_1965_1024.jpg')
pkg.writestr('389225main_sw_1965_1024.jpg', res.content)
res = requests.get('https://raw.githubusercontent.com/mapbox/rasterio/master/tests/data/white-gemini-iv.vrt')
pkg.writestr('white-gemini-iv.vrt', res.content) | _____no_output_____ | MIT | examples/rasterio.ipynb | sackh/python-geospatial |
We then read the zipped VRT file. You must rewind the `BytesIO` file because its current position has been left at its end. | from rasterio.io import ZipMemoryFile
temp.seek(0)
with ZipMemoryFile(temp) as zipmemfile:
with zipmemfile.open('white-gemini-iv.vrt') as src:
rgb = src.read()
import numpy
plt.imshow(numpy.rollaxis(rgb, 0, 3))
plt.show() | /Users/sean/envs/rio-blog-post/lib/python3.6/site-packages/rasterio/io.py:157: NotGeoreferencedWarning: Dataset has no geotransform set. Default transform will be applied (Affine.identity())
return DatasetReader(vsi_path, driver=driver, **kwargs)
| MIT | examples/rasterio.ipynb | sackh/python-geospatial |
SVM (Support Vector Machines) In this notebook, you will use SVM (Support Vector Machines) to build and train a model using human cell records, and classify cells to whether the samples are benign or malignant.SVM works by mapping data to a high-dimensional feature space so that data points can be categorized, even when the data are not otherwise linearly separable. A separator between the categories is found, then the data is transformed in such a way that the separator could be drawn as a hyperplane. Following this, characteristics of new data can be used to predict the group to which a new record should belong. Table of contents Load the Cancer data Modeling Evaluation Practice | import pandas as pd
import pylab as pl
import numpy as np
import scipy.optimize as opt
from sklearn import preprocessing
from sklearn.model_selection import train_test_split
%matplotlib inline
import matplotlib.pyplot as plt | _____no_output_____ | BSD-4-Clause-UC | 08 ML0101EN-Clas-SVM-cancer-py-v1.ipynb | barathevergreen/Machine_Learning_with_python_sklearn_scipy_IBM_Projects |
Load the Cancer dataThe example is based on a dataset that is publicly available from the UCI Machine Learning Repository (Asuncion and Newman, 2007)[http://mlearn.ics.uci.edu/MLRepository.html]. The dataset consists of several hundred human cell sample records, each of which contains the values of a set of cell characteristics. The fields in each record are:|Field name|Description||--- |--- ||ID|Clump thickness||Clump|Clump thickness||UnifSize|Uniformity of cell size||UnifShape|Uniformity of cell shape||MargAdh|Marginal adhesion||SingEpiSize|Single epithelial cell size||BareNuc|Bare nuclei||BlandChrom|Bland chromatin||NormNucl|Normal nucleoli||Mit|Mitoses||Class|Benign or malignant|For the purposes of this example, we're using a dataset that has a relatively small number of predictors in each record. To download the data, we will use `!wget` to download it from IBM Object Storage. __Did you know?__ When it comes to Machine Learning, you will likely be working with large datasets. As a business, where can you host your data? IBM is offering a unique opportunity for businesses, with 10 Tb of IBM Cloud Object Storage: [Sign up now for free](http://cocl.us/ML0101EN-IBM-Offer-CC) | #Click here and press Shift+Enter
!pip install wget
!wget -O cell_samples.csv https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/ML0101ENv3/labs/cell_samples.csv | Requirement already satisfied: wget in /Users/baraths/opt/anaconda3/lib/python3.7/site-packages (3.2)
/bin/sh: wget: command not found
| BSD-4-Clause-UC | 08 ML0101EN-Clas-SVM-cancer-py-v1.ipynb | barathevergreen/Machine_Learning_with_python_sklearn_scipy_IBM_Projects |
Load Data From CSV File | cell_df = pd.read_csv("cell_samples (1).csv")
cell_df.head() | _____no_output_____ | BSD-4-Clause-UC | 08 ML0101EN-Clas-SVM-cancer-py-v1.ipynb | barathevergreen/Machine_Learning_with_python_sklearn_scipy_IBM_Projects |
The ID field contains the patient identifiers. The characteristics of the cell samples from each patient are contained in fields Clump to Mit. The values are graded from 1 to 10, with 1 being the closest to benign.The Class field contains the diagnosis, as confirmed by separate medical procedures, as to whether the samples are benign (value = 2) or malignant (value = 4).Lets look at the distribution of the classes based on Clump thickness and Uniformity of cell size: | #Taking only 50 values to understand
#Giving values in ax and applying ax in another plot to see together (Axes - oo style plot)
#Give Label to automatically show legend
#only Malignant(Class = 4)
ax = cell_df[cell_df['Class'] == 4][0:50].plot(kind='scatter', x='Clump', y='UnifSize', color='DarkBlue', label='malignant')
#only benign(Class = 2)
#plot together
cell_df[cell_df['Class'] == 2][0:50].plot(kind='scatter', x='Clump', y='UnifSize', color='Yellow', label='benign', ax=ax)
plt.show() | _____no_output_____ | BSD-4-Clause-UC | 08 ML0101EN-Clas-SVM-cancer-py-v1.ipynb | barathevergreen/Machine_Learning_with_python_sklearn_scipy_IBM_Projects |
Data pre-processing and selection Lets first look at columns data types: | cell_df.dtypes | _____no_output_____ | BSD-4-Clause-UC | 08 ML0101EN-Clas-SVM-cancer-py-v1.ipynb | barathevergreen/Machine_Learning_with_python_sklearn_scipy_IBM_Projects |
It looks like the __BareNuc__ column includes some values that are not numerical. We can convert them to int wherever values are available:__Note:__errors kwarg in to_numeric:{‘ignore’, ‘raise’, ‘coerce’}, default ‘raise’If ‘raise’, then invalid parsing will raise an exception.If ‘coerce’, then invalid parsing will be set as __NaN__.If ‘ignore’, then invalid parsing will return the input. | #Convert to numeric and put NaN for values wherever not present:
cell_df = cell_df[pd.to_numeric(cell_df['BareNuc'], errors='coerce').notnull()]
cell_df['BareNuc'] = cell_df['BareNuc'].astype('int')
cell_df.dtypes
feature_df = cell_df[['Clump', 'UnifSize', 'UnifShape', 'MargAdh', 'SingEpiSize', 'BareNuc', 'BlandChrom', 'NormNucl', 'Mit']]
X = np.asarray(feature_df)
X[0:5] | _____no_output_____ | BSD-4-Clause-UC | 08 ML0101EN-Clas-SVM-cancer-py-v1.ipynb | barathevergreen/Machine_Learning_with_python_sklearn_scipy_IBM_Projects |
We want the model to predict the value of Class (that is, benign (=2) or malignant (=4)). As this field can have one of only two possible values, we need to change its measurement level to reflect this. | cell_df['Class'] = cell_df['Class'].astype('int')
y = np.asarray(cell_df['Class'])
y [0:5] | _____no_output_____ | BSD-4-Clause-UC | 08 ML0101EN-Clas-SVM-cancer-py-v1.ipynb | barathevergreen/Machine_Learning_with_python_sklearn_scipy_IBM_Projects |
Train/Test dataset Okay, we split our dataset into train and test set: | X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.2, random_state=4)
print ('Train set:', X_train.shape, y_train.shape)
print ('Test set:', X_test.shape, y_test.shape) | Train set: (546, 9) (546,)
Test set: (137, 9) (137,)
| BSD-4-Clause-UC | 08 ML0101EN-Clas-SVM-cancer-py-v1.ipynb | barathevergreen/Machine_Learning_with_python_sklearn_scipy_IBM_Projects |
Modeling (SVM with Scikit-learn) The SVM algorithm offers a choice of kernel functions for performing its processing. Basically, mapping data into a higher dimensional space is called kernelling. The mathematical function used for the transformation is known as the kernel function, and can be of different types, such as: 1.Linear 2.Polynomial 3.Radial basis function (RBF) 4.SigmoidEach of these functions has its characteristics, its pros and cons, and its equation, but as there's no easy way of knowing which function performs best with any given dataset, we usually choose different functions in turn and compare the results. Let's just use the default, RBF (Radial Basis Function) for this lab. | #We use Support vector classifier from Support Vector Machine:
from sklearn import svm
clf = svm.SVC(kernel='rbf') #even if you dont specify default is 'rbf'
clf.fit(X_train, y_train) | _____no_output_____ | BSD-4-Clause-UC | 08 ML0101EN-Clas-SVM-cancer-py-v1.ipynb | barathevergreen/Machine_Learning_with_python_sklearn_scipy_IBM_Projects |
After being fitted, the model can then be used to predict new values: | yhat = clf.predict(X_test)
yhat [0:5] | _____no_output_____ | BSD-4-Clause-UC | 08 ML0101EN-Clas-SVM-cancer-py-v1.ipynb | barathevergreen/Machine_Learning_with_python_sklearn_scipy_IBM_Projects |
Evaluation | from sklearn.metrics import classification_report, confusion_matrix
import itertools
def plot_confusion_matrix(cm, classes,
normalize=False,
title='Confusion matrix',
cmap=plt.cm.Blues):
"""
This function prints and plots the confusion matrix.
Normalization can be applied by setting `normalize=True`.
"""
if normalize:
cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
print("Normalized confusion matrix")
else:
print('Confusion matrix, without normalization')
print(cm)
plt.imshow(cm, interpolation='nearest', cmap=cmap)
plt.title(title)
plt.colorbar()
tick_marks = np.arange(len(classes))
plt.xticks(tick_marks, classes, rotation=45)
plt.yticks(tick_marks, classes)
fmt = '.2f' if normalize else 'd'
thresh = cm.max() / 2.
for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
plt.text(j, i, format(cm[i, j], fmt),
horizontalalignment="center",
color="white" if cm[i, j] > thresh else "black")
plt.tight_layout()
plt.ylabel('True label')
plt.xlabel('Predicted label')
# Compute confusion matrix
cnf_matrix = confusion_matrix(y_test, yhat, labels=[2,4])
np.set_printoptions(precision=2)
print (classification_report(y_test, yhat))
# Plot non-normalized confusion matrix
plt.figure()
plot_confusion_matrix(cnf_matrix, classes=['Benign(2)','Malignant(4)'],normalize= False, title='Confusion matrix') | precision recall f1-score support
2 1.00 0.94 0.97 90
4 0.90 1.00 0.95 47
accuracy 0.96 137
macro avg 0.95 0.97 0.96 137
weighted avg 0.97 0.96 0.96 137
Confusion matrix, without normalization
[[85 5]
[ 0 47]]
| BSD-4-Clause-UC | 08 ML0101EN-Clas-SVM-cancer-py-v1.ipynb | barathevergreen/Machine_Learning_with_python_sklearn_scipy_IBM_Projects |
You can also easily use the __f1_score__ from sklearn library: | from sklearn.metrics import f1_score
f1_score(y_test, yhat, average='weighted') | _____no_output_____ | BSD-4-Clause-UC | 08 ML0101EN-Clas-SVM-cancer-py-v1.ipynb | barathevergreen/Machine_Learning_with_python_sklearn_scipy_IBM_Projects |
Lets try jaccard index for accuracy: | from sklearn.metrics import jaccard_similarity_score
jaccard_similarity_score(y_test, yhat) | /Users/baraths/opt/anaconda3/lib/python3.7/site-packages/sklearn/metrics/_classification.py:664: FutureWarning: jaccard_similarity_score has been deprecated and replaced with jaccard_score. It will be removed in version 0.23. This implementation has surprising behavior for binary and multiclass classification tasks.
FutureWarning)
| BSD-4-Clause-UC | 08 ML0101EN-Clas-SVM-cancer-py-v1.ipynb | barathevergreen/Machine_Learning_with_python_sklearn_scipy_IBM_Projects |
PracticeCan you rebuild the model, but this time with a __linear__ kernel? You can use __kernel='linear'__ option, when you define the svm. How the accuracy changes with the new kernel function? | # write your code here
clf2 = svm.SVC(kernel='linear')
clf2.fit(X_train, y_train)
yhat2 = clf2.predict(X_test)
print("Avg F1-score: %.4f" % f1_score(y_test, yhat2, average='weighted'))
print("Jaccard score: %.4f" % jaccard_similarity_score(y_test, yhat2)) | Avg F1-score: 0.9639
Jaccard score: 0.9635
| BSD-4-Clause-UC | 08 ML0101EN-Clas-SVM-cancer-py-v1.ipynb | barathevergreen/Machine_Learning_with_python_sklearn_scipy_IBM_Projects |
Dictionaries in PythonEstimated time needed: **20** minutes ObjectivesAfter completing this lab you will be able to:- Work with libraries in Python, including operations Table of Contents Dictionaries What are Dictionaries? Keys Quiz on Dictionaries Dictionaries What are Dictionaries? A dictionary consists of keys and values. It is helpful to compare a dictionary to a list. Instead of the numerical indexes such as a list, dictionaries have keys. These keys are the keys that are used to access values within a dictionary. An example of a Dictionary Dict: | # Create the dictionary
Dict = {"key1": 1, "key2": "2", "key3": [3, 3, 3], "key4": (4, 4, 4), ('key5'): 5, (0, 1): 6}
Dict | _____no_output_____ | FSFAP | 4_Python for Data Science, AI & Development/PY0101EN-2-3-Dictionaries.ipynb | lebinh97/IBM-DataScience-Capstone |
The keys can be strings: | # Access to the value by the key
a = Dict["key1"]
b = Dict["key4"]
print(a)
print(b) | 1
(4, 4, 4)
| FSFAP | 4_Python for Data Science, AI & Development/PY0101EN-2-3-Dictionaries.ipynb | lebinh97/IBM-DataScience-Capstone |
Keys can also be any immutable object such as a tuple: | # Access to the value by the key
Dict[(0, 1)] | _____no_output_____ | FSFAP | 4_Python for Data Science, AI & Development/PY0101EN-2-3-Dictionaries.ipynb | lebinh97/IBM-DataScience-Capstone |
Each key is separated from its value by a colon ":". Commas separate the items, and the whole dictionary is enclosed in curly braces. An empty dictionary without any items is written with just two curly braces, like this "{}". | # Create a sample dictionary
release_year_dict = {"Thriller": "1982", "Back in Black": "1980", \
"The Dark Side of the Moon": "1973", "The Bodyguard": "1992", \
"Bat Out of Hell": "1977", "Their Greatest Hits (1971-1975)": "1976", \
"Saturday Night Fever": "1977", "Rumours": "1977"}
release_year_dict | _____no_output_____ | FSFAP | 4_Python for Data Science, AI & Development/PY0101EN-2-3-Dictionaries.ipynb | lebinh97/IBM-DataScience-Capstone |
In summary, like a list, a dictionary holds a sequence of elements. Each element is represented by a key and its corresponding value. Dictionaries are created with two curly braces containing keys and values separated by a colon. For every key, there can only be one single value, however, multiple keys can hold the same value. Keys can only be strings, numbers, or tuples, but values can be any data type. It is helpful to visualize the dictionary as a table, as in the following image. The first column represents the keys, the second column represents the values. Keys You can retrieve the values based on the names: | # Get value by keys
release_year_dict['Thriller'] | _____no_output_____ | FSFAP | 4_Python for Data Science, AI & Development/PY0101EN-2-3-Dictionaries.ipynb | lebinh97/IBM-DataScience-Capstone |
This corresponds to: Similarly for The Bodyguard | # Get value by key
release_year_dict['The Bodyguard'] | _____no_output_____ | FSFAP | 4_Python for Data Science, AI & Development/PY0101EN-2-3-Dictionaries.ipynb | lebinh97/IBM-DataScience-Capstone |
Now let us retrieve the keys of the dictionary using the method keys(): | # Get all the keys in dictionary
release_year_dict.keys() | _____no_output_____ | FSFAP | 4_Python for Data Science, AI & Development/PY0101EN-2-3-Dictionaries.ipynb | lebinh97/IBM-DataScience-Capstone |
You can retrieve the values using the method values(): | # Get all the values in dictionary
release_year_dict.values() | _____no_output_____ | FSFAP | 4_Python for Data Science, AI & Development/PY0101EN-2-3-Dictionaries.ipynb | lebinh97/IBM-DataScience-Capstone |
We can add an entry: | # Append value with key into dictionary
release_year_dict['Graduation'] = '2007'
release_year_dict | _____no_output_____ | FSFAP | 4_Python for Data Science, AI & Development/PY0101EN-2-3-Dictionaries.ipynb | lebinh97/IBM-DataScience-Capstone |
We can delete an entry: | # Delete entries by key
del(release_year_dict['Thriller'])
del(release_year_dict['Graduation'])
release_year_dict | _____no_output_____ | FSFAP | 4_Python for Data Science, AI & Development/PY0101EN-2-3-Dictionaries.ipynb | lebinh97/IBM-DataScience-Capstone |
We can verify if an element is in the dictionary: | # Verify the key is in the dictionary
'The Bodyguard' in release_year_dict | _____no_output_____ | FSFAP | 4_Python for Data Science, AI & Development/PY0101EN-2-3-Dictionaries.ipynb | lebinh97/IBM-DataScience-Capstone |
Quiz on Dictionaries You will need this dictionary for the next two questions: | # Question sample dictionary
soundtrack_dic = {"The Bodyguard":"1992", "Saturday Night Fever":"1977"}
soundtrack_dic | _____no_output_____ | FSFAP | 4_Python for Data Science, AI & Development/PY0101EN-2-3-Dictionaries.ipynb | lebinh97/IBM-DataScience-Capstone |
a) In the dictionary soundtrack_dic what are the keys ? | # Write your code below and press Shift+Enter to execute
soundtrack_dic.keys() | _____no_output_____ | FSFAP | 4_Python for Data Science, AI & Development/PY0101EN-2-3-Dictionaries.ipynb | lebinh97/IBM-DataScience-Capstone |
Click here for the solution```pythonsoundtrack_dic.keys() The Keys "The Bodyguard" and "Saturday Night Fever" ``` b) In the dictionary soundtrack_dic what are the values ? | # Write your code below and press Shift+Enter to execute
soundtrack_dic.values() | _____no_output_____ | FSFAP | 4_Python for Data Science, AI & Development/PY0101EN-2-3-Dictionaries.ipynb | lebinh97/IBM-DataScience-Capstone |
Click here for the solution```pythonsoundtrack_dic.values() The values are "1992" and "1977"``` You will need this dictionary for the following questions: The Albums Back in Black, The Bodyguard and Thriller have the following music recording sales in millions 50, 50 and 65 respectively: a) Create a dictionary album_sales_dict where the keys are the album name and the sales in millions are the values. | # Write your code below and press Shift+Enter to execute
album_sales_dict = { "Back in Black" : 50, "The Bodyguard" : 50, "Thriller" : 65}
album_sales_dict | _____no_output_____ | FSFAP | 4_Python for Data Science, AI & Development/PY0101EN-2-3-Dictionaries.ipynb | lebinh97/IBM-DataScience-Capstone |
Click here for the solution```pythonalbum_sales_dict = {"The Bodyguard":50, "Back in Black":50, "Thriller":65}``` b) Use the dictionary to find the total sales of Thriller: | # Write your code below and press Shift+Enter to execute
album_sales_dict["Thriller"] | _____no_output_____ | FSFAP | 4_Python for Data Science, AI & Development/PY0101EN-2-3-Dictionaries.ipynb | lebinh97/IBM-DataScience-Capstone |
Click here for the solution```pythonalbum_sales_dict["Thriller"]``` c) Find the names of the albums from the dictionary using the method keys(): | # Write your code below and press Shift+Enter to execute
album_sales_dict.keys() | _____no_output_____ | FSFAP | 4_Python for Data Science, AI & Development/PY0101EN-2-3-Dictionaries.ipynb | lebinh97/IBM-DataScience-Capstone |
Click here for the solution```pythonalbum_sales_dict.keys()``` d) Find the values of the recording sales from the dictionary using the method values: | # Write your code below and press Shift+Enter to execute
album_sales_dict.values() | _____no_output_____ | FSFAP | 4_Python for Data Science, AI & Development/PY0101EN-2-3-Dictionaries.ipynb | lebinh97/IBM-DataScience-Capstone |
Capstone Project - The Battle of the Neighborhoods Applied Data Science Capstone by IBM/Coursera Table of contents* [Introduction: Business Problem](introduction)* [Data](data)* [Methodology](methodology)* [Analysis](analysis)* [Results and Discussion](results)* [Conclusion](conclusion) Introduction: Business Problem This project aims to select the safest borough in London based on the **total crimes**, explore the **neighborhoods** of that borough to find the **10 most common venues** in each neighborhood and finally cluster the neighborhoods using **k-mean clustering**.This report will be targeted to people who are looking to **relocate to London**. Inorder to finalise a neighborhood to hunt for an apartment, **safety** is considered as a top concern when moving to a new place. If you don’t feel safe in your own home, you’re not going to be able to enjoy living there. The **crime statistics** will provide an insight into this issue.We will focus on the safest borough and explore its neighborhoods and the 10 most common venues in each neighborhood so that the best neighborhood suited to an individual's needs can be selected. Data Based on definition of our problem, factors that will influence our decision are:* The total number of crimes commited in each of the borough during the last year.* The most common venues in each of the neighborhood in the safest borough selected.Following data sources will be needed to extract/generate the required information:- [**Part 1**: Preprocessing a real world data set from Kaggle showing the London Crimes from 2008 to 2016](part1): A dataset consisting of the crime statistics of each borough in London obtained from Kaggle- [**Part 2**: Scraping additional information of the different Boroughs in London from a Wikipedia page.](part2): More information regarding the boroughs of London is scraped using the Beautifulsoup library- [**Part 3**: Creating a new dataset of the Neighborhoods of the safest borough in London and generating their co-ordinates.](part3): Co-ordinate of neighborhood will be obtained using **Google Maps API geocoding** Part 1: Preprocessing a real world data set from Kaggle showing the London Crimes from 2008 to 2016 London Crime Data About this file- lsoa_code: code for Lower Super Output Area in Greater London.- borough: Common name for London borough.- major_category: High level categorization of crime- minor_category: Low level categorization of crime within major category.- value: monthly reported count of categorical crime in given borough- year: Year of reported counts, 2008-2016- month: Month of reported counts, 1-12Data set URL: https://www.kaggle.com/jboysen/london-crime Import necessary libraries | import requests # library to handle requests
import pandas as pd # library for data analsysis
import numpy as np # library to handle data in a vectorized manner
import random # library for random number generation
from bs4 import BeautifulSoup # library for web scrapping
#!conda install -c conda-forge geocoder --yes
import geocoder
#!conda install -c conda-forge geopy --yes
from geopy.geocoders import Nominatim # module to convert an address into latitude and longitude values
# libraries for displaying images
from IPython.display import Image
from IPython.core.display import HTML
# tranforming json file into a pandas dataframe library
from pandas.io.json import json_normalize
#!conda install -c conda-forge folium=0.5.0 --yes
import folium # plotting library
print('Folium installed')
print('Libraries imported.')
| Folium installed
Libraries imported.
| MIT | Capstone Project - The Battle of the Neighborhoods - London Neighborhood Clustering.ipynb | ZRQ-rikkie/coursera-python |
Define Foursquare Credentials and VersionMake sure that you have created a Foursquare developer account and have your credentials handy | CLIENT_ID = 'R01LINGO2WC45KLRLKT3ZHU2QENAO2IPRK2N2ELOHRNK4P3K' # your Foursquare ID
CLIENT_SECRET = '4JT1TWRMXMPLX5IOKNBAFU3L3ARXK4D5JJDPFK1CLRZM2ZVW' # your Foursquare Secret
VERSION = '20180604'
LIMIT = 30
print('Your credentails:')
print('CLIENT_ID: ' + CLIENT_ID)
print('CLIENT_SECRET:' + CLIENT_SECRET) | Your credentails:
CLIENT_ID: R01LINGO2WC45KLRLKT3ZHU2QENAO2IPRK2N2ELOHRNK4P3K
CLIENT_SECRET:4JT1TWRMXMPLX5IOKNBAFU3L3ARXK4D5JJDPFK1CLRZM2ZVW
| MIT | Capstone Project - The Battle of the Neighborhoods - London Neighborhood Clustering.ipynb | ZRQ-rikkie/coursera-python |
Read in the dataset | # Read in the data
df = pd.read_csv("london_crime_by_lsoa.csv")
# View the top rows of the dataset
df.head() | _____no_output_____ | MIT | Capstone Project - The Battle of the Neighborhoods - London Neighborhood Clustering.ipynb | ZRQ-rikkie/coursera-python |
Accessing the most recent crime rates (2016) | # Taking only the most recent year (2016) and dropping the rest
df.drop(df.index[df['year'] != 2016], inplace = True)
# Removing all the entires where crime values are null
df = df[df.value != 0]
# Reset the index and dropping the previous index
df = df.reset_index(drop=True)
# Shape of the data frame
df.shape
# View the top of the dataset
df.head() | _____no_output_____ | MIT | Capstone Project - The Battle of the Neighborhoods - London Neighborhood Clustering.ipynb | ZRQ-rikkie/coursera-python |
Change the column names | df.columns = ['LSOA_Code', 'Borough','Major_Category','Minor_Category','No_of_Crimes','Year','Month']
df.head()
# View the information of the dataset
df.info() | <class 'pandas.core.frame.DataFrame'>
RangeIndex: 392042 entries, 0 to 392041
Data columns (total 7 columns):
LSOA_Code 392042 non-null object
Borough 392042 non-null object
Major_Category 392042 non-null object
Minor_Category 392042 non-null object
No_of_Crimes 392042 non-null int64
Year 392042 non-null int64
Month 392042 non-null int64
dtypes: int64(3), object(4)
memory usage: 20.9+ MB
| MIT | Capstone Project - The Battle of the Neighborhoods - London Neighborhood Clustering.ipynb | ZRQ-rikkie/coursera-python |
Total number of crimes in each Borough | df['Borough'].value_counts() | _____no_output_____ | MIT | Capstone Project - The Battle of the Neighborhoods - London Neighborhood Clustering.ipynb | ZRQ-rikkie/coursera-python |
The total crimes per major category | df['Major_Category'].value_counts() | _____no_output_____ | MIT | Capstone Project - The Battle of the Neighborhoods - London Neighborhood Clustering.ipynb | ZRQ-rikkie/coursera-python |
Pivoting the table to view the no. of crimes for each major category in each Borough | London_crime = pd.pivot_table(df,values=['No_of_Crimes'],
index=['Borough'],
columns=['Major_Category'],
aggfunc=np.sum,fill_value=0)
London_crime.head()
# Reset the index
London_crime.reset_index(inplace = True)
# Total crimes per Borough
London_crime['Total'] = London_crime.sum(axis=1)
London_crime.head(33) | _____no_output_____ | MIT | Capstone Project - The Battle of the Neighborhoods - London Neighborhood Clustering.ipynb | ZRQ-rikkie/coursera-python |
Removing the multi index so that it will be easier to merge | London_crime.columns = London_crime.columns.map(''.join)
London_crime.head() | _____no_output_____ | MIT | Capstone Project - The Battle of the Neighborhoods - London Neighborhood Clustering.ipynb | ZRQ-rikkie/coursera-python |
Renaming the columns | London_crime.columns = ['Borough','Burglary', 'Criminal Damage','Drugs','Other Notifiable Offences',
'Robbery','Theft and Handling','Violence Against the Person','Total']
London_crime.head()
# Shape of the data set
London_crime.shape
# View the Columns in the data frame
# London_crime.columns.tolist() | _____no_output_____ | MIT | Capstone Project - The Battle of the Neighborhoods - London Neighborhood Clustering.ipynb | ZRQ-rikkie/coursera-python |
Part 2: Scraping additional information of the different Boroughs in London from a Wikipedia page **Using Beautiful soup to scrap the latitude and longitiude of the boroughs in London**URL: https://en.wikipedia.org/wiki/List_of_London_boroughs | # getting data from internet
wikipedia_link='https://en.wikipedia.org/wiki/List_of_London_boroughs'
raw_wikipedia_page= requests.get(wikipedia_link).text
# using beautiful soup to parse the HTML/XML codes.
soup = BeautifulSoup(raw_wikipedia_page,'xml')
print(soup.prettify())
# extracting the raw table inside that webpage
table = soup.find_all('table', {'class':'wikitable sortable'})
print(table) | [<table class="wikitable sortable" style="font-size:100%" width="100%">
<tbody><tr>
<th>Borough
</th>
<th>Inner
</th>
<th>Status
</th>
<th>Local authority
</th>
<th>Political control
</th>
<th>Headquarters
</th>
<th>Area (sq mi)
</th>
<th>Population (2013 est)<sup class="reference" id="cite_ref-1"><a href="#cite_note-1">[1]</a></sup>
</th>
<th>Co-ordinates
</th>
<th><span style="background:#67BCD3"> Nr. in map </span>
</th></tr>
<tr>
<td><a href="/wiki/London_Borough_of_Barking_and_Dagenham" title="London Borough of Barking and Dagenham">Barking and Dagenham</a> <sup class="reference" id="cite_ref-2"><a href="#cite_note-2">[note 1]</a></sup>
</td>
<td>
</td>
<td>
</td>
<td><a href="/wiki/Barking_and_Dagenham_London_Borough_Council" title="Barking and Dagenham London Borough Council">Barking and Dagenham London Borough Council</a>
</td>
<td><a href="/wiki/Labour_Party_(UK)" title="Labour Party (UK)">Labour</a>
</td>
<td><a class="new" href="/w/index.php?title=Barking_Town_Hall&action=edit&redlink=1" title="Barking Town Hall (page does not exist)">Town Hall</a>, 1 Town Square
</td>
<td>13.93
</td>
<td>194,352
</td>
<td><span class="plainlinks nourlexpansion"><a class="external text" href="//tools.wmflabs.org/geohack/geohack.php?pagename=List_of_London_boroughs&params=51.5607_N_0.1557_E_region:GB_type:city&title=Barking+and+Dagenham"><span class="geo-nondefault"><span class="geo-dms" title="Maps, aerial photos, and other data for this location"><span class="latitude">51°33′39″N</span> <span class="longitude">0°09′21″E</span></span></span><span class="geo-multi-punct"> / </span><span class="geo-default"><span class="vcard"><span class="geo-dec" title="Maps, aerial photos, and other data for this location">51.5607°N 0.1557°E</span><span style="display:none"> / <span class="geo">51.5607; 0.1557</span></span><span style="display:none"> (<span class="fn org">Barking and Dagenham</span>)</span></span></span></a></span>
</td>
<td>25
</td></tr>
<tr>
<td><a href="/wiki/London_Borough_of_Barnet" title="London Borough of Barnet">Barnet</a>
</td>
<td>
</td>
<td>
</td>
<td><a href="/wiki/Barnet_London_Borough_Council" title="Barnet London Borough Council">Barnet London Borough Council</a>
</td>
<td><a href="/wiki/Conservative_Party_(UK)" title="Conservative Party (UK)">Conservative</a>
</td>
<td><a class="new" href="/w/index.php?title=North_London_Business_Park&action=edit&redlink=1" title="North London Business Park (page does not exist)">North London Business Park</a>, Oakleigh Road South
</td>
<td>33.49
</td>
<td>369,088
</td>
<td><span class="plainlinks nourlexpansion"><a class="external text" href="//tools.wmflabs.org/geohack/geohack.php?pagename=List_of_London_boroughs&params=51.6252_N_0.1517_W_region:GB_type:city&title=Barnet"><span class="geo-nondefault"><span class="geo-dms" title="Maps, aerial photos, and other data for this location"><span class="latitude">51°37′31″N</span> <span class="longitude">0°09′06″W</span></span></span><span class="geo-multi-punct"> / </span><span class="geo-default"><span class="vcard"><span class="geo-dec" title="Maps, aerial photos, and other data for this location">51.6252°N 0.1517°W</span><span style="display:none"> / <span class="geo">51.6252; -0.1517</span></span><span style="display:none"> (<span class="fn org">Barnet</span>)</span></span></span></a></span>
</td>
<td>31
</td></tr>
<tr>
<td><a href="/wiki/London_Borough_of_Bexley" title="London Borough of Bexley">Bexley</a>
</td>
<td>
</td>
<td>
</td>
<td><a href="/wiki/Bexley_London_Borough_Council" title="Bexley London Borough Council">Bexley London Borough Council</a>
</td>
<td><a href="/wiki/Conservative_Party_(UK)" title="Conservative Party (UK)">Conservative</a>
</td>
<td><a class="new" href="/w/index.php?title=Civic_Offices&action=edit&redlink=1" title="Civic Offices (page does not exist)">Civic Offices</a>, 2 Watling Street
</td>
<td>23.38
</td>
<td>236,687
</td>
<td><span class="plainlinks nourlexpansion"><a class="external text" href="//tools.wmflabs.org/geohack/geohack.php?pagename=List_of_London_boroughs&params=51.4549_N_0.1505_E_region:GB_type:city&title=Bexley"><span class="geo-nondefault"><span class="geo-dms" title="Maps, aerial photos, and other data for this location"><span class="latitude">51°27′18″N</span> <span class="longitude">0°09′02″E</span></span></span><span class="geo-multi-punct"> / </span><span class="geo-default"><span class="vcard"><span class="geo-dec" title="Maps, aerial photos, and other data for this location">51.4549°N 0.1505°E</span><span style="display:none"> / <span class="geo">51.4549; 0.1505</span></span><span style="display:none"> (<span class="fn org">Bexley</span>)</span></span></span></a></span>
</td>
<td>23
</td></tr>
<tr>
<td><a href="/wiki/London_Borough_of_Brent" title="London Borough of Brent">Brent</a>
</td>
<td>
</td>
<td>
</td>
<td><a href="/wiki/Brent_London_Borough_Council" title="Brent London Borough Council">Brent London Borough Council</a>
</td>
<td><a href="/wiki/Labour_Party_(UK)" title="Labour Party (UK)">Labour</a>
</td>
<td><a href="/wiki/Brent_Civic_Centre" title="Brent Civic Centre">Brent Civic Centre</a>, Engineers Way
</td>
<td>16.70
</td>
<td>317,264
</td>
<td><span class="plainlinks nourlexpansion"><a class="external text" href="//tools.wmflabs.org/geohack/geohack.php?pagename=List_of_London_boroughs&params=51.5588_N_0.2817_W_region:GB_type:city&title=Brent"><span class="geo-nondefault"><span class="geo-dms" title="Maps, aerial photos, and other data for this location"><span class="latitude">51°33′32″N</span> <span class="longitude">0°16′54″W</span></span></span><span class="geo-multi-punct"> / </span><span class="geo-default"><span class="vcard"><span class="geo-dec" title="Maps, aerial photos, and other data for this location">51.5588°N 0.2817°W</span><span style="display:none"> / <span class="geo">51.5588; -0.2817</span></span><span style="display:none"> (<span class="fn org">Brent</span>)</span></span></span></a></span>
</td>
<td>12
</td></tr>
<tr>
<td><a href="/wiki/London_Borough_of_Bromley" title="London Borough of Bromley">Bromley</a>
</td>
<td>
</td>
<td>
</td>
<td><a href="/wiki/Bromley_London_Borough_Council" title="Bromley London Borough Council">Bromley London Borough Council</a>
</td>
<td><a href="/wiki/Conservative_Party_(UK)" title="Conservative Party (UK)">Conservative</a>
</td>
<td><a class="new" href="/w/index.php?title=Bromley_Civic_Centre&action=edit&redlink=1" title="Bromley Civic Centre (page does not exist)">Civic Centre</a>, Stockwell Close
</td>
<td>57.97
</td>
<td>317,899
</td>
<td><span class="plainlinks nourlexpansion"><a class="external text" href="//tools.wmflabs.org/geohack/geohack.php?pagename=List_of_London_boroughs&params=51.4039_N_0.0198_E_region:GB_type:city&title=Bromley"><span class="geo-nondefault"><span class="geo-dms" title="Maps, aerial photos, and other data for this location"><span class="latitude">51°24′14″N</span> <span class="longitude">0°01′11″E</span></span></span><span class="geo-multi-punct"> / </span><span class="geo-default"><span class="vcard"><span class="geo-dec" title="Maps, aerial photos, and other data for this location">51.4039°N 0.0198°E</span><span style="display:none"> / <span class="geo">51.4039; 0.0198</span></span><span style="display:none"> (<span class="fn org">Bromley</span>)</span></span></span></a></span>
</td>
<td>20
</td></tr>
<tr>
<td><a href="/wiki/London_Borough_of_Camden" title="London Borough of Camden">Camden</a>
</td>
<td><img alt="☑" data-file-height="600" data-file-width="600" decoding="async" height="20" src="//upload.wikimedia.org/wikipedia/en/thumb/f/fb/Yes_check.svg/20px-Yes_check.svg.png" srcset="//upload.wikimedia.org/wikipedia/en/thumb/f/fb/Yes_check.svg/30px-Yes_check.svg.png 1.5x, //upload.wikimedia.org/wikipedia/en/thumb/f/fb/Yes_check.svg/40px-Yes_check.svg.png 2x" width="20"/><span style="display:none">Y</span>
</td>
<td>
</td>
<td><a href="/wiki/Camden_London_Borough_Council" title="Camden London Borough Council">Camden London Borough Council</a>
</td>
<td><a href="/wiki/Labour_Party_(UK)" title="Labour Party (UK)">Labour</a>
</td>
<td><a href="/wiki/Camden_Town_Hall" title="Camden Town Hall">Camden Town Hall</a>, Judd Street
</td>
<td>8.40
</td>
<td>229,719
</td>
<td><span class="plainlinks nourlexpansion"><a class="external text" href="//tools.wmflabs.org/geohack/geohack.php?pagename=List_of_London_boroughs&params=51.529_N_0.1255_W_region:GB_type:city&title=Camden"><span class="geo-nondefault"><span class="geo-dms" title="Maps, aerial photos, and other data for this location"><span class="latitude">51°31′44″N</span> <span class="longitude">0°07′32″W</span></span></span><span class="geo-multi-punct"> / </span><span class="geo-default"><span class="vcard"><span class="geo-dec" title="Maps, aerial photos, and other data for this location">51.5290°N 0.1255°W</span><span style="display:none"> / <span class="geo">51.5290; -0.1255</span></span><span style="display:none"> (<span class="fn org">Camden</span>)</span></span></span></a></span>
</td>
<td>11
</td></tr>
<tr>
<td><a href="/wiki/London_Borough_of_Croydon" title="London Borough of Croydon">Croydon</a>
</td>
<td>
</td>
<td>
</td>
<td><a href="/wiki/Croydon_London_Borough_Council" title="Croydon London Borough Council">Croydon London Borough Council</a>
</td>
<td><a href="/wiki/Labour_Party_(UK)" title="Labour Party (UK)">Labour</a>
</td>
<td><a class="new" href="/w/index.php?title=Bernard_Weatherill_House&action=edit&redlink=1" title="Bernard Weatherill House (page does not exist)">Bernard Weatherill House</a>, Mint Walk
</td>
<td>33.41
</td>
<td>372,752
</td>
<td><span class="plainlinks nourlexpansion"><a class="external text" href="//tools.wmflabs.org/geohack/geohack.php?pagename=List_of_London_boroughs&params=51.3714_N_0.0977_W_region:GB_type:city&title=Croydon"><span class="geo-nondefault"><span class="geo-dms" title="Maps, aerial photos, and other data for this location"><span class="latitude">51°22′17″N</span> <span class="longitude">0°05′52″W</span></span></span><span class="geo-multi-punct"> / </span><span class="geo-default"><span class="vcard"><span class="geo-dec" title="Maps, aerial photos, and other data for this location">51.3714°N 0.0977°W</span><span style="display:none"> / <span class="geo">51.3714; -0.0977</span></span><span style="display:none"> (<span class="fn org">Croydon</span>)</span></span></span></a></span>
</td>
<td>19
</td></tr>
<tr>
<td><a href="/wiki/London_Borough_of_Ealing" title="London Borough of Ealing">Ealing</a>
</td>
<td>
</td>
<td>
</td>
<td><a href="/wiki/Ealing_London_Borough_Council" title="Ealing London Borough Council">Ealing London Borough Council</a>
</td>
<td><a href="/wiki/Labour_Party_(UK)" title="Labour Party (UK)">Labour</a>
</td>
<td><a class="new" href="/w/index.php?title=Perceval_House,_Ealing&action=edit&redlink=1" title="Perceval House, Ealing (page does not exist)">Perceval House</a>, 14-16 Uxbridge Road
</td>
<td>21.44
</td>
<td>342,494
</td>
<td><span class="plainlinks nourlexpansion"><a class="external text" href="//tools.wmflabs.org/geohack/geohack.php?pagename=List_of_London_boroughs&params=51.513_N_0.3089_W_region:GB_type:city&title=Ealing"><span class="geo-nondefault"><span class="geo-dms" title="Maps, aerial photos, and other data for this location"><span class="latitude">51°30′47″N</span> <span class="longitude">0°18′32″W</span></span></span><span class="geo-multi-punct"> / </span><span class="geo-default"><span class="vcard"><span class="geo-dec" title="Maps, aerial photos, and other data for this location">51.5130°N 0.3089°W</span><span style="display:none"> / <span class="geo">51.5130; -0.3089</span></span><span style="display:none"> (<span class="fn org">Ealing</span>)</span></span></span></a></span>
</td>
<td>13
</td></tr>
<tr>
<td><a href="/wiki/London_Borough_of_Enfield" title="London Borough of Enfield">Enfield</a>
</td>
<td>
</td>
<td>
</td>
<td><a href="/wiki/Enfield_London_Borough_Council" title="Enfield London Borough Council">Enfield London Borough Council</a>
</td>
<td><a href="/wiki/Labour_Party_(UK)" title="Labour Party (UK)">Labour</a>
</td>
<td><a class="new" href="/w/index.php?title=Enfield_Civic_Centre&action=edit&redlink=1" title="Enfield Civic Centre (page does not exist)">Civic Centre</a>, Silver Street
</td>
<td>31.74
</td>
<td>320,524
</td>
<td><span class="plainlinks nourlexpansion"><a class="external text" href="//tools.wmflabs.org/geohack/geohack.php?pagename=List_of_London_boroughs&params=51.6538_N_0.0799_W_region:GB_type:city&title=Enfield"><span class="geo-nondefault"><span class="geo-dms" title="Maps, aerial photos, and other data for this location"><span class="latitude">51°39′14″N</span> <span class="longitude">0°04′48″W</span></span></span><span class="geo-multi-punct"> / </span><span class="geo-default"><span class="vcard"><span class="geo-dec" title="Maps, aerial photos, and other data for this location">51.6538°N 0.0799°W</span><span style="display:none"> / <span class="geo">51.6538; -0.0799</span></span><span style="display:none"> (<span class="fn org">Enfield</span>)</span></span></span></a></span>
</td>
<td>30
</td></tr>
<tr>
<td><a href="/wiki/Royal_Borough_of_Greenwich" title="Royal Borough of Greenwich">Greenwich</a> <sup class="reference" id="cite_ref-3"><a href="#cite_note-3">[note 2]</a></sup>
</td>
<td><img alt="☑" data-file-height="600" data-file-width="600" decoding="async" height="20" src="//upload.wikimedia.org/wikipedia/en/thumb/f/fb/Yes_check.svg/20px-Yes_check.svg.png" srcset="//upload.wikimedia.org/wikipedia/en/thumb/f/fb/Yes_check.svg/30px-Yes_check.svg.png 1.5x, //upload.wikimedia.org/wikipedia/en/thumb/f/fb/Yes_check.svg/40px-Yes_check.svg.png 2x" width="20"/><span style="display:none">Y</span> <sup class="reference" id="cite_ref-note2_4-0"><a href="#cite_note-note2-4">[note 3]</a></sup>
</td>
<td><a class="mw-redirect" href="/wiki/Royal_borough" title="Royal borough">Royal</a>
</td>
<td><a href="/wiki/Greenwich_London_Borough_Council" title="Greenwich London Borough Council">Greenwich London Borough Council</a>
</td>
<td><a href="/wiki/Labour_Party_(UK)" title="Labour Party (UK)">Labour</a>
</td>
<td><a href="/wiki/Woolwich_Town_Hall" title="Woolwich Town Hall">Woolwich Town Hall</a>, Wellington Street
</td>
<td>18.28
</td>
<td>264,008
</td>
<td><span class="plainlinks nourlexpansion"><a class="external text" href="//tools.wmflabs.org/geohack/geohack.php?pagename=List_of_London_boroughs&params=51.4892_N_0.0648_E_region:GB_type:city&title=Greenwich"><span class="geo-nondefault"><span class="geo-dms" title="Maps, aerial photos, and other data for this location"><span class="latitude">51°29′21″N</span> <span class="longitude">0°03′53″E</span></span></span><span class="geo-multi-punct"> / </span><span class="geo-default"><span class="vcard"><span class="geo-dec" title="Maps, aerial photos, and other data for this location">51.4892°N 0.0648°E</span><span style="display:none"> / <span class="geo">51.4892; 0.0648</span></span><span style="display:none"> (<span class="fn org">Greenwich</span>)</span></span></span></a></span>
</td>
<td>22
</td></tr>
<tr>
<td><a href="/wiki/London_Borough_of_Hackney" title="London Borough of Hackney">Hackney</a>
</td>
<td><img alt="☑" data-file-height="600" data-file-width="600" decoding="async" height="20" src="//upload.wikimedia.org/wikipedia/en/thumb/f/fb/Yes_check.svg/20px-Yes_check.svg.png" srcset="//upload.wikimedia.org/wikipedia/en/thumb/f/fb/Yes_check.svg/30px-Yes_check.svg.png 1.5x, //upload.wikimedia.org/wikipedia/en/thumb/f/fb/Yes_check.svg/40px-Yes_check.svg.png 2x" width="20"/><span style="display:none">Y</span>
</td>
<td>
</td>
<td><a href="/wiki/Hackney_London_Borough_Council" title="Hackney London Borough Council">Hackney London Borough Council</a>
</td>
<td><a href="/wiki/Labour_Party_(UK)" title="Labour Party (UK)">Labour</a>
</td>
<td><a class="new" href="/w/index.php?title=Hackney_Town_Hall&action=edit&redlink=1" title="Hackney Town Hall (page does not exist)">Hackney Town Hall</a>, Mare Street
</td>
<td>7.36
</td>
<td>257,379
</td>
<td><span class="plainlinks nourlexpansion"><a class="external text" href="//tools.wmflabs.org/geohack/geohack.php?pagename=List_of_London_boroughs&params=51.545_N_0.0553_W_region:GB_type:city&title=Hackney"><span class="geo-nondefault"><span class="geo-dms" title="Maps, aerial photos, and other data for this location"><span class="latitude">51°32′42″N</span> <span class="longitude">0°03′19″W</span></span></span><span class="geo-multi-punct"> / </span><span class="geo-default"><span class="vcard"><span class="geo-dec" title="Maps, aerial photos, and other data for this location">51.5450°N 0.0553°W</span><span style="display:none"> / <span class="geo">51.5450; -0.0553</span></span><span style="display:none"> (<span class="fn org">Hackney</span>)</span></span></span></a></span>
</td>
<td>9
</td></tr>
<tr>
<td><a href="/wiki/London_Borough_of_Hammersmith_and_Fulham" title="London Borough of Hammersmith and Fulham">Hammersmith and Fulham</a> <sup class="reference" id="cite_ref-5"><a href="#cite_note-5">[note 4]</a></sup>
</td>
<td><img alt="☑" data-file-height="600" data-file-width="600" decoding="async" height="20" src="//upload.wikimedia.org/wikipedia/en/thumb/f/fb/Yes_check.svg/20px-Yes_check.svg.png" srcset="//upload.wikimedia.org/wikipedia/en/thumb/f/fb/Yes_check.svg/30px-Yes_check.svg.png 1.5x, //upload.wikimedia.org/wikipedia/en/thumb/f/fb/Yes_check.svg/40px-Yes_check.svg.png 2x" width="20"/><span style="display:none">Y</span>
</td>
<td>
</td>
<td><a href="/wiki/Hammersmith_and_Fulham_London_Borough_Council" title="Hammersmith and Fulham London Borough Council">Hammersmith and Fulham London Borough Council</a>
</td>
<td><a href="/wiki/Labour_Party_(UK)" title="Labour Party (UK)">Labour</a>
</td>
<td><a class="new" href="/w/index.php?title=Hammersmith_and_Fulham_Town_Hall&action=edit&redlink=1" title="Hammersmith and Fulham Town Hall (page does not exist)">Town Hall</a>, King Street
</td>
<td>6.33
</td>
<td>178,685
</td>
<td><span class="plainlinks nourlexpansion"><a class="external text" href="//tools.wmflabs.org/geohack/geohack.php?pagename=List_of_London_boroughs&params=51.4927_N_0.2339_W_region:GB_type:city&title=Hammersmith+and+Fulham"><span class="geo-nondefault"><span class="geo-dms" title="Maps, aerial photos, and other data for this location"><span class="latitude">51°29′34″N</span> <span class="longitude">0°14′02″W</span></span></span><span class="geo-multi-punct"> / </span><span class="geo-default"><span class="vcard"><span class="geo-dec" title="Maps, aerial photos, and other data for this location">51.4927°N 0.2339°W</span><span style="display:none"> / <span class="geo">51.4927; -0.2339</span></span><span style="display:none"> (<span class="fn org">Hammersmith and Fulham</span>)</span></span></span></a></span>
</td>
<td>4
</td></tr>
<tr>
<td><a href="/wiki/London_Borough_of_Haringey" title="London Borough of Haringey">Haringey</a>
</td>
<td><sup class="reference" id="cite_ref-note2_4-1"><a href="#cite_note-note2-4">[note 3]</a></sup>
</td>
<td>
</td>
<td><a href="/wiki/Haringey_London_Borough_Council" title="Haringey London Borough Council">Haringey London Borough Council</a>
</td>
<td><a href="/wiki/Labour_Party_(UK)" title="Labour Party (UK)">Labour</a>
</td>
<td><a class="new" href="/w/index.php?title=Haringey_Civic_Centre&action=edit&redlink=1" title="Haringey Civic Centre (page does not exist)">Civic Centre</a>, High Road
</td>
<td>11.42
</td>
<td>263,386
</td>
<td><span class="plainlinks nourlexpansion"><a class="external text" href="//tools.wmflabs.org/geohack/geohack.php?pagename=List_of_London_boroughs&params=51.6_N_0.1119_W_region:GB_type:city&title=Haringey"><span class="geo-nondefault"><span class="geo-dms" title="Maps, aerial photos, and other data for this location"><span class="latitude">51°36′00″N</span> <span class="longitude">0°06′43″W</span></span></span><span class="geo-multi-punct"> / </span><span class="geo-default"><span class="vcard"><span class="geo-dec" title="Maps, aerial photos, and other data for this location">51.6000°N 0.1119°W</span><span style="display:none"> / <span class="geo">51.6000; -0.1119</span></span><span style="display:none"> (<span class="fn org">Haringey</span>)</span></span></span></a></span>
</td>
<td>29
</td></tr>
<tr>
<td><a href="/wiki/London_Borough_of_Harrow" title="London Borough of Harrow">Harrow</a>
</td>
<td>
</td>
<td>
</td>
<td><a href="/wiki/Harrow_London_Borough_Council" title="Harrow London Borough Council">Harrow London Borough Council</a>
</td>
<td><a href="/wiki/Labour_Party_(UK)" title="Labour Party (UK)">Labour</a>
</td>
<td><a class="new" href="/w/index.php?title=Harrow_Civic_Centre&action=edit&redlink=1" title="Harrow Civic Centre (page does not exist)">Civic Centre</a>, Station Road
</td>
<td>19.49
</td>
<td>243,372
</td>
<td><span class="plainlinks nourlexpansion"><a class="external text" href="//tools.wmflabs.org/geohack/geohack.php?pagename=List_of_London_boroughs&params=51.5898_N_0.3346_W_region:GB_type:city&title=Harrow"><span class="geo-nondefault"><span class="geo-dms" title="Maps, aerial photos, and other data for this location"><span class="latitude">51°35′23″N</span> <span class="longitude">0°20′05″W</span></span></span><span class="geo-multi-punct"> / </span><span class="geo-default"><span class="vcard"><span class="geo-dec" title="Maps, aerial photos, and other data for this location">51.5898°N 0.3346°W</span><span style="display:none"> / <span class="geo">51.5898; -0.3346</span></span><span style="display:none"> (<span class="fn org">Harrow</span>)</span></span></span></a></span>
</td>
<td>32
</td></tr>
<tr>
<td><a href="/wiki/London_Borough_of_Havering" title="London Borough of Havering">Havering</a>
</td>
<td>
</td>
<td>
</td>
<td><a href="/wiki/Havering_London_Borough_Council" title="Havering London Borough Council">Havering London Borough Council</a>
</td>
<td><a href="/wiki/Conservative_Party_(UK)" title="Conservative Party (UK)">Conservative</a> (council <a href="/wiki/No_overall_control" title="No overall control">NOC</a>)
</td>
<td><a class="new" href="/w/index.php?title=Havering_Town_Hall&action=edit&redlink=1" title="Havering Town Hall (page does not exist)">Town Hall</a>, Main Road
</td>
<td>43.35
</td>
<td>242,080
</td>
<td><span class="plainlinks nourlexpansion"><a class="external text" href="//tools.wmflabs.org/geohack/geohack.php?pagename=List_of_London_boroughs&params=51.5812_N_0.1837_E_region:GB_type:city&title=Havering"><span class="geo-nondefault"><span class="geo-dms" title="Maps, aerial photos, and other data for this location"><span class="latitude">51°34′52″N</span> <span class="longitude">0°11′01″E</span></span></span><span class="geo-multi-punct"> / </span><span class="geo-default"><span class="vcard"><span class="geo-dec" title="Maps, aerial photos, and other data for this location">51.5812°N 0.1837°E</span><span style="display:none"> / <span class="geo">51.5812; 0.1837</span></span><span style="display:none"> (<span class="fn org">Havering</span>)</span></span></span></a></span>
</td>
<td>24
</td></tr>
<tr>
<td><a href="/wiki/London_Borough_of_Hillingdon" title="London Borough of Hillingdon">Hillingdon</a>
</td>
<td>
</td>
<td>
</td>
<td><a href="/wiki/Hillingdon_London_Borough_Council" title="Hillingdon London Borough Council">Hillingdon London Borough Council</a>
</td>
<td><a href="/wiki/Conservative_Party_(UK)" title="Conservative Party (UK)">Conservative</a>
</td>
<td><a href="/wiki/Hillingdon_Civic_Centre" title="Hillingdon Civic Centre">Civic Centre</a>, High Street
</td>
<td>44.67
</td>
<td>286,806
</td>
<td><span class="plainlinks nourlexpansion"><a class="external text" href="//tools.wmflabs.org/geohack/geohack.php?pagename=List_of_London_boroughs&params=51.5441_N_0.476_W_region:GB_type:city&title=Hillingdon"><span class="geo-nondefault"><span class="geo-dms" title="Maps, aerial photos, and other data for this location"><span class="latitude">51°32′39″N</span> <span class="longitude">0°28′34″W</span></span></span><span class="geo-multi-punct"> / </span><span class="geo-default"><span class="vcard"><span class="geo-dec" title="Maps, aerial photos, and other data for this location">51.5441°N 0.4760°W</span><span style="display:none"> / <span class="geo">51.5441; -0.4760</span></span><span style="display:none"> (<span class="fn org">Hillingdon</span>)</span></span></span></a></span>
</td>
<td>33
</td></tr>
<tr>
<td><a href="/wiki/London_Borough_of_Hounslow" title="London Borough of Hounslow">Hounslow</a>
</td>
<td>
</td>
<td>
</td>
<td><a href="/wiki/Hounslow_London_Borough_Council" title="Hounslow London Borough Council">Hounslow London Borough Council</a>
</td>
<td><a href="/wiki/Labour_Party_(UK)" title="Labour Party (UK)">Labour</a>
</td>
<td><a class="new" href="/w/index.php?title=Hounslow_Civic_Centre&action=edit&redlink=1" title="Hounslow Civic Centre (page does not exist)">Civic Centre</a>, Lampton Road
</td>
<td>21.61
</td>
<td>262,407
</td>
<td><span class="plainlinks nourlexpansion"><a class="external text" href="//tools.wmflabs.org/geohack/geohack.php?pagename=List_of_London_boroughs&params=51.4746_N_0.368_W_region:GB_type:city&title=Hounslow"><span class="geo-nondefault"><span class="geo-dms" title="Maps, aerial photos, and other data for this location"><span class="latitude">51°28′29″N</span> <span class="longitude">0°22′05″W</span></span></span><span class="geo-multi-punct"> / </span><span class="geo-default"><span class="vcard"><span class="geo-dec" title="Maps, aerial photos, and other data for this location">51.4746°N 0.3680°W</span><span style="display:none"> / <span class="geo">51.4746; -0.3680</span></span><span style="display:none"> (<span class="fn org">Hounslow</span>)</span></span></span></a></span>
</td>
<td>14
</td></tr>
<tr>
<td><a href="/wiki/London_Borough_of_Islington" title="London Borough of Islington">Islington</a>
</td>
<td><img alt="☑" data-file-height="600" data-file-width="600" decoding="async" height="20" src="//upload.wikimedia.org/wikipedia/en/thumb/f/fb/Yes_check.svg/20px-Yes_check.svg.png" srcset="//upload.wikimedia.org/wikipedia/en/thumb/f/fb/Yes_check.svg/30px-Yes_check.svg.png 1.5x, //upload.wikimedia.org/wikipedia/en/thumb/f/fb/Yes_check.svg/40px-Yes_check.svg.png 2x" width="20"/><span style="display:none">Y</span>
</td>
<td>
</td>
<td><a href="/wiki/Islington_London_Borough_Council" title="Islington London Borough Council">Islington London Borough Council</a>
</td>
<td><a href="/wiki/Labour_Party_(UK)" title="Labour Party (UK)">Labour</a>
</td>
<td><a class="new" href="/w/index.php?title=Islington_Municipal_Offices&action=edit&redlink=1" title="Islington Municipal Offices (page does not exist)">Municipal Offices</a>, 222 Upper Street
</td>
<td>5.74
</td>
<td>215,667
</td>
<td><span class="plainlinks nourlexpansion"><a class="external text" href="//tools.wmflabs.org/geohack/geohack.php?pagename=List_of_London_boroughs&params=51.5416_N_0.1022_W_region:GB_type:city&title=Islington"><span class="geo-nondefault"><span class="geo-dms" title="Maps, aerial photos, and other data for this location"><span class="latitude">51°32′30″N</span> <span class="longitude">0°06′08″W</span></span></span><span class="geo-multi-punct"> / </span><span class="geo-default"><span class="vcard"><span class="geo-dec" title="Maps, aerial photos, and other data for this location">51.5416°N 0.1022°W</span><span style="display:none"> / <span class="geo">51.5416; -0.1022</span></span><span style="display:none"> (<span class="fn org">Islington</span>)</span></span></span></a></span>
</td>
<td>10
</td></tr>
<tr>
<td><a href="/wiki/Royal_Borough_of_Kensington_and_Chelsea" title="Royal Borough of Kensington and Chelsea">Kensington and Chelsea</a>
</td>
<td><img alt="☑" data-file-height="600" data-file-width="600" decoding="async" height="20" src="//upload.wikimedia.org/wikipedia/en/thumb/f/fb/Yes_check.svg/20px-Yes_check.svg.png" srcset="//upload.wikimedia.org/wikipedia/en/thumb/f/fb/Yes_check.svg/30px-Yes_check.svg.png 1.5x, //upload.wikimedia.org/wikipedia/en/thumb/f/fb/Yes_check.svg/40px-Yes_check.svg.png 2x" width="20"/><span style="display:none">Y</span>
</td>
<td><a class="mw-redirect" href="/wiki/Royal_borough" title="Royal borough">Royal</a>
</td>
<td><a href="/wiki/Kensington_and_Chelsea_London_Borough_Council" title="Kensington and Chelsea London Borough Council">Kensington and Chelsea London Borough Council</a>
</td>
<td><a href="/wiki/Conservative_Party_(UK)" title="Conservative Party (UK)">Conservative</a>
</td>
<td><a href="/wiki/Kensington_Town_Hall,_London" title="Kensington Town Hall, London">The Town Hall</a>, <a href="/wiki/Hornton_Street" title="Hornton Street">Hornton Street</a>
</td>
<td>4.68
</td>
<td>155,594
</td>
<td><span class="plainlinks nourlexpansion"><a class="external text" href="//tools.wmflabs.org/geohack/geohack.php?pagename=List_of_London_boroughs&params=51.502_N_0.1947_W_region:GB_type:city&title=Kensington+and+Chelsea"><span class="geo-nondefault"><span class="geo-dms" title="Maps, aerial photos, and other data for this location"><span class="latitude">51°30′07″N</span> <span class="longitude">0°11′41″W</span></span></span><span class="geo-multi-punct"> / </span><span class="geo-default"><span class="vcard"><span class="geo-dec" title="Maps, aerial photos, and other data for this location">51.5020°N 0.1947°W</span><span style="display:none"> / <span class="geo">51.5020; -0.1947</span></span><span style="display:none"> (<span class="fn org">Kensington and Chelsea</span>)</span></span></span></a></span>
</td>
<td>3
</td></tr>
<tr>
<td><a href="/wiki/Royal_Borough_of_Kingston_upon_Thames" title="Royal Borough of Kingston upon Thames">Kingston upon Thames</a>
</td>
<td>
</td>
<td><a class="mw-redirect" href="/wiki/Royal_borough" title="Royal borough">Royal</a>
</td>
<td><a href="/wiki/Kingston_upon_Thames_London_Borough_Council" title="Kingston upon Thames London Borough Council">Kingston upon Thames London Borough Council</a>
</td>
<td><a href="/wiki/Liberal_Democrats_(UK)" title="Liberal Democrats (UK)">Liberal Democrat</a>
</td>
<td><a href="/wiki/Kingston_upon_Thames_Guildhall" title="Kingston upon Thames Guildhall">Guildhall</a>, High Street
</td>
<td>14.38
</td>
<td>166,793
</td>
<td><span class="plainlinks nourlexpansion"><a class="external text" href="//tools.wmflabs.org/geohack/geohack.php?pagename=List_of_London_boroughs&params=51.4085_N_0.3064_W_region:GB_type:city&title=Kingston+upon+Thames"><span class="geo-nondefault"><span class="geo-dms" title="Maps, aerial photos, and other data for this location"><span class="latitude">51°24′31″N</span> <span class="longitude">0°18′23″W</span></span></span><span class="geo-multi-punct"> / </span><span class="geo-default"><span class="vcard"><span class="geo-dec" title="Maps, aerial photos, and other data for this location">51.4085°N 0.3064°W</span><span style="display:none"> / <span class="geo">51.4085; -0.3064</span></span><span style="display:none"> (<span class="fn org">Kingston upon Thames</span>)</span></span></span></a></span>
</td>
<td>16
</td></tr>
<tr>
<td><a href="/wiki/London_Borough_of_Lambeth" title="London Borough of Lambeth">Lambeth</a>
</td>
<td><img alt="☑" data-file-height="600" data-file-width="600" decoding="async" height="20" src="//upload.wikimedia.org/wikipedia/en/thumb/f/fb/Yes_check.svg/20px-Yes_check.svg.png" srcset="//upload.wikimedia.org/wikipedia/en/thumb/f/fb/Yes_check.svg/30px-Yes_check.svg.png 1.5x, //upload.wikimedia.org/wikipedia/en/thumb/f/fb/Yes_check.svg/40px-Yes_check.svg.png 2x" width="20"/><span style="display:none">Y</span>
</td>
<td>
</td>
<td><a href="/wiki/Lambeth_London_Borough_Council" title="Lambeth London Borough Council">Lambeth London Borough Council</a>
</td>
<td><a href="/wiki/Labour_Party_(UK)" title="Labour Party (UK)">Labour</a>
</td>
<td><a href="/wiki/Lambeth_Town_Hall" title="Lambeth Town Hall">Lambeth Town Hall</a>, Brixton Hill
</td>
<td>10.36
</td>
<td>314,242
</td>
<td><span class="plainlinks nourlexpansion"><a class="external text" href="//tools.wmflabs.org/geohack/geohack.php?pagename=List_of_London_boroughs&params=51.4607_N_0.1163_W_region:GB_type:city&title=Lambeth"><span class="geo-nondefault"><span class="geo-dms" title="Maps, aerial photos, and other data for this location"><span class="latitude">51°27′39″N</span> <span class="longitude">0°06′59″W</span></span></span><span class="geo-multi-punct"> / </span><span class="geo-default"><span class="vcard"><span class="geo-dec" title="Maps, aerial photos, and other data for this location">51.4607°N 0.1163°W</span><span style="display:none"> / <span class="geo">51.4607; -0.1163</span></span><span style="display:none"> (<span class="fn org">Lambeth</span>)</span></span></span></a></span>
</td>
<td>6
</td></tr>
<tr>
<td><a href="/wiki/London_Borough_of_Lewisham" title="London Borough of Lewisham">Lewisham</a>
</td>
<td><img alt="☑" data-file-height="600" data-file-width="600" decoding="async" height="20" src="//upload.wikimedia.org/wikipedia/en/thumb/f/fb/Yes_check.svg/20px-Yes_check.svg.png" srcset="//upload.wikimedia.org/wikipedia/en/thumb/f/fb/Yes_check.svg/30px-Yes_check.svg.png 1.5x, //upload.wikimedia.org/wikipedia/en/thumb/f/fb/Yes_check.svg/40px-Yes_check.svg.png 2x" width="20"/><span style="display:none">Y</span>
</td>
<td>
</td>
<td><a href="/wiki/Lewisham_London_Borough_Council" title="Lewisham London Borough Council">Lewisham London Borough Council</a>
</td>
<td><a href="/wiki/Labour_Party_(UK)" title="Labour Party (UK)">Labour</a>
</td>
<td><a class="new" href="/w/index.php?title=Lewisham_Town_Hall&action=edit&redlink=1" title="Lewisham Town Hall (page does not exist)">Town Hall</a>, 1 Catford Road
</td>
<td>13.57
</td>
<td>286,180
</td>
<td><span class="plainlinks nourlexpansion"><a class="external text" href="//tools.wmflabs.org/geohack/geohack.php?pagename=List_of_London_boroughs&params=51.4452_N_0.0209_W_region:GB_type:city&title=Lewisham"><span class="geo-nondefault"><span class="geo-dms" title="Maps, aerial photos, and other data for this location"><span class="latitude">51°26′43″N</span> <span class="longitude">0°01′15″W</span></span></span><span class="geo-multi-punct"> / </span><span class="geo-default"><span class="vcard"><span class="geo-dec" title="Maps, aerial photos, and other data for this location">51.4452°N 0.0209°W</span><span style="display:none"> / <span class="geo">51.4452; -0.0209</span></span><span style="display:none"> (<span class="fn org">Lewisham</span>)</span></span></span></a></span>
</td>
<td>21
</td></tr>
<tr>
<td><a href="/wiki/London_Borough_of_Merton" title="London Borough of Merton">Merton</a>
</td>
<td>
</td>
<td>
</td>
<td><a href="/wiki/Merton_London_Borough_Council" title="Merton London Borough Council">Merton London Borough Council</a>
</td>
<td><a href="/wiki/Labour_Party_(UK)" title="Labour Party (UK)">Labour</a>
</td>
<td><a class="new" href="/w/index.php?title=Merton_Civic_Centre&action=edit&redlink=1" title="Merton Civic Centre (page does not exist)">Civic Centre</a>, London Road
</td>
<td>14.52
</td>
<td>203,223
</td>
<td><span class="plainlinks nourlexpansion"><a class="external text" href="//tools.wmflabs.org/geohack/geohack.php?pagename=List_of_London_boroughs&params=51.4014_N_0.1958_W_region:GB_type:city&title=Merton"><span class="geo-nondefault"><span class="geo-dms" title="Maps, aerial photos, and other data for this location"><span class="latitude">51°24′05″N</span> <span class="longitude">0°11′45″W</span></span></span><span class="geo-multi-punct"> / </span><span class="geo-default"><span class="vcard"><span class="geo-dec" title="Maps, aerial photos, and other data for this location">51.4014°N 0.1958°W</span><span style="display:none"> / <span class="geo">51.4014; -0.1958</span></span><span style="display:none"> (<span class="fn org">Merton</span>)</span></span></span></a></span>
</td>
<td>17
</td></tr>
<tr>
<td><a href="/wiki/London_Borough_of_Newham" title="London Borough of Newham">Newham</a>
</td>
<td><sup class="reference" id="cite_ref-note2_4-2"><a href="#cite_note-note2-4">[note 3]</a></sup>
</td>
<td>
</td>
<td><a href="/wiki/Newham_London_Borough_Council" title="Newham London Borough Council">Newham London Borough Council</a>
</td>
<td><a href="/wiki/Labour_Party_(UK)" title="Labour Party (UK)">Labour</a>
</td>
<td><a class="new" href="/w/index.php?title=Newham_Dockside&action=edit&redlink=1" title="Newham Dockside (page does not exist)">Newham Dockside</a>, 1000 Dockside Road
</td>
<td>13.98
</td>
<td>318,227
</td>
<td><span class="plainlinks nourlexpansion"><a class="external text" href="//tools.wmflabs.org/geohack/geohack.php?pagename=List_of_London_boroughs&params=51.5077_N_0.0469_E_region:GB_type:city&title=Newham"><span class="geo-nondefault"><span class="geo-dms" title="Maps, aerial photos, and other data for this location"><span class="latitude">51°30′28″N</span> <span class="longitude">0°02′49″E</span></span></span><span class="geo-multi-punct"> / </span><span class="geo-default"><span class="vcard"><span class="geo-dec" title="Maps, aerial photos, and other data for this location">51.5077°N 0.0469°E</span><span style="display:none"> / <span class="geo">51.5077; 0.0469</span></span><span style="display:none"> (<span class="fn org">Newham</span>)</span></span></span></a></span>
</td>
<td>27
</td></tr>
<tr>
<td><a href="/wiki/London_Borough_of_Redbridge" title="London Borough of Redbridge">Redbridge</a>
</td>
<td>
</td>
<td>
</td>
<td><a href="/wiki/Redbridge_London_Borough_Council" title="Redbridge London Borough Council">Redbridge London Borough Council</a>
</td>
<td><a href="/wiki/Labour_Party_(UK)" title="Labour Party (UK)">Labour</a>
</td>
<td><a class="new" href="/w/index.php?title=Redbridge_Town_Hall&action=edit&redlink=1" title="Redbridge Town Hall (page does not exist)">Town Hall</a>, 128-142 High Road
</td>
<td>21.78
</td>
<td>288,272
</td>
<td><span class="plainlinks nourlexpansion"><a class="external text" href="//tools.wmflabs.org/geohack/geohack.php?pagename=List_of_London_boroughs&params=51.559_N_0.0741_E_region:GB_type:city&title=Redbridge"><span class="geo-nondefault"><span class="geo-dms" title="Maps, aerial photos, and other data for this location"><span class="latitude">51°33′32″N</span> <span class="longitude">0°04′27″E</span></span></span><span class="geo-multi-punct"> / </span><span class="geo-default"><span class="vcard"><span class="geo-dec" title="Maps, aerial photos, and other data for this location">51.5590°N 0.0741°E</span><span style="display:none"> / <span class="geo">51.5590; 0.0741</span></span><span style="display:none"> (<span class="fn org">Redbridge</span>)</span></span></span></a></span>
</td>
<td>26
</td></tr>
<tr>
<td><a href="/wiki/London_Borough_of_Richmond_upon_Thames" title="London Borough of Richmond upon Thames">Richmond upon Thames</a>
</td>
<td>
</td>
<td>
</td>
<td><a href="/wiki/Richmond_upon_Thames_London_Borough_Council" title="Richmond upon Thames London Borough Council">Richmond upon Thames London Borough Council</a>
</td>
<td><a href="/wiki/Liberal_Democrats_(UK)" title="Liberal Democrats (UK)">Liberal Democrat</a>
</td>
<td><a class="new" href="/w/index.php?title=Richmond_upon_Thames_Civic_Centre&action=edit&redlink=1" title="Richmond upon Thames Civic Centre (page does not exist)">Civic Centre</a>, 44 York Street
</td>
<td>22.17
</td>
<td>191,365
</td>
<td><span class="plainlinks nourlexpansion"><a class="external text" href="//tools.wmflabs.org/geohack/geohack.php?pagename=List_of_London_boroughs&params=51.4479_N_0.326_W_region:GB_type:city&title=Richmond+upon+Thames"><span class="geo-nondefault"><span class="geo-dms" title="Maps, aerial photos, and other data for this location"><span class="latitude">51°26′52″N</span> <span class="longitude">0°19′34″W</span></span></span><span class="geo-multi-punct"> / </span><span class="geo-default"><span class="vcard"><span class="geo-dec" title="Maps, aerial photos, and other data for this location">51.4479°N 0.3260°W</span><span style="display:none"> / <span class="geo">51.4479; -0.3260</span></span><span style="display:none"> (<span class="fn org">Richmond upon Thames</span>)</span></span></span></a></span>
</td>
<td>15
</td></tr>
<tr>
<td><a href="/wiki/London_Borough_of_Southwark" title="London Borough of Southwark">Southwark</a>
</td>
<td><img alt="☑" data-file-height="600" data-file-width="600" decoding="async" height="20" src="//upload.wikimedia.org/wikipedia/en/thumb/f/fb/Yes_check.svg/20px-Yes_check.svg.png" srcset="//upload.wikimedia.org/wikipedia/en/thumb/f/fb/Yes_check.svg/30px-Yes_check.svg.png 1.5x, //upload.wikimedia.org/wikipedia/en/thumb/f/fb/Yes_check.svg/40px-Yes_check.svg.png 2x" width="20"/><span style="display:none">Y</span>
</td>
<td>
</td>
<td><a href="/wiki/Southwark_London_Borough_Council" title="Southwark London Borough Council">Southwark London Borough Council</a>
</td>
<td><a href="/wiki/Labour_Party_(UK)" title="Labour Party (UK)">Labour</a>
</td>
<td><a class="new" href="/w/index.php?title=160_Tooley_Street&action=edit&redlink=1" title="160 Tooley Street (page does not exist)">160 Tooley Street</a>
</td>
<td>11.14
</td>
<td>298,464
</td>
<td><span class="plainlinks nourlexpansion"><a class="external text" href="//tools.wmflabs.org/geohack/geohack.php?pagename=List_of_London_boroughs&params=51.5035_N_0.0804_W_region:GB_type:city&title=Southwark"><span class="geo-nondefault"><span class="geo-dms" title="Maps, aerial photos, and other data for this location"><span class="latitude">51°30′13″N</span> <span class="longitude">0°04′49″W</span></span></span><span class="geo-multi-punct"> / </span><span class="geo-default"><span class="vcard"><span class="geo-dec" title="Maps, aerial photos, and other data for this location">51.5035°N 0.0804°W</span><span style="display:none"> / <span class="geo">51.5035; -0.0804</span></span><span style="display:none"> (<span class="fn org">Southwark</span>)</span></span></span></a></span>
</td>
<td>7
</td></tr>
<tr>
<td><a href="/wiki/London_Borough_of_Sutton" title="London Borough of Sutton">Sutton</a>
</td>
<td>
</td>
<td>
</td>
<td><a href="/wiki/Sutton_London_Borough_Council" title="Sutton London Borough Council">Sutton London Borough Council</a>
</td>
<td><a href="/wiki/Liberal_Democrats_(UK)" title="Liberal Democrats (UK)">Liberal Democrat</a>
</td>
<td><a class="new" href="/w/index.php?title=Sutton_Civic_Offices&action=edit&redlink=1" title="Sutton Civic Offices (page does not exist)">Civic Offices</a>, St Nicholas Way
</td>
<td>16.93
</td>
<td>195,914
</td>
<td><span class="plainlinks nourlexpansion"><a class="external text" href="//tools.wmflabs.org/geohack/geohack.php?pagename=List_of_London_boroughs&params=51.3618_N_0.1945_W_region:GB_type:city&title=Sutton"><span class="geo-nondefault"><span class="geo-dms" title="Maps, aerial photos, and other data for this location"><span class="latitude">51°21′42″N</span> <span class="longitude">0°11′40″W</span></span></span><span class="geo-multi-punct"> / </span><span class="geo-default"><span class="vcard"><span class="geo-dec" title="Maps, aerial photos, and other data for this location">51.3618°N 0.1945°W</span><span style="display:none"> / <span class="geo">51.3618; -0.1945</span></span><span style="display:none"> (<span class="fn org">Sutton</span>)</span></span></span></a></span>
</td>
<td>18
</td></tr>
<tr>
<td><a href="/wiki/London_Borough_of_Tower_Hamlets" title="London Borough of Tower Hamlets">Tower Hamlets</a>
</td>
<td><img alt="☑" data-file-height="600" data-file-width="600" decoding="async" height="20" src="//upload.wikimedia.org/wikipedia/en/thumb/f/fb/Yes_check.svg/20px-Yes_check.svg.png" srcset="//upload.wikimedia.org/wikipedia/en/thumb/f/fb/Yes_check.svg/30px-Yes_check.svg.png 1.5x, //upload.wikimedia.org/wikipedia/en/thumb/f/fb/Yes_check.svg/40px-Yes_check.svg.png 2x" width="20"/><span style="display:none">Y</span>
</td>
<td>
</td>
<td><a href="/wiki/Tower_Hamlets_London_Borough_Council" title="Tower Hamlets London Borough Council">Tower Hamlets London Borough Council</a>
</td>
<td><a href="/wiki/Labour_Party_(UK)" title="Labour Party (UK)">Labour</a>
</td>
<td><a class="new" href="/w/index.php?title=Tower_Hamlets_Town_Hall&action=edit&redlink=1" title="Tower Hamlets Town Hall (page does not exist)">Town Hall</a>, Mulberry Place, 5 Clove Crescent
</td>
<td>7.63
</td>
<td>272,890
</td>
<td><span class="plainlinks nourlexpansion"><a class="external text" href="//tools.wmflabs.org/geohack/geohack.php?pagename=List_of_London_boroughs&params=51.5099_N_0.0059_W_region:GB_type:city&title=Tower+Hamlets"><span class="geo-nondefault"><span class="geo-dms" title="Maps, aerial photos, and other data for this location"><span class="latitude">51°30′36″N</span> <span class="longitude">0°00′21″W</span></span></span><span class="geo-multi-punct"> / </span><span class="geo-default"><span class="vcard"><span class="geo-dec" title="Maps, aerial photos, and other data for this location">51.5099°N 0.0059°W</span><span style="display:none"> / <span class="geo">51.5099; -0.0059</span></span><span style="display:none"> (<span class="fn org">Tower Hamlets</span>)</span></span></span></a></span>
</td>
<td>8
</td></tr>
<tr>
<td><a href="/wiki/London_Borough_of_Waltham_Forest" title="London Borough of Waltham Forest">Waltham Forest</a>
</td>
<td>
</td>
<td>
</td>
<td><a href="/wiki/Waltham_Forest_London_Borough_Council" title="Waltham Forest London Borough Council">Waltham Forest London Borough Council</a>
</td>
<td><a href="/wiki/Labour_Party_(UK)" title="Labour Party (UK)">Labour</a>
</td>
<td><a href="/wiki/Waltham_Forest_Town_Hall" title="Waltham Forest Town Hall">Waltham Forest Town Hall</a>, Forest Road
</td>
<td>14.99
</td>
<td>265,797
</td>
<td><span class="plainlinks nourlexpansion"><a class="external text" href="//tools.wmflabs.org/geohack/geohack.php?pagename=List_of_London_boroughs&params=51.5908_N_0.0134_W_region:GB_type:city&title=Waltham+Forest"><span class="geo-nondefault"><span class="geo-dms" title="Maps, aerial photos, and other data for this location"><span class="latitude">51°35′27″N</span> <span class="longitude">0°00′48″W</span></span></span><span class="geo-multi-punct"> / </span><span class="geo-default"><span class="vcard"><span class="geo-dec" title="Maps, aerial photos, and other data for this location">51.5908°N 0.0134°W</span><span style="display:none"> / <span class="geo">51.5908; -0.0134</span></span><span style="display:none"> (<span class="fn org">Waltham Forest</span>)</span></span></span></a></span>
</td>
<td>28
</td></tr>
<tr>
<td><a href="/wiki/London_Borough_of_Wandsworth" title="London Borough of Wandsworth">Wandsworth</a>
</td>
<td><img alt="☑" data-file-height="600" data-file-width="600" decoding="async" height="20" src="//upload.wikimedia.org/wikipedia/en/thumb/f/fb/Yes_check.svg/20px-Yes_check.svg.png" srcset="//upload.wikimedia.org/wikipedia/en/thumb/f/fb/Yes_check.svg/30px-Yes_check.svg.png 1.5x, //upload.wikimedia.org/wikipedia/en/thumb/f/fb/Yes_check.svg/40px-Yes_check.svg.png 2x" width="20"/><span style="display:none">Y</span>
</td>
<td>
</td>
<td><a href="/wiki/Wandsworth_London_Borough_Council" title="Wandsworth London Borough Council">Wandsworth London Borough Council</a>
</td>
<td><a href="/wiki/Conservative_Party_(UK)" title="Conservative Party (UK)">Conservative</a>
</td>
<td><a class="new" href="/w/index.php?title=Wandsworth_Town_Hall&action=edit&redlink=1" title="Wandsworth Town Hall (page does not exist)">The Town Hall</a>, <a href="/wiki/Wandsworth_High_Street" title="Wandsworth High Street">Wandsworth High Street</a>
</td>
<td>13.23
</td>
<td>310,516
</td>
<td><span class="plainlinks nourlexpansion"><a class="external text" href="//tools.wmflabs.org/geohack/geohack.php?pagename=List_of_London_boroughs&params=51.4567_N_0.191_W_region:GB_type:city&title=Wandsworth"><span class="geo-nondefault"><span class="geo-dms" title="Maps, aerial photos, and other data for this location"><span class="latitude">51°27′24″N</span> <span class="longitude">0°11′28″W</span></span></span><span class="geo-multi-punct"> / </span><span class="geo-default"><span class="vcard"><span class="geo-dec" title="Maps, aerial photos, and other data for this location">51.4567°N 0.1910°W</span><span style="display:none"> / <span class="geo">51.4567; -0.1910</span></span><span style="display:none"> (<span class="fn org">Wandsworth</span>)</span></span></span></a></span>
</td>
<td>5
</td></tr>
<tr>
<td><a href="/wiki/City_of_Westminster" title="City of Westminster">Westminster</a>
</td>
<td><img alt="☑" data-file-height="600" data-file-width="600" decoding="async" height="20" src="//upload.wikimedia.org/wikipedia/en/thumb/f/fb/Yes_check.svg/20px-Yes_check.svg.png" srcset="//upload.wikimedia.org/wikipedia/en/thumb/f/fb/Yes_check.svg/30px-Yes_check.svg.png 1.5x, //upload.wikimedia.org/wikipedia/en/thumb/f/fb/Yes_check.svg/40px-Yes_check.svg.png 2x" width="20"/><span style="display:none">Y</span>
</td>
<td><a href="/wiki/City_status_in_the_United_Kingdom" title="City status in the United Kingdom">City</a>
</td>
<td><a href="/wiki/Westminster_City_Council" title="Westminster City Council">Westminster City Council</a>
</td>
<td><a href="/wiki/Conservative_Party_(UK)" title="Conservative Party (UK)">Conservative</a>
</td>
<td><a class="new" href="/w/index.php?title=Westminster_City_Hall&action=edit&redlink=1" title="Westminster City Hall (page does not exist)">Westminster City Hall</a>, 64 Victoria Street
</td>
<td>8.29
</td>
<td>226,841
</td>
<td><span class="plainlinks nourlexpansion"><a class="external text" href="//tools.wmflabs.org/geohack/geohack.php?pagename=List_of_London_boroughs&params=51.4973_N_0.1372_W_region:GB_type:city&title=Westminster"><span class="geo-nondefault"><span class="geo-dms" title="Maps, aerial photos, and other data for this location"><span class="latitude">51°29′50″N</span> <span class="longitude">0°08′14″W</span></span></span><span class="geo-multi-punct"> / </span><span class="geo-default"><span class="vcard"><span class="geo-dec" title="Maps, aerial photos, and other data for this location">51.4973°N 0.1372°W</span><span style="display:none"> / <span class="geo">51.4973; -0.1372</span></span><span style="display:none"> (<span class="fn org">Westminster</span>)</span></span></span></a></span>
</td>
<td>2
</td></tr></tbody></table>, <table class="wikitable sortable" style="font-size:95%" width="100%">
<tbody><tr>
<th width="100px"><i>‘Borough’</i>
</th>
<th>Inner
</th>
<th width="100px">Status
</th>
<th>Local authority
</th>
<th>Political control
</th>
<th width="120px">Headquarters
</th>
<th>Area<br/>(sq mi)
</th>
<th>Population<br/>(2011 est)
</th>
<th width="20px">Co-ordinates
</th>
<th><span style="background:#67BCD3"> Nr. in<br/>map </span>
</th></tr>
<tr>
<td><a href="/wiki/City_of_London" title="City of London">City of London</a>
</td>
<td>(<img alt="☑" data-file-height="600" data-file-width="600" decoding="async" height="20" src="//upload.wikimedia.org/wikipedia/en/thumb/f/fb/Yes_check.svg/20px-Yes_check.svg.png" srcset="//upload.wikimedia.org/wikipedia/en/thumb/f/fb/Yes_check.svg/30px-Yes_check.svg.png 1.5x, //upload.wikimedia.org/wikipedia/en/thumb/f/fb/Yes_check.svg/40px-Yes_check.svg.png 2x" width="20"/><span style="display:none">Y</span>)<br/><sup class="reference" id="cite_ref-6"><a href="#cite_note-6">[note 5]</a></sup>
</td>
<td><i><a href="/wiki/Sui_generis" title="Sui generis">Sui generis</a></i>;<br/><a href="/wiki/City_status_in_the_United_Kingdom" title="City status in the United Kingdom">City</a>;<br/><a href="/wiki/Ceremonial_counties_of_England" title="Ceremonial counties of England">Ceremonial county</a>
</td>
<td><a class="mw-redirect" href="/wiki/Corporation_of_London" title="Corporation of London">Corporation of London</a>;<br/><a href="/wiki/Inner_Temple" title="Inner Temple">Inner Temple</a>;<br/><a href="/wiki/Middle_Temple" title="Middle Temple">Middle Temple</a>
</td>
<td>?
</td>
<td><a href="/wiki/Guildhall,_London" title="Guildhall, London">Guildhall</a>
</td>
<td>1.12
</td>
<td>7,000
</td>
<td><span class="plainlinks nourlexpansion"><a class="external text" href="//tools.wmflabs.org/geohack/geohack.php?pagename=List_of_London_boroughs&params=51.5155_N_0.0922_W_region:GB_type:city&title=City+of+London"><span class="geo-nondefault"><span class="geo-dms" title="Maps, aerial photos, and other data for this location"><span class="latitude">51°30′56″N</span> <span class="longitude">0°05′32″W</span></span></span><span class="geo-multi-punct"> / </span><span class="geo-default"><span class="vcard"><span class="geo-dec" title="Maps, aerial photos, and other data for this location">51.5155°N 0.0922°W</span><span style="display:none"> / <span class="geo">51.5155; -0.0922</span></span><span style="display:none"> (<span class="fn org">City of London</span>)</span></span></span></a></span>
</td>
<td>1
</td></tr></tbody></table>]
| MIT | Capstone Project - The Battle of the Neighborhoods - London Neighborhood Clustering.ipynb | ZRQ-rikkie/coursera-python |
Converting the table into a data frame | London_table = pd.read_html(str(table[0]), index_col=None, header=0)[0]
London_table.head() | _____no_output_____ | MIT | Capstone Project - The Battle of the Neighborhoods - London Neighborhood Clustering.ipynb | ZRQ-rikkie/coursera-python |
The second table on the site contains the addition Borough i.e. City of London | # Read in the second table
London_table1 = pd.read_html(str(table[1]), index_col=None, header=0)[0]
# Rename the columns to match the previous table to append the tables.
London_table1.columns = ['Borough','Inner','Status','Local authority','Political control',
'Headquarters','Area (sq mi)','Population (2013 est)[1]','Co-ordinates','Nr. in map']
# View the table
London_table1 | _____no_output_____ | MIT | Capstone Project - The Battle of the Neighborhoods - London Neighborhood Clustering.ipynb | ZRQ-rikkie/coursera-python |
Append the data frame together | # A continuous index value will be maintained
# across the rows in the new appended data frame.
London_table = London_table.append(London_table1, ignore_index = True)
London_table.head() | _____no_output_____ | MIT | Capstone Project - The Battle of the Neighborhoods - London Neighborhood Clustering.ipynb | ZRQ-rikkie/coursera-python |
Check if the last row was appended correctly | London_table.tail() | _____no_output_____ | MIT | Capstone Project - The Battle of the Neighborhoods - London Neighborhood Clustering.ipynb | ZRQ-rikkie/coursera-python |
View the information of the data set | London_table.info() | <class 'pandas.core.frame.DataFrame'>
RangeIndex: 33 entries, 0 to 32
Data columns (total 10 columns):
Borough 33 non-null object
Inner 15 non-null object
Status 5 non-null object
Local authority 33 non-null object
Political control 33 non-null object
Headquarters 33 non-null object
Area (sq mi) 33 non-null float64
Population (2013 est)[1] 33 non-null int64
Co-ordinates 33 non-null object
Nr. in map 33 non-null int64
dtypes: float64(1), int64(2), object(7)
memory usage: 2.7+ KB
| MIT | Capstone Project - The Battle of the Neighborhoods - London Neighborhood Clustering.ipynb | ZRQ-rikkie/coursera-python |
Removing Unnecessary string in the Data set | London_table = London_table.replace('note 1','', regex=True)
London_table = London_table.replace('note 2','', regex=True)
London_table = London_table.replace('note 3','', regex=True)
London_table = London_table.replace('note 4','', regex=True)
London_table = London_table.replace('note 5','', regex=True)
# View the top of the data set
London_table.head() | _____no_output_____ | MIT | Capstone Project - The Battle of the Neighborhoods - London Neighborhood Clustering.ipynb | ZRQ-rikkie/coursera-python |
Check the type of the newly created table | type(London_table)
# Shape of the data frame
London_table.shape | _____no_output_____ | MIT | Capstone Project - The Battle of the Neighborhoods - London Neighborhood Clustering.ipynb | ZRQ-rikkie/coursera-python |
Check if the Borough in both the data frames match. | set(df.Borough) - set(London_table.Borough) | _____no_output_____ | MIT | Capstone Project - The Battle of the Neighborhoods - London Neighborhood Clustering.ipynb | ZRQ-rikkie/coursera-python |
These 3 Boroughs don't match because of the unnecessary symobols present "[]" Find the index of the Boroughs that didn't match | print("The index of first borough is",London_table.index[London_table['Borough'] == 'Barking and Dagenham []'].tolist())
print("The index of second borough is",London_table.index[London_table['Borough'] == 'Greenwich []'].tolist())
print("The index of third borough is",London_table.index[London_table['Borough'] == 'Hammersmith and Fulham []'].tolist()) | The index of first borough is [0]
The index of second borough is [9]
The index of third borough is [11]
| MIT | Capstone Project - The Battle of the Neighborhoods - London Neighborhood Clustering.ipynb | ZRQ-rikkie/coursera-python |
Changing the Borough names to match the other data frame | London_table.iloc[0,0] = 'Barking and Dagenham'
London_table.iloc[9,0] = 'Greenwich'
London_table.iloc[11,0] = 'Hammersmith and Fulham' | _____no_output_____ | MIT | Capstone Project - The Battle of the Neighborhoods - London Neighborhood Clustering.ipynb | ZRQ-rikkie/coursera-python |
Check if the Borough names in both data sets match | set(df.Borough) - set(London_table.Borough) | _____no_output_____ | MIT | Capstone Project - The Battle of the Neighborhoods - London Neighborhood Clustering.ipynb | ZRQ-rikkie/coursera-python |
The Borough names in both data frames match We can combine both the data frames together | Ld_crime = pd.merge(London_crime, London_table, on='Borough')
Ld_crime.head(10)
Ld_crime.shape
set(df.Borough) - set(Ld_crime.Borough) | _____no_output_____ | MIT | Capstone Project - The Battle of the Neighborhoods - London Neighborhood Clustering.ipynb | ZRQ-rikkie/coursera-python |
Rearranging the Columns | # List of Column names of the data frame
list(Ld_crime)
columnsTitles = ['Borough','Local authority','Political control','Headquarters',
'Area (sq mi)','Population (2013 est)[1]',
'Inner','Status',
'Burglary','Criminal Damage','Drugs','Other Notifiable Offences',
'Robbery','Theft and Handling','Violence Against the Person','Total','Co-ordinates']
Ld_crime = Ld_crime.reindex(columns=columnsTitles)
Ld_crime = Ld_crime[['Borough','Local authority','Political control','Headquarters',
'Area (sq mi)','Population (2013 est)[1]','Co-ordinates',
'Burglary','Criminal Damage','Drugs','Other Notifiable Offences',
'Robbery','Theft and Handling','Violence Against the Person','Total']]
Ld_crime.head() | _____no_output_____ | MIT | Capstone Project - The Battle of the Neighborhoods - London Neighborhood Clustering.ipynb | ZRQ-rikkie/coursera-python |
Methodology The methodology in this project consists of two parts:- [Exploratory Data Analysis](EDA): Visualise the crime rates in the London boroughs to idenity the safest borough and extract the neighborhoods in that borough to find the 10 most common venues in each neighborhood.- [Modelling](modelling): To help people find similar neighborhoods in the safest borough we will be clustering similar neighborhoods using K - means clustering which is a form of unsupervised machine learning algorithm that clusters data based on predefined cluster size. We will use a cluster size of 5 for this project that will cluster the 15 neighborhoods into 5 clusters. The reason to conduct a K- means clustering is to cluster neighborhoods with similar venues together so that people can shortlist the area of their interests based on the venues/amenities around each neighborhood. Exploratory Data Analysis Descriptive statistics of the data | London_crime.describe()
# use the inline backend to generate the plots within the browser
%matplotlib inline
import matplotlib as mpl
import matplotlib.pyplot as plt
mpl.style.use('ggplot') # optional: for ggplot-like style
# check for latest version of Matplotlib
print ('Matplotlib version: ', mpl.__version__) # >= 2.0.0
# Matplotlib and associated plotting modules
import matplotlib.cm as cm
import matplotlib.colors as colors | Matplotlib version: 2.1.2
| MIT | Capstone Project - The Battle of the Neighborhoods - London Neighborhood Clustering.ipynb | ZRQ-rikkie/coursera-python |
Check if the column names are strings | Ld_crime.columns = list(map(str, Ld_crime.columns))
# let's check the column labels types now
all(isinstance(column, str) for column in Ld_crime.columns) | _____no_output_____ | MIT | Capstone Project - The Battle of the Neighborhoods - London Neighborhood Clustering.ipynb | ZRQ-rikkie/coursera-python |
Sort the total crimes in descenting order to see 5 boroughs with the highest number of crimes | Ld_crime.sort_values(['Total'], ascending = False, axis = 0, inplace = True )
df_top5 = Ld_crime.head()
df_top5 | _____no_output_____ | MIT | Capstone Project - The Battle of the Neighborhoods - London Neighborhood Clustering.ipynb | ZRQ-rikkie/coursera-python |
Visualize the five boroughs with the highest number of crimes | df_tt = df_top5[['Borough','Total']]
df_tt.set_index('Borough',inplace = True)
ax = df_tt.plot(kind='bar', figsize=(10, 6), rot=0)
ax.set_ylabel('Number of Crimes') # add to x-label to the plot
ax.set_xlabel('Borough') # add y-label to the plot
ax.set_title('London Boroughs with the Highest no. of crime') # add title to the plot
# Creating a function to display the percentage.
for p in ax.patches:
ax.annotate(np.round(p.get_height(),decimals=2),
(p.get_x()+p.get_width()/2., p.get_height()),
ha='center',
va='center',
xytext=(0, 10),
textcoords='offset points',
fontsize = 14
)
plt.show() | _____no_output_____ | MIT | Capstone Project - The Battle of the Neighborhoods - London Neighborhood Clustering.ipynb | ZRQ-rikkie/coursera-python |
We'll stay clear from these places :) Sort the total crimes in ascending order to see 5 boroughs with the highest number of crimes | Ld_crime.sort_values(['Total'], ascending = True, axis = 0, inplace = True )
df_bot5 = Ld_crime.head()
df_bot5 | _____no_output_____ | MIT | Capstone Project - The Battle of the Neighborhoods - London Neighborhood Clustering.ipynb | ZRQ-rikkie/coursera-python |
Visualize the five boroughs with the least number of crimes | df_bt = df_bot5[['Borough','Total']]
df_bt.set_index('Borough',inplace = True)
ax = df_bt.plot(kind='bar', figsize=(10, 6), rot=0)
ax.set_ylabel('Number of Crimes') # add to x-label to the plot
ax.set_xlabel('Borough') # add y-label to the plot
ax.set_title('London Boroughs with the least no. of crime') # add title to the plot
# Creating a function to display the percentage.
for p in ax.patches:
ax.annotate(np.round(p.get_height(),decimals=2),
(p.get_x()+p.get_width()/2., p.get_height()),
ha='center',
va='center',
xytext=(0, 10),
textcoords='offset points',
fontsize = 14
)
plt.show() | _____no_output_____ | MIT | Capstone Project - The Battle of the Neighborhoods - London Neighborhood Clustering.ipynb | ZRQ-rikkie/coursera-python |
The borough City of London has the lowest no. of crimes recorded for the year 2016, Looking into the details of the borough: | df_col = df_bot5[df_bot5['Borough'] == 'City of London']
df_col = df_col[['Borough','Total','Area (sq mi)','Population (2013 est)[1]']]
df_col | _____no_output_____ | MIT | Capstone Project - The Battle of the Neighborhoods - London Neighborhood Clustering.ipynb | ZRQ-rikkie/coursera-python |
As per the wikipedia page, The City of London is the 33rd principal division of Greater London but it is not a London borough. URL: https://en.wikipedia.org/wiki/List_of_London_boroughs Hence we will focus on the next borough with the least crime i.e. Kingston upon Thames Visualizing different types of crimes in the borough 'Kingston upon Thames' | df_bc1 = df_bot5[df_bot5['Borough'] == 'Kingston upon Thames']
df_bc = df_bc1[['Borough','Burglary','Criminal Damage','Drugs','Other Notifiable Offences',
'Robbery','Theft and Handling','Violence Against the Person']]
df_bc.set_index('Borough',inplace = True)
ax = df_bc.plot(kind='bar', figsize=(10, 6), rot=0)
ax.set_ylabel('Number of Crimes') # add to x-label to the plot
ax.set_xlabel('Borough') # add y-label to the plot
ax.set_title('London Boroughs with the least no. of crime') # add title to the plot
# Creating a function to display the percentage.
for p in ax.patches:
ax.annotate(np.round(p.get_height(),decimals=2),
(p.get_x()+p.get_width()/2., p.get_height()),
ha='center',
va='center',
xytext=(0, 10),
textcoords='offset points',
fontsize = 14
)
plt.show()
| _____no_output_____ | MIT | Capstone Project - The Battle of the Neighborhoods - London Neighborhood Clustering.ipynb | ZRQ-rikkie/coursera-python |
We can conclude that Kingston upon Thames is the safest borough when compared to the other boroughs in London. Part 3: Creating a new dataset of the Neighborhoods of the safest borough in London and generating their co-ordinates. The list of Neighborhoods in the Royal Borough of Kingston upon Thames was found on a wikipedia page: https://en.wikipedia.org/wiki/List_of_districts_in_the_Royal_Borough_of_Kingston_upon_Thames | Neighborhood = ['Berrylands','Canbury','Chessington','Coombe','Hook','Kingston upon Thames',
'Kingston Vale','Malden Rushett','Motspur Park','New Malden','Norbiton',
'Old Malden','Seething Wells','Surbiton','Tolworth']
Borough = ['Kingston upon Thames','Kingston upon Thames','Kingston upon Thames','Kingston upon Thames',
'Kingston upon Thames','Kingston upon Thames','Kingston upon Thames','Kingston upon Thames',
'Kingston upon Thames','Kingston upon Thames','Kingston upon Thames','Kingston upon Thames',
'Kingston upon Thames','Kingston upon Thames','Kingston upon Thames']
Latitude = ['','','','','','','','','','','','','','','']
Longitude = ['','','','','','','','','','','','','','','']
df_neigh = {'Neighborhood': Neighborhood,'Borough':Borough,'Latitude': Latitude,'Longitude':Longitude}
kut_neig = pd.DataFrame(data=df_neigh, columns=['Neighborhood', 'Borough', 'Latitude', 'Longitude'], index=None)
kut_neig | _____no_output_____ | MIT | Capstone Project - The Battle of the Neighborhoods - London Neighborhood Clustering.ipynb | ZRQ-rikkie/coursera-python |
Find the Co-ordiantes of each Neighborhood in the Kingston upon Thames Neighborhood | Latitude = []
Longitude = []
for i in range(len(Neighborhood)):
address = '{},London,United Kingdom'.format(Neighborhood[i])
geolocator = Nominatim(user_agent="London_agent")
location = geolocator.geocode(address)
Latitude.append(location.latitude)
Longitude.append(location.longitude)
print(Latitude, Longitude)
df_neigh = {'Neighborhood': Neighborhood,'Borough':Borough,'Latitude': Latitude,'Longitude':Longitude}
kut_neig = pd.DataFrame(data=df_neigh, columns=['Neighborhood', 'Borough', 'Latitude', 'Longitude'], index=None)
kut_neig | _____no_output_____ | MIT | Capstone Project - The Battle of the Neighborhoods - London Neighborhood Clustering.ipynb | ZRQ-rikkie/coursera-python |
Get the co-ordinates of Berrylands, London, United Kingdom (The center neighborhood of Kingston upon Thames) | address = 'Berrylands, London, United Kingdom'
geolocator = Nominatim(user_agent="ld_explorer")
location = geolocator.geocode(address)
latitude = location.latitude
longitude = location.longitude
print('The geograpical coordinate of Berrylands, London are {}, {}.'.format(latitude, longitude)) | The geograpical coordinate of London are 51.3937811, -0.2848024.
| MIT | Capstone Project - The Battle of the Neighborhoods - London Neighborhood Clustering.ipynb | ZRQ-rikkie/coursera-python |
Visualize the Neighborhood of Kingston upon Thames Borough | # create map of New York using latitude and longitude values
map_lon = folium.Map(location=[latitude, longitude], zoom_start=12)
# add markers to map
for lat, lng, borough, neighborhood in zip(kut_neig['Latitude'], kut_neig['Longitude'], kut_neig['Borough'], kut_neig['Neighborhood']):
label = '{}, {}'.format(neighborhood, borough)
label = folium.Popup(label, parse_html=True)
folium.CircleMarker(
[lat, lng],
radius=5,
popup=label,
color='blue',
fill=True,
fill_color='#3186cc',
fill_opacity=0.7,
parse_html=False).add_to(map_lon)
map_lon | _____no_output_____ | MIT | Capstone Project - The Battle of the Neighborhoods - London Neighborhood Clustering.ipynb | ZRQ-rikkie/coursera-python |
Modelling - Finding all the venues within a 500 meter radius of each neighborhood.- Perform one hot ecoding on the venues data.- Grouping the venues by the neighborhood and calculating their mean.- Performing a K-means clustering (Defining K = 5) Create a function to extract the venues from each Neighborhood | def getNearbyVenues(names, latitudes, longitudes, radius=500):
venues_list=[]
for name, lat, lng in zip(names, latitudes, longitudes):
print(name)
# create the API request URL
url = 'https://api.foursquare.com/v2/venues/explore?&client_id={}&client_secret={}&v={}&ll={},{}&radius={}&limit={}'.format(
CLIENT_ID,
CLIENT_SECRET,
VERSION,
lat,
lng,
radius,
LIMIT)
# make the GET request
results = requests.get(url).json()["response"]['groups'][0]['items']
# return only relevant information for each nearby venue
venues_list.append([(
name,
lat,
lng,
v['venue']['name'],
v['venue']['location']['lat'],
v['venue']['location']['lng'],
v['venue']['categories'][0]['name']) for v in results])
nearby_venues = pd.DataFrame([item for venue_list in venues_list for item in venue_list])
nearby_venues.columns = ['Neighborhood',
'Neighborhood Latitude',
'Neighborhood Longitude',
'Venue',
'Venue Latitude',
'Venue Longitude',
'Venue Category']
return(nearby_venues)
kut_venues = getNearbyVenues(names=kut_neig['Neighborhood'],
latitudes=kut_neig['Latitude'],
longitudes=kut_neig['Longitude']
)
print(kut_venues.shape)
kut_venues.head()
kut_venues.groupby('Neighborhood').count()
print('There are {} uniques categories.'.format(len(kut_venues['Venue Category'].unique()))) | There are 65 uniques categories.
| MIT | Capstone Project - The Battle of the Neighborhoods - London Neighborhood Clustering.ipynb | ZRQ-rikkie/coursera-python |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.