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 |
|---|---|---|---|---|---|
Accessing Tokens and Spans | import pandas as pd
def info(obj):
return {'type':type(obj),'__str__': str(obj)}
text = u"""spaCy excels at large-scale information extraction tasks.
It's written from the ground up in carefully memory-managed Cython. """
document = nlp(text)
token = document[0]
span = document[0:3]
pd.DataFrame(list(map(info, [... | _____no_output_____ | MIT | spacy-examples/Introduction to Natural Language Processing with SpaCy - Working Files/Chapter 2/Working-with-SpaCy-for-the-first-time_Part_1.ipynb | peterwilliams97/spaCy_practice |
Sentence boundary detection | print(list(document.sents))
print()
for i, sent in enumerate(document.sents):
print('%2d: "%s"' % (i, sent)) | [spaCy excels at large-scale information extraction tasks.
, It's written from the ground up in carefully memory-managed Cython.]
0: "spaCy excels at large-scale information extraction tasks.
"
1: "It's written from the ground up in carefully memory-managed Cython."
| MIT | spacy-examples/Introduction to Natural Language Processing with SpaCy - Working Files/Chapter 2/Working-with-SpaCy-for-the-first-time_Part_1.ipynb | peterwilliams97/spaCy_practice |
Tokenization | for i, token in enumerate(document):
print('%2d: "%s"' % (i, token)) | 0: "spaCy"
1: "excels"
2: "at"
3: "large"
4: "-"
5: "scale"
6: "information"
7: "extraction"
8: "tasks"
9: "."
10: "
"
11: "It"
12: "'s"
13: "written"
14: "from"
15: "the"
16: "ground"
17: "up"
18: "in"
19: "carefully"
20: "memory"
21: "-"
22: "managed"
23: "Cython"
24: "."
| MIT | spacy-examples/Introduction to Natural Language Processing with SpaCy - Working Files/Chapter 2/Working-with-SpaCy-for-the-first-time_Part_1.ipynb | peterwilliams97/spaCy_practice |
Morphological decomposition | token = document[13]
print("text: %s" % token.text)
print("suffix: %s" % token.suffix_)
print("lemma: %s" % token.lemma_) | text: written
suffix: ten
lemma: write
| MIT | spacy-examples/Introduction to Natural Language Processing with SpaCy - Working Files/Chapter 2/Working-with-SpaCy-for-the-first-time_Part_1.ipynb | peterwilliams97/spaCy_practice |
Part of Speech Tagging | #Part of speech and Dependency tagging
attrs = list(map(lambda token: {
"token":token,
"part of speech":token.pos_,
"Dependency" : token.dep_},
document))
pd.DataFrame(attrs) | _____no_output_____ | MIT | spacy-examples/Introduction to Natural Language Processing with SpaCy - Working Files/Chapter 2/Working-with-SpaCy-for-the-first-time_Part_1.ipynb | peterwilliams97/spaCy_practice |
Noun Chunking | print("noun chunks: %s" % list(document.noun_chunks)) | noun chunks: [spaCy, large-scale information extraction tasks, It, the ground]
| MIT | spacy-examples/Introduction to Natural Language Processing with SpaCy - Working Files/Chapter 2/Working-with-SpaCy-for-the-first-time_Part_1.ipynb | peterwilliams97/spaCy_practice |
Named Entity Recognition | ents = [(ent, ent.root.ent_type_) for ent in document.ents]
print("entities: %s" % ents) | entities: [(Cython, 'ORG')]
| MIT | spacy-examples/Introduction to Natural Language Processing with SpaCy - Working Files/Chapter 2/Working-with-SpaCy-for-the-first-time_Part_1.ipynb | peterwilliams97/spaCy_practice |
Text Similarity (Using Word Vectors) | #document, span, and token similarity
def plot_similarities(similarities, target):
import matplotlib.pyplot as plt
%matplotlib inline
f, ax = plt.subplots(1)
index = range(len(similarities))
ax.barh(index, similarities)
ax.set_yticks([i + 0. for i in index])
ax.set_yticklabels(document2)
... | _____no_output_____ | MIT | spacy-examples/Introduction to Natural Language Processing with SpaCy - Working Files/Chapter 2/Working-with-SpaCy-for-the-first-time_Part_1.ipynb | peterwilliams97/spaCy_practice |
Unpacking the paper - CATEGORICAL REPARAMETERIZATION WITH GUMBEL-SOFTMAX* https://arxiv.org/pdf/1611.01144.pdf Introduction* Not much to get here THE GUMBEL-SOFTMAX Distribution * Gumbel-Softmax distribution, a continuous distribution over the simplex that can approximate samples from a categorical distribution: Simp... | def sample_gumbel(shape, eps=1e-20):
U = tf.random_uniform(shape,minval=0,maxval=1)
return -tf.log(-tf.log(U + eps) + eps)
def gumbel_softmax_sample(logits, temperature):
y = logits + sample_gumbel(tf.shape(logits))
return tf.nn.softmax( y / temperature)
def gumbel_softmax(logits, temperature, hard=F... | _____no_output_____ | MIT | Gumbel Softmax Exploration.ipynb | stefanthaler/gumbel-softmax-exploration |
Sentiment Analysis Using XGBoost in SageMaker_Deep Learning Nanodegree Program | Deployment_---As our first 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 ha... | # %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 | _____no_output_____ | MIT | Mini-Projects/IMDB Sentiment Analysis - XGBoost (Batch Transform).ipynb | Will282/mle-nanodegree |
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 (Batch Transform).ipynb | Will282/mle-nanodegree |
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 (Batch Transform).ipynb | Will282/mle-nanodegree |
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
from sklearn.externals 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_... | Read features from cache file: bow_features.pkl
| MIT | Mini-Projects/IMDB Sentiment Analysis - XGBoost (Batch Transform).ipynb | Will282/mle-nanodegree |
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. (TODO) Writing the datasetThe XGBoost classifier that we will be using requires the dataset to be written to... | print(len(train_y))
import pandas as pd
from sklearn.model_selection import train_test_split
# TODO: Split the train_X and train_y arrays into the DataFrames val_X, train_X and val_y, train_y. Make sure that
# val_X and val_y contain 10 000 entires while train_X and train_y contain the remaining 15 000 entries.
... | (15000, 5000)
(10000, 5000)
| MIT | Mini-Projects/IMDB Sentiment Analysis - XGBoost (Batch Transform).ipynb | Will282/mle-nanodegree |
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 (Batch Transform).ipynb | Will282/mle-nanodegree |
(TODO) 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 Sag... | import sagemaker
session = sagemaker.Session() # Store the current SageMaker session
# S3 prefix (which folder will we use)
prefix = 'sentiment-xgboost'
# TODO: Upload the test.csv, train.csv and validation.csv files which are contained in data_dir to S3 using sess.upload_data().
test_location = session.upload_data(... | _____no_output_____ | MIT | Mini-Projects/IMDB Sentiment Analysis - XGBoost (Batch Transform).ipynb | Will282/mle-nanodegree |
(TODO) Creating the XGBoost modelNow that the data has been uploaded it is time to create the XGBoost model. To begin with, we need to do some setup. At this point it is worth discussing what a model is in SageMaker. It is easiest to think of a model of comprising three different objects in the SageMaker ecosystem, wh... | 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... | _____no_output_____ | MIT | Mini-Projects/IMDB Sentiment Analysis - XGBoost (Batch Transform).ipynb | Will282/mle-nanodegree |
Fit the XGBoost modelNow that our model has been set up we simply need to attach the training and validation datasets and then ask SageMaker to set up the computation. | 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.fit({'train': s3_input_train, 'validation': s3_input_validation}) | 2020-05-02 12:55:23 Starting - Starting the training job...
2020-05-02 12:55:25 Starting - Launching requested ML instances...
2020-05-02 12:56:20 Starting - Preparing the instances for training......
2020-05-02 12:57:09 Downloading - Downloading input data...
2020-05-02 12:57:47 Training - Training image download comp... | MIT | Mini-Projects/IMDB Sentiment Analysis - XGBoost (Batch Transform).ipynb | Will282/mle-nanodegree |
(TODO) Testing the modelNow that we've fit our XGBoost model, it's time to see how well it performs. To do this we will use SageMakers Batch Transform functionality. Batch Transform is a convenient way to perform inference on a large dataset in a way that is not realtime. That is, we don't necessarily need to use our ... | # TODO: Create a transformer object from the trained model. Using an instance count of 1 and an instance type of ml.m4.xlarge
# should be more than enough.
xgb_transformer = xgb.transformer(instance_count = 1, instance_type = 'ml.m4.xlarge') | _____no_output_____ | MIT | Mini-Projects/IMDB Sentiment Analysis - XGBoost (Batch Transform).ipynb | Will282/mle-nanodegree |
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 (Batch Transform).ipynb | Will282/mle-nanodegree |
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
[34m[2020-05-02 13:07:37 +0000] [1] [INFO] Starting gunicorn 19.7.1[0m
[34m[2020-05-02 13:07:37 +0000] [1] [INFO] Listening at: http://0.0.0.0:8080 (1)[0m
[34m[2020-05-02 13:07:37 +0000] [1] [INFO] Using worker: gevent[0m
[34m[2020-05-02 13:07:37 +0000] [38] [INFO] ... | MIT | Mini-Projects/IMDB Sentiment Analysis - XGBoost (Batch Transform).ipynb | Will282/mle-nanodegree |
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 | Completed 256.0 KiB/370.4 KiB (3.5 MiB/s) with 1 file(s) remaining
Completed 370.4 KiB/370.4 KiB (4.9 MiB/s) with 1 file(s) remaining
download: s3://sagemaker-eu-west-2-463062221782/xgboost-2020-05-02-13-04-13-686/test.csv.out to ../data/xgboost/test.csv.out
| MIT | Mini-Projects/IMDB Sentiment Analysis - XGBoost (Batch Transform).ipynb | Will282/mle-nanodegree |
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 (Batch Transform).ipynb | Will282/mle-nanodegree |
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 (Batch Transform).ipynb | Will282/mle-nanodegree |
DataFrame & SeriesDi Pandas terdapat 2 kelas data baru yang digunakan sebagai struktur dari spreadsheet:1. Series: satu kolom bagian dari tabel dataframe yang merupakan 1 dimensional numpy array sebagai basis datanya, terdiri dari 1 tipe data (integer, string, float, dll).2. DataFrame: gabungan dari Series, berbentuk ... | import pandas as pd
# Series
number_list = pd.Series([1,2,3,4,5,6])
print("Series:")
print(number_list)
# DataFrame
matrix = [[1,2,3],
['a','b','c'],
[3,4,5],
['d',4,6]]
matrix_list = pd.DataFrame(matrix)
print("DataFrame:")
print(matrix_list) | Series:
0 1
1 2
2 3
3 4
4 5
5 6
dtype: int64
DataFrame:
0 1 2
0 1 2 3
1 a b c
2 3 4 5
3 d 4 6
| MIT | Python/Learn/Kelas Persiapan/12. Data Manipulation with Pandas - Part 1.ipynb | Miadwicynthia/DQLab |
Atribut DataFrame & Series - Part 1Dataframe dan Series memiliki sangat banyak atribut yang digunakan untuk transformasi data, tetapi ada beberapa attribute yang sering dipakai. Di sini series number_list dan dataframe matrix_list pada subbab sebelumnya digunakan kembali. | import pandas as pd
# Series
number_list = pd.Series([1,2,3,4,5,6])
# DataFrame
matrix_list = pd.DataFrame([[1,2,3],
['a','b','c'],
[3,4,5],
['d',4,6]])
# [1] attribute .info()
print("[1] attribute .info()")
print(matrix_list.info())
# [2] attribute .shape
print("\n[2] at... | [1] attribute .info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 4 entries, 0 to 3
Data columns (total 3 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 0 4 non-null object
1 1 4 non-null object
2 2 4 non-null object
dtypes: object(3)
... | MIT | Python/Learn/Kelas Persiapan/12. Data Manipulation with Pandas - Part 1.ipynb | Miadwicynthia/DQLab |
Atribut DataFrame & Series - Part 2 | import pandas as pd
# Series
number_list = pd.Series([1,2,3,4,5,6])
# DataFrame
matrix_list = pd.DataFrame([[1,2,3],
['a','b','c'],
[3,4,5],
['d',4,6]])
# [5] attribute .copy()
print("[5] attribute .copy()")
num_list = number_list.copy()
print(" Copy number_list ke num... | [5] attribute .copy()
Copy number_list ke num_list: 0 1
1 2
2 3
3 4
4 5
5 6
dtype: int64
Copy matrix_list ke mtr_list: 0 1 2
0 1 2 3
1 a b c
2 3 4 5
3 d 4 6
[6] attribute .to_list()
[1, 2, 3, 4, 5, 6]
[7] attribute .unique()
[1 2 3 4 5 6]
| MIT | Python/Learn/Kelas Persiapan/12. Data Manipulation with Pandas - Part 1.ipynb | Miadwicynthia/DQLab |
Atribut DataFrame & Series - Part 3 | import pandas as pd
# Series
number_list = pd.Series([1,2,3,4,5,6])
# DataFrame
matrix_list = pd.DataFrame([[1,2,3],
['a','b','c'],
[3,4,5],
['d',4,6]])
# [8] attribute .index
print("[8] attribute .index")
print(" Index number_list:", number_list.index)
print(" Inde... | _____no_output_____ | MIT | Python/Learn/Kelas Persiapan/12. Data Manipulation with Pandas - Part 1.ipynb | Miadwicynthia/DQLab |
Creating Series & Dataframe from ListUntuk membuat Series atau Dataframe bisa dari berbagai macam tipe data container/mapping di python, seperti list dan dictionary, maupun dari numpy array.Pada sub bagian ini, membuat Series dan Dataframe yang bersumber dari list. Sekadar meninjau bahwa list merupakan sebuah kumpulan... | import pandas as pd
# Creating series from list
ex_list = ['a',1,3,5,'c','d']
ex_series = pd.Series(ex_list)
print(ex_series)
# Creating dataframe from list of list
ex_list_of_list = [[1 , 'a', 'b' , 'c'],
[2.5, 'd', 'e' , 'f'],
[5 , 'g', 'h' , 'i'],
[7.5, 'j', 10.5, 'l']]... | 0 a
1 1
2 3
3 5
4 c
5 d
dtype: object
float char obj char
dq 1.0 a b c
lab 2.5 d e f
kar 5.0 g h i
lan 7.5 j 10.5 l
| MIT | Python/Learn/Kelas Persiapan/12. Data Manipulation with Pandas - Part 1.ipynb | Miadwicynthia/DQLab |
Creating Series & Dataframe from DictionaryUntuk membuat Series atau Dataframe bisa dari berbagai macam tipe data container/mapping di python, seperti list dan dictionary, maupun dari numpy array.Pada sub bagian ini, akan membuat Series dan Dataframe yang bersumber dari dictionary. Sekadar meninjau bahwa, dictionary m... | import pandas as pd
# Creating series from dictionary
dict_series = {'1':'a',
'2':'b',
'3':'c'}
ex_series = pd.Series(dict_series)
print(ex_series)
# Creating dataframe from dictionary
df_series = {'1':['a','b','c'],
'2':['b','c','d'],
'4':[2,3,'z']}
ex_df = pd.DataFrame(df_series)... | 1 a
2 b
3 c
dtype: object
1 2 4
0 a b 2
1 b c 3
2 c d z
| MIT | Python/Learn/Kelas Persiapan/12. Data Manipulation with Pandas - Part 1.ipynb | Miadwicynthia/DQLab |
reating Series & Dataframe from Numpy ArrayUntuk membuat Series atau Dataframe bisa dari berbagai macam tipe data container/mapping di python, seperti list dan dictionary, maupun dari numpy array.Pada sub bagian ini, akan membuat Series dan Dataframe yang bersumber dari numpy array. Sekadar meninjau bahwa, numpy array... | import pandas as pd
import numpy as np
# Creating series from numpy array (1D)
arr_series = np.array([1,2,3,4,5,6,6,7])
ex_series = pd.Series(arr_series)
print(ex_series)
# Creating dataframe from numpy array (2D)
arr_df = np.array([[1 ,2 ,3 ,5],
[5 ,6 ,7 ,8],
['a','b','c',10... | 0 1
1 2
2 3
3 4
4 5
5 6
6 6
7 7
dtype: int32
0 1 2 3
0 1 2 3 5
1 5 6 7 8
2 a b c 10
| MIT | Python/Learn/Kelas Persiapan/12. Data Manipulation with Pandas - Part 1.ipynb | Miadwicynthia/DQLab |
Read Dataset - CSV dan TSVCSV dan TSV pada hakikatnya adalah tipe data text dengan perbedaan terletak pada pemisah antar data dalam satu baris. Pada file CSV, antar data dalam satu baris dipisahkan oleh comma, ",". Namun, pada file TSV antar data dalam satu baris dipisahkan oleh "Tab".Fungsi .read_csv() digunakan untu... | import pandas as pd
# File CSV
df_csv = pd.read_csv("https://storage.googleapis.com/dqlab-dataset/sample_csv.csv")
print(df_csv.head(3)) # Menampilkan 3 data teratas
# File TSV
df_tsv = pd.read_csv("https://storage.googleapis.com/dqlab-dataset/sample_tsv.tsv", sep='\t')
print(df_tsv.head(3)) # Menampilkan 3 data terata... | order_id order_date customer_id city province product_id \
0 1612339 2019-01-01 18055 Jakarta Selatan DKI Jakarta P0648
1 1612339 2019-01-01 18055 Jakarta Selatan DKI Jakarta P3826
2 1612339 2019-01-01 18055 Jakarta Selatan DKI Jakarta P1508... | MIT | Python/Learn/Kelas Persiapan/12. Data Manipulation with Pandas - Part 1.ipynb | Miadwicynthia/DQLab |
Read Dataset - ExcelFile Excel dengan ekstensi *.xls atau *.xlsx cukup banyak digunakan dalam menyimpan data. Pandas juga memiliki fitur untuk membaca file excel. | import pandas as pd
# File xlsx dengan data di sheet "test"
df_excel = pd.read_excel("https://storage.googleapis.com/dqlab-dataset/sample_excel.xlsx", sheet_name="test")
print(df_excel.head(4)) # Menampilkan 4 data teratas | order_id order_date customer_id city province product_id \
0 1612339 2019-01-01 18055 Jakarta Selatan DKI Jakarta P0648
1 1612339 2019-01-01 18055 Jakarta Selatan DKI Jakarta P3826
2 1612339 2019-01-01 18055 Jakarta Selatan DKI Jakarta P1508... | MIT | Python/Learn/Kelas Persiapan/12. Data Manipulation with Pandas - Part 1.ipynb | Miadwicynthia/DQLab |
Read Dataset - JSONMethod .read_json() digunakan untuk membaca URL API yang formatnya JSON dan mengubahnya menjadi dataframe pandas. | import pandas as pd
# File JSON
url = "https://storage.googleapis.com/dqlab-dataset/covid2019-api-herokuapp-v2.json"
df_json = pd.read_json(url)
print(df_json.head(10)) # Menampilkan 10 data teratas | data dt ts
0 {'location': 'US', 'confirmed': 3363056, 'deat... 07-14-2020 1594684800
1 {'location': 'Brazil', 'confirmed': 1884967, '... 07-14-2020 1594684800
2 {'location': 'India', 'confirmed': 906752, 'de... 07-14-2020 1594684800
3 {'locatio... | MIT | Python/Learn/Kelas Persiapan/12. Data Manipulation with Pandas - Part 1.ipynb | Miadwicynthia/DQLab |
Read Dataset - SQLFungsi .read_sql() atau .read_sql_query() digunakan untuk membaca query dari database dan translate menjadi pandas dataframe, contoh case ini database sqlite. Read Dataset - Google BigQueryUntuk data yang besar (big data), umumnya digunakan Google BigQuery. Layanan ini dapat digunakan jika telah mem... | import pandas as pd
# Baca file sample_csv.csv
df = pd.read_csv("https://storage.googleapis.com/dqlab-dataset/sample_csv.csv")
# Tampilkan 3 data teratas
print("Tiga data teratas:\n", df.head(3))
# Tampilkan 3 data terbawah
print("Tiga data terbawah:\n", df.tail(3)) | Tiga data teratas:
order_id order_date customer_id city province product_id \
0 1612339 2019-01-01 18055 Jakarta Selatan DKI Jakarta P0648
1 1612339 2019-01-01 18055 Jakarta Selatan DKI Jakarta P3826
2 1612339 2019-01-01 18055 Jakarta Selatan DK... | MIT | Python/Learn/Kelas Persiapan/12. Data Manipulation with Pandas - Part 1.ipynb | Miadwicynthia/DQLab |
Indexing - Part 1Index merupakan key identifier dari tiap row/column untuk Series atau Dataframe (sifatnya tidak mutable untuk masing-masing value tapi bisa diganti untuk semua value sekaligus).Jika tidak disediakan, pandas akan membuat kolom index default secara otomatis sebagai bilangan bulat (integer) dari 0 sampai... | import pandas as pd
# Baca file TSV sample_tsv.tsv
df = pd.read_csv("https://storage.googleapis.com/dqlab-dataset/sample_tsv.tsv", sep="\t")
# Index dari df
print("Index:", df.index)
# Column dari df
print("Columns:", df.columns) | Index: RangeIndex(start=0, stop=101, step=1)
Columns: Index(['order_id', 'order_date', 'customer_id', 'city', 'province',
'product_id', 'brand', 'quantity', 'item_price'],
dtype='object')
| MIT | Python/Learn/Kelas Persiapan/12. Data Manipulation with Pandas - Part 1.ipynb | Miadwicynthia/DQLab |
Indexing - Part 3Di sub bab sebelumnya telah dibahas terkait single index, tentunya pada sub bab ini akan bahas multi index atau disebut juga dengan hierarchical indexing.Untuk membuat multi index (hierarchical indexing) dengan pandas diperlukan kolom-kolom mana saja yang perlu disusun agar index dari dataframe menjad... | import pandas as pd
# Baca file TSV sample_tsv.tsv
df = pd.read_csv("https://storage.googleapis.com/dqlab-dataset/sample_tsv.tsv", sep="\t")
# Set multi index df
df_x = df.set_index(['order_date', 'city', 'customer_id'])
# Print nama dan level dari multi index
for name, level in zip(df_x.index.names, df_x.index.levels)... | order_date : Index(['2019-01-01'], dtype='object', name='order_date')
city : Index(['Bogor', 'Jakarta Pusat', 'Jakarta Selatan', 'Jakarta Utara',
'Makassar', 'Malang', 'Surabaya', 'Tangerang'],
dtype='object', name='city')
customer_id : Int64Index([12681, 13963, 15649, 17091, 17228, 17450, 17470, 17511, 17... | MIT | Python/Learn/Kelas Persiapan/12. Data Manipulation with Pandas - Part 1.ipynb | Miadwicynthia/DQLab |
Indexing - Part 4Terdapat beberapa cara untuk membuat index, salah satunya adalah seperti yang telah dilakukan pada sub bab sebelumnya dengan menggunakan method .set_index().Di sub bab ini akan menggunakan assignment untuk menset index dari suatu dataframe. Untuk itu file "sample_excel.xlsx" yang digunakan | import pandas as pd
# Baca file sample_tsv.tsv untuk 10 baris pertama saja
df = pd.read_csv("https://storage.googleapis.com/dqlab-dataset/sample_tsv.tsv", sep="\t", nrows=10)
# Cetak data frame awal
print("Dataframe awal:\n", df)
# Set index baru
df.index = ["Pesanan ke-" + str(i) for i in range(1, 11)]
# Cetak data fr... | Dataframe awal:
order_id order_date customer_id city province product_id \
0 1612339 2019-01-01 18055 Jakarta Selatan DKI Jakarta P0648
1 1612339 2019-01-01 18055 Jakarta Selatan DKI Jakarta P3826
2 1612339 2019-01-01 18055 Jakarta Selatan DKI J... | MIT | Python/Learn/Kelas Persiapan/12. Data Manipulation with Pandas - Part 1.ipynb | Miadwicynthia/DQLab |
Indexing - Part 5Jika file yang akan dibaca melalui penggunaan library pandas dapat di-preview terlebih dahulu struktur datanya maka melalui fungsi yang ditujukan untuk membaca file dapat diset mana kolom yang akan dijadikan index.Fitur ini telah dimiliki oleh setiap fungsi yang digunakan dalam membaca data dengan pan... | import pandas as pd
# Baca file sample_tsv.tsv dan set lah index_col sesuai instruksi
df = pd.read_csv("https://storage.googleapis.com/dqlab-dataset/sample_tsv.tsv", sep="\t", index_col=["order_date", "order_id"])
# Cetak data frame untuk 8 data teratas
print("Dataframe:\n", df.head(8))
df_week = pd.DataFrame({'day_num... | _____no_output_____ | MIT | Python/Learn/Kelas Persiapan/12. Data Manipulation with Pandas - Part 1.ipynb | Miadwicynthia/DQLab |
Slicing - Part 1Seperti artinya slicing adalah cara untuk melakukan filter ke dataframe/series berdasarkan kriteria tertentu dari nilai kolomnya ataupun kriteria index-nya.Terdapat 2 cara paling terkenal untuk slicing dataframe, yaitu dengan menggunakan method .loc dan .iloc pada variabel bertipe pandas DataFrame/Seri... | import pandas as pd
# Baca file sample_csv.csv
df = pd.read_csv("https://storage.googleapis.com/dqlab-dataset/sample_csv.csv")
# Slice langsung berdasarkan kolom
df_slice = df.loc[(df["customer_id"] == "18055") &
(df["product_id"].isin(["P0029", "P0040", "P0041", "P0116", "P0117"]))
]
print("Slice lang... | Slice langsung berdasarkan kolom:
Empty DataFrame
Columns: [order_id, order_date, customer_id, city, province, product_id, brand, quantity, item_price]
Index: []
| MIT | Python/Learn/Kelas Persiapan/12. Data Manipulation with Pandas - Part 1.ipynb | Miadwicynthia/DQLab |
Slicing - Part 2Dalam sub bab sebelumnya telah mempelajari bagaimana melakukan slicing/filtering dataset dengan menggunakan method .loc pada kolom dataset.Sekarang, menerapkan berdasarkan index. Tentu syaratnya adalah dataset sudah dilakukan indexing terlebih dahulu melalui penerapan method .set_index | import pandas as pd
# Baca file sample_csv.csv
df = pd.read_csv("https://storage.googleapis.com/dqlab-dataset/sample_csv.csv")
# Set index dari df sesuai instruksi
df = df.set_index(["order_date", "order_id", "product_id"])
# Slice sesuai intruksi
df_slice = df.loc[("2019-01-01", 1612339, ["P2154", "P2159"]),:]
print("... | Slice df:
customer_id city province \
order_date order_id product_id
2019-01-01 1612339 P2154 18055 Jakarta Selatan DKI Jakarta
P2159 18055 Jakarta Selatan DKI Jakarta
... | MIT | Python/Learn/Kelas Persiapan/12. Data Manipulation with Pandas - Part 1.ipynb | Miadwicynthia/DQLab |
Transforming - Part 1Transform adalah ketika mengubah dataset yang ada menjadi entitas baru, dapat dilakukan dengan:konversi dari satu data type ke data type yang lain,transpose dataframe,atau yang lainnya.Hal yang biasa dilakukan pertama kali setelah data dibaca adalah mengecek tipe data di setiap kolomnya apakah ses... | import pandas as pd
# Baca file sample_csv.csv
df = pd.read_csv("https://storage.googleapis.com/dqlab-dataset/sample_csv.csv")
# Tampilkan tipe data
print("Tipe data df:\n", df.dtypes)
# Ubah tipe data kolom order_date menjadi datetime
df["order_date"] = pd.to_datetime(df["order_date"])
# Tampilkan tipe data df setelah... | Tipe data df:
order_id int64
order_date object
customer_id int64
city object
province object
product_id object
brand object
quantity int64
item_price int64
dtype: object
Tipe data df setelah transformasi:
order_id int64
order_date datetime64[... | MIT | Python/Learn/Kelas Persiapan/12. Data Manipulation with Pandas - Part 1.ipynb | Miadwicynthia/DQLab |
Transforming - Part 2Pada sub bab ini akan mengubah tipe data pada kolom dataframe yang telah dibaca menjadi tipe data float (kolom quantity) dan tipe kategori (kolom city).Secara umum, untuk mengubah ke numerik dapat menggunakan pd.to_numeric(), yaitu:nama_dataframe["nama_kolom"] = pd.to_numeric(nama_dataframe["nama_... | import pandas as pd
# Baca file sample_csv.csv
df = pd.read_csv("https://storage.googleapis.com/dqlab-dataset/sample_csv.csv")
# Tampilkan tipe data
print("Tipe data df:\n", df.dtypes)
# Ubah tipe data kolom quantity menjadi tipe data numerik float
df["quantity"] = pd.to_numeric(df["quantity"], downcast="float")
# Ubah... | Tipe data df:
order_id int64
order_date object
customer_id int64
city object
province object
product_id object
brand object
quantity int64
item_price int64
dtype: object
Tipe data df setelah transformasi:
order_id int64
order_date object
customer... | MIT | Python/Learn/Kelas Persiapan/12. Data Manipulation with Pandas - Part 1.ipynb | Miadwicynthia/DQLab |
Transforming - Part 3Sekarang akan mempelajari teknik/cara berikutnya dalam proses transformasi suatu dataframe. Di sub bab ini akan memakai method .apply() dan .map() pada suatu dataframe.Method .apply() digunakan untuk menerapkan suatu fungsi python (yang dibuat dengan def atau anonymous dengan lambda) pada datafram... | import pandas as pd
# Baca file sample_csv.csv
df = pd.read_csv("https://storage.googleapis.com/dqlab-dataset/sample_csv.csv")
# Cetak 5 baris teratas kolom brand
print("Kolom brand awal:\n", df["brand"].head())
# Gunakan method apply untuk merubah isi kolom menjadi lower case
df["brand"] = df["brand"].apply(lambda x: ... | Kolom brand awal:
0 BRAND_C
1 BRAND_V
2 BRAND_G
3 BRAND_B
4 BRAND_G
Name: brand, dtype: object
Kolom brand setelah apply:
0 brand_c
1 brand_v
2 brand_g
3 brand_b
4 brand_g
Name: brand, dtype: object
Kolom brand setelah map:
0 c
1 v
2 g
3 b
4 g
Name: brand, dtype: object
| MIT | Python/Learn/Kelas Persiapan/12. Data Manipulation with Pandas - Part 1.ipynb | Miadwicynthia/DQLab |
Transforming - Part 4Di sub bab sebelumnya sudah mengetahui bahwa map hanya dapat digunakan untuk pandas series. Pada sub bab ini akan menggunakan method .applymap pada dataframe. | import numpy as np
import pandas as pd
# number generator, set angka seed menjadi suatu angka, bisa semua angka, supaya hasil random nya selalu sama ketika kita run
np.random.seed(1234)
# create dataframe 3 baris dan 4 kolom dengan angka random
df_tr = pd.DataFrame(np.random.rand(3,4))
# Cetak dataframe
print("Datafram... | Dataframe:
0 1 2 3
0 0.191519 0.622109 0.437728 0.785359
1 0.779976 0.272593 0.276464 0.801872
2 0.958139 0.875933 0.357817 0.500995
Dataframe - cara 1:
0 1 2 3
0 2.611238 4.253346 3.504789 4.972864
1 4.948290 2.892085 2.905825 5... | MIT | Python/Learn/Kelas Persiapan/12. Data Manipulation with Pandas - Part 1.ipynb | Miadwicynthia/DQLab |
Inspeksi Missing ValueValue yang hilang/tidak lengkap dari dataframe akan membuat analisis atau model prediksi yang dibuat menjadi tidak akurat dan mengakibatkan keputusan salah yang diambil. Terdapat beberapa cara untuk mengatasi data yang hilang/tidak lengkap tersebut.Data COVID-19 yang akan digunakan ini diambil da... | import pandas as pd
# Baca file "public data covid19 jhu csse eu.csv"
df = pd.read_csv("https://storage.googleapis.com/dqlab-dataset/CHAPTER%204%20-%20missing%20value%20-%20public%20data%20covid19%20.csv")
# Cetak info dari df
print(df.info())
# Cetak jumlah missing value di setiap kolom
mv = df.isna().sum()
print("\nJ... | <class 'pandas.core.frame.DataFrame'>
RangeIndex: 1000 entries, 0 to 999
Data columns (total 13 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 province_state 960 non-null object
1 country_region 1000 non-null object
2 date 1000 non-null... | MIT | Python/Learn/Kelas Persiapan/12. Data Manipulation with Pandas - Part 1.ipynb | Miadwicynthia/DQLab |
Treatment untuk Missing Value - Part 1Terdapat beberapa cara untuk mengatasi missing value, antara lain:dibiarkan saja,hapus value itu, atauisi value tersebut dengan value yang lain (biasanya interpolasi, mean, median, etc) Treatment untuk Missing Value - Part 2Sekarang dapat menerapkan dua aksi yaituMembiarkannya sa... | import pandas as pd
# Baca file "public data covid19 jhu csse eu.csv"
df = pd.read_csv("https://storage.googleapis.com/dqlab-dataset/CHAPTER%204%20-%20missing%20value%20-%20public%20data%20covid19%20.csv")
# Cetak ukuran awal dataframe
print("Ukuran awal df: %d baris, %d kolom." % df.shape)
# Drop kolom yang seluruhnya... | Ukuran awal df: 1000 baris, 13 kolom.
Ukuran df setelah buang kolom dengan seluruh data missing: 1000 baris, 12 kolom.
Ukuran df setelah dibuang baris yang memiliki sekurangnya 1 missing value: 746 baris, 12 kolom.
| MIT | Python/Learn/Kelas Persiapan/12. Data Manipulation with Pandas - Part 1.ipynb | Miadwicynthia/DQLab |
Treatment untuk Missing Value - Part 3Sekarang, akan melakukan treatment ketiga untuk melakukan handle missing value pada dataframe. Treatment ini dilakukan dengan cara mengisi missing value dengan nilai lain, yang dapat berupa :nilai statistik seperti mean atau medianinterpolasi datatext tertentu Akan mulai pada kolo... | import pandas as pd
# Baca file "public data covid19 jhu csse eu.csv"
df = pd.read_csv("https://storage.googleapis.com/dqlab-dataset/CHAPTER%204%20-%20missing%20value%20-%20public%20data%20covid19%20.csv")
# Cetak unique value pada kolom province_state
print("Unique value awal:\n", df["province_state"].unique())
# Gant... | Unique value awal:
[nan 'US' 'Guam' 'Iowa']
Unique value setelah fillna:
['unknown_province_state' 'US' 'Guam' 'Iowa']
| MIT | Python/Learn/Kelas Persiapan/12. Data Manipulation with Pandas - Part 1.ipynb | Miadwicynthia/DQLab |
Treatment untuk Missing Value - Part 4Masih melanjutkan bagaimana melakukan handle missing value tentunya dengan jalan mengganti missing value dengan nilai lainnya. Pada bab sebelumnya telah mengganti kolom bertipe objek dengan sesuatu string/teks.Dalam sub bab ini akan mengganti missing value dengan nilai statistik k... | import pandas as pd
# Baca file "https://dqlab-dataset.s3-ap-southeast-1.amazonaws.com/CHAPTER+4+-+missing+value+-+public+data+covid19+.csv"
df = pd.read_csv("https://storage.googleapis.com/dqlab-dataset/CHAPTER%204%20-%20missing%20value%20-%20public%20data%20covid19%20.csv")
# Cetak nilai mean dan median awal
print("A... | Awal: mean = 192.571128, median = 41.000000.
Fillna median: mean = 184.841000, median = 41.000000.
Fillna mean: mean = 192.571128, median = 49.000000.
| MIT | Python/Learn/Kelas Persiapan/12. Data Manipulation with Pandas - Part 1.ipynb | Miadwicynthia/DQLab |
Treatment untuk Missing Value - Part 5Di bagian ini akan menggunakan teknik interpolasi dalam mengisi nilai missing value pada suatu dataset.Data yang menggunakan interpolasi untuk mengisi data yang hilang adalah time series data, yang secara default akan diisi dengan interpolasi linear. | import numpy as np
import pandas as pd
# Data
ts = pd.Series({
"2020-01-01":9,
"2020-01-02":np.nan,
"2020-01-05":np.nan,
"2020-01-07":24,
"2020-01-10":np.nan,
"2020-01-12":np.nan,
"2020-01-15":33,
"2020-01-17":np.nan,
"2020-01-16":40,
"2020-01-20":45,
"2020-01-22":52,
"2020-01-25":75... | Setelah diisi missing valuenya:
2020-01-01 9.0
2020-01-02 14.0
2020-01-05 19.0
2020-01-07 24.0
2020-01-10 27.0
2020-01-12 30.0
2020-01-15 33.0
2020-01-17 36.5
2020-01-16 40.0
2020-01-20 45.0
2020-01-22 52.0
2020-01-25 75.0
2020-01-28 75.0
2020-01-30 75.0
dtype: float64
| MIT | Python/Learn/Kelas Persiapan/12. Data Manipulation with Pandas - Part 1.ipynb | Miadwicynthia/DQLab |
Project Diberikan dataset ‘retail_raw_test.csv’1. Baca dataset2. Tipe data diubah menjadi tipe yang seharusnya- customer_id dari string ke int64,- quantity dari string ke int64,- item_price dari string ke int643. transform product_value supaya bentuknya seragam dengan format PXXXX, assign ke kolom baru "product_id", d... | import pandas as pd
# 1. Baca dataset
print("[1] BACA DATASET")
df = pd.read_csv("https://storage.googleapis.com/dqlab-dataset/retail_raw_test.csv", low_memory=False)
print(" Dataset:\n", df.head())
print(" Info:\n", df.info())
# 2. Ubah tipe data
print("\n[2] UBAH TIPE DATA")
df["customer_id"] = df["customer_i... | [1] BACA DATASET
Dataset:
order_id order_date customer_id city province brand \
0 1730350 Dec 11, 2019 '13447 Surakarta Jawa Tengah BRAND_F
1 1677490 Jul 31, 2019 '0 NaN NaN BRAND_F
2 1704211 Oct 18, 2019 '16128 Jakarta Pusat D... | MIT | Python/Learn/Kelas Persiapan/12. Data Manipulation with Pandas - Part 1.ipynb | Miadwicynthia/DQLab |
Drawing flight routes with NetworkX | import math
import json
import numpy as np
import pandas as pd
import networkx as nx
import cartopy.crs as ccrs
import matplotlib.pyplot as plt
from IPython.display import Image
%matplotlib inline
names = ('airline,airline_id,source,source_id,dest,dest_id,codeshare,stops,equipment').split(',')
routes = pd.read_csv(
... | _____no_output_____ | MIT | notebooks/D2_L5_Visualization/02-airports.ipynb | highrain2/myTestProjs |
1 L/s Plants in Parallel CHANCEUX Priya Aggarwal, Sung Min Kim, Felix Yang AguaClara has been designing and building water treatment plants since 2005 in Honduras, 2013 in India, and 2017 in Nicaragua. It has been providing gravity powered water treatment systems to thousands of people in rural communities. However,... | #using Q_plant as the target variable, sample values of what a plant conditions might be are included below
Temperature = u.Quantity(20,u.degC)
Desired_PACl_Concentration=3*u.mg/u.L
Desired_Cl_Concentration=3*u.mg/u.L
C_stock_PACl=70*u.gram/u.L
C_stock_Cl=51.4*u.gram/u.L
NuPaCl = cdc.viscosity_kinematic_pacl(C_stock_P... | The flow rate of coagulant is 0.4629 liter / hour
The flow rate of chlorine is 0.6304 liter / hour
| MIT | Previous Final Projects/2017/1 Liter per Second Plants in Parallel/.ipynb_checkpoints/Team_CHANCEUX_1_LPS_Plants_in_Parallel_Report-checkpoint.ipynb | CEE-4540/python-tutorial-juandirection |
SPACE CONSTRAINTS In the code below the team is calculating the floor plan area. The X distance and Y distance are the length and width of the floor plan respectively. The dimensions of the sedimentation tank, flocculator, and entrance tank are accounted for in this calculation. | #Claculting the Y distance For the Sed Tank
#properties of sedimentation tank
Sed_Tank_Diameter=0.965*u.m
Length_Top_Half=1.546*u.m #See image for clearer understanding
Y_Sed_Top_Half=Length_Top_Half*math.cos(60*u.degrees)
print(Y_Sed_Top_Half)
Y_Sed_Total=Sed_Tank_Diameter+Y_Sed_Top_Half
print(Y_Sed_Total) | 0.773 meter
1.738 meter
| MIT | Previous Final Projects/2017/1 Liter per Second Plants in Parallel/.ipynb_checkpoints/Team_CHANCEUX_1_LPS_Plants_in_Parallel_Report-checkpoint.ipynb | CEE-4540/python-tutorial-juandirection |
SED TANK: Based on the calculation above, the space the Sedimentation tank would take on the floor plant is found to be 1.738 m. 
Y_Length_Bottom=Y_Length_Top-0.488*u.m | _____no_output_____ | MIT | Previous Final Projects/2017/1 Liter per Second Plants in Parallel/.ipynb_checkpoints/Team_CHANCEUX_1_LPS_Plants_in_Parallel_Report-checkpoint.ipynb | CEE-4540/python-tutorial-juandirection |
Below are functions that can be used to design a plant based on the desired flow rate | def X(Q):
if Q>3*u.L/u.s:
X_Distance_Bottom=X(Q-3*u.L/u.s)
X_Distance_Top=6.9*u.m
return(X_Distance_Top,X_Distance_Bottom)
else:
Q_Plant=Q.to(u.L/u.s)
Extra_Space=2*u.m
X_Distance=(Q_Plant.magnitude-1)*1*u.m+(Q_Plant.magnitude)*.965*u.m+Extra_Space
r... | 2.965 meter
| MIT | Previous Final Projects/2017/1 Liter per Second Plants in Parallel/.ipynb_checkpoints/Team_CHANCEUX_1_LPS_Plants_in_Parallel_Report-checkpoint.ipynb | CEE-4540/python-tutorial-juandirection |
:
if (Q_Plant+Q_Extra>3*u.L/u.s):
X_Distance_Extra=X(Q_Extra)
Y_Distance_Extra=Y_Length_Bottom
Area=(X_Distance_Extra*Y_Distance_Extra).to(u.m**2)
return(Area)
else:
Q=Q_Extra.to(u.L/u.s)
Horizontal=(Q_Extra.magnitude)*.965*u.m... | _____no_output_____ | MIT | Previous Final Projects/2017/1 Liter per Second Plants in Parallel/.ipynb_checkpoints/Team_CHANCEUX_1_LPS_Plants_in_Parallel_Report-checkpoint.ipynb | CEE-4540/python-tutorial-juandirection |
ESTaRSThe total surface area required for the ESTaRS filter is simply a product of the area one ESTaRS requires and the flow rate coming into the plant. The surface area required for an ESTaRS was measured in the DeFrees lab. It is approximately a square meter. | ESTaRS_SA=1*u.m**2/u.L
def Area_ESTaRS(Q):
Q_Plant=Q.to(u.L/u.s)
Surface_Area_ESTaRS=(ESTaRS_SA.magnitude)*Q_Plant.magnitude
return(Surface_Area_ESTaRS*u.m**2)
print('Surface area required for the ESTaR(s) is',Area_ESTaRS(Q_Plant)) | _____no_output_____ | MIT | Previous Final Projects/2017/1 Liter per Second Plants in Parallel/.ipynb_checkpoints/Team_CHANCEUX_1_LPS_Plants_in_Parallel_Report-checkpoint.ipynb | CEE-4540/python-tutorial-juandirection |
FlocculatorsThe total surface area required for the ESTaRS filter is simply a product of the area one ESTaRS requires and the flow rate coming into the plant. The surface area required for an ESTaRS was measured in the DeFrees lab. It is approximately a square meter. | Flocc_SA=0.972*u.m*0.536*u.m*u.L/u.s
def Area_Flocc(Q):
Q_Plant=Q.to(u.L/u.s)
Surface_Area_Flocc=(Flocc_SA.magnitude)*Q_Plant.magnitude
return(Surface_Area_Flocc*u.m**2)
print('Surface area required for the flocculator(s) is',Area_Flocc(Q_Plant))
| _____no_output_____ | MIT | Previous Final Projects/2017/1 Liter per Second Plants in Parallel/.ipynb_checkpoints/Team_CHANCEUX_1_LPS_Plants_in_Parallel_Report-checkpoint.ipynb | CEE-4540/python-tutorial-juandirection |
Manifold Headloss Calculations The amount of headloss has to be minimal so that the amount of head availible coming out of the exit launder is enough to drive water fast enough to fluidize the sand bed in ESTaRS. This fluidization is required for backwashing the filter. Since the calculation for 4 inch pipe has a head... | SDR = 26
SF=1.33
Q_Manifold = 1 * u.L/u.s #max flowrate for a manifold
Q_UpperBound=SF*Q_Manifold
L_pipe = 5*u.m #Length sed tank to it’s ESTaRS
K_minor_bend=0.3
K_minor_branch=1
K_minor_contractions=1
K_minor_total= 2*(K_minor_bend+K_minor_branch+K_minor_contractions) # (two bends, two dividing branch, and two contra... | _____no_output_____ | MIT | Previous Final Projects/2017/1 Liter per Second Plants in Parallel/.ipynb_checkpoints/Team_CHANCEUX_1_LPS_Plants_in_Parallel_Report-checkpoint.ipynb | CEE-4540/python-tutorial-juandirection |
Index [Contrast and velocity fields](contrast)[Classification](classification) Contrast and velocity fields | sn.set_style("dark")
f, ax = pl.subplots(figsize=(9,9))
ax.imshow(stI[:,:,0], aspect='auto', cmap=pl.cm.gray) | _____no_output_____ | MIT | notebooks/.ipynb_checkpoints/Profiles and classification-checkpoint.ipynb | aasensio/SolarnetGranada |
Let us compute simple things like the contrast and the Doppler velocity field | contrastFull = np.std(stI[:,:,0]) / np.mean(stI[:,:,0])
contrastQuiet = np.std(stI[400:,100:300,0]) / np.mean(stI[400:,100:300,0])
print("Contrast in the image : {0}%".format(contrastFull * 100.0))
print("Contrast in the quiet Sun : {0}%".format(contrastQuiet * 100.0)) | Contrast in the image : 24.5026469231%
Contrast in the quiet Sun : 6.59198462963%
| MIT | notebooks/.ipynb_checkpoints/Profiles and classification-checkpoint.ipynb | aasensio/SolarnetGranada |
Now let us compute the velocity field. To this end, we compute the location of the core of the line in velocity units for each pixel. | v = np.zeros((512,512))
for i in range(512):
for j in range(512):
pos = np.argmin(stI[i,j,20:40]) + 20
res = np.polyfit(wave[pos-2:pos+2], stI[i,j,pos-2:pos+2], 2)
w = -res[1] / (2.0 * res[0])
v[i,j] = (w-6301.5) / 6301.5 * 3e5
f, ax = pl.subplots(figsize=(9,9))
ax.imshow(np.c... | _____no_output_____ | MIT | notebooks/.ipynb_checkpoints/Profiles and classification-checkpoint.ipynb | aasensio/SolarnetGranada |
Classification | X = stV[50:300,200:450,:].reshape((250*250,112))
maxV = np.max(np.abs(X), axis=1)
X = X / maxV[:,None]
nClusters = 9
km = MiniBatchKMeans(init='k-means++', n_clusters=nClusters, n_init=10, batch_size=500)
km.fit(X)
out = km.predict(X)
avg = np.zeros((nClusters,112))
for i in range(nClusters):
avg[i,:] = np.mean(X[o... | _____no_output_____ | MIT | notebooks/.ipynb_checkpoints/Profiles and classification-checkpoint.ipynb | aasensio/SolarnetGranada |
FixesFixing the schema when the column names are incorrect.Rename the table(with errors) to tempName and then recreate the original tableName and then insert the values into newly created table.https://stackoverflow.com/questions/805363/how-do-i-rename-a-column-in-a-sqlite-database-table fix1 = '''alter table c... | conn.execute('pragma foreign_keys = on')
#Creating an append listfrom old table to insert into new table.
query = '''SELECT ceremonies.id, nominations.category, nominations.nominee, nominations.movie,
nominations.charachter, nominations.won
FROM nominations
INNER JOIN ceremonies ON
nominations.year == ceremonies.year... | _____no_output_____ | MIT | DatabaseNormalization.ipynb | ganprad/jupyter_notebooks |
Many to Many relations through a join table | #Creating the tables
actors = '''create table actors(
id integer primary key,
actor text
)'''
conn.execute(actors)
movies = '''create table movies(
id integer primary key,
movie text
)
'''
conn.execute(movies)
movies_actors = '''create table movies_actors(
id integer primary key,
movie_id integer references movies(id... | _____no_output_____ | MIT | DatabaseNormalization.ipynb | ganprad/jupyter_notebooks |
**Import libraries** | import os
import logging
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import Subset, DataLoader
from torch.backends import cudnn
import torch.utils.data
import torchvision
from torchvision import transforms
from torchvision.models import alexnet
from torchvision.datasets import... | _____no_output_____ | MIT | code/main.ipynb | hadinej/DL-Domain-adaptation-on-PACS-dataset |
**Definitions** | from torch.autograd import Function
class ReverseLayerF(Function):
@staticmethod
def forward(ctx, x, alpha):
ctx.alpha = alpha
return x.view_as(x)
@staticmethod
def backward(ctx, grad_output):
output = grad_output.neg() * ctx.alpha
return output, None | _____no_output_____ | MIT | code/main.ipynb | hadinej/DL-Domain-adaptation-on-PACS-dataset |
**Set Arguments** | device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') # 'cuda' or 'cpu'
DATA_DIR = 'PACS\\' # directory of dataset
NUM_CLASSES = 7
NUM_DOMAINS = 2
image_size = 224 # the size required by AlexNet
BATCH_SIZE = 256 # Higher batch sizes allows for larger learning rates. An emp... | _____no_output_____ | MIT | code/main.ipynb | hadinej/DL-Domain-adaptation-on-PACS-dataset |
**Define Data Preprocessing** | # Define transforms for training phase
source_transform = transforms.Compose([
transforms.ColorJitter(),
transforms.RandomHorizontalFlip(),
transforms.Resize((224, 224)),
... | _____no_output_____ | MIT | code/main.ipynb | hadinej/DL-Domain-adaptation-on-PACS-dataset |
**Prepare Dataset** | source_dataset = ImageFolder(DATA_DIR+'photo//', transform=source_transform)
target_dataset = ImageFolder(DATA_DIR+'art_painting//', transform=target_transform)
print('source Dataset: {}'.format(len(source_dataset)))
print('target Dataset: {}'.format(len(target_dataset))) | source Dataset: 1670
target Dataset: 2048
| MIT | code/main.ipynb | hadinej/DL-Domain-adaptation-on-PACS-dataset |
<!-- xx=Caltech(DATA_DIR, split='train') xx.__getitem__(36) --> **Prepare Dataloaders** | # Dataloaders iterate over pytorch datasets and transparently provide useful functions (e.g. parallelization and shuffling)
source_dataloader = DataLoader(source_dataset, batch_size=BATCH_SIZE, shuffle=True)
target_dataloader = DataLoader(target_dataset, batch_size=BATCH_SIZE, shuffle=True) | _____no_output_____ | MIT | code/main.ipynb | hadinej/DL-Domain-adaptation-on-PACS-dataset |
**Define Network** | import torch
import torch.nn as nn
from torch.hub import load_state_dict_from_url
__all__ = ['AlexNet', 'alexnet']
model_urls = {
'alexnet': 'https://download.pytorch.org/models/alexnet-owt-4df8aa71.pth',
}
class AlexNetDANN(nn.Module):
def __init__(self, num_classes=1000, num_domains=2):
super(Alex... | _____no_output_____ | MIT | code/main.ipynb | hadinej/DL-Domain-adaptation-on-PACS-dataset |
**Prepare Network Training Functions** | # Define model
my_net = alexnetdann(pretrained=True,progress=True, num_classes=NUM_CLASSES, num_domains=NUM_DOMAINS)
# Define loss function
loss_class = nn.CrossEntropyLoss()
loss_domain = nn.CrossEntropyLoss()
# Choose parameters to optimize
parameters_to_optimize = my_net.parameters() # In this case we optimize ove... | _____no_output_____ | MIT | code/main.ipynb | hadinej/DL-Domain-adaptation-on-PACS-dataset |
**Test Function** | def test(dataset_name,epoch):
batch_size = BATCH_SIZE
if dataset_name == source_dataloader:
dataloader = source_dataloader
else:
dataloader = target_dataloader
global my_net
my_net = my_net.to(device)
my_net = my_net.eval()
len_dataloader = len(dataloade... | _____no_output_____ | MIT | code/main.ipynb | hadinej/DL-Domain-adaptation-on-PACS-dataset |
**Train & Test** | cudnn.benchmark # Calling this optimizes runtime
all_err_s_label=[]
all_err_s_domain=[]
all_err_t_domain=[]
all_acc_source_dataset=[]
all_acc_target_dataset=[]
# Start iterating over the epochs
for epoch in range(NUM_EPOCHS):
it_err_s_label=[]
it_err_s_domain=[]
it_err_t_domain=[]
len_dataloader ... | epoch: 1, [iter: 1 / 7], err_s_label: 2.016973, err_s_domain: 0.953112, err_t_domain: 0.519965
epoch: 1, [iter: 2 / 7], err_s_label: 2.006701, err_s_domain: 0.749304, err_t_domain: 0.677271
epoch: 1, [iter: 3 / 7], err_s_label: 1.958613, err_s_domain: 0.702738, err_t_domain: 0.698293
epoch: 1, [iter: 4 / 7], err_s_labe... | MIT | code/main.ipynb | hadinej/DL-Domain-adaptation-on-PACS-dataset |
**Saving & Plotting Results** | # Error plots
plt.figure(figsize=(10, 7))
plt.plot(all_err_s_label, color='green', label='err_s_label')
plt.plot(all_err_s_domain, color='blue', label='err_s_domain')
plt.plot(all_err_t_domain, color='orange', label='err_t_domain')
plt.xlabel('Epochs')
plt.ylabel('Error')
plt.legend()
plt.savefig('Errors.png')
# ... | _____no_output_____ | MIT | code/main.ipynb | hadinej/DL-Domain-adaptation-on-PACS-dataset |
Reset Put OptionA reset put option is similar to a standard put option except that the exercise price is reset equal to the stock price on the pre-specified reset date if this stock price exceeds the original exercise price. Unlike the standard put option, a Reset put option has a stochastic strike price. On issue dat... | import numpy as np
import pandas as pd
from scipy.stats import multivariate_normal as mvn
from scipy.stats import norm
import plotly.express as px
import plotly.io as pio
pio.templates.default = "plotly_white" | _____no_output_____ | MIT | Reset Put Option.ipynb | briangodwinlim/Financial-Math |
Binomial TreeFor the binomial tree implementation, instead of doing the naive approach of doing path dependent options, we can optimize our calculations since we are only concerned with the value at $T_1$. The formula used is from [Shparber and Resheff (2004)](https://www.researchgate.net/publication/240390357_Valuati... | memo = [[-1 for _ in range(1000)] for _ in range(1000)]
def choose(n,r):
if r > n or r < 0:
return 0
elif n == 1:
return 1
elif memo[n][r] == -1:
memo[n][r] = choose(n-1, r-1) + choose(n-1, r)
return memo[n][r]
def BT_option_price(S0, T2, n1, n2, r, q, sigma):
dt = T2 /... | Binomial Tree: 11.50392391907085
| MIT | Reset Put Option.ipynb | briangodwinlim/Financial-Math |
Monte Carlo SimulationFor the Monte Carlo Simulation, we will use the discretized GBM to determine trajectories of the stock price. The discretized GBM is given as$$S_{t + \Delta t} = S_t \left[1 + (r - q) \Delta t + \sigma \sqrt{\Delta t} Z\right],$$where $Z \sim N(0,1)$. After simulating each trajectory, we get the ... | def generate_trajectory(S0, T2, n2, r, q, sigma):
dt = T2 / n2
trajectory = [S0]
for _ in range (n2):
trajectory.append(
trajectory[-1] * (1 + ( r - q ) * dt + sigma * np.sqrt(dt) * np.random.randn())
)
return trajectory
def MC_option_price(S0, T2, n1, n2, r, q, sigma):
... | Monte Carlo: 11.524762360429376
| MIT | Reset Put Option.ipynb | briangodwinlim/Financial-Math |
Closed FormAccording to [Gray and Whaley (1999)](https://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.1015.8221&rep=rep1&type=pdf), the closed form of the reset put option price is \begin{align*} p_0 &= S_0 e^{-qT_1 -r(T_2-T_1)} N(a_1) N(-c_2) - S_0 e^{-qT_2} N(a_1) N(-c_1) \\ & \qquad + S_0 e^{-rT_2} N_2\l... | def closed_form_option_price(S0, T1, T2, r, q, sigma):
a1 = ( (r - q + 0.5 * sigma**2) * T1 ) / (sigma * np.sqrt(T1))
a2 = ( (r - q - 0.5 * sigma**2) * T1 ) / (sigma * np.sqrt(T1))
b1 = ( (r - q + 0.5 * sigma**2) * T2 ) / (sigma * np.sqrt(T2))
b2 = ( (r - q - 0.5 * sigma**2) * T2 ) / (sigma * np.sqrt(T2... | Closed Form: 11.509604706054052
| MIT | Reset Put Option.ipynb | briangodwinlim/Financial-Math |
Sensitivity AnalysisNext, we can perform a sensitivity analysis on the exotic option and compare its valuation against a vanilla European put option. | def vanilla_price(S0, T, r, q, sigma):
d1 = ( (r - q + 0.5 * sigma**2) * T ) / (sigma * np.sqrt(T))
d2 = ( (r - q - 0.5 * sigma**2) * T ) / (sigma * np.sqrt(T))
return (
S0 * np.exp(-r * T) * norm.cdf(-d2)
- S0 * np.exp(- q * T) * norm.cdf(-d1)
) | _____no_output_____ | MIT | Reset Put Option.ipynb | briangodwinlim/Financial-Math |
Reset DateFirst, we perform sensitivity analysis on the reset date. | df = []
for T1 in np.linspace(0.0001,0.9999,50):
df.append([
T1,
closed_form_option_price(S0 = 100, T1 = T1,
T2 = 1, r = 0.1, q = 0.05, sigma = 0.3),
vanilla_price(S0 = 100, T = 1, r = 0.1, q = 0.05, sigma = 0.3)
])
df = pd.DataFrame(df, columns = ["Reset Date", "Reset Put Option", "Put Option"... | _____no_output_____ | MIT | Reset Put Option.ipynb | briangodwinlim/Financial-Math |
Risk-Free RateNext, we perform sensitivity analysis on the risk-free rate. | df = []
for r in np.linspace(0,0.2,50):
df.append([
r,
closed_form_option_price(S0 = 100, T1 = 0.5,
T2 = 1, r = r, q = 0.05, sigma = 0.3),
vanilla_price(S0 = 100, T = 1, r = r, q = 0.05, sigma = 0.3)
])
df = pd.DataFrame(df, columns = ["Risk-Free Rate", "Reset Put Option", "Put Option"])
df = d... | _____no_output_____ | MIT | Reset Put Option.ipynb | briangodwinlim/Financial-Math |
Dividend YieldAfterwards, we perform sensitivity analysis on the dividend yield. | df = []
for q in np.linspace(0,0.1,50):
df.append([
q,
closed_form_option_price(S0 = 100, T1 = 0.5,
T2 = 1, r = 0.1, q = q, sigma = 0.3),
vanilla_price(S0 = 100, T = 1, r = 0.1, q = q, sigma = 0.3)
])
df = pd.DataFrame(df, columns = ["Dividend Yield", "Reset Put Option", "Put Option"])
df = df.... | _____no_output_____ | MIT | Reset Put Option.ipynb | briangodwinlim/Financial-Math |
VolatilityFinally, we perform sensitivity analysis on the volatility. | df = []
for sigma in np.linspace(0.0001,0.5,50):
df.append([
sigma,
closed_form_option_price(S0 = 100, T1 = 0.5,
T2 = 1, r = 0.1, q = 0.05, sigma = sigma),
vanilla_price(S0 = 100, T = 1, r = 0.1, q = 0.05, sigma = sigma)
])
df = pd.DataFrame(df, columns = ["Volatility", "Reset Put Option", "Put... | _____no_output_____ | MIT | Reset Put Option.ipynb | briangodwinlim/Financial-Math |
Step 2: Define Objective Function | def Objective_Function(areas):
member_lengths, member_stresses, node_displacements = Truss_solver(areas)
total_area = np.array(areas)
total_member_lengths = []
for length in member_lengths:
total_member_lengths.append(member_lengths[length])
total_member_lengths = np.array(tot... | _____no_output_____ | MIT | 01 Simulated Annealing/02 200 bar Truss/01 Notebooks/SA-02-02 200 bar Truss Case 3 in groupings.ipynb | mjamezquidilla/Optimization-Practices |
Step 3: Define Constraints | def stress_constraint(stress_new):
if stress_new > 30 or stress_new < -30:
stress_counter = 1
else:
stress_counter = 0
return stress_counter
def displacement_constraint(node_displacement_new):
x = node_displacement_new[0]
y = node_displacement_new[1]
if x > 0.5 or x < -0... | _____no_output_____ | MIT | 01 Simulated Annealing/02 200 bar Truss/01 Notebooks/SA-02-02 200 bar Truss Case 3 in groupings.ipynb | mjamezquidilla/Optimization-Practices |
Step 4: Define Algorithm Step 4.1: Initialize Parameters | D = [0.100, 0.347, 0.440, 0.539, 0.954, 1.081, 1.174, 1.333, 1.488,
1.764, 2.142, 2.697, 2.800, 3.131, 3.565, 3.813, 4.805, 5.952, 6.572,
7.192, 8.525, 9.300, 10.850, 13.330, 14.290, 17.170, 19.180, 23.680,
28.080, 33.700]
def closest(list_of_areas, area_values_list):
for i, area_value in enumerate(area_values_list... | _____no_output_____ | MIT | 01 Simulated Annealing/02 200 bar Truss/01 Notebooks/SA-02-02 200 bar Truss Case 3 in groupings.ipynb | mjamezquidilla/Optimization-Practices |
OkCupid DataSet: Classify using combination of text data and metadata Meeting 5, 03- 03- 2020 Recap last meeting's decisions: Meeting 4, 28- 01- 2020 Approach 1: Merge classs 1, 3 and 5 Under sample class 6 Merge classes 6, 7, 8 Approach 2: Merge classs 1, 3 and 5 as class 1 ... | import pandas as pd
import matplotlib.pyplot as plt
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import MultinomialNB
from sklearn.metrics import accuracy_score
from sklearn.multiclass import OneVsRestClassifier
from sklearn.me... | Final Accuracy for Logistic: 0.8353497315920199
Confusion matrix, without normalization
[[1636 1079]
[ 976 8790]]
precision recall f1-score support
1.0 0.63 0.60 0.61 2715
8.0 0.89 0.90 0.90 9766
accuracy 0.... | MIT | docs/reports/report5_metadata.ipynb | ShNadi/OkCupid-project |
Germany: LK Märkischer Kreis (Nordrhein-Westfalen)* Homepage of project: https://oscovida.github.io* Plots are explained at http://oscovida.github.io/plots.html* [Execute this Jupyter Notebook using myBinder](https://mybinder.org/v2/gh/oscovida/binder/master?filepath=ipynb/Germany-Nordrhein-Westfalen-LK-Märkischer-Kre... | import datetime
import time
start = datetime.datetime.now()
print(f"Notebook executed on: {start.strftime('%d/%m/%Y %H:%M:%S%Z')} {time.tzname[time.daylight]}")
%config InlineBackend.figure_formats = ['svg']
from oscovida import *
overview(country="Germany", subregion="LK Märkischer Kreis", weeks=5);
overview(country=... | _____no_output_____ | CC-BY-4.0 | ipynb/Germany-Nordrhein-Westfalen-LK-Märkischer-Kreis.ipynb | oscovida/oscovida.github.io |
Explore the data in your web browser- If you want to execute this notebook, [click here to use myBinder](https://mybinder.org/v2/gh/oscovida/binder/master?filepath=ipynb/Germany-Nordrhein-Westfalen-LK-Märkischer-Kreis.ipynb)- and wait (~1 to 2 minutes)- Then press SHIFT+RETURN to advance code cell to code cell- See ht... | print(f"Download of data from Johns Hopkins university: cases at {fetch_cases_last_execution()} and "
f"deaths at {fetch_deaths_last_execution()}.")
# to force a fresh download of data, run "clear_cache()"
print(f"Notebook execution took: {datetime.datetime.now()-start}")
| _____no_output_____ | CC-BY-4.0 | ipynb/Germany-Nordrhein-Westfalen-LK-Märkischer-Kreis.ipynb | oscovida/oscovida.github.io |
Task 4: Classification_All credit for the code examples of this notebook goes to the book "Hands-On Machine Learning with Scikit-Learn & TensorFlow" by A. Geron. Modifications were made and text was added by K. Zoch in preparation for the hands-on sessions._ Setup First, import a few common modules, ensure MatplotLib... | # Common imports
import numpy as np
import os
# to make this notebook's output stable across runs
np.random.seed(42)
# To plot pretty figures
%matplotlib inline
import matplotlib as mpl
import matplotlib.pyplot as plt
mpl.rc('axes', labelsize=14)
mpl.rc('xtick', labelsize=12)
mpl.rc('ytick', labelsize=12)
# Function... | _____no_output_____ | Apache-2.0 | solutions/task_4_classification.ipynb | knutzk/handson-ml |
Preparing the dataset Define a function to sort the dataset into the 'targets' train and test data. This is needed because we want to use the same 60,000 data points for training, and the sam e10,000 data points for testing on every machine (and the dataset provided through Scikit-Learn is already prepared in this way... | def sort_by_target(mnist):
reorder_train = np.array(sorted([(target, i) for i, target in enumerate(mnist.target[:60000])]))[:, 1]
reorder_test = np.array(sorted([(target, i) for i, target in enumerate(mnist.target[60000:])]))[:, 1]
mnist.data[:60000] = mnist.data[reorder_train]
mnist.target[:60000] = mn... | _____no_output_____ | Apache-2.0 | solutions/task_4_classification.ipynb | knutzk/handson-ml |
Now fetch the dataset using the SciKit-Learn function (this might take a moment ...). | # We need this try/except for different Scikit-Learn versions.
try:
from sklearn.datasets import fetch_openml
mnist = fetch_openml('mnist_784', version=1, cache=True)
mnist.target = mnist.target.astype(np.int8) # fetch_openml() returns targets as strings
sort_by_target(mnist) # fetch_openml() returns an... | _____no_output_____ | Apache-2.0 | solutions/task_4_classification.ipynb | knutzk/handson-ml |
Let's have a look at what the 'data' key contains: it is a numpy array with one row per instance and one column per feature. | mnist["data"] | _____no_output_____ | Apache-2.0 | solutions/task_4_classification.ipynb | knutzk/handson-ml |
And the same for the 'target' key which is an array of labels. | mnist["target"] | _____no_output_____ | Apache-2.0 | solutions/task_4_classification.ipynb | knutzk/handson-ml |
Now, let's first define the more useful `x` and `y` aliases for the data and target keys, and let's have a look at the type of data using the `shape` function: we see 70,000 entries in the data array, with 784 features each. The 784 correspond to 28x28 pixels of an image with brightness values between 0 and 255. | X, y = mnist["data"], mnist["target"]
X.shape # get some information about its shape
28*28 # just a little cross-check we're doing the correct arithmetics here ...
X[36000][160:200] # Plot brightness values [160:200] of the random image X[36000]. | _____no_output_____ | Apache-2.0 | solutions/task_4_classification.ipynb | knutzk/handson-ml |
Now let's have a look at one of the images. We just pick a random image and use the `numpy.reshape()` function to reshape it into an array of 28x28 pixels. Then we can plot it with `matplotlib.pyplot.imshow()`: | some_digit = X[36000]
some_digit_image = some_digit.reshape(28, 28)
plt.imshow(some_digit_image, cmap = mpl.cm.binary,
interpolation="nearest")
plt.axis("off")
save_fig("some_digit_plot")
plt.show() | Saving figure some_digit_plot
| Apache-2.0 | solutions/task_4_classification.ipynb | knutzk/handson-ml |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.