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
同时 deck 类支持迭代
for card in deck: print(card) # 反向迭代 for card in reversed(deck): print(card)
_____no_output_____
MIT
01-data-model/01-data-model.ipynb
yuechuanx/fluent-python-code-and-notes
迭代通常是隐式的,如果一个集合没有实现 `__contains__` 方法,那么 in 运算符会顺序做一次迭代搜索。
Card('Q', 'hearts') in deck Card('7', 'beasts') in deck
_____no_output_____
MIT
01-data-model/01-data-model.ipynb
yuechuanx/fluent-python-code-and-notes
进行排序,排序规则:2 最小,A最大。花色 黑桃 > 红桃 > 方块 > 梅花
card.rank suit_values = dict(spades=3, hearts=2, diamonds=1, clubs=0) def spades_high(card): rank_value = FrenchDeck.ranks.index(card.rank) return rank_value * len(suit_values) + suit_values[card.suit] for card in sorted(deck, key=spades_high): print(card)
_____no_output_____
MIT
01-data-model/01-data-model.ipynb
yuechuanx/fluent-python-code-and-notes
FrenchDeck 继承了 object 类。通过 `__len__`, `__getitem__` 方法,FrenchDeck和 Python 自有序列数据类型一样,可体现 Python 核心语言特性(如迭代和切片), Python 支持的所有魔术方法,可以参见 Python 文档 [Data Model](https://docs.python.org/3/reference/datamodel.html) 部分。比较重要的一点:不要把 `len`,`str` 等看成一个 Python 普通方法:由于这些操作的频繁程度非常高,所以 Python 对这些方法做了特殊的实现:它可以让 Python 的内置数据结构走后门以提高效率;...
from math import hypot class Vector: def __init__(self, x=0, y=0): self.x = x self.y = y def __repr__(self): return 'Vector(%r, %r)' % (self.x, self.y) def __abs__(self): return hypot(self.x, self.y) def __bool__(self): return bool(abs(self)) def __add__...
_____no_output_____
MIT
01-data-model/01-data-model.ipynb
yuechuanx/fluent-python-code-and-notes
The JSON data is fetched and stored in numpy arrays in sequences of 45 frames which isabout 1.5 seconds of the video [2].60% of the dataset has been used for training,20% for testingand 20% for validation. The training data has 7989 sequences of 45 frames, each containing the 2D coordinates of the 18 keypoints captured...
import torch import numpy as np import numpy as np import pandas as pd import ast from sklearn.model_selection import train_test_split from torch.utils.data import DataLoader, TensorDataset from os import listdir # check if CUDA is available train_on_gpu = torch.cuda.is_available() if not train_on_gpu: print('CU...
_____no_output_____
Apache-2.0
pose_classification/pose_classification_lstm.ipynb
julkar9/deep_learning_nano_degree
---![title](rnn_lstm_00.png)![title](rnn_lstm_0.png)![title](cnn_lstm.png) Define model structure
from torch import nn import torch.nn.functional as F class TimeDistributed(nn.Module): def __init__(self, module, batch_first=True): super(TimeDistributed, self).__init__() self.module = module self.batch_first = batch_first def forward(self, x): if len(x.size()) <= 2: ...
_____no_output_____
Apache-2.0
pose_classification/pose_classification_lstm.ipynb
julkar9/deep_learning_nano_degree
Train the model
import torch.optim as optim model = Combine() if train_on_gpu: model.cuda() criterion = nn.CrossEntropyLoss() optimizer = optim.SGD(model.parameters(), lr=0.01) # number of epochs to train the model n_epochs = 20 valid_loss_min = np.Inf # track change in validation loss for epoch in range(1, n_epochs+1): #...
_____no_output_____
Apache-2.0
pose_classification/pose_classification_lstm.ipynb
julkar9/deep_learning_nano_degree
--- Test you model
model.load_state_dict(torch.load('model_cifar.pt')) model import matplotlib.pyplot as plt from sklearn.metrics import confusion_matrix import seaborn as sn import pandas as pd # track test loss test_loss = 0.0 class_correct = list(0. for i in range(3)) class_total = list(0. for i in range(3)) y_pred = [] y_true = []...
_____no_output_____
Apache-2.0
pose_classification/pose_classification_lstm.ipynb
julkar9/deep_learning_nano_degree
To molsysmt.MolSys
from molsysmt.tools import openff_Topology #openff_Topology.to_molsysmt_MolSys(item)
_____no_output_____
MIT
docs/contents/tools/classes/openff_Topology/to_molsysmt_MolSys.ipynb
dprada/molsysmt
Forecast using Air Passenger DataHere the famous Air Passenger dataset is use to create on step ahead forecast models using recurrent neural networks. + LSTM cells take input of the (n_obs, n_xdims, n_time)+ Statefull networks require the entire sequence of data to be preprocessed+
import pandas as pd import numpy as np from matplotlib import pyplot as plt from sklearn.preprocessing import MinMaxScaler, RobustScaler from sklearn.metrics import r2_score, mean_squared_error from keras.models import Sequential from keras.layers import Dense from keras.layers import LSTM, Dropout, BatchNormalization,...
_____no_output_____
MIT
DeepLearning/ForecastingAirPassengersLSTM.ipynb
mdavis29/DataScience101
Data Pre Processing for Forecasting+ data is lag so that time x = time0 and y= time +1 (One Step ahead)+ in this example, x is used twice to simulate a multi dimension x input for forecasting+ X, and Y sides are scale between (0,1) ( we will reverse the scaling for calculating error metrics+ Y is scaled so that the lo...
n_obs = len(airPass['value'].values) n_ahead = 1 # in this case th n_time_steps = 12 # each observation will have 12 months of data n_obs_trimmed = int(n_obs/n_time_steps) n_xdims = 1 # created by hstacking the sequence to simumlate multi dimensional input n_train_obs = 9 n_outputs = 12 x = np.reshape(airPass['value']...
(n_years ie: obs), (n_xdims) , (time_steps ie months to consider) x_train: (9, 1, 12), y_train: (9, 12) x_test: (11, 1, 12), y_test: (11, 12)
MIT
DeepLearning/ForecastingAirPassengersLSTM.ipynb
mdavis29/DataScience101
ModelingKeras lstm with 12 cells is used, with 12 outputs (one for each month of the year)This forecasting system will forecast an entire year at a time. + Dropout is used to prevent over fitting+ one row of input to this model is essentually 12 months of passenger counts of shape (1, 1, 12)
from keras.callbacks import EarlyStopping esm = EarlyStopping(patience=4) # design network model = Sequential() model.add(LSTM(12, input_shape=(n_xdims, n_time_steps ),return_sequences=False, dropout=0.2, recurrent_dropout=0.2, stateful=False, batch_size=1)) model.add(Dense(n_outputs )) model.add(Act...
_________________________________________________________________ Layer (type) Output Shape Param # ================================================================= lstm_9 (LSTM) (1, 12) 1200 ________________________________________________________...
MIT
DeepLearning/ForecastingAirPassengersLSTM.ipynb
mdavis29/DataScience101
Peformance on Entire DatasetPeformance is check across the entire dataset using mean squared error and R2_scoreThe MaxMin scaler is reversed to get predictions back on the orignal scale
preds = scaler.inverse_transform(np.reshape(model.predict(X_test, batch_size=1), (-1, 1))).flatten() y_true = airPass['value'].values[n_time_steps:] val_df = pd.DataFrame({'preds': preds, 'y_true':y_true}) mse = round(mean_squared_error(y_true, preds), 3) r2 = round(r2_score(y_true, preds), 3) print('performance on ent...
performance on entire data sets mse: 997.776 r2: 0.925
MIT
DeepLearning/ForecastingAirPassengersLSTM.ipynb
mdavis29/DataScience101
Peformance on Test SetSince the last two years (24 timesteps) were held out as a test, we can test performance just on that portionThe MaxMin scaler is reversed to get predictions back on the orignal scale. This should show a small drop in performance.
y_true_test = airPass['value'].values[n_time_steps:][-24:] preds_test = preds[-24:] mse_test = round(mean_squared_error(y_true_test, preds_test), 3) r2_test = round(r2_score(y_true_test, preds_test), 3) print('performance on last two years only in the test set, mse: {} r2: {}'.format(mse_test, r2_test)) val_df.plot()
_____no_output_____
MIT
DeepLearning/ForecastingAirPassengersLSTM.ipynb
mdavis29/DataScience101
Pandas
import pandas as pd dataframe = pd.read_csv('../data/MobileRating.csv') dataframe.head() dataframe.tail(7) print(len(dataframe)) print(dataframe.shape) # Accessing individual row dataframe.loc[3] dataframe_short = dataframe[40:45] dataframe_short dataframe_thin = dataframe[['PhoneId', 'RAM', 'Processor_frequency', 'Hei...
_____no_output_____
MIT
code/DL002-Python Intermediate and Linear Algebra.ipynb
hemendrarajawat/DL-Basic-To-Advanced
Plotting Dataframes
import matplotlib.pyplot as plt import seaborn as sns sns.set() ax = sns.boxplot(x="Internal Memory", y="Weight", data=dataframe) ax = sns.pairplot(dataframe_thin.drop(['PhoneId'], axis=1), diag_kind='hist') ax = sns.pairplot(dataframe_thin.drop('PhoneId', axis=1), diag_kind='hist', hue='Sim1_4G') sns.reset_orig()
_____no_output_____
MIT
code/DL002-Python Intermediate and Linear Algebra.ipynb
hemendrarajawat/DL-Basic-To-Advanced
VectorsVector is a collection of coordinates a point has in a given space. Vector has both magnitude and direction.In geometery, a two or more dimension space is called a Euclidean space. A space in any finite no. of dimensions, in which points are designated by coordinates(one for each dimension) and the distance b/w...
import numpy as np import matplotlib.pyplot as plt plt.quiver(0,0,4,5, scale_units='xy', angles='xy', scale=1) plt.xlim(-10, 10) plt.ylim(-10, 10) plt.show() # Plot multiple vectors plt.quiver(0,0,4,5, scale_units='xy', angles='xy', scale=1, color='r') plt.quiver(0,0,-4,5, scale_units='xy', angles='xy', scale=1, color...
_____no_output_____
MIT
code/DL002-Python Intermediate and Linear Algebra.ipynb
hemendrarajawat/DL-Basic-To-Advanced
Vectors Addition and Substraction
# Addition of two vectors print(vectors[0] - vectors[1]) plot_vectors([vectors[0], vectors[1], vectors[0] + vectors[1]]) # Subtraction of two vectors print(vectors[0] - vectors[2]) plot_vectors([vectors[0], vectors[2], vectors[0] - vectors[2]])
[-3 2]
MIT
code/DL002-Python Intermediate and Linear Algebra.ipynb
hemendrarajawat/DL-Basic-To-Advanced
Vector Dot Product$\large{\vec{a}\cdot\vec{b} = |\vec{a}| |\vec{b}| \cos(\theta) = a_x b_x + a_y b_y} = a^T b$
print(vectors[0], vectors[2]) dot_product = np.dot(vectors[0], vectors[2]) print(dot_product)
[4 3] [7 1] 31
MIT
code/DL002-Python Intermediate and Linear Algebra.ipynb
hemendrarajawat/DL-Basic-To-Advanced
Projection of one vector(a) on another vector(b)$\large{a_b = |\vec{a}| \cos{\theta} = |\vec{a}| \frac{\vec{a} \cdot \vec{b}}{|\vec{a}| |\vec{b}|} = \frac{\vec{a} \cdot \vec{b}}{|\vec{b}|}}$$\large{ \vec{a_b} = a_b \hat{b} = a_b \frac{\vec{b}}{|\vec{b}|} }$
a = vectors[0] b = vectors[2] plot_vectors([a, b]) a_b = np.dot(a, b)/np.linalg.norm(b) print('Magnitude of projected vector:', a_b) vec_a_b = (a_b/np.linalg.norm(b))*b print('Projected vector:', vec_a_b) plot_vectors([a, b, vec_a_b]) # Another example a = vectors[1] b = vectors[2] plot_vectors([a, b]) a_b = np.d...
_____no_output_____
MIT
code/DL002-Python Intermediate and Linear Algebra.ipynb
hemendrarajawat/DL-Basic-To-Advanced
MatricesA matrix is a collection of vectors.
# Row matrix row_matrix = np.random.random((1, 4)) print(row_matrix) # Column matrix column_matrix = np.random.random((4, 1)) print(column_matrix)
[[0.50652656] [0.99386151] [0.6596067 ] [0.88428846]]
MIT
code/DL002-Python Intermediate and Linear Algebra.ipynb
hemendrarajawat/DL-Basic-To-Advanced
Multiplying a matrix with a vectorThe vector gets transformed into a new vector(it strays from its path).
matrix = np.asarray([[1, 2], [2, 4]]) vector = np.asarray([3, 1]).reshape(-1, 1) # plot_vectors([vector]) print(matrix) print(vector) new_vector = np.dot(matrix, vector) print(new_vector) plot_vectors([vector, new_vector])
[[1 2] [2 4]] [[3] [1]] [[ 5] [10]]
MIT
code/DL002-Python Intermediate and Linear Algebra.ipynb
hemendrarajawat/DL-Basic-To-Advanced
Matrix Addition and Substraction
matrix_1 = np.asarray([ [1, 0, 3], [3, 1, 1], [0, 2, 5] ]) matrix_2 = np.asarray([ [0, 1, 2], [3, 0, 5], [1, 2, 1] ]) print(matrix_1 + matrix_2) print(matrix_1 - matrix_2)
[[ 1 -1 1] [ 0 1 -4] [-1 0 4]]
MIT
code/DL002-Python Intermediate and Linear Algebra.ipynb
hemendrarajawat/DL-Basic-To-Advanced
Matrix Multiplication
print(np.dot(matrix_1, matrix_2))
[[ 3 7 5] [ 4 5 12] [11 10 15]]
MIT
code/DL002-Python Intermediate and Linear Algebra.ipynb
hemendrarajawat/DL-Basic-To-Advanced
We are working together on this via vscode live share and are talking over zoom. In terms of sharing the file we have a github repository set up. We met three times to work in total.
import pandas as pd import bs4 from bs4 import BeautifulSoup import requests from datetime import datetime as dt import numpy as np import re #2 url = "https://www.spaceweatherlive.com/en/solar-activity/top-50-solar-flares" webpage = requests.get(url) print(webpage) #response 403, this means that the webserver refused ...
_____no_output_____
MIT
_projects/project1.ipynb
M-Sender/cmps3160
We matched the rows by comparing their start time and end time. If both rows' start times were within three hours of each other, they would get a one point increase in their match rank - and same goes for end times. This means that the maximum possible match rank is 2. The NASA dataframe was sorted by importance in dec...
%matplotlib inline import matplotlib.pyplot as plt # Give each flare an overall rank matchable["overall_rank"] = list(range(1,36)) new_speed = matchable["speed"] / 9 matchable.plot.scatter(x='start_datetime', y='start_frequency', s=new_speed,title="Top 50 Solar Flares, size=speed") #Graph below has the top 50 solar f...
_____no_output_____
MIT
_projects/project1.ipynb
M-Sender/cmps3160
Lambda notebook demo v. 1.0.1 Author: Kyle RawlinsThis notebook provides a demo of the core capabilities of the lambda notebook, aimed at linguists who already have training in semantics (but not necessarily implemented semantics).Last updated Dec 2018. Version history: * 0.5: first version * 0.6: updated to work with...
reload_lamb() from lamb.types import TypeMismatch, type_e, type_t, type_property from lamb.meta import TypedTerm, TypedExpr, LFun, CustomTerm from IPython.display import display # Just some basic configuration meta.constants_use_custom(False) lang.bracket_setting = lang.BRACKET_FANCY lamb.display.default(style=lamb.dis...
_____no_output_____
BSD-3-Clause
notebooks/Lambda Notebook Demo.ipynb
poetaster-org/lambda-notebook
First pitchHave you ever wanted to type something like this in, and have it actually do something?
%%lamb ||every|| = λ f_<e,t> : λ g_<e,t> : Forall x_e : f(x) >> g(x) ||student|| = L x_e : Student(x) ||danced|| = L x_e : Danced(x) r = ((every * student) * danced) r r.tree()
_____no_output_____
BSD-3-Clause
notebooks/Lambda Notebook Demo.ipynb
poetaster-org/lambda-notebook
Two problems in formal semantics 1. Type-driven computation could be a lot easier to visualize and check. (Q: could it be made too easy?)2. Grammar fragments as in Montague Grammar: good idea in principle, hard to use in practice. * A **fragment** is a *complete* formalization of *sublanguage* consisting of the *key...
meta.pmw_test1 meta.pmw_test1._repr_latex_()
_____no_output_____
BSD-3-Clause
notebooks/Lambda Notebook Demo.ipynb
poetaster-org/lambda-notebook
&nbsp; Part 2: a typed metalanguage The **metalanguage** infrastructure is a set of classes that implement the building blocks of logical expressions, lambda terms, and various combinations combinations. This rests on an implementation of a **type system** that matches what semanticists tend to assume.Starting point (...
%%lamb reset x = x_e # define x to have this type x.type
_____no_output_____
BSD-3-Clause
notebooks/Lambda Notebook Demo.ipynb
poetaster-org/lambda-notebook
This next cell defines some variables whose values are more complex object -- in fact, functions in the typed lambda calculus.
%%lamb test1 = L p_t : L x_e : P(x) & p # based on a Partee et al example test1b = L x_e : P(x) & Q(x) t2 = Q(x_e)
_____no_output_____
BSD-3-Clause
notebooks/Lambda Notebook Demo.ipynb
poetaster-org/lambda-notebook
These are now registered as variables in the python namespace and can be manipulated directly. A typed lambda calculus is fully implemented with all that that entails -- e.g. the value of `test1` includes the whole syntactic structure of the formula, its type, etc. and can be used in constructing new formulas. The fo...
test1(t2) test1(t2).reduce() %%lamb catf = L x_e: Cat(x) dogf = λx: Dog(x_e) (catf(x)).type catf.type
_____no_output_____
BSD-3-Clause
notebooks/Lambda Notebook Demo.ipynb
poetaster-org/lambda-notebook
Type checking of course is a part of all this. If the types don't match, the computation will throw a `TypeMismatch` exception. The following cell uses python syntax to catch and print such errors.
result = None try: result = test1(x) # function is type <t<et>> so will trigger a type mismatch. This is a python exception so adds all sorts of extraneous stuff, but look to the bottom except TypeMismatch as e: result = e result
_____no_output_____
BSD-3-Clause
notebooks/Lambda Notebook Demo.ipynb
poetaster-org/lambda-notebook
A more complex expression:
%%lamb p2 = (Cat_<e,t>(x_e) & p_t) >> (Exists y: Dog_<e,t>(y_e))
_____no_output_____
BSD-3-Clause
notebooks/Lambda Notebook Demo.ipynb
poetaster-org/lambda-notebook
What is going on behind the scenes? The objects manipulated are recursively structured python objects of class TypedExpr.Class _TypedExpr_: parent class for typed expressions. Key subclasses:* BinaryOpExpr: parent class for things like conjunction.* TypedTerm: variables, constants of arbitrary type* BindingOp: operat...
%%lamb x = x_e # use cell magic x = te("x_e") # use factory function to parse string x x = meta.TypedTerm("x", types.type_e) # use object constructer x
_____no_output_____
BSD-3-Clause
notebooks/Lambda Notebook Demo.ipynb
poetaster-org/lambda-notebook
Various convenience python operators are overloaded, including functional calls. Here is an example repeated from earlier in two forms:
%%lamb p2 = (Cat_<e,t>(x_e) & p_t) >> (Exists y: Dog_<e,t>(y_e)) p2 = (te("Cat_<e,t>(x)") & te("p_t")) >> te("(Exists y: Dog_<e,t>(y_e))") p2
_____no_output_____
BSD-3-Clause
notebooks/Lambda Notebook Demo.ipynb
poetaster-org/lambda-notebook
Let's examine in detail what happens when a function and argument combine.
catf = meta.LFun(types.type_e, te("Cat(x_e)"), "x") catf catf(te("y_e"))
_____no_output_____
BSD-3-Clause
notebooks/Lambda Notebook Demo.ipynb
poetaster-org/lambda-notebook
Building a function-argument expression builds a complex, unreduced expression. This can be explicitly reduced (note that the `reduce_all()` function would be used to apply reduction recursively):
catf(te("y_e")).reduce() (catf(te("y_e")).reduce()).derivation
_____no_output_____
BSD-3-Clause
notebooks/Lambda Notebook Demo.ipynb
poetaster-org/lambda-notebook
The metalanguage supports some basic type inference. Type inference happens already on combination of a function and argument into an unreduced expression, not on beta-reduction.
%lamb ttest = L x_X : P_<?,t>(x) # type <?,t> %lamb tvar = y_t ttest(tvar)
_____no_output_____
BSD-3-Clause
notebooks/Lambda Notebook Demo.ipynb
poetaster-org/lambda-notebook
&nbsp; Part 3: composition systems for an object language On top of the metalanguage are '**composition systems**' for modeling (step-by-step) semantic composition in an object language such as English. This is the part of the lambda notebook that tracks and manipulates mappings between object language elements (words...
# none of this is strictly necessary, the built-in library already provides effectively this system. fa = lang.BinaryCompositionOp("FA", lang.fa_fun, reduce=True) pm = lang.BinaryCompositionOp("PM", lang.pm_fun, commutative=False, reduce=True) pa = lang.BinaryCompositionOp("PA", lang.pa_fun, allow_none=True) demo_hk_sy...
_____no_output_____
BSD-3-Clause
notebooks/Lambda Notebook Demo.ipynb
poetaster-org/lambda-notebook
Expressing denotations is done in a `%%lamb` cell, and almost always begins with lexical items. The following cell defines several lexical items that will be familiar from introductory exercises in the Heim & Kratzer 1998 textbook "Semantics in Generative Grammar". These definitions produce items that are subclasses ...
%%lamb ||cat|| = L x_e: Cat(x) ||gray|| = L x_e: Gray(x) ||john|| = John_e ||julius|| = Julius_e ||inP|| = L x_e : L y_e : In(y, x) # `in` is a reserved word in python ||texas|| = Texas_e ||isV|| = L p_<e,t> : p # `is` is a reserved word in python
_____no_output_____
BSD-3-Clause
notebooks/Lambda Notebook Demo.ipynb
poetaster-org/lambda-notebook
In the purely type-driven mode, composition is triggered by using the '`*`' operator on a `Composable`. This searches over the available composition operations in the system to see if any results can be had. `inP` and `texas` above should be able to compose using the FA rule:
inP * texas
_____no_output_____
BSD-3-Clause
notebooks/Lambda Notebook Demo.ipynb
poetaster-org/lambda-notebook
On the other hand `isV` is looking for a property, so we shouldn't expect succesful composition. Below this I have given a complete sentence and shown some introspection on that composition result.
julius * isV # will fail due to type mismatches sentence1 = julius * (isV * (inP * texas)) sentence1 sentence1.trace()
_____no_output_____
BSD-3-Clause
notebooks/Lambda Notebook Demo.ipynb
poetaster-org/lambda-notebook
Composition will find all possible paths (beware of combinatorial explosion). I have temporarily disabled the fact that standard PM is symmetric/commutative (because of conjunction), to illustrate a case with multiple composition paths:
gray * cat gray * (cat * (inP * texas)) a = lang.Item("a", isV.content) # identity function for copula as well isV * (a * (gray * cat * (inP * texas))) np = ((gray * cat) * (inP * texas)) vp = (isV * (a * np)) sentence2 = julius * vp sentence2 sentence1.results[0] sentence1.results[0].tree() sentence2.results[0].tree()
_____no_output_____
BSD-3-Clause
notebooks/Lambda Notebook Demo.ipynb
poetaster-org/lambda-notebook
One of the infamous exercise examples from Heim and Kratzer (names different): (1) Julius is a gray cat in Texas fond of John. First let's get rid of all the extra readings, to keep this simple.
demo_hk_system.get_rule("PM").commutative = True fond = lang.Item("fond", "L x_e : L y_e : Fond(y)(x)") ofP = lang.Item("of", "L x_e : x") sentence3 = julius * (isV * (a * (((gray * cat) * (inP * texas)) * (fond * (ofP * john))))) sentence3 sentence3.tree()
_____no_output_____
BSD-3-Clause
notebooks/Lambda Notebook Demo.ipynb
poetaster-org/lambda-notebook
The _Composite_ class subclasses _nltk.Tree_, and so supports the things that class does. E.g. []-based paths:
parse_tree3 = sentence3.results[0] parse_tree3[0][1][1].tree()
_____no_output_____
BSD-3-Clause
notebooks/Lambda Notebook Demo.ipynb
poetaster-org/lambda-notebook
There is support for traces and indexed pronouns, using the PA rule. (The implementation may not be what you expect.)
binder = lang.Binder(23) binder2 = lang.Binder(5) t = lang.Trace(23, types.type_e) t2 = lang.Trace(5) display(t, t2, binder) ((t * gray)) b1 = (binder * (binder2 * (t * (inP * t2)))) b2 = (binder2 * (binder * (t * (inP * t2)))) display(b1, b2) b1.trace() b1.results[0].tree()
_____no_output_____
BSD-3-Clause
notebooks/Lambda Notebook Demo.ipynb
poetaster-org/lambda-notebook
Composition in tree structuresSome in-progress work: implementing tree-based computation, and top-down/deferred computation* using nltk Tree objects.* system for deferred / uncertain types -- basic inference over unknown types* arbitrary order of composition expansion. (Of course, some orders will be far less efficie...
reload_lamb() lang.set_system(lang.hk3_system) %%lamb ||gray|| = L x_e : Gray_<e,t>(x) ||cat|| = L x_e : Cat_<e,t>(x) t2 = Tree("S", ["NP", "VP"]) t2 t2 = Tree("S", ["NP", "VP"]) r2 = lang.hk3_system.compose(t2) r2.tree() r2.paths() Tree = lamb.utils.get_tree_class() t = Tree("NP", ["gray", Tree("N", ["cat"])]) t t2 = ...
_____no_output_____
BSD-3-Clause
notebooks/Lambda Notebook Demo.ipynb
poetaster-org/lambda-notebook
Algorithms 1: Do Something!Today's exercise is to make a piece of code that completes a useful task, but write it as generalized as possible to be reusable for other people (including Future You)!
%matplotlib inline import numpy as np import pandas as pd import matplotlib.pyplot as plt
_____no_output_____
MIT
lab2/lab2-Howard.ipynb
erinleighh/WWU-seminar-2018
DocumentationA "Docstring" is required for every function you write. Otherwise you will forget what it does and how it does it!One very common docstring format is the "[NumPy/SciPy](https://github.com/numpy/numpy/blob/master/doc/HOWTO_DOCUMENT.rst.txt)" standard:Below is a working function with a valid docstring as an...
def MyFunc(arg1, arg2, kwarg1=5.0): ''' This is a function to calculate the number of quatloos required to reverse the polarity of a neutron flow. Parameters ---------- arg1 : float How many bleeps per blorp arg2 : float The foo/bar parameter kwarg1 : float, optional...
273.0
MIT
lab2/lab2-Howard.ipynb
erinleighh/WWU-seminar-2018
Today's AlgorithmHere's the goal:**Which constellation is a given point in?**This is where you could find the detailed constellation boundary lines data:http://vizier.cfa.harvard.edu/viz-bin/Cat?cat=VI%2F49You could use this data and do the full "Ray Casting" approach, or even cheat using matpltlib functions!http://st...
# This is how to read in the coordinates and constellation names using Pandas # (this is a cleaned up version of Table 1 from Roman (1987) I prepared for you!) df = pd.read_csv('data/data.csv') df # Determine which constellation a given coordinate is in. def howard_constellation(ra, dec): ''' This is a functi...
_____no_output_____
MIT
lab2/lab2-Howard.ipynb
erinleighh/WWU-seminar-2018
#Join Data Practice #These are the top 10 most frequently ordered products. How many times was each ordered? #Banana #Bag of Organic Bananas #Organic Strawberries #Organic Baby Spinach #Organic Hass Avocado #Organic Avocado #Large Lemon #Strawberries #Limes #Organic Whole Milk #First, write down which columns you nee...
_____no_output_____
MIT
Join_and_Shape_Data.ipynb
kvinne-anc/Data-Science-Notebooks
Day 20 - Trench Maphttps://adventofcode.com/2021/day/20
from pathlib import Path INPUTS = Path("input.txt").read_text().strip().split("\n") ENHANCER = INPUTS[0] IMAGE = INPUTS[2:] def section_to_decimal(section: str) -> int: output = ''.join('1' if x == '#' else '0' for x in section) return int(output, base=2) assert section_to_decimal(section='...#...#.') == 34...
_____no_output_____
MIT
2021/day20/main.ipynb
GriceTurrble/advent-of-code-2020-answers
I had some trouble at the next stage with AoC site telling me my count was off, despite everything seeming to work correctly. What I didn't account for was that the enhancement of a pixel surrounded by all dark pixels results in index `0`, and index 0 of my enhancer was a *light* pixel. This meant that every dark pixel...
pass1 = enhance_image(original=IMAGE, enhancer=ENHANCER) # As noted above, the second pass has to use the first pixel in the ENHANCER as a padder # in order to get back the correct image. pass2 = enhance_image(original=pass1, enhancer=ENHANCER, padder=ENHANCER[0])
_____no_output_____
MIT
2021/day20/main.ipynb
GriceTurrble/advent-of-code-2020-answers
Once we had a final image (in `pass2` above), we have to count the light pixels. This was a simple matter of flattening and summing all instances of `` in the final list of strings.I could have simplified ever so slightly had I converted the pixels to `1`s and `0`s first, but where's the fun in that?
light_pixels = sum([sum([1 for y in x if y == '#']) for x in pass2]) print(f"Number of light pixels: {light_pixels}")
Number of light pixels: 5057
MIT
2021/day20/main.ipynb
GriceTurrble/advent-of-code-2020-answers
Part 2Running the same algorithm 50x isn't much of a deal compared to running it 2x. We just need to be sure to pull the correct padding character on even-numbered iterations, so we have the `padder` line flipping on the result of `i % 2` (if 1, it's `True`, meaning `i == 1` and `3`, which are indices `2` and `4` etc....
image = IMAGE iterations = 50 for i in range(iterations): padder = ENHANCER[0] if i % 2 else "." image = enhance_image(original=image, enhancer=ENHANCER, padder=padder) light_pixels = sum([sum([1 for y in x if y == '#']) for x in image]) print(f"Number of light pixels: {light_pixels}")
Number of light pixels: 18502
MIT
2021/day20/main.ipynb
GriceTurrble/advent-of-code-2020-answers
Error Mitigation using noise-estimation circuit
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, Aer, transpile, IBMQ from qiskit.circuit import Gate from qiskit.tools.visualization import plot_histogram from typing import Union import numpy as np import math import matplotlib.pyplot as plt qr = QuantumRegister(size = 6, name = 'qr') cr = Class...
_____no_output_____
Apache-2.0
QHack_Project.ipynb
Dran-Z/QHack2022-OpenHackerthon
generate mock SEDs using the `provabgs` pipelineThese SEDs will be used to construct BGS-like spectra and DESI-like photometry, which will be used for P1 and S1 mock challenge tests
import os import numpy as np # --- plotting --- import corner as DFM import matplotlib as mpl import matplotlib.pyplot as plt #if 'NERSC_HOST' not in os.environ.keys(): # mpl.rcParams['text.usetex'] = True mpl.rcParams['font.family'] = 'serif' mpl.rcParams['axes.linewidth'] = 1.5 mpl.rcParams['axes.xmargin'] = 1 m...
_____no_output_____
MIT
nb/mocha_provabgs_mocks.ipynb
changhoonhahn/GQP_mock_challenge
sample $\theta_{\rm obs}$ from prior
# direcotyr on nersc #dat_dir = '/global/cscratch1/sd/chahah/gqp_mc/mini_mocha/provabgs_mocks/' # local direcotry dat_dir = '/Users/chahah/data/gqp_mc/mini_mocha/provabgs_mocks/' theta_obs = np.load(os.path.join(dat_dir, 'provabgs_mock.theta.npy')) z_obs = 0.2 m_nmf = Models.NMF(burst=True, emulator=False) wave_full = ...
_____no_output_____
MIT
nb/mocha_provabgs_mocks.ipynb
changhoonhahn/GQP_mock_challenge
save to file
np.save(os.path.join(dat_dir, 'provabgs_mock.wave_full.npy'), np.array(wave_full)) np.save(os.path.join(dat_dir, 'provabgs_mock.flux_full.npy'), np.array(flux_full)) np.save(os.path.join(dat_dir, 'provabgs_mock.wave_obs.npy'), wave_obs) np.save(os.path.join(dat_dir, 'provabgs_mock.flux_obs.npy'), np.array(flux_obs))
_____no_output_____
MIT
nb/mocha_provabgs_mocks.ipynb
changhoonhahn/GQP_mock_challenge
Load the current s&p 500 ticker list, we will only be trading on these stocks
tickers = open('s&p500_tickers.dat', 'r').read().split('\n') print(tickers)
_____no_output_____
Apache-2.0
Pavol/ray_test.ipynb
AidanMar/reinforcement_learning
Data start and end dates and initialise ticker dataframe dictionary
one_day = pd.Timedelta(days=1) i = 0 cur_day = pd.to_datetime('1992-06-15', format=r'%Y-%m-%d') #pd.to_datetime('1992-06-15') end_day = pd.to_datetime('2020-01-01', format=r'%Y-%m-%d') end_df = pd.read_csv('equity_data/' + (end_day - one_day).strftime(r'%Y%m%d') + '.csv') ticker_df = end_df.loc[end_df.symbol.isin(tic...
_____no_output_____
Apache-2.0
Pavol/ray_test.ipynb
AidanMar/reinforcement_learning
For all dates between start and end range, load the day into ticker dict with the key being ticker and dataframe indexed by day
df_columns = pd.read_csv('equity_data/' + cur_day.strftime(r'%Y%m%d') + '.csv').columns ticker_dfs = { ticker : pd.DataFrame(index=pd.date_range(cur_day, end_day - one_day, freq='D'), columns=df_columns) for ticker in tickers } save_df = False if save_df: pbar = tqdm(total=(end_day - cur_day).days) while (cur_...
_____no_output_____
Apache-2.0
Pavol/ray_test.ipynb
AidanMar/reinforcement_learning
Web Scraping
#Importing the essential libraries #Beautiful Soup is a Python library for pulling data out of HTML and XML files #The Natural Language Toolkit import requests import nltk nltk.download('wordnet') from nltk.stem import WordNetLemmatizer from nltk.sentiment.vader import SentimentIntensityAnalyzer from bs4 import Beaut...
_____no_output_____
MIT
GFL Environmental Text Analysis.ipynb
SayantiDutta2000/Financial-Analysis
LemmatizationLemmatization is the algorithmic process of finding the lemma of a word depending on their meaning. Lemmatization usually refers to the morphological analysis of words, which aims to remove inflectional endings.
from nltk.stem import WordNetLemmatizer wn = WordNetLemmatizer() lem_words=[] for word in words_new: word=wn.lemmatize(word) lem_words.append(word) len(lem_words) same=0 diff=0 for i in range(0,416): if(lem_words[i]==words_new[i]): same=same+1 elif(lem_words[i]!=words_new[i]): diff=di...
_____no_output_____
MIT
GFL Environmental Text Analysis.ipynb
SayantiDutta2000/Financial-Analysis
Все тоже самое, что и в alfabattle_1_parq2, только вместо event_name идет event_category
import numpy as np import pandas as pd import gc import os import re df = pd.read_csv("../input/alfabattle1/alfabattle2_abattle_train_target.csv") parq0 = pd.read_parquet('../your_parqet0.parquet') parq0['timestamp'] = pd.to_datetime(parq0['timestamp']) parq0 = parq0.sort_values(by=['client', 'timestamp']) parq0 = parq...
_____no_output_____
MIT
1.data preprocessing/.ipynb_checkpoints/alfabattle_1_parq3-checkpoint.ipynb
Aindstorm/alfabattle2_1stproblem
COMP 135 day03: Training Linear Regression Models via Analytical Formulas Objectives* Learn how to apply the standard "least squares" formulas for 'training' linear regression in 1 dimension* Learn how to apply the standard "least squares" formulas for 'training' linear regression in many dimensions (with matrix math...
import numpy as np import pandas as pd import sklearn # import plotting libraries import matplotlib import matplotlib.pyplot as plt %matplotlib inline plt.style.use('seaborn') # pretty matplotlib plots import seaborn as sns sns.set('notebook', style='whitegrid', font_scale=1.25) true_slope = 2.345 N = 7 x_N = np.lin...
_____no_output_____
MIT
labs/day03_LinearRegression_ExactFormulasForModelTraining.ipynb
ypark12/comp135-20f-assignments
Part 1: Simplest Linear Regression with 1-dim features and only slopeEstimate slope only. We assume the bias/intercept is fixed to zero. Exact formula to estimate "least squares" solution w in 1D:$$w^* = \frac{\sum_n x_n y_n}{\sum_n x_n^2} = \frac{ \mathbf{x}^T \mathbf{y} }{ \mathbf{x}^T \mathbf{x} }$$ Estimate w u...
w_est = np.inner(x_N, y_N) / np.inner(x_N, x_N) print(w_est)
2.3449999999999998
MIT
labs/day03_LinearRegression_ExactFormulasForModelTraining.ipynb
ypark12/comp135-20f-assignments
Estimate w using the noisy y values
w_est = np.inner(x_N, ynoise_N) / np.inner(x_N, x_N) print(w_est)
2.7606807490017067
MIT
labs/day03_LinearRegression_ExactFormulasForModelTraining.ipynb
ypark12/comp135-20f-assignments
Exercise 1a: What if all examples had $x_n = 0$?What would happen? What does the algebra of the formula suggest? Exercise 1b: Can you show graphically that this minimizes *mean squared error*?
def predict_1d(x_N, w): # TODO fix me return 0.0 def calc_mean_squared_error(yhat_N, y_N): # TODO fix me return 0.0 G = 30 w_candidates_G = np.linspace(-3, 6, G) error_G = np.zeros(G) for gg, w in enumerate(w_candidates_G): yhat_N = predict_1d(x_N, w) error_G[gg] = calc_mean_squared_error(yhat_N...
_____no_output_____
MIT
labs/day03_LinearRegression_ExactFormulasForModelTraining.ipynb
ypark12/comp135-20f-assignments
Exercise 1c: What about *mean absolute error*?Does the least-squares estimate of $w$ minimize mean absolute error for this example?
def calc_mean_abs_error(yhat_N, y_N): # TODO fixme return 0.0 G = 100 w_candidates_G = np.linspace(1, 4, G) error_G = np.zeros(G) for gg, w in enumerate(w_candidates_G): yhat_N = predict_1d(x_N, w) error_G[gg] = calc_mean_abs_error(yhat_N, ynoise_N) plt.plot(w_candidates_G, error_G, 'r.-', label='o...
_____no_output_____
MIT
labs/day03_LinearRegression_ExactFormulasForModelTraining.ipynb
ypark12/comp135-20f-assignments
Part 2: Simpler Linear Regression with slope and biasGoal: estimate slope $w$ and bias $b$ Then the best estimates of the slope and intercept are given by:$$w^* = \frac{ \sum_{n=1}^N (x_n - \bar{x}) (y_n - \bar{y}) }{\sum_{n=1}^N (x_n - \bar{x})^2 }$$and$$b^* = \bar{y} - w^* \bar{x}$$ Using the 'true', noise-free y ...
xbar = np.mean(x_N) ybar = np.mean(y_N) w_est = np.inner(x_N - xbar, y_N - ybar) / np.inner(x_N - xbar, x_N - xbar) print(w_est) b_est = ybar - w_est * xbar print(b_est)
2.3449999999999998 -1.7938032012157886e-16
MIT
labs/day03_LinearRegression_ExactFormulasForModelTraining.ipynb
ypark12/comp135-20f-assignments
Using the noisy y value
xbar = np.mean(x_N) ybar = np.mean(ynoise_N) w_est = np.inner(x_N - xbar, ynoise_N - ybar) / np.inner(x_N - xbar, x_N - xbar) b_est = ybar - w_est * xbar print("Estimated slope: " + str(w_est)) print("Estimated bias: " + str(b_est))
Estimated slope: 2.7606807490017067 Estimated bias: -0.4138756764186623
MIT
labs/day03_LinearRegression_ExactFormulasForModelTraining.ipynb
ypark12/comp135-20f-assignments
Part 3: General case of Linear RegressionGoal:* estimate the vector $w \in \mathbb{R}^F$ of weight coefficients* estimate the bias scalar $b$ (aka intercept) Given a dataset of $N$ examples and $F$ feature dimensions, where* $\tilde{\mathbf{X}}$ is an $N \times F +1$ matrix of feature vectors, where we'll assume the ...
x_N1 = x_N[:,np.newaxis] xtilde_N2 = np.hstack([x_N1, np.ones((x_N.size, 1))]) print(xtilde_N2)
[[-1. 1. ] [-0.66666667 1. ] [-0.33333333 1. ] [ 0. 1. ] [ 0.33333333 1. ] [ 0.66666667 1. ] [ 1. 1. ]]
MIT
labs/day03_LinearRegression_ExactFormulasForModelTraining.ipynb
ypark12/comp135-20f-assignments
Next, print out the $y$ array
print(ynoise_N)
[-2.56819745 -2.68541972 -1.85631918 -0.39928063 0.62995686 1.74174534 2.24038504]
MIT
labs/day03_LinearRegression_ExactFormulasForModelTraining.ipynb
ypark12/comp135-20f-assignments
Next, lets compute the matrix product $\tilde{X}^T \tilde{X}$, which is a $2 \times 2$ matrix
xTx_22 = np.dot(xtilde_N2.T, xtilde_N2) print(xTx_22)
[[ 3.11111111e+00 -2.22044605e-16] [-2.22044605e-16 7.00000000e+00]]
MIT
labs/day03_LinearRegression_ExactFormulasForModelTraining.ipynb
ypark12/comp135-20f-assignments
Next, lets compute the INVERSE of $\tilde{X}^T \tilde{X}$, which is again a $2 \times 2$ matrix
inv_xTx_22 = np.linalg.inv(xTx_22) # compute the inverse! print(inv_xTx_22)
[[3.21428571e-01 1.01959257e-17] [1.01959257e-17 1.42857143e-01]]
MIT
labs/day03_LinearRegression_ExactFormulasForModelTraining.ipynb
ypark12/comp135-20f-assignments
Next, let's compute the optimal $\theta$ vector according to our formula above
theta_G = np.dot(inv_xTx_22, np.dot(xtilde_N2.T, ynoise_N[:,np.newaxis])) # compute theta vector print(theta_G) print("Estimated slope: " + str(theta_G[0])) print("Estimated bias: " + str(theta_G[1]))
Estimated slope: [2.76068075] Estimated bias: [-0.41387568]
MIT
labs/day03_LinearRegression_ExactFormulasForModelTraining.ipynb
ypark12/comp135-20f-assignments
We should get the SAME results as in our simpler LR case in Part 2. So this formula for the general case looks super easy, right? Not so fast...Let's take a minute and review just what the heck an *inverse* is, before we just blindly implement this formula... Part 4: Linear Algebra Review: What is the inverse of a ma...
# Define a square matrix with shape(3,3) A = np.diag(np.asarray([1., -2., 3.])) print(A) # Compute its inverse invA = np.linalg.inv(A) print(invA) np.dot(A, invA) # should equal identity
_____no_output_____
MIT
labs/day03_LinearRegression_ExactFormulasForModelTraining.ipynb
ypark12/comp135-20f-assignments
Remember, in 1 dimensions, the inverse of $a$ is just $1/a$, since $a \cdot \frac{1}{a} = 1.0$
A = np.asarray([[2]]) print(A) invA = np.linalg.inv(A) print(invA)
[[0.5]]
MIT
labs/day03_LinearRegression_ExactFormulasForModelTraining.ipynb
ypark12/comp135-20f-assignments
Does the inverse always exist?No! Remember:* Even when $D=1$, if $A=0$, then the inverse does not exist ($\frac{1}{A}$ is undefined)* When $D \geq 2$, there are *infinitely many* square matrices $A$ that do not have an inverse
# Example 1: A = np.asarray([[0, 0], [0, 1.337]]) print(A) try: np.linalg.inv(A) except Exception as e: print(str(type(e)) + ": " + str(e)) # Example 2: A = np.asarray([[3.4, 3.4], [3.4, 3.4]]) print(A) try: np.linalg.inv(A) except Exception as e: print(str(type(e)) + ": " + str(e)) # Example 3: A = np....
[[-1.2 4.7] [-2.4 9.4]] <class 'numpy.linalg.LinAlgError'>: Singular matrix
MIT
labs/day03_LinearRegression_ExactFormulasForModelTraining.ipynb
ypark12/comp135-20f-assignments
What do these examples have in common???The columns of $A$ are not linearly independent!In other words, $A$ is not invertible whenever we can exactly construct one column of $A$ by a linear combination of other columns$$A_{:,D} = c_1 A_{:,1} + c_2 A_{:,2} + \ldots c_{D-1} A_{:,D-1}$$where $c_1$, $c_2$, $\ldots c_{D-1}$...
# Look, here's the first column: A[:, 0] # And here's it being perfectly reconstructed by a scalar times the second column A[:, 1] * -1.2/4.7 # Example 3: A = np.asarray([[1.0, 2.0, -3.0], [2, 4, -6.0], [1.0, 1.0, 1.0]]) print(A) try: np.linalg.inv(A) except Exception as e: print(str(type(e)) + ": " + str(e))
[[ 1. 2. -3.] [ 2. 4. -6.] [ 1. 1. 1.]] <class 'numpy.linalg.LinAlgError'>: Singular matrix
MIT
labs/day03_LinearRegression_ExactFormulasForModelTraining.ipynb
ypark12/comp135-20f-assignments
Important result from linear algebra: Invertible Matrix TheoremGiven a specific matrix $A$, the following statements are either *all* true or *all* false:* $A$ has an inverse (e.g. a matrix $A^{-1}$ exists s.t. $A A^{-1} = I$)* All $D$ columns of $A$ are linearly independent* The columns of $A$ span the space $\mathbb...
# 3 indep rows of size 3. x_NF = np.random.randn(3, 3) xTx_FF = np.dot(x_NF.T, x_NF) np.linalg.inv(np.dot(x_NF.T, x_NF)) # First, verify the `inv` function computes *something* of the right shape inv_xTx_FF = np.linalg.inv(xTx_FF) print(inv_xTx_FF) # Next, verify the `inv` function result is ACTUALLY the inverse ans_...
[[ 1.00000000e+00 -4.33114505e-16 3.73409184e-16] [ 3.94146478e-16 1.00000000e+00 -4.54028728e-16] [ 1.59364741e-16 8.07877021e-16 1.00000000e+00]] is this close enough to identity matrix? True
MIT
labs/day03_LinearRegression_ExactFormulasForModelTraining.ipynb
ypark12/comp135-20f-assignments
A *bad* example, where `np.linalg.inv` may be unreliable
# Only 2 indep rows of size 3. should NOT be invertible # verify: determinant is close to zero x_NF = np.random.randn(2, 3) xTx_FF = np.dot(x_NF.T, x_NF) xTx_FF # First, verify the `inv` function computes *something* of the right shape inv_xTx_FF = np.linalg.inv(xT...
[[ 1.4520932 0.49807897 -0.24114104] [-0.20159063 -0.27703514 -1.15131685] [-1.53776313 -0.71804165 -0.59193815]] is this close enough to identity matrix? False
MIT
labs/day03_LinearRegression_ExactFormulasForModelTraining.ipynb
ypark12/comp135-20f-assignments
What just happened?We just asked for an inverse.NumPy gave us a result that WAS NOT AN INVERSE, but we received NO WARNINGS OR ERRORS!So what should we do? Avoid naively calling `np.linalg.inv` and trusting the result. A better thing to do is use `np.linalg.solve`, as this will be more *stable* (trustworthy). What `np...
true_w_F1 = np.asarray([1.0, 1.0])[:,np.newaxis] true_b = np.asarray([0.0]) x_NF = np.asarray([[1.0, 2.0], [1.0, 1.0]]) + np.random.randn(2,2) * 0.001 print(x_NF) y_N1 = np.dot(x_NF, true_w_F1) + true_b print(y_N1)
[[2.99948664] [1.9999558 ]]
MIT
labs/day03_LinearRegression_ExactFormulasForModelTraining.ipynb
ypark12/comp135-20f-assignments
Punchline: there should be INFINITELY many weights $w$ and bias values $b$ that can reconstruct our $y$ **perfectly**Question: Can various estimation strategies find such weights? Try out sklearn
import sklearn.linear_model lr = sklearn.linear_model.LinearRegression() lr.fit(x_NF, y_N1)
_____no_output_____
MIT
labs/day03_LinearRegression_ExactFormulasForModelTraining.ipynb
ypark12/comp135-20f-assignments
Print the estimated weights $w$ and intercept $b$
print(lr.coef_) print(lr.intercept_)
[[0.0013517 1.00134805]] [0.99740683]
MIT
labs/day03_LinearRegression_ExactFormulasForModelTraining.ipynb
ypark12/comp135-20f-assignments
Print the predicted values for $y$, alongside the *true* ones
print("Results for sklearn") print("Predicted y: " + str(np.squeeze(lr.predict(x_NF)))) print("True y: " + str(np.squeeze(y_N1)))
Results for sklearn Predicted y: [2.99948664 1.9999558 ] True y: [2.99948664 1.9999558 ]
MIT
labs/day03_LinearRegression_ExactFormulasForModelTraining.ipynb
ypark12/comp135-20f-assignments
Prep for our formulas: make the $\tilde{\mathbf{X}}$ arrayWill have shape $N \times (F+1)$Let's define $G = F+1$
xtilde_NG = np.hstack([x_NF, np.ones((2, 1))]) print(xtilde_NG) xTx_GG = np.dot(xtilde_NG.T, xtilde_NG)
_____no_output_____
MIT
labs/day03_LinearRegression_ExactFormulasForModelTraining.ipynb
ypark12/comp135-20f-assignments
Try out using our least-squares formula, as implemented with `np.linalg.inv`
inv_xTx_GG = np.linalg.inv(xTx_GG) theta_G1 = np.dot(inv_xTx_GG, np.dot(xtilde_NG.T, y_N1))
_____no_output_____
MIT
labs/day03_LinearRegression_ExactFormulasForModelTraining.ipynb
ypark12/comp135-20f-assignments
Best estimate of the weights and bias (after "unpacking" the vector $\theta$):
w_F = theta_G1[:-1, 0] b = theta_G1[-1] print(w_F) print(b) yhat_N1 = np.dot(xtilde_NG, theta_G1) print("Results for using naive np.linalg.inv") print("Predicted y: " + str(yhat_N1[:,0])) print("True y: " + str(y_N1[:,0]))
Results for using naive np.linalg.inv Predicted y: [1.99803269 0.99984927] True y: [2.99948664 1.9999558 ]
MIT
labs/day03_LinearRegression_ExactFormulasForModelTraining.ipynb
ypark12/comp135-20f-assignments
Expected result: you should see that predictions might be *quite far* from true y values! Try out using our formulas, as implemented with `np.linalg.solve`What should happen: We can find estimated parameters $w, b$ that perfectly predict the $y$
theta_G1 = np.linalg.solve(xTx_GG, np.dot(xtilde_NG.T, y_N1)) w_F = theta_G1[:-1,0] b = theta_G1[-1,0] print(w_F) print(b) yhat_N1 = np.dot(xtilde_NG, theta_G1) print("Results for using more stable formula implementation with np.linalg.solve") print("Predicted y: " + str(yhat_N1[:,0])) print("True y: " + str(y_N1[...
Results for using more stable formula implementation with np.linalg.solve Predicted y: [2.99948664 1.9999558 ] True y: [2.99948664 1.9999558 ]
MIT
labs/day03_LinearRegression_ExactFormulasForModelTraining.ipynb
ypark12/comp135-20f-assignments
Introduction to DebuggingIn this book, we want to explore _debugging_ - the art and science of fixing bugs in computer software. In particular, we want to explore techniques that _automatically_ answer questions like: Where is the bug? When does it occur? And how can we repair it? But before we start automating the de...
from bookutils import YouTubeVideo, quiz YouTubeVideo("bCHRCehDOq0")
_____no_output_____
MIT
Intro_Debugging.ipynb
doscac/ReducingCode
**Prerequisites*** The book is meant to be a standalone reference; however, a number of _great books on debugging_ are listed at the end,* Knowing a bit of _Python_ is helpful for understanding the code examples in the book. SynopsisTo [use the code provided in this chapter](Importing.ipynb), write```python>>> from de...
def remove_html_markup(s): tag = False out = "" for c in s: if c == '<': # start of markup tag = True elif c == '>': # end of markup tag = False elif not tag: out = out + c return out
_____no_output_____
MIT
Intro_Debugging.ipynb
doscac/ReducingCode
This function works, but not always. Before we start debugging things, let us first explore its code and how it works. Understanding Python ProgramsIf you're new to Python, you might first have to understand what the above code does. We very much recommend the [Python tutorial](https://docs.python.org/3/tutorial/) to...
remove_html_markup("Here's some <strong>strong argument</strong>.")
_____no_output_____
MIT
Intro_Debugging.ipynb
doscac/ReducingCode
Interacting with NotebooksIf you are reading this in the interactive notebook, you can try out `remove_html_markup()` with other values as well. Click on the above cells with the invocation of `remove_html_markup()` and change the value – say, to `remove_html_markup("foo")`. Press Shift+Enter (or click on the play s...
assert remove_html_markup("Here's some <strong>strong argument</strong>.") == \ "Here's some strong argument."
_____no_output_____
MIT
Intro_Debugging.ipynb
doscac/ReducingCode
If you change the code of `remove_html_markup()` such that the above assertion fails, you will have introduced a bug. Oops! A Bug! As nice and simple as `remove_html_markup()` is, it is buggy. Some HTML markup is not properly stripped away. Consider this HTML tag, which would render as an input field in a form:```html...
remove_html_markup('<input type="text" value="<your name>">')
_____no_output_____
MIT
Intro_Debugging.ipynb
doscac/ReducingCode
Every time we encounter a bug, this means that our earlier tests have failed. We thus need to introduce another test that documents not only how the bug came to be, but also the result we actually expected. The assertion we write now fails with an error message. (The `ExpectError` magic ensures we see the error message...
from ExpectError import ExpectError with ExpectError(): assert remove_html_markup('<input type="text" value="<your name>">') == ""
Traceback (most recent call last): File "<ipython-input-7-c7b482ebf524>", line 2, in <module> assert remove_html_markup('<input type="text" value="<your name>">') == "" AssertionError (expected)
MIT
Intro_Debugging.ipynb
doscac/ReducingCode
With this, we now have our task: _Fix the failure as above._ Visualizing CodeTo properly understand what is going on here, it helps drawing a diagram on how `remove_html_markup()` works. Technically, `remove_html_markup()` implements a _state machine_ with two states `tag` and `¬ tag`. We change between these states d...
from graphviz import Digraph, nohtml from IPython.display import display # ignore PASS = "✔" FAIL = "✘" PASS_COLOR = 'darkgreen' # '#006400' # darkgreen FAIL_COLOR = 'red4' # '#8B0000' # darkred STEP_COLOR = 'peachpuff' FONT_NAME = 'Raleway' # ignore def graph(comment="default"): return Digraph(name='', comment...
_____no_output_____
MIT
Intro_Debugging.ipynb
doscac/ReducingCode
You see that we start in the non-tag state (`¬ tag`). Here, for every character that is not `''` character. A First FixLet us now look at the above state machine, and process through our input:```html">``` So what you can see is: We are interpreting the `'>'` of `""` as the closing of the tag. However, this is a quote...
# ignore state_machine = graph() state_machine.node('Start') state_machine.edge('Start', '¬ quote\n¬ tag') state_machine.edge('¬ quote\n¬ tag', '¬ quote\n¬ tag', label="¬ '<'\nadd character") state_machine.edge('¬ quote\n¬ tag', '¬ quote\ntag', label="'<'") state_machine.edge('¬ quote\ntag', 'quote\n...
_____no_output_____
MIT
Intro_Debugging.ipynb
doscac/ReducingCode