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)
prin... | 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 w... | 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 [======... | 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('Tes... | 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 mo... | _____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... | 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 y... | 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.su... | _________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
global_average_pooling2d_1 ( (None, 512) 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 ... | 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 numbe... | _____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('Tes... | 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 co... | 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 ... | 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 __ne... | 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(pa... | _____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... | # 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")
finalAl... | 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 tha... | %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.s... | 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_L... | 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 accompani... | 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 a... | 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:... | 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 ... | 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.wi... | _____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... | 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:
... | _____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, Raste... | 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()... | {'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.B... | 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://r... | _____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 wh... | 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 charac... | #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 sam... | #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... | _____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 ... | #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',... | _____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 a... | #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 confusio... | 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 ... | 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.
... | 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 ... | # 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": "1... | _____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 sa... | # 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_... | # 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 Probl... | 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... | 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
# Vi... | _____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 ... | 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... | _____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.t... | _____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 web... | [<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... | 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)',... | _____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... | 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 th... | _____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'] == 'Ham... | 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',
... | _____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 pe... | 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__) # >... | 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 titl... | _____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 ... | _____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 b... | 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=(1... | _____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 wi... | 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 Thame... | _____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(Latitud... | _____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(neigh... | _____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={},... | 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 community queries yet
The top public SQL queries from the community will appear here once available.