markdown
stringlengths
0
37k
code
stringlengths
1
33.3k
path
stringlengths
8
215
repo_name
stringlengths
6
77
license
stringclasses
15 values
Retrieving training and test data The MNIST data set already contains both training and test data. There are 55,000 data points of training data, and 10,000 points of test data. Each MNIST data point has: 1. an image of a handwritten digit and 2. a corresponding label (a number 0-9 that identifies the image) We'll cal...
# Retrieve the training and test data trainX, trainY, testX, testY = mnist.load_data(one_hot=True) print(trainX.shape) print(trainY.shape)
intro-to-tflearn/TFLearn_Digit_Recognition.ipynb
abhi1509/deep-learning
mit
Visualize the training data Provided below is a function that will help you visualize the MNIST data. By passing in the index of a training example, the function show_digit will display that training image along with it's corresponding label in the title.
# Visualizing the data import matplotlib.pyplot as plt %matplotlib inline # Function for displaying a training image by it's index in the MNIST set def show_digit(index): label = trainY[index].argmax(axis=0) # Reshape 784 array into 28x28 image image = trainX[index].reshape([28,28]) plt.title('Training...
intro-to-tflearn/TFLearn_Digit_Recognition.ipynb
abhi1509/deep-learning
mit
Building the network TFLearn lets you build the network by defining the layers in that network. For this example, you'll define: The input layer, which tells the network the number of inputs it should expect for each piece of MNIST data. Hidden layers, which recognize patterns in data and connect the input to the ou...
# Define the neural network def build_model(): # This resets all parameters and variables, leave this here tf.reset_default_graph() #### Your code #### # Include the input layer, hidden layer(s), and set how you want to train the model #Input layer net = tflearn.input_data([None, 784])...
intro-to-tflearn/TFLearn_Digit_Recognition.ipynb
abhi1509/deep-learning
mit
Training the network Now that we've constructed the network, saved as the variable model, we can fit it to the data. Here we use the model.fit method. You pass in the training features trainX and the training targets trainY. Below I set validation_set=0.1 which reserves 10% of the data set as the validation set. You ca...
# Training model.fit(trainX, trainY, validation_set=0.1, show_metric=True, batch_size=100, n_epoch=20)
intro-to-tflearn/TFLearn_Digit_Recognition.ipynb
abhi1509/deep-learning
mit
Testing After you're satisified with the training output and accuracy, you can then run the network on the test data set to measure it's performance! Remember, only do this after you've done the training and are satisfied with the results. A good result will be higher than 95% accuracy. Some simple models have been kno...
# Compare the labels that our model predicts with the actual labels # Find the indices of the most confident prediction for each item. That tells us the predicted digit for that sample. predictions = np.array(model.predict(testX)).argmax(axis=1) # Calculate the accuracy, which is the percentage of times the predicate...
intro-to-tflearn/TFLearn_Digit_Recognition.ipynb
abhi1509/deep-learning
mit
Poisson Distribution Independent interval occurrences in an interval. Used for count-based distributions. $$ f(k;\lambda)=Pr(X = k)=\frac{\lambda^ke^{-k}}{k!} $$ Here, e is the Euler's number, k is the number of occurrences for which the probability is going to be determined, and lambda is the mean number of occurren...
from scipy.stats import bernoulli bernoulli.rvs(0.7, size=100)
_oldnotebooks/Inferential_Statistics.ipynb
eneskemalergin/OldBlog
mit
z-score Expresses the value of a distribution in std with respect to mean. $$ z = \frac{X - \mu}{\sigma} $$ Here, X is the value in the distribution, μ is the mean of the distribution, and σ is the standard deviation of the distribution. Example: A classroom has 60 students in it and they have just got their mathemat...
import numpy as np class_score = np.random.normal(50, 10, 60).round() plt.hist(class_score, 30, normed=True) # Number of breaks is 30 plt.show()
_oldnotebooks/Inferential_Statistics.ipynb
eneskemalergin/OldBlog
mit
The score of each student can be converted to a z-score using the following functions:
from scipy import stats stats.zscore(class_score)
_oldnotebooks/Inferential_Statistics.ipynb
eneskemalergin/OldBlog
mit
So, a student with a score of 60 out of 100 has a z-score of 1.334. To make more sense of the z-score, we'll use the standard normal table. This table helps in determining the probability of a score. We would like to know what the probability of getting a score above 60 would be. The standard normal table can help us i...
prob = 1 - stats.norm.cdf(1.334) prob
_oldnotebooks/Inferential_Statistics.ipynb
eneskemalergin/OldBlog
mit
The cdf function gives the probability of getting values up to the z-score of 1.334, and doing a minus one of it will give us the probability of getting a z-score, which is above it. In other words, 0.09 is the probability of getting marks above 60. Let's ask another question, "how many students made it to the top 20%...
stats.norm.ppf(0.80)
_oldnotebooks/Inferential_Statistics.ipynb
eneskemalergin/OldBlog
mit
The z-score for the preceding output that determines whether the top 20% marks are at 0.84 is as follows:
(0.84 * class_score.std()) + class_score.mean()
_oldnotebooks/Inferential_Statistics.ipynb
eneskemalergin/OldBlog
mit
We multiply the z-score with the standard deviation and then add the result with the mean of the distribution. This helps in converting the z-score to a value in the distribution. The 55.83 marks means that students who have marks more than this are in the top 20% of the distribution. The z-score is an essential concep...
zscore = ( 68 - class_score.mean() ) / class_score.std() zscore
_oldnotebooks/Inferential_Statistics.ipynb
eneskemalergin/OldBlog
mit
prob = 1 - stats.norm.cdf(zscore) prob
_oldnotebooks/Inferential_Statistics.ipynb
eneskemalergin/OldBlog
mit
One-tailed and two-tailed tests The example in the previous section was an instance of a one-tailed test where the null hypothesis is rejected or accepted based on one direction of the normal distribution. In a two-tailed test, both the tails of the null hypothesis are used to test the hypothesis. In a two-tailed test...
zscore = (53-50)/3.0 zscore prob = stats.norm.cdf(zscore) prob
_oldnotebooks/Inferential_Statistics.ipynb
eneskemalergin/OldBlog
mit
Type 1 and Type 2 errors Type 1 error is a type of error that occurs when there is a rejection of the null hypothesis when it is actually true. This kind of error is also called an error of the first kind and is equivalent to false positives. Let's understand this concept using an example. There is a new drug that is ...
height_data = np.array([ 186.0, 180.0, 195.0, 189.0, 191.0, 177.0, 161.0, 177.0, 192.0, 182.0, 185.0, 192.0, 173.0, 172.0, 191.0, 184.0, 193.0, 182.0, 190.0, 185.0, 181.0,188.0, 179.0, 188.0, 170.0, 179.0, ...
_oldnotebooks/Inferential_Statistics.ipynb
eneskemalergin/OldBlog
mit
So, the average height of a man from the sample is 183.4 cm. To determine the confidence interval, we'll now define the standard error of the mean. The standard error of the mean is the deviation of the sample mean from the population mean. It is defined using the following formula: $$ SE_{\overline{x}} = \frac{s}{\sqr...
stats.sem(height_data)
_oldnotebooks/Inferential_Statistics.ipynb
eneskemalergin/OldBlog
mit
So, there is a standard error of the mean of 1.38 cm. The lower and upper limit of the confidence interval can be determined by using the following formula: Upper/Lower limit = mean(height) + / - sigma * SEmean(x) For lower limit: 183.24 + (1.96 * 1.38) = 185.94 For...
average_height = [] for i in range(30): # Create a sample of 50 with mean 183 and standard deviation 10 sample50 = np.random.normal(183, 10, 50).round() # Add the mean on sample of 50 into average_height list average_height.append(sample50.mean()) # Plot it with 10 bars and normalization plt.hist(avera...
_oldnotebooks/Inferential_Statistics.ipynb
eneskemalergin/OldBlog
mit
You can observe that the mean ranges from 180 to 187 cm when we simulated the average height of 50 sample men, which was taken 30 times. Let's see what happens when we sample 1000 men and repeat the process 30 times:
average_height = [] for i in range(30): # Create a sample of 50 with mean 183 and standard deviation 10 sample1000 = np.random.normal(183, 10, 1000).round() average_height.append(sample1000.mean()) plt.hist(average_height, 10, normed=True) plt.show()
_oldnotebooks/Inferential_Statistics.ipynb
eneskemalergin/OldBlog
mit
As you can see, the height varies from 182.4 cm and to 183.5 cm. What does this mean? It means that as the sample size increases, the standard error of the mean decreases, which also means that the confidence interval becomes narrower, and we can tell with certainty the interval that the population mean would lie on. ...
mpg = [21.0, 21.0, 22.8, 21.4, 18.7, 18.1, 14.3, 24.4, 22.8, 19.2, 17.8, 16.4, 17.3, 15.2, 10.4, 10.4, 14.7, 32.4, 30.4, 33.9, 21.5, 15.5, 15.2, 13.3, 19.2, 27.3, 26.0, 30.4, 15.8,19.7, 15.0, 21.4] hp = [110, 110, 93, 110, 175, 105, 245, 62, 95, 123, 123, 180, 180, 180, 205, 215, 230, 66, 52, 65, 9...
_oldnotebooks/Inferential_Statistics.ipynb
eneskemalergin/OldBlog
mit
The first value of the output gives the correlation between the horsepower and the mileage The second value gives the p-value. So, the first value tells us that it is highly negatively correlated and the p-value tells us that there is significant correlation between them:
plt.scatter(mpg, hp, color='r') plt.show()
_oldnotebooks/Inferential_Statistics.ipynb
eneskemalergin/OldBlog
mit
Let's look into another correlation called the Spearman correlation. The Spearman correlation applies to the rank order of the values and so it provides a monotonic relation between the two distributions. It is useful for ordinal data (data that has an order, such as movie ratings or grades in class) and is not affect...
stats.spearmanr(mpg, hp)
_oldnotebooks/Inferential_Statistics.ipynb
eneskemalergin/OldBlog
mit
We can see that the Spearman correlation is -0.89 and the p-value is significant. Let's do an experiment in which we introduce a few outlier values in the data and see how the Pearson and Spearman correlation gets affected:
mpg = [21.0, 21.0, 22.8, 21.4, 18.7, 18.1, 14.3, 24.4, 22.8, 19.2, 17.8, 16.4, 17.3, 15.2, 10.4, 10.4, 14.7, 32.4, 30.4, 33.9, 21.5, 15.5, 15.2, 13.3, 19.2, 27.3, 26.0, 30.4, 15.8, 19.7, 15.0, 21.4, 120, 3] hp = [110, 110, 93, 110, 175, 105, 245, 62, 95, 123, 123, 180, 180, 180, 205, 215, 230...
_oldnotebooks/Inferential_Statistics.ipynb
eneskemalergin/OldBlog
mit
From the plot, you can clearly make out the outlier values. Lets see how the correlations get affected for both the Pearson and Spearman correlation
stats.pearsonr(mpg, hp) stats.spearmanr(mpg, hp)
_oldnotebooks/Inferential_Statistics.ipynb
eneskemalergin/OldBlog
mit
We can clearly see that the Pearson correlation has been drastically affected due to the outliers, which are from a correlation of 0.89 to 0.47. The Spearman correlation did not get affected much as it is based on the order rather than the actual value in the data. Z-test vs T-test We have already done a few Z-tests be...
class1_score = np.array([45.0, 40.0, 49.0, 52.0, 54.0, 64.0, 36.0, 41.0, 42.0, 34.0]) class2_score = np.array([75.0, 85.0, 53.0, 70.0, 72.0, 93.0, 61.0, 65.0, 65.0, 72.0]) stats.ttest_ind(class1_score,class2_score)
_oldnotebooks/Inferential_Statistics.ipynb
eneskemalergin/OldBlog
mit
The first value in the output is the calculated t-statistics, whereas the second value is the p-value and p-value shows that the two distributions are not identical. The F distribution The F distribution is also known as Snedecor's F distribution or the Fisher–Snedecor distribution. An f statistic is given by the follo...
expected = np.array([6,6,6,6,6,6]) observed = np.array([7, 5, 3, 9, 6, 6])
_oldnotebooks/Inferential_Statistics.ipynb
eneskemalergin/OldBlog
mit
The null hypothesis in the chi-square test is that the observed value is similar to the expected value. The chi-square can be performed using the chisquare function in the SciPy package:
stats.chisquare(observed,expected)
_oldnotebooks/Inferential_Statistics.ipynb
eneskemalergin/OldBlog
mit
The first value is the chi-square value and the second value is the p-value, which is very high. This means that the null hypothesis is valid and the observed value is similar to the expected value. The chi-square test of independence is a statistical test used to determine whether two categorical variables are indepe...
men_women = np.array([[100, 120, 60],[350, 200, 90]]) stats.chi2_contingency(men_women)
_oldnotebooks/Inferential_Statistics.ipynb
eneskemalergin/OldBlog
mit
The first value is the chi-square value, The second value is the p-value, which is very small, and means that there is an association between the gender of people and the genre of the book they read. The third value is the degrees of freedom. The fourth value, which is an array, is the expected frequencies. Anova Ana...
country1 = np.array([ 176., 201., 172., 179., 180., 188., 187., 184., 171., 181., 192., 187., 178., 178., 180., 199., 185., 176., 207., 177., 160., 174., 176., 192., 189., 187., 183., 180., 181., 200., 190., 187., 175., 179., 181., 183., ...
_oldnotebooks/Inferential_Statistics.ipynb
eneskemalergin/OldBlog
mit
Hyperparameters for training the model follow the same pattern as Word2Vec. FastText supports the folllowing parameters from the original word2vec - - model: Training architecture. Allowed values: cbow, skipgram (Default cbow) - size: Size of embeddings to be learnt (Default 100) - alpha: Initial learni...
model = FastText.train(ft_home, lee_train_file, size=50, alpha=0.05, min_count=10) print(model)
docs/notebooks/FastText_Tutorial.ipynb
macks22/gensim
lgpl-2.1
Continuation of training with FastText models is not supported. Saving/loading models Models can be saved and loaded via the load and save methods.
model.save('saved_fasttext_model') loaded_model = FastText.load('saved_fasttext_model') print(loaded_model)
docs/notebooks/FastText_Tutorial.ipynb
macks22/gensim
lgpl-2.1
The save_word2vec_method causes the vectors for ngrams to be lost. As a result, a model loaded in this way will behave as a regular word2vec model. Word vector lookup FastText models support vector lookups for out-of-vocabulary words by summing up character ngrams belonging to the word.
print('night' in model.wv.vocab) print('nights' in model.wv.vocab) print(model['night']) print(model['nights'])
docs/notebooks/FastText_Tutorial.ipynb
macks22/gensim
lgpl-2.1
The word vector lookup operation only works if atleast one of the component character ngrams is present in the training corpus. For example -
# Raises a KeyError since none of the character ngrams of the word `axe` are present in the training data model['axe']
docs/notebooks/FastText_Tutorial.ipynb
macks22/gensim
lgpl-2.1
The in operation works slightly differently from the original word2vec. It tests whether a vector for the given word exists or not, not whether the word is present in the word vocabulary. To test whether a word is present in the training word vocabulary -
# Tests if word present in vocab print("word" in model.wv.vocab) # Tests if vector present for word print("word" in model)
docs/notebooks/FastText_Tutorial.ipynb
macks22/gensim
lgpl-2.1
Similarity operations Similarity operations work the same way as word2vec. Out-of-vocabulary words can also be used, provided they have atleast one character ngram present in the training data.
print("nights" in model.wv.vocab) print("night" in model.wv.vocab) model.similarity("night", "nights")
docs/notebooks/FastText_Tutorial.ipynb
macks22/gensim
lgpl-2.1
Syntactically similar words generally have high similarity in FastText models, since a large number of the component char-ngrams will be the same. As a result, FastText generally does better at syntactic tasks than Word2Vec. A detailed comparison is provided here. Other similarity operations -
# The example training corpus is a toy corpus, results are not expected to be good, for proof-of-concept only model.most_similar("nights") model.n_similarity(['sushi', 'shop'], ['japanese', 'restaurant']) model.doesnt_match("breakfast cereal dinner lunch".split()) model.most_similar(positive=['baghdad', 'england'], ...
docs/notebooks/FastText_Tutorial.ipynb
macks22/gensim
lgpl-2.1
Below we define a simple exponential decay function of the form $$y(x)=a e^{-b x}+c$$
#Here's a simple test function of an exponential decay def func(x, *params): #this is the important part, if you want to pass an unspecified number of parameters #you need to unpack the parameters list in the function definition and then you need #to specify initial guesses when using curve_fit return p...
notebooks/CurveFitTest.ipynb
david-hoffman/scripts
apache-2.0
2D Fitting Here I've taken the code from here. There's a better definition of a skewed gaussian available here.
#define model function and pass independant variables x and y as a list def twoD_Gaussian(xdata_tuple, amplitude, xo, yo, sigma_x, sigma_y, theta, offset): (x, y) = xdata_tuple xo = float(xo) ...
notebooks/CurveFitTest.ipynb
david-hoffman/scripts
apache-2.0
With my method of using a wrapper function to prepare the data for fitting I avoid the need to reshape the data for plotting and later analysis, but it means I need to ravel the y-data.
# define jacobians for timing experiments. def myDfun( params, xdata, ydata, f): x = xdata[0].ravel() y = xdata[1].ravel() amp, x0, y0, sigma_x, sigma_y, offset = params value = f(xdata, *params)-offset dydamp = value/amp dydx0 = value*(x-x0)/sigma_x**2 dydsigmax = value*(x-x0)**2/sigma_x**3...
notebooks/CurveFitTest.ipynb
david-hoffman/scripts
apache-2.0
Testing timing Comparing using a Jacobian vs not using one
# With MLE fitting mp._general_function = _general_function_mle mp._weighted_general_function = _weighted_general_function_mle %timeit popt, pcov = mp.curve_fit(gaussian2D_fit, (x, y), data_noisy.ravel(), p0=initial_guess, Dfun=myDfun, col_deriv=1) %timeit popt, pcov = mp.curve_fit(gaussian2D_fit, (x, y), data_noisy.ra...
notebooks/CurveFitTest.ipynb
david-hoffman/scripts
apache-2.0
Lorentzians
##Here's my modifcation to the above code #define model function and pass independant variables x and y as a list def lor2D(xdata_tuple, amp, x0, y0, sigma_x, sigma_y, offset): (x, y) = xdata_tuple g = offset + amp/(1+((x-x0)/(sigma_x/2))**2)/(1+((y-y0)/(sigma_y/2))**2) return g #create a wrapper function...
notebooks/CurveFitTest.ipynb
david-hoffman/scripts
apache-2.0
Implementing an SLR-Table-Generator A Grammar for Grammars As the goal is to generate an SLR-table-generator we first need to implement a parser for context free grammars. The file simple.g contains an example grammar that describes arithmetic expressions.
!cat Examples/c-grammar.g
ANTLR4-Python/SLR-Parser-Generator/SLR-Table-Generator.ipynb
Danghor/Formal-Languages
gpl-2.0
We use <span style="font-variant:small-caps;">Antlr</span> to develop a parser for context free grammars. The pure grammar used to parse context free grammars is stored in the file Pure.g4. It is similar to the grammar that we have already used to implement Earley's algorithm, but allows additionally the use of the o...
!cat Pure.g4
ANTLR4-Python/SLR-Parser-Generator/SLR-Table-Generator.ipynb
Danghor/Formal-Languages
gpl-2.0
The annotated grammar is stored in the file Grammar.g4. The parser will return a list of grammar rules, where each rule of the form $$ a \rightarrow \beta $$ is stored as the tuple (a,) + 𝛽.
!cat -n Grammar.g4
ANTLR4-Python/SLR-Parser-Generator/SLR-Table-Generator.ipynb
Danghor/Formal-Languages
gpl-2.0
The Class GrammarRule The class GrammarRule is used to store a single grammar rule. As we have to use objects of type GrammarRule as keys in a dictionary later, we have to provide the methods __eq__, __ne__, and __hash__.
class GrammarRule: def __init__(self, variable, body): self.mVariable = variable self.mBody = body def __eq__(self, other): return isinstance(other, GrammarRule) and \ self.mVariable == other.mVariable and \ self.mBody == other.mBody ...
ANTLR4-Python/SLR-Parser-Generator/SLR-Table-Generator.ipynb
Danghor/Formal-Languages
gpl-2.0
The function parse_grammar takes a string filename as its argument and returns the grammar that is stored in the specified file. The grammar is represented as list of rules. Each rule is represented as a tuple. The example below will clarify this structure.
def parse_grammar(filename): input_stream = antlr4.FileStream(filename, encoding="utf-8") lexer = GrammarLexer(input_stream) token_stream = antlr4.CommonTokenStream(lexer) parser = GrammarParser(token_stream) grammar = parser.start() return [GrammarRule(head, tuple(body)) ...
ANTLR4-Python/SLR-Parser-Generator/SLR-Table-Generator.ipynb
Danghor/Formal-Languages
gpl-2.0
Given a string name, which is either a variable, a token, or a literal, the function is_var checks whether name is a variable. The function can distinguish variable names from tokens and literals because variable names consist only of lower case letters, while tokens are all uppercase and literals start with the chara...
def is_var(name): return name[0] != "'" and name.islower()
ANTLR4-Python/SLR-Parser-Generator/SLR-Table-Generator.ipynb
Danghor/Formal-Languages
gpl-2.0
Fun Fact: The invocation of "'return'".islower() returns True. This is the reason that we have to test that name does not start with a "'" character because otherwise keywords like 'return' or 'while' appearing in a grammar would be mistaken for variables.
"'return'".islower()
ANTLR4-Python/SLR-Parser-Generator/SLR-Table-Generator.ipynb
Danghor/Formal-Languages
gpl-2.0
Given a list Rules of GrammarRules, the function collect_variables(Rules) returns the set of all variables occuring in Rules.
def collect_variables(Rules): Variables = set() for rule in Rules: Variables.add(rule.mVariable) for item in rule.mBody: if is_var(item): Variables.add(item) return Variables
ANTLR4-Python/SLR-Parser-Generator/SLR-Table-Generator.ipynb
Danghor/Formal-Languages
gpl-2.0
Given a set Rules of GrammarRules, the function collect_tokens(Rules) returns the set of all tokens and literals occuring in Rules.
def collect_tokens(Rules): Tokens = set() for rule in Rules: for item in rule.mBody: if not is_var(item): Tokens.add(item) return Tokens
ANTLR4-Python/SLR-Parser-Generator/SLR-Table-Generator.ipynb
Danghor/Formal-Languages
gpl-2.0
Marked Rules The class MarkedRule stores a single marked rule of the form $$ v \rightarrow \alpha \bullet \beta $$ where the variable $v$ is stored in the member variable mVariable, while $\alpha$ and $\beta$ are stored in the variables mAlphaand mBeta respectively. These variables are assumed to contain tuples of gra...
class MarkedRule(): def __init__(self, variable, alpha, beta): self.mVariable = variable self.mAlpha = alpha self.mBeta = beta def __eq__(self, other): return isinstance(other, MarkedRule) and \ self.mVariable == other.mVariable and \ ...
ANTLR4-Python/SLR-Parser-Generator/SLR-Table-Generator.ipynb
Danghor/Formal-Languages
gpl-2.0
Given a marked rule self, the function is_complete checks, whether the marked rule self has the form $$ c \rightarrow \alpha\; \bullet,$$ i.e. it checks, whether the $\bullet$ is at the end of the grammar rule.
def is_complete(self): return len(self.mBeta) == 0 MarkedRule.is_complete = is_complete del is_complete
ANTLR4-Python/SLR-Parser-Generator/SLR-Table-Generator.ipynb
Danghor/Formal-Languages
gpl-2.0
Given a marked rule self of the form $$ c \rightarrow \alpha \bullet X\, \delta, $$ the function symbol_after_dot returns the symbol $X$. If there is no symbol after the $\bullet$, the method returns None.
def symbol_after_dot(self): if len(self.mBeta) > 0: return self.mBeta[0] return None MarkedRule.symbol_after_dot = symbol_after_dot del symbol_after_dot
ANTLR4-Python/SLR-Parser-Generator/SLR-Table-Generator.ipynb
Danghor/Formal-Languages
gpl-2.0
Given a marked rule, this function returns the variable following the dot. If there is no variable following the dot, the function returns None.
def next_var(self): if len(self.mBeta) > 0: var = self.mBeta[0] if is_var(var): return var return None MarkedRule.next_var = next_var del next_var
ANTLR4-Python/SLR-Parser-Generator/SLR-Table-Generator.ipynb
Danghor/Formal-Languages
gpl-2.0
The function move_dot(self) transforms a marked rule of the form $$ c \rightarrow \alpha \bullet X\, \beta $$ into a marked rule of the form $$ c \rightarrow \alpha\, X \bullet \beta, $$ i.e. the $\bullet$ is moved over the next symbol. Invocation of this method assumes that there is a symbol following the $\bullet$...
def move_dot(self): return MarkedRule(self.mVariable, self.mAlpha + (self.mBeta[0],), self.mBeta[1:]) MarkedRule.move_dot = move_dot del move_dot
ANTLR4-Python/SLR-Parser-Generator/SLR-Table-Generator.ipynb
Danghor/Formal-Languages
gpl-2.0
The function to_rule(self) turns the marked rule self into a GrammarRule, i.e. the marked rule $$ c \rightarrow \alpha \bullet \beta $$ is turned into the grammar rule $$ c \rightarrow \alpha\, \beta. $$
def to_rule(self): return GrammarRule(self.mVariable, self.mAlpha + self.mBeta) MarkedRule.to_rule = to_rule del to_rule
ANTLR4-Python/SLR-Parser-Generator/SLR-Table-Generator.ipynb
Danghor/Formal-Languages
gpl-2.0
SLR-Table-Generation The class Grammar represents a context free grammar. It stores a list of the GrammarRules of the given grammar. Each grammar rule is of the form $$ a \rightarrow \beta $$ where $\beta$ is a tuple of variables, tokens, and literals. The start symbol is assumed to be the variable on the left hand si...
class Grammar(): def __init__(self, Rules): self.mRules = Rules self.mStart = Rules[0].mVariable self.mVariables = collect_variables(Rules) self.mTokens = collect_tokens(Rules) self.mStates = set() self.mStateNames = {} self.mConflicts = Fa...
ANTLR4-Python/SLR-Parser-Generator/SLR-Table-Generator.ipynb
Danghor/Formal-Languages
gpl-2.0
Given a set of Variables, the function initialize_dictionary returns a dictionary that assigns the empty set to all variables.
def initialize_dictionary(Variables): return { a: set() for a in Variables }
ANTLR4-Python/SLR-Parser-Generator/SLR-Table-Generator.ipynb
Danghor/Formal-Languages
gpl-2.0
Given a Grammar, the function compute_tables computes - the sets First(v) and Follow(v) for every variable v, - the set of all states of the SLR-Parser, - the action table, and - the goto table. Given a grammar g, - the set g.mFirst is a dictionary such that g.mFirst[a] = First[a] and - the set g.mFollow is a dictiona...
def compute_tables(self): self.mFirst = initialize_dictionary(self.mVariables) self.mFollow = initialize_dictionary(self.mVariables) self.compute_first() self.compute_follow() self.compute_rule_names() self.all_states() self.compute_action_table() self.compute_goto_table() Grammar....
ANTLR4-Python/SLR-Parser-Generator/SLR-Table-Generator.ipynb
Danghor/Formal-Languages
gpl-2.0
The function compute_rule_names assigns a unique name to each rule of the grammar. These names are used later to represent reduce actions in the action table.
def compute_rule_names(self): self.mRuleNames = {} counter = 0 for rule in self.mRules: self.mRuleNames[rule] = 'r' + str(counter) counter += 1 Grammar.compute_rule_names = compute_rule_names del compute_rule_names
ANTLR4-Python/SLR-Parser-Generator/SLR-Table-Generator.ipynb
Danghor/Formal-Languages
gpl-2.0
The function compute_first(self) computes the sets $\texttt{First}(c)$ for all variables $c$ and stores them in the dictionary mFirst. Abstractly, given a variable $c$ the function $\texttt{First}(c)$ is the set of all tokens that can start a string that is derived from $c$: $$\texttt{First}(\texttt{c}) := \Bigl{ t...
def compute_first(self): change = True while change: change = False for rule in self.mRules: a, body = rule.mVariable, rule.mBody first_body = self.first_list(body) if not (first_body <= self.mFirst[a]): change = True self.mFirs...
ANTLR4-Python/SLR-Parser-Generator/SLR-Table-Generator.ipynb
Danghor/Formal-Languages
gpl-2.0
Given a tuple of variables and tokens alpha, the function first_list(alpha) computes the function $\texttt{FirstList}(\alpha)$ that has been defined above. If alpha is nullable, then the result will contain the empty string $\varepsilon = \texttt{''}$.
def first_list(self, alpha): if len(alpha) == 0: return { '' } elif is_var(alpha[0]): v, *r = alpha return eps_union(self.mFirst[v], self.first_list(r)) else: t = alpha[0] return { t } Grammar.first_list = first_list del first_list
ANTLR4-Python/SLR-Parser-Generator/SLR-Table-Generator.ipynb
Danghor/Formal-Languages
gpl-2.0
The arguments S and T of eps_union are sets that contain tokens and, additionally, they might contain the empty string.
def eps_union(S, T): if '' in S: if '' in T: return S | T return (S - { '' }) | T return S
ANTLR4-Python/SLR-Parser-Generator/SLR-Table-Generator.ipynb
Danghor/Formal-Languages
gpl-2.0
Given an augmented grammar $G = \langle V,T,R\cup{\widehat{s} \rightarrow s\,\$}, \widehat{s}\rangle$ and a variable $a$, the set of tokens that might follow $a$ is defined as: $$\texttt{Follow}(a) := \bigl{ t \in \widehat{T} \,\bigm|\, \exists \beta,\gamma \in (V \cup \widehat{T})^: \wid...
def compute_follow(self): self.mFollow[self.mStart] = { '$' } change = True while change: change = False for rule in self.mRules: a, body = rule.mVariable, rule.mBody for i in range(len(body)): if is_var(body[i]): yi = body[i...
ANTLR4-Python/SLR-Parser-Generator/SLR-Table-Generator.ipynb
Danghor/Formal-Languages
gpl-2.0
If $\mathcal{M}$ is a set of marked rules, then the closure of $\mathcal{M}$ is the smallest set $\mathcal{K}$ such that we have the following: - $\mathcal{M} \subseteq \mathcal{K}$, - If $a \rightarrow \beta \bullet c\, \delta$ is a marked rule from $\mathcal{K}$, and $c$ is a variable and if, furthermore, $c \ri...
def cmp_closure(self, Marked_Rules): All_Rules = Marked_Rules New_Rules = Marked_Rules while True: More_Rules = set() for rule in New_Rules: c = rule.next_var() if c == None: continue for rule in self.mRules: head, alpha = r...
ANTLR4-Python/SLR-Parser-Generator/SLR-Table-Generator.ipynb
Danghor/Formal-Languages
gpl-2.0
Given a set of marked rules $\mathcal{M}$ and a grammar symbol $X$, the function $\texttt{goto}(\mathcal{M}, X)$ is defined as follows: $$\texttt{goto}(\mathcal{M}, X) := \texttt{closure}\Bigl( \bigl{ a \rightarrow \beta\, X \bullet \delta \bigm| (a \rightarrow \beta \bullet X\, \delta) \in \mathcal{M} \bigr} ...
def goto(self, Marked_Rules, x): Result = set() for mr in Marked_Rules: if mr.symbol_after_dot() == x: Result.add(mr.move_dot()) return self.cmp_closure(Result) Grammar.goto = goto del goto
ANTLR4-Python/SLR-Parser-Generator/SLR-Table-Generator.ipynb
Danghor/Formal-Languages
gpl-2.0
The function all_states computes the set of all states of an SLR-parser. The function starts with the state $$ \texttt{closure}\bigl({ \widehat{s} \rightarrow \bullet s \, $}\bigr) $$ and then tries to compute new states by using the function goto. This computation proceeds via a fixed-point iteration. Once all sta...
def all_states(self): start_state = self.cmp_closure({ MarkedRule('ŝ', (), (self.mStart, '$')) }) self.mStates = { start_state } New_States = self.mStates while True: More_States = set() for Rule_Set in New_States: for mr in Rule_Set: if not mr.is_complet...
ANTLR4-Python/SLR-Parser-Generator/SLR-Table-Generator.ipynb
Danghor/Formal-Languages
gpl-2.0
The following function computes the action table and is defined as follows: - If $\mathcal{M}$ contains a marked rule of the form $a \rightarrow \beta \bullet t\, \delta$ then we have $$\texttt{action}(\mathcal{M},t) := \langle \texttt{shift}, \texttt{goto}(\mathcal{M},t) \rangle.$$ - If $\mathcal{M}$ contains a ma...
def compute_action_table(self): self.mActionTable = {} print('\nAction Table:') for state in self.mStates: stateName = self.mStateNames[state] actionTable = {} # compute shift actions for token in self.mTokens: if token != '$': newState = self.got...
ANTLR4-Python/SLR-Parser-Generator/SLR-Table-Generator.ipynb
Danghor/Formal-Languages
gpl-2.0
The function compute_goto_table computes the goto table.
def compute_goto_table(self): self.mGotoTable = {} print('\nGoto Table:') for state in self.mStates: for var in self.mVariables: newState = self.goto(state, var) if newState != set(): stateName = self.mStateNames[state] newName = self.mStateN...
ANTLR4-Python/SLR-Parser-Generator/SLR-Table-Generator.ipynb
Danghor/Formal-Languages
gpl-2.0
Let's start with a showcase Case study: air quality in Europe AirBase (The European Air quality dataBase): hourly measurements of all air quality monitoring stations from Europe Starting from these hourly data for different stations:
data = pd.read_csv('data/airbase_data.csv', index_col=0, parse_dates=True, na_values='-9999') data
01 - Introduction.ipynb
btel/2015_eitn_swc_pandas
bsd-2-clause
to answering questions about this data in a few lines of code: Does the air pollution show a decreasing trend over the years?
data['1999':].resample('A').plot(ylim=[0,100])
01 - Introduction.ipynb
btel/2015_eitn_swc_pandas
bsd-2-clause
How many exceedances of the limit values?
exceedances = data > 200 exceedances = exceedances.groupby(exceedances.index.year).sum() ax = exceedances.loc[2005:].plot(kind='bar') ax.axhline(18, color='k', linestyle='--')
01 - Introduction.ipynb
btel/2015_eitn_swc_pandas
bsd-2-clause
What is the difference in diurnal profile between weekdays and weekend?
data['weekday'] = data.index.weekday data['weekend'] = data['weekday'].isin([5, 6]) data_weekend = data.groupby(['weekend', data.index.hour])['FR04012'].mean().unstack(level=0) data_weekend.plot()
01 - Introduction.ipynb
btel/2015_eitn_swc_pandas
bsd-2-clause
Adding Polynomials When you add two polynomials, the result is a polynomial. Here's an example: \begin{equation}(3x^{3} - 4x + 5) + (2x^{3} + 3x^{2} - 2x + 2) \end{equation} because this is an addition operation, you can simply add all of the like terms from both polynomials. To make this clear, let's first put the...
from random import randint x = randint(1,100) (3*x**3 - 4*x + 5) + (2*x**3 + 3*x**2 - 2*x + 2) == 5*x**3 + 3*x**2 - 6*x + 7
courses/DAT256x/Module01/01-05-Polynomials.ipynb
alexandrnikitin/algorithm-sandbox
mit
Subtracting Polynomials Subtracting polynomials is similar to adding them but you need to take into account that one of the polynomials is a negative. Consider this expression: \begin{equation}(2x^{2} - 4x + 5) - (x^{2} - 2x + 2) \end{equation} The key to performing this calculation is to realize that the subtracti...
from random import randint x = randint(1,100) (2*x**2 - 4*x + 5) - (x**2 - 2*x + 2) == x**2 - 2*x + 3
courses/DAT256x/Module01/01-05-Polynomials.ipynb
alexandrnikitin/algorithm-sandbox
mit
Multiplying Polynomials To multiply two polynomials, you need to perform the following two steps: 1. Multiply each term in the first polynomial by each term in the second polynomial. 2. Add the results of the multiplication operations, combining like terms where possible. For example, consider this expression: \begin{e...
from random import randint x = randint(1,100) (x**4 + 2)*(2*x**2 + 3*x - 3) == 2*x**6 + 3*x**5 - 3*x**4 + 4*x**2 + 6*x - 6
courses/DAT256x/Module01/01-05-Polynomials.ipynb
alexandrnikitin/algorithm-sandbox
mit
Dividing Polynomials When you need to divide one polynomial by another, there are two approaches you can take depending on the number of terms in the divisor (the expression you're dividing by). Dividing Polynomials Using Simplification In the simplest case, division of a polynomial by a monomial, the operation is real...
from random import randint x = randint(1,100) (4*x + 6*x**2) / (2*x) == 2 + 3*x
courses/DAT256x/Module01/01-05-Polynomials.ipynb
alexandrnikitin/algorithm-sandbox
mit
Dividing Polynomials Using Long Division Things get a little more complicated for divisors with more than one term. Suppose we have the following expression: \begin{equation}(x^{2} + 2x - 3) \div (x - 2) \end{equation} Another way of writing this is to use the long-division format, like this: \begin{equation} x - 2 |\o...
from random import randint x = randint(3,100) (x**2 + 2*x -3)/(x-2) == x + 4 + (5/(x-2))
courses/DAT256x/Module01/01-05-Polynomials.ipynb
alexandrnikitin/algorithm-sandbox
mit
ConvNet Codes Below, we'll run through all the images in our dataset and get codes for each of them. That is, we'll run the images through the VGGNet convolutional layers and record the values of the first fully connected layer. We can then write these to a file for later when we build our own classifier. Here we're us...
!pip install scikit-image import os import numpy as np import tensorflow as tf from tensorflow_vgg import vgg16 from tensorflow_vgg import utils data_dir = 'flower_photos/' contents = os.listdir(data_dir) classes = [each for each in contents if os.path.isdir(data_dir + each)]
transfer-learning/Transfer_Learning.ipynb
Lstyle1/Deep_learning_projects
mit
Below I'm running images through the VGG network in batches. Exercise: Below, build the VGG network. Also get the codes from the first fully connected layer (make sure you get the ReLUd values).
# Set the batch size higher if you can fit in in your GPU memory batch_size = 10 codes_list = [] labels = [] batch = [] codes = None with tf.Session() as sess: # TODO: Build the vgg network here vgg = vgg16.Vgg16() input_ = tf.placeholder(tf.float32, [None, 224, 224, 3]) with tf.name_scope("conte...
transfer-learning/Transfer_Learning.ipynb
Lstyle1/Deep_learning_projects
mit
Building the Classifier Now that we have codes for all the images, we can build a simple classifier on top of them. The codes behave just like normal input into a simple neural network. Below I'm going to have you do most of the work.
# read codes and labels from file import csv with open('labels') as f: reader = csv.reader(f, delimiter='\n') labels = np.array([each for each in reader if len(each) > 0]).squeeze() with open('codes') as f: codes = np.fromfile(f, dtype=np.float32) codes = codes.reshape((len(labels), -1)) #Test print(l...
transfer-learning/Transfer_Learning.ipynb
Lstyle1/Deep_learning_projects
mit
Data prep As usual, now we need to one-hot encode our labels and create validation/test sets. First up, creating our labels! Exercise: From scikit-learn, use LabelBinarizer to create one-hot encoded vectors from the labels.
from sklearn import preprocessing label_binarizer = preprocessing.LabelBinarizer() label_binarizer.fit(classes) labels_vecs = label_binarizer.transform(labels) # Your one-hot encoded labels array here #Test label_binarizer.classes_ print(labels_vecs[:5])
transfer-learning/Transfer_Learning.ipynb
Lstyle1/Deep_learning_projects
mit
Now you'll want to create your training, validation, and test sets. An important thing to note here is that our labels and data aren't randomized yet. We'll want to shuffle our data so the validation and test sets contain data from all classes. Otherwise, you could end up with testing sets that are all one class. Typic...
from sklearn.model_selection import StratifiedShuffleSplit #shufflesplitter for train and test(valid) shuffle_train_test = StratifiedShuffleSplit(n_splits=1, test_size=0.2) shuffle_test_valid = StratifiedShuffleSplit(n_splits=1, test_size=0.5) train_index, test_valid_index = next(shuffle_train_test.split(codes, label...
transfer-learning/Transfer_Learning.ipynb
Lstyle1/Deep_learning_projects
mit
If you did it right, you should see these sizes for the training sets: Train shapes (x, y): (2936, 4096) (2936, 5) Validation shapes (x, y): (367, 4096) (367, 5) Test shapes (x, y): (367, 4096) (367, 5) Classifier layers Once you have the convolutional codes, you just need to build a classfier from some fully connected...
inputs_ = tf.placeholder(tf.float32, shape=[None, codes.shape[1]]) labels_ = tf.placeholder(tf.int64, shape=[None, labels_vecs.shape[1]]) # TODO: Classifier layers and operations fully_layer = tf.contrib.layers.fully_connected(inputs=inputs_,\ num_outputs=256,\ ...
transfer-learning/Transfer_Learning.ipynb
Lstyle1/Deep_learning_projects
mit
Training Here, we'll train the network. Exercise: So far we've been providing the training code for you. Here, I'm going to give you a bit more of a challenge and have you write the code to train the network. Of course, you'll be able to see my solution if you need help. Use the get_batches function I wrote before to ...
epochs = 5 saver = tf.train.Saver() with tf.Session() as sess: sess.run(tf.global_variables_initializer()) # TODO: Your training code here for epoch in range(epochs): for x, y in get_batches(train_x, train_y): loss, _ = sess.run([cost,optimizer], feed_dict={inputs_: x, labels_: y}) ...
transfer-learning/Transfer_Learning.ipynb
Lstyle1/Deep_learning_projects
mit
Below, feel free to choose images and see how the trained classifier predicts the flowers in them.
test_img_path = 'flower_photos/roses/10894627425_ec76bbc757_n.jpg' test_img = imread(test_img_path) plt.imshow(test_img) # Run this cell if you don't have a vgg graph built if 'vgg' in globals(): print('"vgg" object already exists. Will not create again.') else: #create vgg with tf.Session() as sess: ...
transfer-learning/Transfer_Learning.ipynb
Lstyle1/Deep_learning_projects
mit
Kullback-Leibler Divergence In this post we're going to take a look at way of comparing two probability distributions called Kullback-Leibler Divergence (a.k.a KL divergence). Very often in machine learning, we'll replace observed data or a complex distributions with a simpler, approximating distribution. KL Divergence...
# ensure the probability adds up to 1 true_data = np.array([0.02, 0.03, 0.05, 0.14, 0.16, 0.15, 0.12, 0.08, 0.1, 0.08, 0.07]) n = true_data.shape[0] index = np.arange(n) assert sum(true_data) == 1.0 # change default style figure and font size plt.rcParams['figure.figsize'] = 8, 6 plt.rcParams['font.size'] = 12 plt.ba...
model_selection/kl_divergence.ipynb
ethen8181/machine-learning
mit
Now we need to send this information back to earth. But the problem is that sending information from space to earth is expensive. So we wish to represent this information with a minimum amount of information, perhaps just one or two parameters. One option to represent the distribution of teeth in worms is a uniform dis...
uniform_data = np.full(n, 1.0 / n) # we can plot our approximated distribution against the original distribution width = 0.3 plt.bar(index, true_data, width=width, label='True') plt.bar(index + width, uniform_data, width=width, label='Uniform') plt.xlabel('Teeth Number') plt.title('Probability Distribution of Space Wo...
model_selection/kl_divergence.ipynb
ethen8181/machine-learning
mit
Another option is to use a binomial distribution.
# we estimate the parameter of the binomial distribution p = true_data.dot(index) / n print('p for binomial distribution:', p) binom_data = binom.pmf(index, n, p) binom_data width = 0.3 plt.bar(index, true_data, width=width, label='True') plt.bar(index + width, binom_data, width=width, label='Binomial') plt.xlabel('Te...
model_selection/kl_divergence.ipynb
ethen8181/machine-learning
mit
Comparing each of our models with our original data we can see that neither one is the perfect match, but the question now becomes, which one is better?
plt.bar(index - width, true_data, width=width, label='True') plt.bar(index, uniform_data, width=width, label='Uniform') plt.bar(index + width, binom_data, width=width, label='Binomial') plt.xlabel('Teeth Number') plt.title('Probability Distribution of Space Worm Teeth Number') plt.ylabel('Probability') plt.xticks(index...
model_selection/kl_divergence.ipynb
ethen8181/machine-learning
mit
Given these two distributions that we are using to approximate the original distribution, we need a quantitative way to measure which one does the job better. This is where Kullback-Leibler (KL) Divergence comes in. KL Divergence has its origins in information theory. The primary goal of information theory is to quanti...
# both function are equivalent ways of computing KL-divergence # one uses for loop and the other uses vectorization def compute_kl_divergence(p_probs, q_probs): """"KL (p || q)""" kl_div = 0.0 for p, q in zip(p_probs, q_probs): kl_div += p * np.log(p / q) return kl_div def compute_kl_divergen...
model_selection/kl_divergence.ipynb
ethen8181/machine-learning
mit
Array views and slicing A NumPy array is an object of numpy.ndarray type:
a = np.arange(3) type(a)
taking_numpy_in_stride/Taking NumPy In Stride - Student Version.ipynb
jaimefrio/pydatabcn2017
unlicense
All ndarrays have a .base attribute. If this attribute is not None, then the array is a view of some other object's memory, typically another ndarray. This is a very powerful tool, because allocating memory and copying memory contents are expensive operations, but updating metadata on how to interpret some already allo...
a = np.arange(3) a.base is None a[:].base is None
taking_numpy_in_stride/Taking NumPy In Stride - Student Version.ipynb
jaimefrio/pydatabcn2017
unlicense
Let's look more closely at what an array's metadata looks like. NumPy provides the np.info function, which can list for us some low level attributes of an array:
np.info(a)
taking_numpy_in_stride/Taking NumPy In Stride - Student Version.ipynb
jaimefrio/pydatabcn2017
unlicense
By the end of the workshop you will understand what most of these mean. But rather than listen through a lesson, you get to try and figure what they mean yourself. To help you with that, here's a function that prints the information from two arrays side by side:
def info_for_two(one_array, another_array): """Prints side-by-side results of running np.info on its inputs.""" def info_as_ordered_dict(array): """Converts return of np.infor into an ordered dict.""" import collections import io buffer = io.StringIO() np.info(array, outp...
taking_numpy_in_stride/Taking NumPy In Stride - Student Version.ipynb
jaimefrio/pydatabcn2017
unlicense
Exercise 1. Create a one dimensional NumPy array with a few items (consider using np.arange). Compare the printout of np.info on your array and on slices of it (use the [start:stop:step] indexing syntax, and make sure to try steps other than one). Do you see any patterns?
# Your code goes here
taking_numpy_in_stride/Taking NumPy In Stride - Student Version.ipynb
jaimefrio/pydatabcn2017
unlicense
Exercise 1 debrief Every array has an underlying block of memory assigned to it. When we slice an array, rather than making a copy of it, NumPy makes a view, reusing the memory block, but interpreting it differently. Lets take a look at what NumPy did for us in the above examples, and make sense of some of the changes ...
# Your code goes here
taking_numpy_in_stride/Taking NumPy In Stride - Student Version.ipynb
jaimefrio/pydatabcn2017
unlicense
A look at data types Similarly to how we can change the shape, strides and data pointer of an array through slicing, we can change how it's items are interpreted by changing it's data type. This is done by calling the array's .view() method, and passing it the new data type. But before we go there, lets look a little c...
# Your code goes here
taking_numpy_in_stride/Taking NumPy In Stride - Student Version.ipynb
jaimefrio/pydatabcn2017
unlicense
The Constructor They Don't Want You To Know About. You typically construct your NumPy arrays using one of the many factory fuctions provided, np.array() being the most popular. But it is also possible to call the np.ndarray object constructor directly. You will typically not want to do this, because there are probably ...
# Your code goes here
taking_numpy_in_stride/Taking NumPy In Stride - Student Version.ipynb
jaimefrio/pydatabcn2017
unlicense
Reshaping Into Higher Dimensions So far we have sticked to one dimensional arrays. Things get substantially more interesting when we move into higher dimensions. One way of getting views with a different number of dimensions is by using the .reshape() method of NumPy arrays, or the equivalent np.reshape() function. The...
# Your code goes here
taking_numpy_in_stride/Taking NumPy In Stride - Student Version.ipynb
jaimefrio/pydatabcn2017
unlicense
Exercise 5 debrief As the examples show, an n-dimensional array will have an n item tuple .shape and .strides. The number of dimensions can be directly queried from the .ndim attribute. The shape tells us how large the array is along each dimension, the strides tell us how many bytes to skip in memory to get to the nex...
a = np.arange(12, dtype=float) a a.reshape(4, 3).sum(axis=-1)
taking_numpy_in_stride/Taking NumPy In Stride - Student Version.ipynb
jaimefrio/pydatabcn2017
unlicense