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 |
|---|---|---|---|---|---|
RM average number of rooms per dwelling | boston_data['RM'].unique()[0:20] | _____no_output_____ | Apache-2.0 | boston_housing/house_price_prediction.ipynb | Mohamed-3ql/RegressionProjects |
AGE proportion of owner-occupied units built prior to 1940 | boston_data['AGE'].unique()[0:20] | _____no_output_____ | Apache-2.0 | boston_housing/house_price_prediction.ipynb | Mohamed-3ql/RegressionProjects |
DIS weighted distances to five Boston employment centres | boston_data['DIS'].unique()[0:20] | _____no_output_____ | Apache-2.0 | boston_housing/house_price_prediction.ipynb | Mohamed-3ql/RegressionProjects |
TAX full-value property-tax rate per 10,000 | boston_data['TAX'].unique()[0:20] | _____no_output_____ | Apache-2.0 | boston_housing/house_price_prediction.ipynb | Mohamed-3ql/RegressionProjects |
PTRATIO pupil-teacher ratio by town | boston_data['PTRATIO'].unique() | _____no_output_____ | Apache-2.0 | boston_housing/house_price_prediction.ipynb | Mohamed-3ql/RegressionProjects |
B where Bk is the proportion of blacks by town | boston_data['B'].unique()[0:20] | _____no_output_____ | Apache-2.0 | boston_housing/house_price_prediction.ipynb | Mohamed-3ql/RegressionProjects |
LSTAT percentage lower status of the population | boston_data['LSTAT'].unique()[0:20] | _____no_output_____ | Apache-2.0 | boston_housing/house_price_prediction.ipynb | Mohamed-3ql/RegressionProjects |
MEDV Median value of owner-occupied homes in 1000$ | boston_data['MEDV'].unique()[0:20] | _____no_output_____ | Apache-2.0 | boston_housing/house_price_prediction.ipynb | Mohamed-3ql/RegressionProjects |
after we checked the dat type of each variable. we have 2 discrete numerical variable and 10 floating or continuous variales. To understand wheather a variable is contious or discrete. we can also make a histogram for each:* CRIM per capita crime rate by town* ZN proportion of residential land zoned for lots... | n_data = len(boston_data['CRIM'])
bins = int(np.sqrt(n_data))
boston_data['CRIM'].hist(bins=bins) | _____no_output_____ | Apache-2.0 | boston_housing/house_price_prediction.ipynb | Mohamed-3ql/RegressionProjects |
making histogram for proportion of residential land zoned for lots over 25,000 sq.ft `ZN`, variable by dividing the variable range into intervals. | n_data = len(boston_data['ZN'])
bins = int(np.sqrt(n_data))
boston_data['ZN'].hist(bins=bins) | _____no_output_____ | Apache-2.0 | boston_housing/house_price_prediction.ipynb | Mohamed-3ql/RegressionProjects |
making histogram for proportion of non-retail business acres per town `INDUS`, variable by dividing the variable range into intervals. | n_data = len(boston_data['INDUS'])
bins = int(np.sqrt(n_data))
boston_data['INDUS'].hist(bins=bins) | _____no_output_____ | Apache-2.0 | boston_housing/house_price_prediction.ipynb | Mohamed-3ql/RegressionProjects |
making histogram for nitric oxides concentration (parts per 10 million) `NOX`, variable by dividing the variable range into intervals. | n_data = len(boston_data['NOX'])
bins = int(np.sqrt(n_data))
boston_data['NOX'].hist(bins=bins) | 22
| Apache-2.0 | boston_housing/house_price_prediction.ipynb | Mohamed-3ql/RegressionProjects |
making histogram for average number of rooms per dwelling `RM`, variable by dividing the variable range into intervals. | n_data = len(boston_data['RM'])
bins = int(np.sqrt(n_data))
boston_data['RM'].hist(bins=bins) | _____no_output_____ | Apache-2.0 | boston_housing/house_price_prediction.ipynb | Mohamed-3ql/RegressionProjects |
making histogram for proportion of owner-occupied units built prior to 1940 `AGE`, variable by dividing the variable range into intervals. | n_data = len(boston_data['AGE'])
bins = int(np.sqrt(n_data))
boston_data['AGE'].hist(bins=bins) | _____no_output_____ | Apache-2.0 | boston_housing/house_price_prediction.ipynb | Mohamed-3ql/RegressionProjects |
making histogram for weighted distances to five Boston employment centres `DIS`, variable by dividing the variable range into intervals. | n_data = len(boston_data['DIS'])
bins = int(np.sqrt(n_data))
boston_data['DIS'].hist(bins=bins) | _____no_output_____ | Apache-2.0 | boston_housing/house_price_prediction.ipynb | Mohamed-3ql/RegressionProjects |
making histogram for full-value property-tax rate per 10,000 `TAX`, variable by dividing the variable range into intervals. | n_data = len(boston_data['TAX'])
bins = int(np.sqrt(n_data))
boston_data['TAX'].hist(bins=bins) | _____no_output_____ | Apache-2.0 | boston_housing/house_price_prediction.ipynb | Mohamed-3ql/RegressionProjects |
making histogram for pupil-teacher ratio by town `PTRATIO`, variable by dividing the variable range into intervals. | n_data = len(boston_data['PTRATIO'])
bins = int(np.sqrt(n_data))
boston_data['PTRATIO'].hist(bins=bins) | _____no_output_____ | Apache-2.0 | boston_housing/house_price_prediction.ipynb | Mohamed-3ql/RegressionProjects |
making histogram where Bk is the proportion of blacks by town `B`, variable by dividing the variable range into intervals. | n_data = len(boston_data['B'])
bins = int(np.sqrt(n_data))
boston_data['B'].hist(bins=bins) | _____no_output_____ | Apache-2.0 | boston_housing/house_price_prediction.ipynb | Mohamed-3ql/RegressionProjects |
making histogram for percentage lower status of the population `LSTAT `, variable by dividing the variable range into intervals. | n_data = len(boston_data['LSTAT'])
bins = int(np.sqrt(n_data))
boston_data['LSTAT'].hist(bins=bins) | _____no_output_____ | Apache-2.0 | boston_housing/house_price_prediction.ipynb | Mohamed-3ql/RegressionProjects |
making histogram for Median value of owner-occupied homes in 1000$ ` MEDV`, variable by dividing the variable range into intervals. | n_data = len(boston_data['MEDV'])
bins = int(np.sqrt(n_data))
boston_data['MEDV'].hist(bins=bins) | _____no_output_____ | Apache-2.0 | boston_housing/house_price_prediction.ipynb | Mohamed-3ql/RegressionProjects |
making histogram for index of accessibility to radial highways`RAD`, variable by dividing the variable range into intervals. | n_data = len(boston_data['RAD'])
bins = int(np.sqrt(n_data))
boston_data['RAD'].hist(bins=bins) | _____no_output_____ | Apache-2.0 | boston_housing/house_price_prediction.ipynb | Mohamed-3ql/RegressionProjects |
by taking a look to histogram of features we noticing that the continuous variables values range is not discrete. making histogram for Charles River dummy variable (= 1 if tract bounds river; 0 otherwise) ` CHAS`, variable by dividing the variable range into intervals. | n_data = len(boston_data['CHAS'])
bins = int(np.sqrt(n_data))
boston_data['CHAS'].hist(bins=bins) | _____no_output_____ | Apache-2.0 | boston_housing/house_price_prediction.ipynb | Mohamed-3ql/RegressionProjects |
we noticing here the values of this variable is discrete. Quantifying Missing Datacalculating the missing values in the dataset. | boston_data.isnull().sum() | _____no_output_____ | Apache-2.0 | boston_housing/house_price_prediction.ipynb | Mohamed-3ql/RegressionProjects |
There is no Missing Values Determining the cardinality in cateogrical varaibles find unique values in each categorical variable | boston_data.nunique() | _____no_output_____ | Apache-2.0 | boston_housing/house_price_prediction.ipynb | Mohamed-3ql/RegressionProjects |
The nunique() method ignores missing values by default. If we want toconsider missing values as an additional category, we should set the dropna argument to False: data.nunique(dropna=False). let's print out the unique category in Charles River dummy variable (= 1 if tract bounds river; 0 otherwise) ` CHAS` | boston_data['CHAS'].unique() | _____no_output_____ | Apache-2.0 | boston_housing/house_price_prediction.ipynb | Mohamed-3ql/RegressionProjects |
pandas nunique() can be used in the entire dataframe. pandas unique(), on the other hand, works only on a pandas Series. Thus, weneed to specify the column name that we want to return the unique valuesfor. | boston_data[['CHAS','RAD']].nunique().plot.bar(figsize=(12,6))
plt.xlabel("Variables")
plt.ylabel("Number Of Unique Values")
plt.title("Cardinality")
plt.show() | _____no_output_____ | Apache-2.0 | boston_housing/house_price_prediction.ipynb | Mohamed-3ql/RegressionProjects |
第5章 計算機を作る 5.1.2 スタックマシン | def calc(expression: str):
# 空白で分割して字句にする
tokens = expression.split()
stack = []
for token in tokens:
if token.isdigit():
# 数値はスタックに push する
stack.append(int(token))
continue
# 数値でないなら,演算子として処理する
x = stack.pop()
y = stack.pop()
... | _____no_output_____ | MIT | pegbook_chap5.ipynb | kkuramitsu/pegbook2021 |
構文木を表示するためには、graphviz があらかじめインストールされている必要がある。 | %%peg
Expr = Prod ("+" Prod)*
Prod = Value ("*" Value)*
Value = { [0-9]+ #Int } _
example Expr 1+2+3
%%peg
Expr = { Prod ("+" Prod)* #Add }
Prod = { Value ("*" Value)* #Mul }
Value = { [0-9]+ #Int } _
example Expr 1+2+3
%%peg
Expr = Prod {^ "+" Prod #Add }*
Prod = Value {^ "*" Value #Mul }*
Value = { [0-9]+ #Int } ... | _____no_output_____ | MIT | pegbook_chap5.ipynb | kkuramitsu/pegbook2021 |
PegTree によるパーザ生成 | %%peg calc.pegtree
Start = Expr EOF // 未消費文字を構文エラーに
Expr = Prod ({^ "+" Prod #Add } / {^ "-" Prod #Sub } )*
Prod = Value ({^ "*" Value #Mul } / {^ "/" Value #Div } )*
Value = { [0-9]+ #Int} _ / "(" Expr ")"
example Expr 1+2*3
example Expr (1+2)*3
example Expr 1*2+3 | _____no_output_____ | MIT | pegbook_chap5.ipynb | kkuramitsu/pegbook2021 |
PegTree 文法のロード | peg = pg.grammar('calc.pegtree')
GRAMMAR = '''
Start = Expr EOF
Expr = Prod ({^ "+" Prod #Add } / {^ "-" Prod #Sub } )*
Prod = Value ({^ "*" Value #Mul } / {^ "/" Value #Div } )*
Value = { [0-9]+ #Int} _ / "(" Expr ")"
'''
peg = pg.grammar(GRAMMAR)
peg['Expr'] | _____no_output_____ | MIT | pegbook_chap5.ipynb | kkuramitsu/pegbook2021 |
5.3.2 パーザの生成 | parser = pg.generate(peg)
tree = parser('1+2')
print(repr(tree))
tree = parser('3@14')
print(repr(tree)) | Syntax Error ((unknown source):1:1+1)
3@14
^
| MIT | pegbook_chap5.ipynb | kkuramitsu/pegbook2021 |
構文木とVisitor パターン | peg = pg.grammar('calc.pegtree')
parser = pg.generate(peg)
tree = parser('1+2*3')
tree.getTag()
len(tree)
left = tree[0]
left.getTag()
left = tree[0]
str(left)
def calc(tree):
tag = tree.getTag()
if tag == 'Add':
t0 = tree[0]
t1 = tree[1]
return calc(t0) + calc(t1)
if tag == 'Mul':... | 7
| MIT | pegbook_chap5.ipynb | kkuramitsu/pegbook2021 |
Visitor パターン | class Visitor(object):
def visit(self, tree):
tag = tree.getTag()
name = f'accept{tag}'
if hasattr(self, name): # accept メソッドがあるか調べる
# メソッド名からメソッドを得る
acceptMethod = getattr(self, name)
return acceptMethod(tree)
print(f'TODO: accept{tag} method')
... | Syntax Error ((unknown source):1:1+1)
1@2
^
| MIT | pegbook_chap5.ipynb | kkuramitsu/pegbook2021 |
This notebook will walk through the steps of using the Colorado Information Marketplace (https://data.colorado.gov/) API with python The first step will be to aquire the API endpoint and user tokens. For this tutorial I will be using the Aquaculture Permittees in Colorado dataset (https://data.colorado.gov/Agricultur... | # import pandas
import pandas as pd
# create these variables using the information found in step one
api_url = 'https://data.colorado.gov/xxxxx/xxxxxx.json'
App_Token = 'xxxxxxxxxxxxxxxx' | _____no_output_____ | MIT | tutorial-notebook.ipynb | mtchem/python_for_colorado-API |
Create urls to request data. The maximum number of returns for each request is 50,000 records per page. The *limit* parameter chooses how many records to return per page, and the *offset* parameter determines which record the request will start with. | limit = 100 # limits the number of records to 100
offset = 20 # starts collecting records at record 20
# url_1 creates a url that will query the API and return all the fields (columns) of records 20-120
url_1 = api_url + '?' + '$$app_token=' + App_Token + '&$limit=' + str(limit) + '&$offset=' + str(offset) | _____no_output_____ | MIT | tutorial-notebook.ipynb | mtchem/python_for_colorado-API |
Pandas has a method that retrieves api data and creates a dataframe | raw_data = pd.read_json(url_1)
| _____no_output_____ | MIT | tutorial-notebook.ipynb | mtchem/python_for_colorado-API |
This is for conventional and irregular forc diagrams.two example of irforc and convential forc data in PmagPy/data_files/forc_diagram/The input data format could be very different due to different softwares and instruments,Nevertheless, only if the line [' Field Moment '] included before the measured data,... | from forc_diagram import *
from matplotlib import pyplot as plt
#forc = Forc(fileAdres='/data_files/irforc_example.irforc',SF=3)
forc = Forc(fileAdres='../example/MSM33-60-1-d416_2.irforc',SF=3)
fig = plt.figure(figsize=(6,5), facecolor='white')
fig.subplots_adjust(left=0.18, right=0.97,
bottom=0.... | _____no_output_____ | BSD-3-Clause | data_files/forc_diagram/.ipynb_checkpoints/forc_diagram-checkpoint.ipynb | apivarunas/PmagPy |
Chapter 1: The way of program The First Program | print('Hello, World!') | Hello, World!
| MIT | Chapter_1/The way of the Program.ipynb | Shrihith/Think-python |
Arithmetic Operators ( +, -, *, /, **, ^) (addition, substraction, multiplication, division, exponentiation, XOR) | 40 + 2 # add
43 - 1 # Sub
6 * 7 # multiply
84/ 2 # Division
6**2 + 6 # Exponent
6 ^ 2 # XOR(Bitwise operator) | _____no_output_____ | MIT | Chapter_1/The way of the Program.ipynb | Shrihith/Think-python |
Values and Types: A valus is one of the basic things a program works with,like a letter or a number. | type(2)
type(42.0)
type('Hello, World!')
1,000,000 | _____no_output_____ | MIT | Chapter_1/The way of the Program.ipynb | Shrihith/Think-python |
Formal and Natural Languages:1).Programming languages are formal languages that have been designed to express computations.2).Syntax rules comes with two flavors pertaining to token(such as, words, numbers, and chemical elements) and Token combination( order, well structured).3).parsing:figure outh the structure in fo... | print('helloworld)
print 'helloworld'
2++2
02+02
2 2 | _____no_output_____ | MIT | Chapter_1/The way of the Program.ipynb | Shrihith/Think-python |
1. How many seconds are ther in 42 minutes 42 seconds? | 42 * 60 + 42 | _____no_output_____ | MIT | Chapter_1/The way of the Program.ipynb | Shrihith/Think-python |
2. How many miles are there in 10 kilometers? hint: there are 1.61 kilometers in a mile | 10/1.61 | _____no_output_____ | MIT | Chapter_1/The way of the Program.ipynb | Shrihith/Think-python |
3. If you run a 10 kilometer race in 42 minutes 42 seconds, what is your average pace(time per mile in minutes and seconds)? what is your average speed in miles per hour? | 10/1.61
42*60+42
6.214/2562
42+42/60
6.214/42.7 | _____no_output_____ | MIT | Chapter_1/The way of the Program.ipynb | Shrihith/Think-python |
Final Exam ***Problem Statement 1***: Create a Python Program that will produce an output of sum of 10 numbers less than 5 using FOR LOOP statement. | sum = 0
num = [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4]
for x in (num):
sum = sum + x
print ("The sum of 10 numbers less than five is",sum) | The sum of 10 numbers less than five is -5
| Apache-2.0 | Final_Exam.ipynb | JuliusCaezarEugenio/CPEN21-A-CPE-1-1 |
***Problem Statement 2***: Create a Python program that will produce accept five numbers and determine the sum offirst and last number among the five numbers entered using WHILE LOOP | num = int(input("1st number: "))
while (num !=0):
l = int(input("2nd number: "))
o = int(input("3rd number: "))
v = int(input("4th number: "))
e = int(input("5th number: "))
break
x = e
while (x!=0):
x = num + e
print ("The sum of first and last number is", x)
num -=1
break | 1st number: 1
2nd number: 2
3rd number: 3
4th number: 4
5th number: 5
The sum of first and last number is 6
| Apache-2.0 | Final_Exam.ipynb | JuliusCaezarEugenio/CPEN21-A-CPE-1-1 |
***Problem Statement 3***: Create a Python program to calculate student grades. It accepts a numerical grade as inputand it will display the character grade as output based on the given scale: (Use Nested-IF-Elsestatement) | grade = float(input("Enter numerical grade: "))
if grade >=90:
print ("Character Grade: A")
elif grade <=89 and grade >80:
print ("Character Grade: B")
elif grade <=79 and grade >70:
print ("Character Grade: C")
elif grade <= 69 and grade >60:
print ("Character Grade: D")
else:
print ("Character Grade: F")
... | Enter numerical grade: 98.5
Character Grade: A
| Apache-2.0 | Final_Exam.ipynb | JuliusCaezarEugenio/CPEN21-A-CPE-1-1 |
Week 3 - Ungraded Lab: Data LabelingWelcome to the ungraded lab for week 3 of Machine Learning Engineering for Production. In this lab, you will see how the data labeling process affects the performance of a classification model. Labeling data is usually a very labor intensive and costly task but it is of great import... | import os
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt | _____no_output_____ | Apache-2.0 | course1/week3-lab/C1W3_Data_Labeling_Ungraded_Lab.ipynb | sidmontu/MLEP-public |
Loading the datasetThe dataset consists of 5 CSV files, one for each video. Pandas `DataFrame` are very powerful to handle data in CSV format. The following helper function will load the data using pandas: | def load_labeled_spam_dataset():
"""Load labeled spam dataset."""
# Path where csv files are located
base_path = "./data/"
# List of csv files with full path
csv_files = [os.path.join(base_path, csv) for csv in os.listdir(base_path)]
# List of dataframes for each file
dfs = [pd.read_csv(f... | _____no_output_____ | Apache-2.0 | course1/week3-lab/C1W3_Data_Labeling_Ungraded_Lab.ipynb | sidmontu/MLEP-public |
To have a feeling of how the data is organized, let's inspect the top 5 rows of the data: | # Take a look at the first 5 rows
df_labeled.head() | _____no_output_____ | Apache-2.0 | course1/week3-lab/C1W3_Data_Labeling_Ungraded_Lab.ipynb | sidmontu/MLEP-public |
Further inspection and preprocessing Checking for data imbalanceIt is fairly common to assume that the data you are working on is balanced. This means that the dataset contains a similar proportion of examples for all classes. Before moving forward let's actually test this assumption: | # Print actual value count
print(f"Value counts for each class:\n\n{df_labeled.label.value_counts()}\n")
# Display pie chart to visually check the proportion
df_labeled.label.value_counts().plot.pie(y='label', title='Proportion of each class')
plt.show() | _____no_output_____ | Apache-2.0 | course1/week3-lab/C1W3_Data_Labeling_Ungraded_Lab.ipynb | sidmontu/MLEP-public |
There is roughly the same number of data points for each class so class imbalance is not an issue for this particular dataset. Cleaning the datasetIf you scroll back to the cell where you inspected the data, you will realize that the dataframe includes information that is not relevant for the task at hand. At the mome... | # Drop unused columns
df_labeled = df_labeled.drop(['index', 'COMMENT_ID', 'AUTHOR', 'DATE'], axis=1)
# Look at the cleaned dataset
df_labeled.head() | _____no_output_____ | Apache-2.0 | course1/week3-lab/C1W3_Data_Labeling_Ungraded_Lab.ipynb | sidmontu/MLEP-public |
Now the dataset only includes the information you are going to use moving forward. Splitting the datasetBefore jumping to the data labeling section let's split the data into training and test sets so you can use the latter to measure the performance of models that were trained using data labeled through different metho... | from sklearn.model_selection import train_test_split
# Save the text into the X variable
X = df_labeled.drop("label", axis=1)
# Save the true labels into the y variable
y = df_labeled["label"]
# Use 1/5 of the data for testing later
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_stat... | _____no_output_____ | Apache-2.0 | course1/week3-lab/C1W3_Data_Labeling_Ungraded_Lab.ipynb | sidmontu/MLEP-public |
Let's do a visual to check that the stratification actually worked: | plt.subplot(1, 3, 1)
y_train.value_counts().plot.pie(y='label', title='Proportion of each class for train set', figsize=(10, 6))
plt.subplot(1, 3, 3)
y_test.value_counts().plot.pie(y='label', title='Proportion of each class for test set', figsize=(10, 6))
plt.tight_layout()
plt.show() | _____no_output_____ | Apache-2.0 | course1/week3-lab/C1W3_Data_Labeling_Ungraded_Lab.ipynb | sidmontu/MLEP-public |
Both, the training and test sets a balanced proportion of examples per class. So, the code successfully implemented stratification. Let's get going! Data Labeling Establishing performance lower and upper bounds for referenceTo properly compare different labeling strategies you need to establish a baseline for model ... | from sklearn.feature_extraction.text import CountVectorizer
# Allow unigrams and bigrams
vectorizer = CountVectorizer(ngram_range=(1, 5)) | _____no_output_____ | Apache-2.0 | course1/week3-lab/C1W3_Data_Labeling_Ungraded_Lab.ipynb | sidmontu/MLEP-public |
Now that the text encoding is defined, you need to select a model to make predictions. For simplicity you will use a [Multinomial Naive Bayes](https://scikit-learn.org/stable/modules/generated/sklearn.naive_bayes.MultinomialNB.html) classifier. This model is well suited for text classification and is fairly quick to tr... | from sklearn.metrics import accuracy_score
from sklearn.naive_bayes import MultinomialNB
def calculate_accuracy(X_tr, y_tr, X_te=X_test, y_te=y_test,
clf=MultinomialNB(), vectorizer=vectorizer):
# Encode train text
X_train_vect = vectorizer.fit_transform(X_tr.text.tolist())
... | _____no_output_____ | Apache-2.0 | course1/week3-lab/C1W3_Data_Labeling_Ungraded_Lab.ipynb | sidmontu/MLEP-public |
Now let's create a dictionary to store the accuracy of each labeling method: | # Empty dictionary
accs = dict() | _____no_output_____ | Apache-2.0 | course1/week3-lab/C1W3_Data_Labeling_Ungraded_Lab.ipynb | sidmontu/MLEP-public |
Random LabelingGenerating random labels is a natural way to establish a lower bound. You will expect that any successful alternative labeling model to outperform randomly generated labels. Now let's calculate the accuracy for the random labeling method | # Calculate random labels
rnd_labels = np.random.randint(0, 2, X_train.shape[0])
# Feed them alongside X_train to calculate_accuracy function
rnd_acc = calculate_accuracy(X_train, rnd_labels)
rnd_acc | _____no_output_____ | Apache-2.0 | course1/week3-lab/C1W3_Data_Labeling_Ungraded_Lab.ipynb | sidmontu/MLEP-public |
You will see a different accuracy everytime you run the previous cell. This is due to the fact that the labeling is done randomly. Remember, this is a binary classification problem and both classes are balanced, so you can expect to see accuracies that revolve around 50%.To further gain intuition let's look at the aver... | # Empty list to save accuracies
rnd_accs = []
for _ in range(10):
# Add every accuracy to the list
rnd_accs.append(calculate_accuracy(X_train, np.random.randint(0, 2, X_train.shape[0])))
# Save result in accs dictionary
accs['random-labels'] = sum(rnd_accs)/len(rnd_accs)
# Print result
print(f"The random lab... | _____no_output_____ | Apache-2.0 | course1/week3-lab/C1W3_Data_Labeling_Ungraded_Lab.ipynb | sidmontu/MLEP-public |
Random labelling is completely disregarding the information from the solution space you are working on, and is just guessing the correct label. You can't probably do worse than this (or maybe you can). For this reason, this method serves as reference for comparing other labeling methods Labeling with true valuesNow let... | # Calculate accuracy when using the true labels
true_acc = calculate_accuracy(X_train, y_train)
# Save the result
accs['true-labels'] = true_acc
print(f"The true labelling method achieved and accuracy of {accs['true-labels']*100:.2f}%") | _____no_output_____ | Apache-2.0 | course1/week3-lab/C1W3_Data_Labeling_Ungraded_Lab.ipynb | sidmontu/MLEP-public |
Training with the true labels produced a noticeable boost in accuracy. This is expected as the classifier is now able to properly identify patterns in the training data which were lacking with randomly generated labels. Achieving higher accuracy is possible by either fine-tunning the model or even selecting a different... | def labeling_rules_1(x):
# Convert text to lowercase
x = x.lower()
# Define list of rules
rules = [
"free" in x,
"subs" in x,
"http" in x
]
# If the comment falls under any of the rules classify as SPAM
if any(rules):
return 1
# Otherwi... | _____no_output_____ | Apache-2.0 | course1/week3-lab/C1W3_Data_Labeling_Ungraded_Lab.ipynb | sidmontu/MLEP-public |
For lots of points the automatic labeling algorithm decided to not settle for a label, this is expected given the nature of the rules that were defined. These points should be deleted since they don't provide information about the classification process and tend to hurt performance. | # Create the automatic labeled version of X_train by removing points with NO_LABEL label
X_train_al = X_train[labels != -1]
# Remove predictions with NO_LABEL label
labels_al = labels[labels != -1]
print(f"Predictions with concrete label have shape: {labels_al.shape}")
print(f"Proportion of data points kept: {labels... | _____no_output_____ | Apache-2.0 | course1/week3-lab/C1W3_Data_Labeling_Ungraded_Lab.ipynb | sidmontu/MLEP-public |
Notice that only 379 data points remained out of the original 1564. The rules defined didn't provide enough context for the labeling algorithm to settle on a label, so around 75% of the data has been trimmed.Let's test the accuracy of the model when using these automatic generated labels: | # Compute accuracy when using these labels
iter_1_acc = calculate_accuracy(X_train_al, labels_al)
# Display accuracy
print(f"First iteration of automatic labeling has an accuracy of {iter_1_acc*100:.2f}%")
# Save the result
accs['first-iteration'] = iter_1_acc | _____no_output_____ | Apache-2.0 | course1/week3-lab/C1W3_Data_Labeling_Ungraded_Lab.ipynb | sidmontu/MLEP-public |
Let's compare this accuracy to the baselines by plotting: | def plot_accuracies(accs=accs):
colors = list("rgbcmy")
items_num = len(accs)
cont = 1
for x, y in accs.items():
if x in ['true-labels', 'random-labels', 'true-labels-best-clf']:
plt.hlines(y, 0, (items_num-2)*2, colors=colors.pop())
else:
plt.scatter(cont, y, s=... | _____no_output_____ | Apache-2.0 | course1/week3-lab/C1W3_Data_Labeling_Ungraded_Lab.ipynb | sidmontu/MLEP-public |
This first iteration had an accuracy very close to the random labeling, we should strive to do better than this. Before moving forward let's define the `label_given_rules` function that performs all of the steps you just saw, these are: - Apply the rules to a dataframe of comments- Cast the resulting labels to a numpy... | def label_given_rules(df, rules_function, name,
accs_dict=accs, verbose=True):
# Apply labeling rules to the comments
labels = [rules_function(label) for label in df.text]
# Convert to a numpy array
labels = np.asarray(labels)
# Save initial number of data point... | _____no_output_____ | Apache-2.0 | course1/week3-lab/C1W3_Data_Labeling_Ungraded_Lab.ipynb | sidmontu/MLEP-public |
Going forward we should come up with rules that have a better coverage of the training data, thus making pattern discovery an easier task. Also notice how the rules were only able to label as either SPAM or NO_LABEL, we should also create some rules that help the identification of NOT_SPAM comments. Second iteration -... | def labeling_rules_2(x):
# Convert text to lowercase
x = x.lower()
# Define list of rules to classify as NOT_SPAM
not_spam_rules = [
"view" in x,
"song" in x
]
# Define list of rules to classify as SPAM
spam_rules = [
"free" in x,
"subs" in x,
... | _____no_output_____ | Apache-2.0 | course1/week3-lab/C1W3_Data_Labeling_Ungraded_Lab.ipynb | sidmontu/MLEP-public |
This new set of rules looks more promising as it includes more patterns to classify as SPAM as well as some patterns to classify as NOT_SPAM. This should result in more data points with a label different to NO_LABEL.Let's check if this is the case. | label_given_rules(X_train, labeling_rules_2, "second-iteration")
plot_accuracies() | _____no_output_____ | Apache-2.0 | course1/week3-lab/C1W3_Data_Labeling_Ungraded_Lab.ipynb | sidmontu/MLEP-public |
This time 44% of the original dataset was given a decisive label and there were data points for both labels, this helped the model reach a higher accuracy when compared to the first iteration. Now the accuracy is considerably higher than the random labeling but it is still very far away from the upper bound.Let's see i... | from statistics import mean
print(f"NOT_SPAM comments have an average of {mean([len(t) for t in df_labeled[df_labeled.label==0].text]):.2f} characters.")
print(f"SPAM comments have an average of {mean([len(t) for t in df_labeled[df_labeled.label==1].text]):.2f} characters.") | _____no_output_____ | Apache-2.0 | course1/week3-lab/C1W3_Data_Labeling_Ungraded_Lab.ipynb | sidmontu/MLEP-public |
It sure looks like there is a big difference in the number of characters for both types of comments.To decide on a threshold to classify as NOT_SPAM let's plot a histogram of the number of characters for NOT_SPAM comments: | plt.hist([len(t) for t in df_labeled[df_labeled.label==0].text], range=(0,100))
plt.show() | _____no_output_____ | Apache-2.0 | course1/week3-lab/C1W3_Data_Labeling_Ungraded_Lab.ipynb | sidmontu/MLEP-public |
The majority of NOT_SPAM comments have 30 or less characters so we'll use that as a threshold.Another prevalent pattern in spam comments is to ask users to "check out" a channel, website or link.Let's add these two new rules: | def labeling_rules_3(x):
# Convert text to lowercase
x = x.lower()
# Define list of rules to classify as NOT_SPAM
not_spam_rules = [
"view" in x,
"song" in x,
len(x) < 30
]
# Define list of rules to classify as SPAM
spam_rules = [
"free" in x,
... | _____no_output_____ | Apache-2.0 | course1/week3-lab/C1W3_Data_Labeling_Ungraded_Lab.ipynb | sidmontu/MLEP-public |
These new rules do a pretty good job at both, covering the dataset and having a good model accuracy. To be more concrete this labeling strategy reached an accuracy of ~86%! We are getting closer and closer to the upper bound defined by using the true labels.We could keep going on adding more rules to improve accuracy a... | # Configure pandas to print out all rows to check the complete dataset
pd.set_option('display.max_rows', None)
# Check NOT_SPAM comments
df_labeled[df_labeled.label==0]
# Check SPAM comments
df_labeled[df_labeled.label==1]
def your_labeling_rules(x):
# Convert text to lowercase
x = x.lower()
# De... | _____no_output_____ | Apache-2.0 | course1/week3-lab/C1W3_Data_Labeling_Ungraded_Lab.ipynb | sidmontu/MLEP-public |
Example - Simple Vertically Partitioned Split Neural Network- Alice - Has model Segment 1 - Has the handwritten Images- Bob - Has model Segment 2 - Has the image Labels Based on [SplitNN - Tutorial 3](https://github.com/OpenMined/PySyft/blob/master/examples/tutorials/advanced/split_neural_network/Tutori... | class SplitNN:
def __init__(self, models, optimizers):
self.models = models
self.optimizers = optimizers
self.data = []
self.remote_tensors = []
def forward(self, x):
data = []
remote_tensors = []
data.append(self.models[0](x))
if data[-1].loca... | _____no_output_____ | Apache-2.0 | examples/PyVertical Example.ipynb | Koukyosyumei/PyVertical |
Check if the datasets are unorderedIn MNIST, we have 2 datasets (the images and the labels). | # We need matplotlib library to plot the dataset
import matplotlib.pyplot as plt
# Plot the first 10 entries of the labels and the dataset
figure = plt.figure()
num_of_entries = 10
for index in range(1, num_of_entries + 1):
plt.subplot(6, 10, index)
plt.axis('off')
plt.imshow(dataloader.dataloader1.dataset... | 1 4 0 7 0 1 5 1 5 1 | Apache-2.0 | examples/PyVertical Example.ipynb | Koukyosyumei/PyVertical |
Implement PSI and order the datasets accordingly | # Compute private set intersection
client_items = dataloader.dataloader1.dataset.get_ids()
server_items = dataloader.dataloader2.dataset.get_ids()
client = Client(client_items)
server = Server(server_items)
setup, response = server.process_request(client.request, len(client_items))
intersection = client.compute_inter... | _____no_output_____ | Apache-2.0 | examples/PyVertical Example.ipynb | Koukyosyumei/PyVertical |
Check again if the datasets are ordered | # We need matplotlib library to plot the dataset
import matplotlib.pyplot as plt
# Plot the first 10 entries of the labels and the dataset
figure = plt.figure()
num_of_entries = 10
for index in range(1, num_of_entries + 1):
plt.subplot(6, 10, index)
plt.axis('off')
plt.imshow(dataloader.dataloader1.dataset... | Labels pointing to: (Wrapper)>[PointerTensor | me:88412365445 -> bob:61930132897]
Images pointing to: (Wrapper)>[PointerTensor | me:17470208323 -> alice:25706803556]
| Apache-2.0 | examples/PyVertical Example.ipynb | Koukyosyumei/PyVertical |
1-3. 複数量子ビットの記述 ここまでは1量子ビットの状態とその操作(演算)の記述について学んできた。この章の締めくくりとして、$n$個の量子ビットがある場合の状態の記述について学んでいこう。テンソル積がたくさん出てきてややこしいが、コードをいじりながら身につけていってほしい。$n$個の**古典**ビットの状態は$n$個の$0,1$の数字によって表現され、そのパターンの総数は$2^n$個ある。量子力学では、これらすべてのパターンの重ね合わせ状態が許されているので、$n$個の**量子**ビットの状態$|\psi \rangle$はどのビット列がどのような重みで重ね合わせになっているかという$2^n$個の複素確率振幅で記述される:$... | from IPython.display import Image, display_png
from sympy import *
from sympy.physics.quantum import *
from sympy.physics.quantum.qubit import Qubit,QubitBra
from sympy.physics.quantum.gate import X,Y,Z,H,S,T,CNOT,SWAP, CPHASE
init_printing() # ベクトルや行列を綺麗に表示するため
# Google Colaboratory上でのみ実行してください
from IPython.display im... | _____no_output_____ | BSD-3-Clause | notebooks/1.3_multiqubit_representation_and_operations.ipynb | speed1313/quantum-native-dojo |
さらに$|\psi\rangle$とのテンソル積をとると8次元のベクトルになる: | represent(TensorProduct(psi,TensorProduct(psi, phi))) | _____no_output_____ | BSD-3-Clause | notebooks/1.3_multiqubit_representation_and_operations.ipynb | speed1313/quantum-native-dojo |
演算子のテンソル積演算子についても何番目の量子ビットに作用するのか、というのをテンソル積をもちいて表現することができる。たとえば、1つめの量子ビットには$A$という演算子、2つめの量子ビットには$B$という演算子を作用させるという場合には、$$ A \otimes B$$としてテンソル積演算子が与えられる。$A$と$B$をそれぞれ、2×2の行列とすると、$A\otimes B$は4×4の行列として$$\left(\begin{array}{cc}a_{11} & a_{12}\\a_{21} & a_{22}\end{array}\right)\otimes \left(\begin{array}{cc}b_{11} & b_{1... | represent(H(0),nqubits=1) | _____no_output_____ | BSD-3-Clause | notebooks/1.3_multiqubit_representation_and_operations.ipynb | speed1313/quantum-native-dojo |
2量子ビット空間では$H \otimes I$に対応しており、その表示は | represent(H(1),nqubits=2) | _____no_output_____ | BSD-3-Clause | notebooks/1.3_multiqubit_representation_and_operations.ipynb | speed1313/quantum-native-dojo |
CNOT演算は、 | represent(CNOT(1,0),nqubits=2) | _____no_output_____ | BSD-3-Clause | notebooks/1.3_multiqubit_representation_and_operations.ipynb | speed1313/quantum-native-dojo |
パウリ演算子のテンソル積$X\otimes Y \otimes Z$も、 | represent(X(2)*Y(1)*Z(0),nqubits=3) | _____no_output_____ | BSD-3-Clause | notebooks/1.3_multiqubit_representation_and_operations.ipynb | speed1313/quantum-native-dojo |
このようにして、上記のテンソル積のルールを実際にたしかめてみることができる。 複数の量子ビットの一部分だけを測定した場合複数の量子ビットを全て測定した場合の測定結果の確率については既に説明した。複数の量子ビットのうち、一部だけを測定することもできる。その場合、測定結果の確率は、測定結果に対応する(部分系の)基底で射影したベクトルの長さの2乗になり、測定後の状態は射影されたベクトルを規格化したものになる。具体的に見ていこう。以下の$n$量子ビットの状態を考える。\begin{align}|\psi\rangle &=c_{00...0} |00...0\rangle +c_{00...1} |00...1\rangle + \cdo... | psi = qapply(CNOT(1, 0)*H(1)*H(0)*Qubit('00'))
psi | _____no_output_____ | BSD-3-Clause | notebooks/1.3_multiqubit_representation_and_operations.ipynb | speed1313/quantum-native-dojo |
この状態の1つ目の量子ビットを測定して0になる確率は$$p_0 = \langle \psi | \bigl( |0\rangle\langle0| \otimes I \bigr) | \psi \rangle =\left(\frac{\langle 00 | + \langle 10 | + \langle 01 | + \langle 11 |}{2}\right)\left(\frac{| 00 \rangle + | 01 \rangle}{2}\right) =\frac{1}{2}$$で、測定後の状態は$$\frac{1}{\sqrt{p_0}} \bigl( |0\rangle\langle0| \otimes I... | from sympy.physics.quantum.qubit import measure_all, measure_partial
measured_state_and_probability = measure_partial(psi, (1,))
measured_state_and_probability[0] | _____no_output_____ | BSD-3-Clause | notebooks/1.3_multiqubit_representation_and_operations.ipynb | speed1313/quantum-native-dojo |
上で手計算した結果と合っていることが分かる。測定結果が1だった場合も同様に計算できる。 | measured_state_and_probability[1] | _____no_output_____ | BSD-3-Clause | notebooks/1.3_multiqubit_representation_and_operations.ipynb | speed1313/quantum-native-dojo |
Evaluation of a Pipeline and its Components[](https://colab.research.google.com/github/deepset-ai/haystack/blob/master/tutorials/Tutorial5_Evaluation.ipynb)To be able to make a statement about the quality of results a question-answering pipeline... | # Make sure you have a GPU running
!nvidia-smi
# Install the latest release of Haystack in your own environment
#! pip install farm-haystack
# Install the latest master of Haystack
!pip install --upgrade pip
!pip install git+https://github.com/deepset-ai/haystack.git#egg=farm-haystack[colab] | _____no_output_____ | Apache-2.0 | tutorials/Tutorial5_Evaluation.ipynb | carloslago/haystack |
Start an Elasticsearch serverYou can start Elasticsearch on your local machine instance using Docker. If Docker is not readily available in your environment (eg., in Colab notebooks), then you can manually download and execute Elasticsearch from source. | # If Docker is available: Start Elasticsearch as docker container
# from haystack.utils import launch_es
# launch_es()
# Alternative in Colab / No Docker environments: Start Elasticsearch from source
! wget https://artifacts.elastic.co/downloads/elasticsearch/elasticsearch-7.9.2-linux-x86_64.tar.gz -q
! tar -xzf elast... | _____no_output_____ | Apache-2.0 | tutorials/Tutorial5_Evaluation.ipynb | carloslago/haystack |
Fetch, Store And Preprocess the Evaluation Dataset | from haystack.utils import fetch_archive_from_http
# Download evaluation data, which is a subset of Natural Questions development set containing 50 documents with one question per document and multiple annotated answers
doc_dir = "data/tutorial5"
s3_url = "https://s3.eu-central-1.amazonaws.com/deepset.ai-farm-qa/datas... | _____no_output_____ | Apache-2.0 | tutorials/Tutorial5_Evaluation.ipynb | carloslago/haystack |
Initialize the Two Components of an ExtractiveQAPipeline: Retriever and Reader | # Initialize Retriever
from haystack.nodes import ElasticsearchRetriever
retriever = ElasticsearchRetriever(document_store=document_store)
# Alternative: Evaluate dense retrievers (EmbeddingRetriever or DensePassageRetriever)
# The EmbeddingRetriever uses a single transformer based encoder model for query and documen... | _____no_output_____ | Apache-2.0 | tutorials/Tutorial5_Evaluation.ipynb | carloslago/haystack |
Evaluation of an ExtractiveQAPipelineHere we evaluate retriever and reader in open domain fashion on the full corpus of documents i.e. a document is consideredcorrectly retrieved if it contains the gold answer string within it. The reader is evaluated based purely on thepredicted answer string, regardless of which doc... | from haystack.schema import EvaluationResult, MultiLabel
# We can load evaluation labels from the document store
# We are also opting to filter out no_answer samples
eval_labels = document_store.get_all_labels_aggregated(drop_negative_labels=True, drop_no_answers=False)
eval_labels = [label for label in eval_labels if... | _____no_output_____ | Apache-2.0 | tutorials/Tutorial5_Evaluation.ipynb | carloslago/haystack |
Calculating Evaluation MetricsLoad an EvaluationResult to quickly calculate standard evaluation metrics for all predictions,such as F1-score of each individual prediction of the Reader node or recall of the retriever.To learn more about the metrics, see [Evaluation Metrics](https://haystack.deepset.ai/guides/evaluatio... | saved_eval_result = EvaluationResult.load("../")
metrics = saved_eval_result.calculate_metrics()
print(f'Retriever - Recall (single relevant document): {metrics["Retriever"]["recall_single_hit"]}')
print(f'Retriever - Recall (multiple relevant documents): {metrics["Retriever"]["recall_multi_hit"]}')
print(f'Retriever -... | _____no_output_____ | Apache-2.0 | tutorials/Tutorial5_Evaluation.ipynb | carloslago/haystack |
Generating an Evaluation ReportA summary of the evaluation results can be printed to get a quick overview. It includes some aggregated metrics and also shows a few wrongly predicted examples. | pipeline.print_eval_report(saved_eval_result) | _____no_output_____ | Apache-2.0 | tutorials/Tutorial5_Evaluation.ipynb | carloslago/haystack |
Advanced Evaluation MetricsAs an advanced evaluation metric, semantic answer similarity (SAS) can be calculated. This metric takes into account whether the meaning of a predicted answer is similar to the annotated gold answer rather than just doing string comparison.To this end SAS relies on pre-trained models. For En... | advanced_eval_result = pipeline.eval(
labels=eval_labels, params={"Retriever": {"top_k": 1}}, sas_model_name_or_path="cross-encoder/stsb-roberta-large"
)
metrics = advanced_eval_result.calculate_metrics()
print(metrics["Reader"]["sas"]) | _____no_output_____ | Apache-2.0 | tutorials/Tutorial5_Evaluation.ipynb | carloslago/haystack |
Isolated Evaluation ModeThe isolated node evaluation uses labels as input to the Reader node instead of the output of the preceeding Retriever node.Thereby, we can additionally calculate the upper bounds of the evaluation metrics of the Reader. Note that even with isolated evaluation enabled, integrated evaluation wil... | eval_result_with_upper_bounds = pipeline.eval(
labels=eval_labels, params={"Retriever": {"top_k": 5}, "Reader": {"top_k": 5}}, add_isolated_node_eval=True
)
pipeline.print_eval_report(eval_result_with_upper_bounds) | _____no_output_____ | Apache-2.0 | tutorials/Tutorial5_Evaluation.ipynb | carloslago/haystack |
Evaluation of Individual Components: RetrieverSometimes you might want to evaluate individual components, for example, if you don't have a pipeline but only a retriever or a reader with a model that you trained yourself.Here we evaluate only the retriever, based on whether the gold_label document is retrieved. | ## Evaluate Retriever on its own
# Note that no_answer samples are omitted when evaluation is performed with this method
retriever_eval_results = retriever.eval(top_k=5, label_index=label_index, doc_index=doc_index)
# Retriever Recall is the proportion of questions for which the correct document containing the answer i... | _____no_output_____ | Apache-2.0 | tutorials/Tutorial5_Evaluation.ipynb | carloslago/haystack |
Just as a sanity check, we can compare the recall from `retriever.eval()` with the multi hit recall from `pipeline.eval(add_isolated_node_eval=True)`.These two recall metrics are only comparable since we chose to filter out no_answer samples when generating eval_labels. | metrics = eval_result_with_upper_bounds.calculate_metrics()
print(metrics["Retriever"]["recall_multi_hit"]) | _____no_output_____ | Apache-2.0 | tutorials/Tutorial5_Evaluation.ipynb | carloslago/haystack |
Evaluation of Individual Components: ReaderHere we evaluate only the reader in a closed domain fashion i.e. the reader is given one queryand its corresponding relevant document and metrics are calculated on whether the right position in this text is selected bythe model as the answer span (i.e. SQuAD style) | # Evaluate Reader on its own
reader_eval_results = reader.eval(document_store=document_store, label_index=label_index, doc_index=doc_index)
# Evaluation of Reader can also be done directly on a SQuAD-formatted file without passing the data to Elasticsearch
# reader_eval_results = reader.eval_on_file("../data/nq", "nq_d... | _____no_output_____ | Apache-2.0 | tutorials/Tutorial5_Evaluation.ipynb | carloslago/haystack |
Calculate Rider-Bicycle Weight DistributionCompare weight distribution on front wheel (WDF) between force plate measurements and the CoM model prediction. Calculate WDF from CoM modelUse CoM model to predict WDF | # Set variables for gravity, mass, and frame geometry.
g = -9.81 #gravity (m/s^2)
Mb = 4.94 #mass of bike (kg)
Mr = 87.2562 #mass of rider (kg)
Mt = Mb + Mr #mass of rider + bike
Wb = Mb * g #weight of bike
Wr = Mr * g #weight of rider
Wt = Wb + Wr #weight of bike + rider
Lfc = 0.579 #length bottom bracket to center ... | _____no_output_____ | MIT | docs/calculate-wdf.ipynb | ross-wilkinson/vantage-com |
Mount your google drive folder | from google.colab import drive
drive.mount('/content/drive') | Mounted at /content/drive
| MIT | docs/calculate-wdf.ipynb | ross-wilkinson/vantage-com |
*NOTE* You need to create a copy of the "com2bb.json" file in your main google drive folder for this to work.Load CoM data from json file stored in Google Drive | import json
with open("/content/drive/My Drive/com2bb.json", "r") as read_file:
data = json.load(read_file)
data[:10] | _____no_output_____ | MIT | docs/calculate-wdf.ipynb | ross-wilkinson/vantage-com |
Work on data | import statistics as st
import numpy as np
Lcmbb = np.array(data) / 1000 #convert mm to m
Lcmrc = Lrc - Lcmbb #length rider CoM to rear center
Ffwt = (Wr * Lcmrc) / Lt + Ffwb #reaction force on front wheel - total (N)
Wdft = Ffwt / Wt * 100 #distribution of weight on front wheel - total (%)
print(st.mean(Lcmbb))
prin... | -0.04212060080728705
47.00747507077737
| MIT | docs/calculate-wdf.ipynb | ross-wilkinson/vantage-com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.