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 |
|---|---|---|---|---|---|
Compute new attributes Then we need to loop through the CityObjects and update add the new attributes. Note that the `attributes` CityObject attribute is just a dictionary.Thus we compute the number of vertices of the CityObject and the area of is footprint. Then we going to cluster these two variables. This is comple... | for co_id, co in zurich.cityobjects.items():
co.attributes['nr_vertices'] = len(co.get_vertices())
co.attributes['fp_area'] = compute_footprint_area(co)
zurich.cityobjects[co_id] = co | _____no_output_____ | CC-BY-4.0 | cjio_tutorial.ipynb | balazsdukai/foss4g2019 |
It is possible to export the city model into a pandas DataFrame. Note that only the CityObject attributes are exported into the dataframe, with CityObject IDs as the index of the dataframe. Thus if you want to export the attributes of SemanticSurfaces for example, then you need to add them as CityObject attributes.The ... | def assign_cityobject_attribute(cm):
"""Copy the semantic surface attributes to CityObject attributes.
Returns a copy of the citymodel.
"""
new_cos = {}
cm_copy = deepcopy(cm)
for co_id, co in cm.cityobjects.items():
for geom in co.geometry:
for srf in geom.surfaces.values():... | _____no_output_____ | CC-BY-4.0 | cjio_tutorial.ipynb | balazsdukai/foss4g2019 |
In order to have a nicer distribution of the data, we remove the missing values and apply a log-transform on the two variables. Note that the `FuntionTransformer.transform` transforms a DataFrame to a numpy array that is ready to be used in `scikit-learn`. The details of a machine learning workflow is beyond the scope ... | df_subset = df[df['Geomtype'].notnull() & df['fp_area'] > 0.0].loc[:, ['nr_vertices', 'fp_area']]
transformer = FunctionTransformer(np.log, validate=True)
df_logtransform = transformer.transform(df_subset)
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.scatter(df_logtransform[:,0], df_logtransform[:,1], alpha=0.3,... | _____no_output_____ | CC-BY-4.0 | cjio_tutorial.ipynb | balazsdukai/foss4g2019 |
Since we transformed our DataFrame, we can fit any model in `scikit-learn`. I use DBSCAN because I wanted to find the data points on the fringes of the central cluster. | %matplotlib notebook
model = cluster.DBSCAN(eps=0.2).fit(df_logtransform)
plot_model_results(model, df_logtransform)
# merge the cluster labels back to the data frame
df_subset['dbscan'] = model.labels_ | _____no_output_____ | CC-BY-4.0 | cjio_tutorial.ipynb | balazsdukai/foss4g2019 |
Save the results back to CityJSON And merge the DataFrame with cluster labels back to the city model. | for co_id, co in zurich.cityobjects.items():
if co_id in df_subset.index:
ml_results = dict(df_subset.loc[co_id])
else:
ml_results = {'nr_vertices': 'nan', 'fp_area': 'nan', 'dbscan': 'nan'}
new_attrs = {**co.attributes, **ml_results}
co.attributes = new_attrs
zurich.cityobjects[co_i... | _____no_output_____ | CC-BY-4.0 | cjio_tutorial.ipynb | balazsdukai/foss4g2019 |
At the end, the `save()` method saves the edited city model into a CityJSON file. | path_out = os.path.join('data', 'zurich_output.json')
cityjson.save(zurich, path_out) | _____no_output_____ | CC-BY-4.0 | cjio_tutorial.ipynb | balazsdukai/foss4g2019 |
Working With TileMatrixSets (other than WebMercator)[](https://mybinder.org/v2/gh/developmentseed/titiler/master?filepath=docs%2Fexamples%2FWorking_with_nonWebMercatorTMS.ipynb)TiTiler has builtin support for serving tiles in multiple Projections by using [rio-tiler](https... | # Uncomment if you need to install those module within the notebook
# !pip install ipyleaflet requests
import json
import requests
from ipyleaflet import (
Map,
basemaps,
basemap_to_tiles,
TileLayer,
WMSLayer,
GeoJSON,
projections
)
titiler_endpoint = "https://api.cogeo.xyz" # Devseed Cus... | _____no_output_____ | MIT | docs/examples/Working_with_nonWebMercatorTMS.ipynb | Anagraph/titiler |
List Supported TileMatrixSets | r = requests.get("https://api.cogeo.xyz/tileMatrixSets").json()
print("Supported TMS:")
for tms in r["tileMatrixSets"]:
print("-", tms["id"]) | _____no_output_____ | MIT | docs/examples/Working_with_nonWebMercatorTMS.ipynb | Anagraph/titiler |
WGS 84 -- WGS84 - World Geodetic System 1984 - EPSG:4326https://epsg.io/4326 | r = requests.get(
"https://api.cogeo.xyz/cog/WorldCRS84Quad/tilejson.json", params = {"url": url}
).json()
m = Map(center=(45, 0), zoom=4, basemap={}, crs=projections.EPSG4326)
layer = TileLayer(url=r["tiles"][0], opacity=1)
m.add_layer(layer)
m | _____no_output_____ | MIT | docs/examples/Working_with_nonWebMercatorTMS.ipynb | Anagraph/titiler |
WGS 84 / NSIDC Sea Ice Polar Stereographic North - EPSG:3413https://epsg.io/3413 | r = requests.get(
"https://api.cogeo.xyz/cog/EPSG3413/tilejson.json", params = {"url": url}
).json()
m = Map(center=(70, 0), zoom=1, basemap={}, crs=projections.EPSG3413)
layer = TileLayer(url=r["tiles"][0], opacity=1)
m.add_layer(layer)
m | _____no_output_____ | MIT | docs/examples/Working_with_nonWebMercatorTMS.ipynb | Anagraph/titiler |
ETRS89-extended / LAEA Europe - EPSG:3035https://epsg.io/3035 | r = requests.get(
"https://api.cogeo.xyz/cog/EuropeanETRS89_LAEAQuad/tilejson.json", params = {"url": url}
).json()
my_projection = {
'name': 'EPSG:3035',
'custom': True, #This is important, it tells ipyleaflet that this projection is not on the predefined ones.
'proj4def': '+proj=laea +lat_0=52 +lon_0... | _____no_output_____ | MIT | docs/examples/Working_with_nonWebMercatorTMS.ipynb | Anagraph/titiler |
100 pandas puzzlesInspired by [100 Numpy exerises](https://github.com/rougier/numpy-100), here are 100* short puzzles for testing your knowledge of [pandas'](http://pandas.pydata.org/) power.Since pandas is a large library with many different specialist features and functions, these excercises focus mainly on the fund... | import numpy as np
data = {'animal': ['cat', 'cat', 'snake', 'dog', 'dog', 'cat', 'snake', 'cat', 'dog', 'dog'],
'age': [2.5, 3, 0.5, np.nan, 5, 2, 4.5, np.nan, 7, 3],
'visits': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1],
'priority': ['yes', 'yes', 'no', 'yes', 'no', 'no', 'no', 'yes', 'no', 'no']}
labels... | _____no_output_____ | MIT | 100-pandas-puzzles.ipynb | greenteausa/100-pandas-puzzles |
**5.** Display a summary of the basic information about this DataFrame and its data (*hint: there is a single method that can be called on the DataFrame*). **6.** Return the first 3 rows of the DataFrame `df`. **7.** Select just the 'animal' and 'age' columns from the DataFrame `df`. **8.** Select the data in rows `[3,... | nan = np.nan
data = [[0.04, nan, nan, 0.25, nan, 0.43, 0.71, 0.51, nan, nan],
[ nan, nan, nan, 0.04, 0.76, nan, nan, 0.67, 0.76, 0.16],
[ nan, nan, 0.5 , nan, 0.31, 0.4 , nan, nan, 0.24, 0.01],
[0.49, nan, nan, 0.62, 0.73, 0.26, 0.85, nan, nan, nan],
[ nan, nan, 0.41,... | _____no_output_____ | MIT | 100-pandas-puzzles.ipynb | greenteausa/100-pandas-puzzles |
**27.** A DataFrame has a column of groups 'grps' and and column of integer values 'vals': ```pythondf = pd.DataFrame({'grps': list('aaabbcaabcccbbc'), 'vals': [12,345,3,1,45,14,4,52,54,23,235,21,57,3,87]})```For each *group*, find the sum of the three greatest values. You should end up with the answ... | df = pd.DataFrame({'grps': list('aaabbcaabcccbbc'),
'vals': [12,345,3,1,45,14,4,52,54,23,235,21,57,3,87]})
# write a solution to the question here | _____no_output_____ | MIT | 100-pandas-puzzles.ipynb | greenteausa/100-pandas-puzzles |
**28.** The DataFrame `df` constructed below has two integer columns 'A' and 'B'. The values in 'A' are between 1 and 100 (inclusive). For each group of 10 consecutive integers in 'A' (i.e. `(0, 10]`, `(10, 20]`, ...), calculate the sum of the corresponding values in column 'B'.The answer should be a Series as follows:... | df = pd.DataFrame(np.random.RandomState(8765).randint(1, 101, size=(100, 2)), columns = ["A", "B"])
# write a solution to the question here | _____no_output_____ | MIT | 100-pandas-puzzles.ipynb | greenteausa/100-pandas-puzzles |
DataFrames: harder problems These might require a bit of thinking outside the box......but all are solvable using just the usual pandas/NumPy methods (and so avoid using explicit `for` loops).Difficulty: *hard* **29.** Consider a DataFrame `df` where there is an integer column 'X':```pythondf = pd.DataFrame({'X': [7,... | df = pd.DataFrame(np.random.RandomState(30).randint(1, 101, size=(8, 8))) | _____no_output_____ | MIT | 100-pandas-puzzles.ipynb | greenteausa/100-pandas-puzzles |
**31.** You are given the DataFrame below with a column of group IDs, 'grps', and a column of corresponding integer values, 'vals'.```pythondf = pd.DataFrame({"vals": np.random.RandomState(31).randint(-30, 30, size=15), "grps": np.random.RandomState(31).choice(["A", "B"], 15)})```Create a new column ... | import numpy as np
def float_to_time(x):
return str(int(x)) + ":" + str(int(x%1 * 60)).zfill(2) + ":" + str(int(x*60 % 1 * 60)).zfill(2)
def day_stock_data():
#NYSE is open from 9:30 to 4:00
time = 9.5
price = 100
results = [(float_to_time(time), price)]
while time < 16:
elapsed = np.ra... | _____no_output_____ | MIT | 100-pandas-puzzles.ipynb | greenteausa/100-pandas-puzzles |
**Inheritence in Python**Object Oriented Programming is a coding paradigm that revolves around creating modular code and stopping mulitple uses of the same structure. It is aimed at increasing stability and usability of code. It consists of some well-known concepts stated below:1. Classes: These often show a collect... | # Implementation of Classes in Python
# Creating a Class Math with 2 functions
class Math:
def subtract (self, i, j):
return i-j
def add (self, x, y):
return x+y
# Creating an object of the class Math
math_child = Math()
test_int_A = 10
test_int_B = 20
print(math_child.subtract(test_int_B, test_int_A))
# C... | George
34
| MIT | 01. Getting Started with Python/Python_Revision_and_Statistical_Methods.ipynb | Jamess-ai/ai-with-python-series |
**Constructors and Inheritance**The constructor is an initialization function that is always called when a class’s instance is created. The constructor is named __init__() in Python and defines the specifics of instantiating a class and its attributes. Class inheritance is a concept of taking values of a class from its... | # Creating a class and instantiating variables
class Animal_Dog:
species = "Canis"
def __init__(self, name, age):
self.name = name
self.age = age
# Instance method
def description(self):
return f"{self.name} is {self.age} years old"
# Another instance method
def animal_so... | 100
1000.0
John
| MIT | 01. Getting Started with Python/Python_Revision_and_Statistical_Methods.ipynb | Jamess-ai/ai-with-python-series |
Variables and Data Types in PythonVariables are reserved locations in the computer’s memory that store values defined within them. Whenever a variable is created, a piece of the computer’s memory is allocated to it. Based on the data type of this declared variable, the interpreter allocates varied chunks of memory. The... | # Multiple Assignment: All are assigned to the same memory location
a = b = c = 1
# Assigning multiple variables with multiple values
a,b,c = 1,2,"jacob"
# Assigning and deleting variable references
var1 = 1
var2 = 10
del var1 # Removes the reference of var1
del var2
# Basic String Operations in Py... | _____no_output_____ | MIT | 01. Getting Started with Python/Python_Revision_and_Statistical_Methods.ipynb | Jamess-ai/ai-with-python-series |
Models and features | #for route in df.route.unique():
for route in routes:
try:
df2 = df[df['route'] == route]
sns.barplot(data=df2, x="model", y="R2_test", hue="feature_labels")
y1,y2 = plt.ylim()
plt.ylim((max(0,y1),y2))
plt.title(route)
plt.ylabel("$R^2$(test)")
f = plt.gcf()
... | _____no_output_____ | MIT | analyse_regression_results.ipynb | SusTra/TraCo |
Best features | fig, axs = plt.subplots(4, 2, sharey=False)
#for i, (route,ax) in enumerate(zip(df.route.unique(), axs.flatten())):
for i, (route,ax) in enumerate(zip(routes, axs.flatten())):
try:
df2 = df[df['route'] == route]
df3 = pd.DataFrame()
for features in df2.feature_labels.unique():
... | _____no_output_____ | MIT | analyse_regression_results.ipynb | SusTra/TraCo |
Best models | #for features in df.features.unique():
fig, axs = plt.subplots(4, 2, sharey=False)
#for i, (route,ax) in enumerate(zip(df.route.unique(), axs.flatten())):
for i, (route,ax) in enumerate(zip(routes, axs.flatten())):
try:
df2 = df[df['route'] == route]
df3 = pd.DataFrame()
#features = df2.fe... | _____no_output_____ | MIT | analyse_regression_results.ipynb | SusTra/TraCo |
Best results | df_best = pd.read_csv("regression_results_best.csv")
df_best['feature_labels'] = df_best['features'].map(lambda x: set_feature_labels(x, sep=", "))
df_best['R2_test'] = round(df_best['R2_test'],3)
df_best['R2_train'] = round(df_best['R2_train'],3)
df_best = df_best[['route', 'feature_labels','model', 'R2_train','R2_tes... | _____no_output_____ | MIT | analyse_regression_results.ipynb | SusTra/TraCo |
Sentiment Analysis Using XGBoost in SageMaker_Deep Learning Nanodegree Program | Deployment_---In this example of using Amazon's SageMaker service we will construct a random tree model to predict the sentiment of a movie review. You may have seen a version of this example in a pervious lesson although it would have be... | %mkdir ../data
!wget -O ../data/aclImdb_v1.tar.gz http://ai.stanford.edu/~amaas/data/sentiment/aclImdb_v1.tar.gz
!tar -zxf ../data/aclImdb_v1.tar.gz -C ../data | mkdir: cannot create directory ‘../data’: File exists
--2020-08-26 07:30:30-- http://ai.stanford.edu/~amaas/data/sentiment/aclImdb_v1.tar.gz
Resolving ai.stanford.edu (ai.stanford.edu)... 171.64.68.10
Connecting to ai.stanford.edu (ai.stanford.edu)|171.64.68.10|:80... connected.
HTTP request sent, awaiting response...... | MIT | Mini-Projects/IMDB Sentiment Analysis - XGBoost (Hyperparameter Tuning).ipynb | itirkaa/sagemaker-deployment |
Step 2: Preparing the dataThe data we have downloaded is split into various files, each of which contains a single review. It will be much easier going forward if we combine these individual files into two large files, one for training and one for testing. | import os
import glob
def read_imdb_data(data_dir='../data/aclImdb'):
data = {}
labels = {}
for data_type in ['train', 'test']:
data[data_type] = {}
labels[data_type] = {}
for sentiment in ['pos', 'neg']:
data[data_type][sentiment] = []
labels[d... | _____no_output_____ | MIT | Mini-Projects/IMDB Sentiment Analysis - XGBoost (Hyperparameter Tuning).ipynb | itirkaa/sagemaker-deployment |
Step 3: Processing the dataNow that we have our training and testing datasets merged and ready to use, we need to start processing the raw data into something that will be useable by our machine learning algorithm. To begin with, we remove any html formatting that may appear in the reviews and perform some standard na... | import nltk
nltk.download("stopwords")
from nltk.corpus import stopwords
from nltk.stem.porter import *
stemmer = PorterStemmer()
import re
from bs4 import BeautifulSoup
def review_to_words(review):
text = BeautifulSoup(review, "html.parser").get_text() # Remove HTML tags
text = re.sub(r"[^a-zA-Z0-9]", " ", te... | Read preprocessed data from cache file: preprocessed_data.pkl
| MIT | Mini-Projects/IMDB Sentiment Analysis - XGBoost (Hyperparameter Tuning).ipynb | itirkaa/sagemaker-deployment |
Extract Bag-of-Words featuresFor the model we will be implementing, rather than using the reviews directly, we are going to transform each review into a Bag-of-Words feature representation. Keep in mind that 'in the wild' we will only have access to the training set so our transformer can only use the training set to ... | import numpy as np
from sklearn.feature_extraction.text import CountVectorizer
import joblib
# joblib is an enhanced version of pickle that is more efficient for storing NumPy arrays
def extract_BoW_features(words_train, words_test, vocabulary_size=5000,
cache_dir=cache_dir, cache_file="bow_fe... | Read features from cache file: bow_features.pkl
| MIT | Mini-Projects/IMDB Sentiment Analysis - XGBoost (Hyperparameter Tuning).ipynb | itirkaa/sagemaker-deployment |
Step 4: Classification using XGBoostNow that we have created the feature representation of our training (and testing) data, it is time to start setting up and using the XGBoost classifier provided by SageMaker. Writing the datasetThe XGBoost classifier that we will be using requires the dataset to be written to a file... | import pandas as pd
val_X = pd.DataFrame(train_X[:10000])
train_X = pd.DataFrame(train_X[10000:])
val_y = pd.DataFrame(train_y[:10000])
train_y = pd.DataFrame(train_y[10000:])
test_y = pd.DataFrame(test_y)
test_X = pd.DataFrame(test_X) | _____no_output_____ | MIT | Mini-Projects/IMDB Sentiment Analysis - XGBoost (Hyperparameter Tuning).ipynb | itirkaa/sagemaker-deployment |
The documentation for the XGBoost algorithm in SageMaker requires that the saved datasets should contain no headers or index and that for the training and validation data, the label should occur first for each sample.For more information about this and other algorithms, the SageMaker developer documentation can be foun... | # First we make sure that the local directory in which we'd like to store the training and validation csv files exists.
data_dir = '../data/xgboost'
if not os.path.exists(data_dir):
os.makedirs(data_dir)
# First, save the test data to test.csv in the data_dir directory. Note that we do not save the associated groun... | _____no_output_____ | MIT | Mini-Projects/IMDB Sentiment Analysis - XGBoost (Hyperparameter Tuning).ipynb | itirkaa/sagemaker-deployment |
Uploading Training / Validation files to S3Amazon's S3 service allows us to store files that can be access by both the built-in training models such as the XGBoost model we will be using as well as custom models such as the one we will see a little later.For this, and most other tasks we will be doing using SageMaker,... | import sagemaker
session = sagemaker.Session() # Store the current SageMaker session
# S3 prefix (which folder will we use)
prefix = 'sentiment-xgboost'
test_location = session.upload_data(os.path.join(data_dir, 'test.csv'), key_prefix=prefix)
val_location = session.upload_data(os.path.join(data_dir, 'validation.csv... | _____no_output_____ | MIT | Mini-Projects/IMDB Sentiment Analysis - XGBoost (Hyperparameter Tuning).ipynb | itirkaa/sagemaker-deployment |
(TODO) Creating a hypertuned XGBoost modelNow that the data has been uploaded it is time to create the XGBoost model. As in the Boston Housing notebook, the first step is to create an estimator object which will be used as the *base* of your hyperparameter tuning job. | from sagemaker import get_execution_role
# Our current execution role is require when creating the model as the training
# and inference code will need to access the model artifacts.
role = get_execution_role()
# We need to retrieve the location of the container which is provided by Amazon for using XGBoost.
# As a ma... | Parameter image_name will be renamed to image_uri in SageMaker Python SDK v2.
| MIT | Mini-Projects/IMDB Sentiment Analysis - XGBoost (Hyperparameter Tuning).ipynb | itirkaa/sagemaker-deployment |
(TODO) Create the hyperparameter tunerNow that the base estimator has been set up we need to construct a hyperparameter tuner object which we will use to request SageMaker construct a hyperparameter tuning job.**Note:** Training a single sentiment analysis XGBoost model takes longer than training a Boston Housing XGBo... | # First, make sure to import the relevant objects used to construct the tuner
from sagemaker.tuner import IntegerParameter, ContinuousParameter, HyperparameterTuner
# TODO: Create the hyperparameter tuner object
xgb_hyperparameter_tuner = HyperparameterTuner(estimator=xgb,
... | _____no_output_____ | MIT | Mini-Projects/IMDB Sentiment Analysis - XGBoost (Hyperparameter Tuning).ipynb | itirkaa/sagemaker-deployment |
Fit the hyperparameter tunerNow that the hyperparameter tuner object has been constructed, it is time to fit the various models and find the best performing model. | s3_input_train = sagemaker.s3_input(s3_data=train_location, content_type='csv')
s3_input_validation = sagemaker.s3_input(s3_data=val_location, content_type='csv')
xgb_hyperparameter_tuner.fit({'train': s3_input_train, 'validation': s3_input_validation}) | _____no_output_____ | MIT | Mini-Projects/IMDB Sentiment Analysis - XGBoost (Hyperparameter Tuning).ipynb | itirkaa/sagemaker-deployment |
Remember that the tuning job is constructed and run in the background so if we want to see the progress of our training job we need to call the `wait()` method. | xgb_hyperparameter_tuner.wait() | ..................................................................................................................................................................................................................................................................................................................!
| MIT | Mini-Projects/IMDB Sentiment Analysis - XGBoost (Hyperparameter Tuning).ipynb | itirkaa/sagemaker-deployment |
(TODO) Testing the modelNow that we've run our hyperparameter tuning job, it's time to see how well the best performing model actually performs. To do this we will use SageMaker's Batch Transform functionality. Batch Transform is a convenient way to perform inference on a large dataset in a way that is not realtime. T... | # TODO: Create a new estimator object attached to the best training job found during hyperparameter tuning
xgb_attached = sagemaker.estimator.Estimator.attach(xgb_hyperparameter_tuner.best_training_job())
| Parameter image_name will be renamed to image_uri in SageMaker Python SDK v2.
| MIT | Mini-Projects/IMDB Sentiment Analysis - XGBoost (Hyperparameter Tuning).ipynb | itirkaa/sagemaker-deployment |
Now that we have an estimator object attached to the correct training job, we can proceed as we normally would and create a transformer object. | # TODO: Create a transformer object from the attached estimator. Using an instance count of 1 and an instance type of ml.m4.xlarge
# should be more than enough.
xgb_transformer = xgb_attached.transformer(instance_count=1, instance_type='ml.m4.xlarge')
| Parameter image will be renamed to image_uri in SageMaker Python SDK v2.
| MIT | Mini-Projects/IMDB Sentiment Analysis - XGBoost (Hyperparameter Tuning).ipynb | itirkaa/sagemaker-deployment |
Next we actually perform the transform job. When doing so we need to make sure to specify the type of data we are sending so that it is serialized correctly in the background. In our case we are providing our model with csv data so we specify `text/csv`. Also, if the test data that we have provided is too large to proc... | # TODO: Start the transform job. Make sure to specify the content type and the split type of the test data.
xgb_transformer.transform(test_location, content_type='text/csv', split_type='Line') | _____no_output_____ | MIT | Mini-Projects/IMDB Sentiment Analysis - XGBoost (Hyperparameter Tuning).ipynb | itirkaa/sagemaker-deployment |
Currently the transform job is running but it is doing so in the background. Since we wish to wait until the transform job is done and we would like a bit of feedback we can run the `wait()` method. | xgb_transformer.wait() | ............................[34mArguments: serve[0m
[35mArguments: serve[0m
[34m[2020-08-26 08:02:52 +0000] [1] [INFO] Starting gunicorn 19.7.1[0m
[35m[2020-08-26 08:02:52 +0000] [1] [INFO] Starting gunicorn 19.7.1[0m
[34m[2020-08-26 08:02:52 +0000] [1] [INFO] Listening at: http://0.0.0.0:8080 (1)[0m
[34m[20... | MIT | Mini-Projects/IMDB Sentiment Analysis - XGBoost (Hyperparameter Tuning).ipynb | itirkaa/sagemaker-deployment |
Now the transform job has executed and the result, the estimated sentiment of each review, has been saved on S3. Since we would rather work on this file locally we can perform a bit of notebook magic to copy the file to the `data_dir`. | !aws s3 cp --recursive $xgb_transformer.output_path $data_dir | download: s3://sagemaker-ap-south-1-714138043953/xgboost-200826-0732-001-281d2aa4-2020-08-26-07-58-22-744/test.csv.out to ../data/xgboost/test.csv.out
| MIT | Mini-Projects/IMDB Sentiment Analysis - XGBoost (Hyperparameter Tuning).ipynb | itirkaa/sagemaker-deployment |
The last step is now to read in the output from our model, convert the output to something a little more usable, in this case we want the sentiment to be either `1` (positive) or `0` (negative), and then compare to the ground truth labels. | predictions = pd.read_csv(os.path.join(data_dir, 'test.csv.out'), header=None)
predictions = [round(num) for num in predictions.squeeze().values]
from sklearn.metrics import accuracy_score
accuracy_score(test_y, predictions) | _____no_output_____ | MIT | Mini-Projects/IMDB Sentiment Analysis - XGBoost (Hyperparameter Tuning).ipynb | itirkaa/sagemaker-deployment |
Optional: Clean upThe default notebook instance on SageMaker doesn't have a lot of excess disk space available. As you continue to complete and execute notebooks you will eventually fill up this disk space, leading to errors which can be difficult to diagnose. Once you are completely finished using a notebook it is a ... | # First we will remove all of the files contained in the data_dir directory
!rm $data_dir/*
# And then we delete the directory itself
!rmdir $data_dir
# Similarly we will remove the files in the cache_dir directory and the directory itself
!rm $cache_dir/*
!rmdir $cache_dir | _____no_output_____ | MIT | Mini-Projects/IMDB Sentiment Analysis - XGBoost (Hyperparameter Tuning).ipynb | itirkaa/sagemaker-deployment |
The Boston housing data is a built in dataset in the sklearn library of python. You will be using two of the variables from this dataset, which are stored in **df**. The median home price in thousands of dollars and the crime per capita in the area of the home are shown above.`1.` Use this dataframe to fit a linear mo... | df['intercept'] = 1
lm = sms.OLS(df['MedianHomePrice'], df[['intercept', 'CrimePerCapita']])
results = lm.fit()
results.summary() | _____no_output_____ | Unlicense | 03 Stats/14 Regression/HomesVCrime - Solution.ipynb | Alashmony/DA_Udacity |
`2.`Plot the relationship between the crime rate and median home price below. Use your plot and the results from the first question as necessary to answer the remaining quiz questions below. | plt.scatter(df['CrimePerCapita'], df['MedianHomePrice']);
plt.xlabel('Crime/Capita');
plt.ylabel('Median Home Price');
plt.title('Median Home Price vs. CrimePerCapita');
## To show the line that was fit I used the following code from
## https://plot.ly/matplotlib/linear-fits/
## It isn't the greatest fit... but it isn... | _____no_output_____ | Unlicense | 03 Stats/14 Regression/HomesVCrime - Solution.ipynb | Alashmony/DA_Udacity |
Continuous Control---In this notebook, you will learn how to use the Unity ML-Agents environment for the second project of the [Deep Reinforcement Learning Nanodegree](https://www.udacity.com/course/deep-reinforcement-learning-nanodegree--nd893) program. 1. Start the EnvironmentWe begin by importing the necessary pack... | import numpy as np
import torch
import matplotlib.pyplot as plt
import time
from unityagents import UnityEnvironment
from collections import deque
from itertools import count
import datetime
from ddpg import DDPG, ReplayBuffer
%matplotlib inline | _____no_output_____ | MIT | Continuous_Control.ipynb | bobiblazeski/reacher |
Next, we will start the environment! **_Before running the code cell below_**, change the `file_name` parameter to match the location of the Unity environment that you downloaded.- **Mac**: `"path/to/Reacher.app"`- **Windows** (x86): `"path/to/Reacher_Windows_x86/Reacher.exe"`- **Windows** (x86_64): `"path/to/Reacher_... | #env = UnityEnvironment(file_name='envs/Reacher_Linux_NoVis_20/Reacher.x86_64') # Headless
env = UnityEnvironment(file_name='envs/Reacher_Linux_20/Reacher.x86_64') # Visual | INFO:unityagents:
'Academy' started successfully!
Unity Academy name: Academy
Number of Brains: 1
Number of External Brains : 1
Lesson number : 0
Reset Parameters :
goal_speed -> 1.0
goal_size -> 5.0
Unity brain name: ReacherBrain
Number of Visual Observations (per agent): 0
... | MIT | Continuous_Control.ipynb | bobiblazeski/reacher |
Environments contain **_brains_** which are responsible for deciding the actions of their associated agents. Here we check for the first brain available, and set it as the default brain we will be controlling from Python. | # get the default brain
brain_name = env.brain_names[0]
brain = env.brains[brain_name] | _____no_output_____ | MIT | Continuous_Control.ipynb | bobiblazeski/reacher |
2. Examine the State and Action SpacesIn this environment, a double-jointed arm can move to target locations. A reward of `+0.1` is provided for each step that the agent's hand is in the goal location. Thus, the goal of your agent is to maintain its position at the target location for as many time steps as possible.Th... | # reset the environment
env_info = env.reset(train_mode=True)[brain_name]
# number of agents
num_agents = len(env_info.agents)
print('Number of agents:', num_agents)
# size of each action
action_size = brain.vector_action_space_size
print('Size of each action:', action_size)
# examine the state space
states = env_i... | Number of agents: 20
Size of each action: 4
There are 20 agents. Each observes a state with length: 33
The state for the first agent looks like: [ 0.00000000e+00 -4.00000000e+00 0.00000000e+00 1.00000000e+00
-0.00000000e+00 -0.00000000e+00 -4.37113883e-08 0.00000000e+00
0.00000000e+00 0.00000000e+00 0.00000000e... | MIT | Continuous_Control.ipynb | bobiblazeski/reacher |
3. Take Random Actions in the EnvironmentIn the next code cell, you will learn how to use the Python API to control the agent and receive feedback from the environment.Once this cell is executed, you will watch the agent's performance, if it selects an action at random with each time step. A window should pop up that... | env_info = env.reset(train_mode=False)[brain_name] # reset the environment
states = env_info.vector_observations # get the current state (for each agent)
scores = np.zeros(num_agents) # initialize the score (for each agent)
while True:
actions = np.random.randn(num_... | Total score (averaged over agents) this episode: 0.0
| MIT | Continuous_Control.ipynb | bobiblazeski/reacher |
When finished, you can close the environment. 4. It's Your Turn!Now it's your turn to train your own agent to solve the environment! When training the environment, set `train_mode=True`, so that the line for resetting the environment looks like the following:```pythonenv_info = env.reset(train_mode=True)[brain_name]`... | BUFFER_SIZE = int(5e5) # replay buffer size
CACHE_SIZE = int(6e4)
BATCH_SIZE = 256 # minibatch size
GAMMA = 0.99 # discount factor
TAU = 1e-3 # for soft update of target parameters
LR_ACTOR = 1e-3 # learning rate of the actor
LR_CRITIC = 1e-3 # learning rate of the critic
... | _____no_output_____ | MIT | Continuous_Control.ipynb | bobiblazeski/reacher |
Saves experiences for training future agents. Warning file is quite large. | memory, cache = buffers
memory.save('experiences.pkl')
#env.close() | _____no_output_____ | MIT | Continuous_Control.ipynb | bobiblazeski/reacher |
5. See the pre-trained agent in action | agent = DDPG(state_size=state_size, action_size=action_size, random_seed=23,
fc1_units=96, fc2_units=96)
agent.load('./saves/96_96_108_actor.pth', './saves/96_96_108_critic.pth')
def play(agent, episodes=3):
for i_episode in range(episodes):
env_info = env.reset(train_mode=False)[brain_name] ... | Ep No: 0 Total score (averaged over agents): 37.69499915745109
Ep No: 1 Total score (averaged over agents): 36.70099917966873
Ep No: 2 Total score (averaged over agents): 36.49249918432906
Ep No: 3 Total score (averaged over agents): 37.94049915196374
Ep No: 4 Total score (averaged over agents): 37.35449916506186
Ep No... | MIT | Continuous_Control.ipynb | bobiblazeski/reacher |
6. ExperiencesExperiences from the Replay Buffer could be saved and loaded for training different agents.As an example I've provided `experiences.pkl.7z` which you should unpack with your favorite archiver. Create new ReplayBuffer and load saved experiences | savedBuffer = ReplayBuffer(action_size, BUFFER_SIZE, BATCH_SIZE, random_seed)
savedBuffer.load('experiences.pkl') | _____no_output_____ | MIT | Continuous_Control.ipynb | bobiblazeski/reacher |
Afterward you can use it to train your agent | savedBuffer.sample() | _____no_output_____ | MIT | Continuous_Control.ipynb | bobiblazeski/reacher |
NumPy Übung - AufgabeJetzt wo wir schon einiges über NumPy gelernt haben können wir unser Wissen überprüfen. Wir starten dazu mit einigen einfachen Aufgaben und steigern uns zu komplizierteren Fragestellungen. **Importiere NumPy als np** **Erstelle ein Array von 10 Nullen** **Erstelle ein Array von 10 Einsen** **Erste... | # Schreibe deinen Code hier, der das Ergebnis reproduzieren soll
# Achte darauf, die untere Zelle nicht auszuführen, sonst
# wirst du das Ergebnis nicht mehr sehen können
# Schreibe deinen Code hier, der das Ergebnis reproduzieren soll
# Achte darauf, die untere Zelle nicht auszuführen, sonst
# wirst du das Ergebnis ni... | _____no_output_____ | BSD-3-Clause | 2-Data-Analysis/1-Numpy/4-Numpy Uebung - Aufgabe.ipynb | Klaynie/Jupyter-Test |
Species distribution modelingModeling species' geographic distributions is an importantproblem in conservation biology. In this example wemodel the geographic distribution of two south americanmammals given past observations and 14 environmentalvariables. Since we have only positive examples (there areno unsuccessful ... | # Authors: Peter Prettenhofer <peter.prettenhofer@gmail.com>
# Jake Vanderplas <vanderplas@astro.washington.edu>
#
# License: BSD 3 clause
from time import time
import numpy as np
import matplotlib.pyplot as plt
from sklearn.utils import Bunch
from sklearn.datasets import fetch_species_distributions
from sk... | _____no_output_____ | MIT | sklearn/sklearn learning/demonstration/auto_examples_jupyter/applications/plot_species_distribution_modeling.ipynb | wangyendt/deeplearning_models |
First create some random 3d data points | N = 10 # The number of points
points = np.random.rand(N, 3) | _____no_output_____ | MIT | NaiveCoverage.ipynb | dk1010101/astroplay |
Now create KDTree from these so that we can look for the neighbours. TBH we don't really need KDTree. We can do this probably better and easier with a distance matrix but this will do for now. | kdt = KDTree(points) | _____no_output_____ | MIT | NaiveCoverage.ipynb | dk1010101/astroplay |
Test by looking for the two neighbours of the first point | kdt.query([points[0]], 3, False) | _____no_output_____ | MIT | NaiveCoverage.ipynb | dk1010101/astroplay |
So the neighbous of 0 are point 2 and 4. ok. Let's plot the 3d points and see them | x = [p[0] for p in points]
y = [p[1] for p in points]
z = [p[2] for p in points]
fig = plt.figure(figsize=(8, 8), constrained_layout=True)
ax = fig.add_subplot(projection='3d')
ax.scatter(points[0][0],points[0][1],points[0][2], c='yellow',s=75)
ax.scatter(x[1:],y[1:],z[1:],c='blue',s=45)
for i, p in enumerate(points):... | _____no_output_____ | MIT | NaiveCoverage.ipynb | dk1010101/astroplay |
Now we will look at the the algo and if it works... | def gen_tris(points):
processed_points = set()
points_to_do = set(range(len(points)))
tris = []
# pick the first three points
start = 0
nns = kdt.query([points[start]], N, False)
work_pts = nns[0][:3]
tris.append(Poly3DCollection([[points[i] for i in work_pts]], edgecolors='black', facec... | added tri [0, 1, 6]
added tri [1, 2, 0]
added tri [2, 4, 6]
added tri [4, 3, 6]
added tri [3, 8, 6]
added tri [8, 7, 3]
added tri [7, 9, 3]
added tri [9, 5, 3]
| MIT | NaiveCoverage.ipynb | dk1010101/astroplay |
Introduction to the Python language**Note**: This notebooks is not really a ready-to-use tutorial but rather serves as a table of contents that we will fill during the short course. It might later be useful as a memo, but it clearly lacks important notes and explanations.There are lots of tutorials that you can find o... | # this is a comment | _____no_output_____ | CC-BY-4.0 | notebooks/lectures_potsdam_201802/python_intro.ipynb | benbovy/python_short_course |
Using Python as a calculator | 2 / 2 | _____no_output_____ | CC-BY-4.0 | notebooks/lectures_potsdam_201802/python_intro.ipynb | benbovy/python_short_course |
Automatic type casting for int and float (more on that later) | 2 + 2. | _____no_output_____ | CC-BY-4.0 | notebooks/lectures_potsdam_201802/python_intro.ipynb | benbovy/python_short_course |
Automatic float conversion for division (only in Python 3 !!!) | 2 / 3 | _____no_output_____ | CC-BY-4.0 | notebooks/lectures_potsdam_201802/python_intro.ipynb | benbovy/python_short_course |
**Tip**: if you don't want integer division, use float explicitly (works with both Python 2 and 3) | 2. / 3 | _____no_output_____ | CC-BY-4.0 | notebooks/lectures_potsdam_201802/python_intro.ipynb | benbovy/python_short_course |
Integer division (in Python: returns floor) | 2 // 3 | _____no_output_____ | CC-BY-4.0 | notebooks/lectures_potsdam_201802/python_intro.ipynb | benbovy/python_short_course |
Import math module for built-in math functions (more on how to import modules later) | import math
math.sin(math.pi / 2)
math.log(2.) | _____no_output_____ | CC-BY-4.0 | notebooks/lectures_potsdam_201802/python_intro.ipynb | benbovy/python_short_course |
**Tip**: to get help interactively for a function, press shift-tab when the cursor is on the function, or alternatively use `?` or `help()` | math.log?
help(math.log) | Help on built-in function log in module math:
log(...)
log(x[, base])
Return the logarithm of x to the given base.
If the base not specified, returns the natural logarithm (base e) of x.
| CC-BY-4.0 | notebooks/lectures_potsdam_201802/python_intro.ipynb | benbovy/python_short_course |
Complex numbers built in the language | 0+1j**2
(3+4j).real
(3+4j).imag | _____no_output_____ | CC-BY-4.0 | notebooks/lectures_potsdam_201802/python_intro.ipynb | benbovy/python_short_course |
Create variables, or rather bound values (objects) to identifiers (more on that later) | earth_radius = 6.371e6
earth_radius * 2 | _____no_output_____ | CC-BY-4.0 | notebooks/lectures_potsdam_201802/python_intro.ipynb | benbovy/python_short_course |
*Note*: Python instructions are usually separated by new line characters | a = 1
a + 2 | _____no_output_____ | CC-BY-4.0 | notebooks/lectures_potsdam_201802/python_intro.ipynb | benbovy/python_short_course |
It is possible to write several instructions on a single line using semi-colons, but it is strongly discouraged | a = 1; a + 1
A | _____no_output_____ | CC-BY-4.0 | notebooks/lectures_potsdam_201802/python_intro.ipynb | benbovy/python_short_course |
In a notebook, only the output of the last line executed in the cell is shown | a = 10
2 + 2
a
2 + 2
2 + 1 | _____no_output_____ | CC-BY-4.0 | notebooks/lectures_potsdam_201802/python_intro.ipynb | benbovy/python_short_course |
To show intermediate results, you need to use the `print()` built-in function, or write code in separate notebook cells | print(2 + 2)
print(2 + 1) | 4
3
| CC-BY-4.0 | notebooks/lectures_potsdam_201802/python_intro.ipynb | benbovy/python_short_course |
Strings String are created using single or double quotes | food = "bradwurst"
dessert = 'cake' | _____no_output_____ | CC-BY-4.0 | notebooks/lectures_potsdam_201802/python_intro.ipynb | benbovy/python_short_course |
You may need to include a single (double) quote in a string | s = 'you\'ll need the \\ character'
s | _____no_output_____ | CC-BY-4.0 | notebooks/lectures_potsdam_201802/python_intro.ipynb | benbovy/python_short_course |
We still see two "\". Why??? This is actually what you want when printing the string | print(s) | you'll need the \ character
| CC-BY-4.0 | notebooks/lectures_potsdam_201802/python_intro.ipynb | benbovy/python_short_course |
Other special characters (e.g., line return) | two_lines = "frist_line\n\tsecond_line"
two_lines
print(two_lines) | frist_line
second_line
| CC-BY-4.0 | notebooks/lectures_potsdam_201802/python_intro.ipynb | benbovy/python_short_course |
Long strings | lunch = """
Menu
Main courses
"""
lunch
print(lunch) |
Menu
Main courses
| CC-BY-4.0 | notebooks/lectures_potsdam_201802/python_intro.ipynb | benbovy/python_short_course |
Concatenate strings using the `+` operator | food + ' and ' + dessert | _____no_output_____ | CC-BY-4.0 | notebooks/lectures_potsdam_201802/python_intro.ipynb | benbovy/python_short_course |
Concatenate strings using `join()` | s = ' '.join([food, 'and', dessert, 'coffee'])
s
s = '\n'.join([food, 'and', dessert, 'coffee'])
print(s) | bradwurst
and
cake
coffee
| CC-BY-4.0 | notebooks/lectures_potsdam_201802/python_intro.ipynb | benbovy/python_short_course |
Some useful string manipulation (see https://docs.python.org/3/library/stdtypes.htmlstring-methods) | food = ' bradwurst '
food.strip() | _____no_output_____ | CC-BY-4.0 | notebooks/lectures_potsdam_201802/python_intro.ipynb | benbovy/python_short_course |
Format stringsFor more info, see this very nice user guide: https://pyformat.info/ | nb = 2
"{} bradwursts bitte!".format(nb)
"{number} bradwursts bitte!".format(number=nb) | _____no_output_____ | CC-BY-4.0 | notebooks/lectures_potsdam_201802/python_intro.ipynb | benbovy/python_short_course |
Control flow Example of an if/else statement | x = -1
if x < 0:
print("negative") | negative
| CC-BY-4.0 | notebooks/lectures_potsdam_201802/python_intro.ipynb | benbovy/python_short_course |
Indentation is important! | x = 1
if x < 0:
print("negative")
print(x)
print(x) | 1
| CC-BY-4.0 | notebooks/lectures_potsdam_201802/python_intro.ipynb | benbovy/python_short_course |
**Warning**: don't mix tabs and space!!! visually it may look as properly indented but for Python tab and space are different. A more complete example: if elif else example + comparison operators (==, !=, , ) + logical operators (and, or, not) | x = -1
if x < 0:
x = 0
print("negative and changed to zero")
elif x == 0:
print("zero")
elif x == 1:
print("Single")
else:
print("More")
True and False | _____no_output_____ | CC-BY-4.0 | notebooks/lectures_potsdam_201802/python_intro.ipynb | benbovy/python_short_course |
The `range()` function, used in a `for` loop | for i in range(10):
print(i) | 0
1
2
3
4
5
6
7
8
9
| CC-BY-4.0 | notebooks/lectures_potsdam_201802/python_intro.ipynb | benbovy/python_short_course |
*Note*: by default, range starts from 0 (this is consistent with other behavior that we'll see later). Also, its stops just before the given value.Range can be used with more parameters (see help). For example: start, stop, step: | for i in range(1, 11, 2):
print(i) | 1
3
5
7
9
| CC-BY-4.0 | notebooks/lectures_potsdam_201802/python_intro.ipynb | benbovy/python_short_course |
A loop can also be used to iterate through values other than incrementing numbers (more on how to create iterables later). | words = ['cat', 'open', 'window', 'floor 20', 'be careful']
for w in words:
print(w) | cat
open
window
floor 20
be careful
| CC-BY-4.0 | notebooks/lectures_potsdam_201802/python_intro.ipynb | benbovy/python_short_course |
Control the loop: the continue statement | for w in words:
if w == 'open':
continue
print(w) | cat
window
floor 20
be careful
| CC-BY-4.0 | notebooks/lectures_potsdam_201802/python_intro.ipynb | benbovy/python_short_course |
More possibilities, e.g., a `while` loop and the `break` statement | i = 0
while True:
i = i + 1
print(i)
if i > 9:
break | 1
2
3
4
5
6
7
8
9
10
| CC-BY-4.0 | notebooks/lectures_potsdam_201802/python_intro.ipynb | benbovy/python_short_course |
Containers Lists | a = [1, 2, 3, 4]
a | _____no_output_____ | CC-BY-4.0 | notebooks/lectures_potsdam_201802/python_intro.ipynb | benbovy/python_short_course |
Lists may contain different types of values | a = [1, "2", 3., 4+0j]
a | _____no_output_____ | CC-BY-4.0 | notebooks/lectures_potsdam_201802/python_intro.ipynb | benbovy/python_short_course |
Lists may contain lists (nested) | c = [1, [2, 3], 4]
c | _____no_output_____ | CC-BY-4.0 | notebooks/lectures_potsdam_201802/python_intro.ipynb | benbovy/python_short_course |
"Indexing": retrieve elements of a list by location**Warning**: Unlike Fortran and Matlab, position start at zero!! | c[0] | _____no_output_____ | CC-BY-4.0 | notebooks/lectures_potsdam_201802/python_intro.ipynb | benbovy/python_short_course |
Negative position is for starting the search at the end of the list | a = [1, 2, 3, 4]
a[-1] | _____no_output_____ | CC-BY-4.0 | notebooks/lectures_potsdam_201802/python_intro.ipynb | benbovy/python_short_course |
"Slicing": extract a sublist | a
list(range(4)) | _____no_output_____ | CC-BY-4.0 | notebooks/lectures_potsdam_201802/python_intro.ipynb | benbovy/python_short_course |
$$[0, 4[$$ Iterate through a list | for i in a:
print(i) | 1
2
3
4
| CC-BY-4.0 | notebooks/lectures_potsdam_201802/python_intro.ipynb | benbovy/python_short_course |
Tuplesvery similar to lists | t = (1, 2, 3, 4)
t | _____no_output_____ | CC-BY-4.0 | notebooks/lectures_potsdam_201802/python_intro.ipynb | benbovy/python_short_course |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.