markdown
stringlengths
0
37k
code
stringlengths
1
33.3k
path
stringlengths
8
215
repo_name
stringlengths
6
77
license
stringclasses
15 values
Python can make a set of words:
WORDS = set(open('words4.txt').read().split()) len(WORDS)
notes/python/p_norvig/word/Fred Buns.ipynb
kunaltyagi/SDES
gpl-3.0
So that means that no lock could ever make more than 4,360 words. Let's define words_from(lock):
def words_from(lock): "A list of words that can be made by lock." return [c for c in combinations(lock) if c in WORDS] words_from(fredbuns)
notes/python/p_norvig/word/Fred Buns.ipynb
kunaltyagi/SDES
gpl-3.0
Note: An alternative is to represent a collection of words as a set, not a list; then words_from could be implemented as: return combinations(lock) & WORDS. I will also introduce the function show to print out a lock and its words:
def show(lock): "Show a lock and the words it makes." words = words_from(lock) N = len(lock[0]) ** len(lock) print('Lock: {}\n\nWords: {}\n\nNumber of Words: {} / {}' .format(space(lock), space(sorted(words)), len(words), N)) space = ' '.join # Function to concatenate strings with a spac...
notes/python/p_norvig/word/Fred Buns.ipynb
kunaltyagi/SDES
gpl-3.0
For this tiny lock with just two letters on each tumbler, we find that 6 out of the 16 possible combinations are words. We're now ready to answer the real questions. Question 1: How Many Words? Here is the answer:
wordlock = ['SPHMTWDLFB', 'LEYHNRUOAI', 'ENMLRTAOSK', 'DSNMPYLKTE'] show(wordlock)
notes/python/p_norvig/word/Fred Buns.ipynb
kunaltyagi/SDES
gpl-3.0
How Secure is WordLock? The lock makes 1118 words (according to my word list). You might say that an attacker who knows the combination is a word would find this lock to be only 11.18% as secure as a 4-digit lock with 10,000 combinations. But in reality, every cable lock is vulnerable to an attacker with wire cutter...
def random_lock(d=4, c=10): "Make a lock by sampling randomly and uniformly from the alphabet." return Lock(Tumbler(random.sample(alphabet, c)) for i in range(d)) Lock = list # A Lock is a list of tumblers Tumbler = cat # A Tumbler is 10 cha...
notes/python/p_norvig/word/Fred Buns.ipynb
kunaltyagi/SDES
gpl-3.0
Wow, that's not very many words. Let's repeat 100 times and take the best one, with "best" determined by the function word_count:
def word_count(lock): return len(words_from(lock)) random_locks = [random_lock() for _ in range(100)] show(max(random_locks, key=word_count))
notes/python/p_norvig/word/Fred Buns.ipynb
kunaltyagi/SDES
gpl-3.0
Still not very good. We will need a more systematic approach. Question 2: More Words (via Greedy Locks) My first idea for a lock with more words is this: consider each tumbler, one at a time, and fill the tumbler with the letters that make the most words. How do I determine what letters make the most words? A Counte...
first_letters = [w[0] for w in WORDS] Counter(first_letters).most_common(10)
notes/python/p_norvig/word/Fred Buns.ipynb
kunaltyagi/SDES
gpl-3.0
In other words, the letters SPTBDCLMAR are the most common ways to start a word. Let's add up those counts:
def n_most_common(counter, n): return sum(n for (_, n) in counter.most_common(n)) n_most_common(Counter(first_letters), 10)
notes/python/p_norvig/word/Fred Buns.ipynb
kunaltyagi/SDES
gpl-3.0
This means that SPTBDCLMAR covers 2,599 words. We don't know for sure that these are the best 10 letters to put on the first tumbler, but we do know that whatever letters are best, they can't form more than 2,599 words, so we have an upper bound on the number of words in a lock (and the 1,118 from wordlock is a lower b...
def greedy_lock(d=4, c=10, words=WORDS): "Make a lock with d tumblers, each consisting of the c letters that cover the most words at that position." lock = Lock('?' * d) for i in range(d): # Make a tumbler of c letters, to be used in position i, such that the tumbler covers the most words. c...
notes/python/p_norvig/word/Fred Buns.ipynb
kunaltyagi/SDES
gpl-3.0
Remember that the wordlock gave 1118 words, so the greedy lock is better, but not by much (only 5%). Is it possible to do better still? Question 2: More Words (via Improved Locks) Here's another idea to get more words from a lock: Start with some lock. Pick, at random, one letter on one tumbler and change it to a ne...
def improved_lock(lock, num_changes=2000): "Randomly change letters in lock, keeping changes that improve the score." score = word_count(lock) for i in range(num_changes): lock2 = changed_lock(lock) score2 = word_count(lock2) if score2 >= score: lock, score = lock2, sc...
notes/python/p_norvig/word/Fred Buns.ipynb
kunaltyagi/SDES
gpl-3.0
We'll need a way to produce a new lock with a random change:
def changed_lock(lock): "Change one letter in one tumbler." i = random.randrange(len(lock)) other_letters = [L for L in alphabet if L not in lock[i]] new_tumbler = lock[i].replace(random.choice(lock[i]), random.choice(other_letters)) return lock[:i] + [new_tumbler] +...
notes/python/p_norvig/word/Fred Buns.ipynb
kunaltyagi/SDES
gpl-3.0
(Note: I use the participle form (improved, changed) in analogy to the built-in function sorted, to indicate that the function creates a new object. I would tend to use the verb form (improve, change, sort) to indicate a function that mutates its argument.) Let's see how this does to improve the best lock we've seen so...
%time show(improved_lock(greedy_lock()))
notes/python/p_norvig/word/Fred Buns.ipynb
kunaltyagi/SDES
gpl-3.0
Could we do better starting from wordlock?
show(improved_lock(wordlock))
notes/python/p_norvig/word/Fred Buns.ipynb
kunaltyagi/SDES
gpl-3.0
How about starting from a random lock?
show(improved_lock(random_lock()))
notes/python/p_norvig/word/Fred Buns.ipynb
kunaltyagi/SDES
gpl-3.0
It seems to be easy to generate a lock with about 1230 words, and it doesn't seem to matter much where you start. How hard is it to get more than about 1240 words? I'll improve 50 random locks and see (this will take around 10 minutes):
%%time improved_locks = [improved_lock(random_lock(), 5000) for i in range(50)]
notes/python/p_norvig/word/Fred Buns.ipynb
kunaltyagi/SDES
gpl-3.0
Let's get some basic stats on the scores:
def mean(numbers): "The mean, or average, of a sequence of numbers." return sum(numbers) / len(numbers) scores = [word_count(lock) for lock in improved_locks] min(scores), mean(scores), max(scores)
notes/python/p_norvig/word/Fred Buns.ipynb
kunaltyagi/SDES
gpl-3.0
The scores are tightly grouped from 1232 to 1240, with the majority of them scoring 1240. We can also visualize the scores as a histogram:
plt.hist(scores);
notes/python/p_norvig/word/Fred Buns.ipynb
kunaltyagi/SDES
gpl-3.0
And see the best lock:
show(max(improved_locks, key=word_count))
notes/python/p_norvig/word/Fred Buns.ipynb
kunaltyagi/SDES
gpl-3.0
Is 1240 the maximum? At first I thought that there are probably locks with more than 1240 words. Bit after a discussion with Matt Chisholm, I now think that 1240 might be the maximum (given my 4360 word dictionary). I came to this realization after investigating how many different locks there are in improved_locks. T...
def alock(lock): "Canonicalize lock by alphabetizing the letters in each tumbler." return tuple(cat(sorted(tumbler)) for tumbler in lock) unique_locks = {alock(lock): word_count(lock) for lock in improved_locks} unique_locks
notes/python/p_norvig/word/Fred Buns.ipynb
kunaltyagi/SDES
gpl-3.0
So out of the 50 improved_locks there are actually only 6 distinct ones. And only two have a score of 1240.
L1240 = {lock for lock in unique_locks if unique_locks[lock] == 1240} L1240
notes/python/p_norvig/word/Fred Buns.ipynb
kunaltyagi/SDES
gpl-3.0
These two differ in just one letter (a P or a W in the second tumbler). This discovery changes my whole thinking about the space of scores for locks. Previously I thought there were many distinct locks with score 1240, and I imagined a spiky "porcupine-shaped" landscape with many peaks at 1240, and therefore it seeme...
def transpose(strings): return [cat(letters) for letters in zip(*strings)]
notes/python/p_norvig/word/Fred Buns.ipynb
kunaltyagi/SDES
gpl-3.0
And we can see the transpose of the wordlock is a list of words:
transpose(['SPHMTWDLFB', 'LEYHNRUOAI', 'ENMLRTAOSK', 'DSNMPYLKTE'])
notes/python/p_norvig/word/Fred Buns.ipynb
kunaltyagi/SDES
gpl-3.0
The first row of the word list has the letters SLED, because those are the letters in the first column of the lock. You can see that the WordLock® is designed to spell out LOOK FAST BIKE, among other words. Now we're ready to find a good word list with this strategy: Start with some word list (e.g., a random samp...
def improved_wordlist(wordlist): "Find a wordlist that has no duplicate letters, via random changes to wordlist." score = duplicates(wordlist) while score > 0: wordlist2 = changed_wordlist(wordlist) score2 = duplicates(wordlist2) if score2 < score: wordlist, score = wo...
notes/python/p_norvig/word/Fred Buns.ipynb
kunaltyagi/SDES
gpl-3.0
The structure of improved_wordlist is similar to improved_lock, with a few differences: 1. We are minimizing duplicates, not maximizing word count. 2. We stop when the score is 0, rather than continuing for a given number of iterations. 3. We want to make a random.choice from WORDS. But random.choice can't operate on...
improved_wordlist(random.sample(WORDS, 10))
notes/python/p_norvig/word/Fred Buns.ipynb
kunaltyagi/SDES
gpl-3.0
That was easy! Can we go to 11?
improved_wordlist(random.sample(WORDS, 11))
notes/python/p_norvig/word/Fred Buns.ipynb
kunaltyagi/SDES
gpl-3.0
Improving Anything We now have two similar functions, improved_lock and improved_wordlist. Could (and should?) we replace them by a single function, say, improved, that could improve locks, wordlists, and anything else? The answer is: yes we could, and maybe we should. It is nice to form an abstraction for the idea of...
def improved(item, changed, scorer, stop, extremum=max): """Apply the function changed to item and evaluate with the function scorer; When stop(i, score, item) is true, return item.""" score = scorer(item) for i in itertools.count(0): if stop(i, score, item): return item item...
notes/python/p_norvig/word/Fred Buns.ipynb
kunaltyagi/SDES
gpl-3.0
Now we can re-implement improved_lock and improved_wordlist using improved:
def improved_lock(lock, num_changes=2000): "Randomly change letters in lock, keeping changes that improve the score." def stop_after_num_changes(i, _, __): return i == num_changes return improved(lock, changed_lock, word_count, stop_after_num_changes, max) def improved_wordlist(wordlist): "Find a wordl...
notes/python/p_norvig/word/Fred Buns.ipynb
kunaltyagi/SDES
gpl-3.0
Question 4: Coincidence? There is still one unanswered question: did the designers of WordLock&reg; deliberately put "FRED BUNS" in, or was it a coincidence? Astute Hacker News reader emhart commented that he had found the patent assigned to WordLock; it describes an algorithm similar to my greedy_lock. After seeing t...
def patented_lock(d=4, c=10, words=WORDS): "Make a lock with d tumblers, each consisting of the c letters that cover the most words at that position." lock = Lock('?' * d) for i in range(d): # Make a tumbler of c letters, to be used in position i, such that the tumbler covers the most words. ...
notes/python/p_norvig/word/Fred Buns.ipynb
kunaltyagi/SDES
gpl-3.0
Tests It is a good idea to have some tests, in case you want to change some code and see if you have introduced an error. Also, tests serve as examples of usage of functions. The following tests have poor coverage, because it is harder to test non-deterministic functions, and I didn't attempt that here.
def tests(): assert 'WORD' in WORDS assert 'FRED' in WORDS assert 'BUNS' in WORDS assert 'XYZZ' not in WORDS assert 'word' not in WORDS assert 'FIVER' not in WORDS assert len(WORDS) == 4360 assert fredbuns == ['FB', 'RU', 'EN', 'DS'] assert combinations(fredbuns) == ['FRED','FRE...
notes/python/p_norvig/word/Fred Buns.ipynb
kunaltyagi/SDES
gpl-3.0
One More Question I wonder if @BIKESNOBNYC would appreciate this notebook? On the one hand, he is the kind of guy who, in discussing the fact that bicycling is the seventh most popular recreational activity, wrote "the number seven is itself a highly significant number. It is the lowest number that cannot be represen...
def not_sum_3_squares(N): "Positive integers < N that are not the sum of three squares." squares = [i ** 2 for i in range(int(N ** 0.5)+1)] sums = {A + B + C for A in squares for B in squares for C in squares} return set(range(N)) - sums not_sum_3_squares(100)
notes/python/p_norvig/word/Fred Buns.ipynb
kunaltyagi/SDES
gpl-3.0
Neural network classes for testing The following class, NeuralNet, allows us to create identical neural networks with and without batch normalization. The code is heaviy documented, but there is also some additional discussion later. You do not need to read through it all before going through the rest of the notebook, ...
class NeuralNet: def __init__(self, initial_weights, activation_fn, use_batch_norm): """ Initializes this object, creating a TensorFlow graph using the given parameters. :param initial_weights: list of NumPy arrays or Tensors Initial values for the weights for every laye...
batch-norm/Batch_Normalization_Lesson.ipynb
chetnapriyadarshini/deep-learning
mit
In the rest of the examples, we use really bad starting weights. That is, normally we would use very small values close to zero. However, in these examples we choose randome values with a standard deviation of 5. If you were really training a neural network, you would not want to do this. But these examples demonstrate...
train_and_test(True, 0.01, tf.nn.relu)
batch-norm/Batch_Normalization_Lesson.ipynb
chetnapriyadarshini/deep-learning
mit
The content of the raw IMU file The columns of the IMU data contain: <ol start="0"> <li>Packet number</li> <li>Gyroscope X (deg/s)</li> <li>Gyroscope Y (deg/s)</li> <li>Gyroscope Z (deg/s)</li> <li>Accelerometer X (g)</li> <li>Accelerometer Y (g)</li> <li>Accelerometer Z (g)</li> <li>Magnetometer X (G)...
db.plot_imu_data("S12", "D", "RA")
notebooks/Get started.ipynb
alfkjartan/nvgimu
gpl-3.0
Try an analysis
db.get_angle_to_vertical_markers(subject="S4") res = db.apply_to_all_trials(db.get_RoM_angle_to_vertical, {'imu':'LH'}, subjlist=['S4', 'S6'], triallist=['B', 'N']) res = db.apply_to_all_trials(db.get_angle_to_vertical_markers, {'imu':'LH'}, ...
notebooks/Get started.ipynb
alfkjartan/nvgimu
gpl-3.0
We also have a Python file containing implementations for several functions that will be used during the course of this assignment.
from em_utilities import *
coursera/ml-clustering-and-retrieval/assignments/4_em-with-text-data_blank.ipynb
jinntrance/MOOC
cc0-1.0
Load Wikipedia data and extract TF-IDF features Load Wikipedia data and transform each of the first 5000 document into a TF-IDF representation.
wiki = graphlab.SFrame('people_wiki.gl/').head(5000) wiki['tf_idf'] = graphlab.text_analytics.tf_idf(wiki['text'])
coursera/ml-clustering-and-retrieval/assignments/4_em-with-text-data_blank.ipynb
jinntrance/MOOC
cc0-1.0
Using a utility we provide, we will create a sparse matrix representation of the documents. This is the same utility function you used during the previous assignment on k-means with text data.
tf_idf, map_index_to_word = sframe_to_scipy(wiki, 'tf_idf')
coursera/ml-clustering-and-retrieval/assignments/4_em-with-text-data_blank.ipynb
jinntrance/MOOC
cc0-1.0
As in the previous assignment, we will normalize each document's TF-IDF vector to be a unit vector.
tf_idf = normalize(tf_idf)
coursera/ml-clustering-and-retrieval/assignments/4_em-with-text-data_blank.ipynb
jinntrance/MOOC
cc0-1.0
We can check that the length (Euclidean norm) of each row is now 1.0, as expected.
for i in range(5): doc = tf_idf[i] print(np.linalg.norm(doc.todense()))
coursera/ml-clustering-and-retrieval/assignments/4_em-with-text-data_blank.ipynb
jinntrance/MOOC
cc0-1.0
EM in high dimensions EM for high-dimensional data requires some special treatment: * E step and M step must be vectorized as much as possible, as explicit loops are dreadfully slow in Python. * All operations must be cast in terms of sparse matrix operations, to take advantage of computational savings enabled by spa...
from sklearn.cluster import KMeans np.random.seed(5) num_clusters = 25 # Use scikit-learn's k-means to simplify workflow kmeans_model = KMeans(n_clusters=num_clusters, n_init=5, max_iter=400, random_state=1, n_jobs=-1) kmeans_model.fit(tf_idf) centroids, cluster_assignment = kmeans_model.cluster_centers_, kmeans_mode...
coursera/ml-clustering-and-retrieval/assignments/4_em-with-text-data_blank.ipynb
jinntrance/MOOC
cc0-1.0
Initializing cluster weights We will initialize each cluster weight to be the proportion of documents assigned to that cluster by k-means above.
num_docs = tf_idf.shape[0] weights = [] for i in xrange(num_clusters): # Compute the number of data points assigned to cluster i: num_assigned = (cluster_assignment == i).sum() # YOUR CODE HERE w = float(num_assigned) / num_docs weights.append(w)
coursera/ml-clustering-and-retrieval/assignments/4_em-with-text-data_blank.ipynb
jinntrance/MOOC
cc0-1.0
Initializing covariances To initialize our covariance parameters, we compute $\hat{\sigma}{k, j}^2 = \sum{i=1}^{N}(x_{i,j} - \hat{\mu}_{k, j})^2$ for each feature $j$. For features with really tiny variances, we assign 1e-8 instead to prevent numerical instability. We do this computation in a vectorized fashion in the...
covs = [] for i in xrange(num_clusters): member_rows = tf_idf[cluster_assignment==i] cov = (member_rows.power(2) - 2*member_rows.dot(diag(means[i]))).sum(axis=0).A1 / member_rows.shape[0] \ + means[i]**2 cov[cov < 1e-8] = 1e-8 covs.append(cov)
coursera/ml-clustering-and-retrieval/assignments/4_em-with-text-data_blank.ipynb
jinntrance/MOOC
cc0-1.0
Running EM Now that we have initialized all of our parameters, run EM.
out = EM_for_high_dimension(tf_idf, means, covs, weights, cov_smoothing=1e-10) out['loglik']
coursera/ml-clustering-and-retrieval/assignments/4_em-with-text-data_blank.ipynb
jinntrance/MOOC
cc0-1.0
Interpret clustering results In contrast to k-means, EM is able to explicitly model clusters of varying sizes and proportions. The relative magnitude of variances in the word dimensions tell us much about the nature of the clusters. Write yourself a cluster visualizer as follows. Examining each cluster's mean vector, ...
# Fill in the blanks def visualize_EM_clusters(tf_idf, means, covs, map_index_to_word): print('') print('==========================================================') num_clusters = len(means) for c in xrange(num_clusters): print('Cluster {0:d}: Largest mean parameters in cluster '.format(c)) ...
coursera/ml-clustering-and-retrieval/assignments/4_em-with-text-data_blank.ipynb
jinntrance/MOOC
cc0-1.0
Quiz Question. Select all the topics that have a cluster in the model created above. [multiple choice] Comparing to random initialization Create variables for randomly initializing the EM algorithm. Complete the following code block.
np.random.seed(5) # See the note below to see why we set seed=5. num_clusters = len(means) num_docs, num_words = tf_idf.shape random_means = [] random_covs = [] random_weights = [] for k in range(num_clusters): # Create a numpy array of length num_words with random normally distributed values. # Use the ...
coursera/ml-clustering-and-retrieval/assignments/4_em-with-text-data_blank.ipynb
jinntrance/MOOC
cc0-1.0
Quiz Question: Try fitting EM with the random initial parameters you created above. (Use cov_smoothing=1e-5.) Store the result to out_random_init. What is the final loglikelihood that the algorithm converges to?
out_random_init = EM_for_high_dimension(tf_idf, random_means, random_covs, random_weights, cov_smoothing=1e-5) out_random_init['loglik']
coursera/ml-clustering-and-retrieval/assignments/4_em-with-text-data_blank.ipynb
jinntrance/MOOC
cc0-1.0
Quiz Question: Is the final loglikelihood larger or smaller than the final loglikelihood we obtained above when initializing EM with the results from running k-means?
out_random_init['loglik'][-1] > out['loglik'][-1]
coursera/ml-clustering-and-retrieval/assignments/4_em-with-text-data_blank.ipynb
jinntrance/MOOC
cc0-1.0
Quiz Question: For the above model, out_random_init, use the visualize_EM_clusters method you created above. Are the clusters more or less interpretable than the ones found after initializing using k-means?
# YOUR CODE HERE. Use visualize_EM_clusters, which will require you to pass in tf_idf and map_index_to_word. visualize_EM_clusters(tf_idf, out_random_init['means'], out_random_init['covs'], map_index_to_word)
coursera/ml-clustering-and-retrieval/assignments/4_em-with-text-data_blank.ipynb
jinntrance/MOOC
cc0-1.0
Exploring the Fermi distribution In quantum statistics, the Fermi-Dirac distribution is related to the probability that a particle will be in a quantum state with energy $\epsilon$. The equation for the distribution $F(\epsilon)$ is:
Image('fermidist.png')
assignments/midterm/InteractEx06.ipynb
hunterherrin/phys202-2015-work
mit
In this equation: $\epsilon$ is the single particle energy. $\mu$ is the chemical potential, which is related to the total number of particles. $k$ is the Boltzmann constant. $T$ is the temperature in Kelvin. In the cell below, typeset this equation using LaTeX: \begin{equation} F(\epsilon)=\frac{1}{e^{(\epsilon-\mu)...
np.exp(2) def fermidist(energy, mu, kT): """Compute the Fermi distribution at energy, mu and kT.""" x=np.exp((energy-mu)/(kT)) F=1/(x+1) return F assert np.allclose(fermidist(0.5, 1.0, 10.0), 0.51249739648421033) assert np.allclose(fermidist(np.linspace(0.0,1.0,10), 1.0, 10.0), np.array([ 0.524979...
assignments/midterm/InteractEx06.ipynb
hunterherrin/phys202-2015-work
mit
Write a function plot_fermidist(mu, kT) that plots the Fermi distribution $F(\epsilon)$ as a function of $\epsilon$ as a line plot for the parameters mu and kT. Use enegies over the range $[0,10.0]$ and a suitable number of points. Choose an appropriate x and y limit for your visualization. Label your x and y axis and...
plt.plot? def plot_fermidist(mu, kT): energy=np.linspace(0.0,10.0,100) plot_f=fermidist(energy,mu,kT) plt.figure(figsize=(5,5)) plt.plot(energy,plot_f, 'ro') plt.ylabel('F($\epsilon$)') plt.xlabel('$\epsilon$') plt.title('F($\epsilon$) vs $\epsilon$') plt.tight_layout() plt.xlim(0,2...
assignments/midterm/InteractEx06.ipynb
hunterherrin/phys202-2015-work
mit
Use interact with plot_fermidist to explore the distribution: For mu use a floating point slider over the range $[0.0,5.0]$. for kT use a floating point slider over the range $[0.1,10.0]$.
interact(plot_fermidist, mu=(0.0,5.0), kT=(0.1,10.0))
assignments/midterm/InteractEx06.ipynb
hunterherrin/phys202-2015-work
mit
Pesquisando
tweets = api.search(q='Python', lang='pt') # Teste o parâmetro count=150 for i, tweet in enumerate(tweets, start=1): print("%d ---- %s" % (i, tweet.text))
Python/2016-07-29/aula4-parte4-pesquisar-tweets.ipynb
rubensfernando/mba-analytics-big-data
mit
Recuperar 1000 tweets
tweets_salvos = [] ultimo_id = -1 qtde_tweets = 1000 while len(tweets_salvos) < qtde_tweets: contador = qtde_tweets - len(tweets_salvos) try: novos_tweets = api.search(q='Python', count=contador, max_id=str(ultimo_id - 1)) # Teste com o parâmetro lang='pt' if not novos_tweets: print...
Python/2016-07-29/aula4-parte4-pesquisar-tweets.ipynb
rubensfernando/mba-analytics-big-data
mit
Filling in Missing Values
# Impute missing values # Manually set metadata properties, as current py_entitymatching.impute_table() # requires 'fk_ltable', 'fk_rtable', 'ltable', 'rtable' properties em.set_property(A, 'fk_ltable', 'id') em.set_property(A, 'fk_rtable', 'id') em.set_property(A, 'ltable', A) em.set_property(A, 'rtable', A) A_all_a...
stage5/stage5_report.ipynb
malnoxon/board-game-data-science
gpl-3.0
Generating Features Here, we generate all the features we decided upon after our final iteration of cross validation and debugging. We only use the relevant subset of all these features in the reported iterations below.
# Generate a set of features #import pdb; pdb.set_trace(); import py_entitymatching.feature.attributeutils as au import py_entitymatching.feature.simfunctions as sim import py_entitymatching.feature.tokenizers as tok ltable = A1 rtable = B1 # Get similarity functions for generating the features for matching sim_funcs...
stage5/stage5_report.ipynb
malnoxon/board-game-data-science
gpl-3.0
Generate training set
# Apply train, test set evaluation I_table = em.extract_feature_vecs(I, feature_table=F_2, attrs_after='label', show_progress=False) J_table = em.extract_feature_vecs(J, feature_table=F_2, attrs_after='label', show_progress=False) total_cand_set_features = em.extract_feature_vecs(total_cand_set, feature_table=F_2, sho...
stage5/stage5_report.ipynb
malnoxon/board-game-data-science
gpl-3.0
Joining Tables
# Join tables on matched tuples match_tuples = total_cand_set_features[total_cand_set_features['prediction']==1] match_tuples = match_tuples[['ltable_id','rtable_id']] A1['ltable_id'] = A1['id'] B1['rtable_id'] = B1['id'] joined_tables = pd.merge(match_tuples, A1, how='left', on='ltable_id') joined_tables = pd.merge(jo...
stage5/stage5_report.ipynb
malnoxon/board-game-data-science
gpl-3.0
Adventure Time!
import pandas as pd import matplotlib as plt from scipy.stats.stats import pearsonr %matplotlib inline joined_tables = pd.read_csv('new_joined_table.csv') joined_tables.iloc[1:4].to_csv('4_tuples.csv') from StringIO import StringIO import prettytable pt = prettytable.from_csv(open('new_joined_table.csv')) print ...
stage5/stage5_report.ipynb
malnoxon/board-game-data-science
gpl-3.0
Read Salaries.csv as a dataframe called sal.
sal = pd.read_csv('Salaries.csv')
udemy_ml_bootcamp/Python-for-Data-Analysis/Pandas/Pandas Exercises/SF Salaries Exercise- Solutions.ipynb
AtmaMani/pyChakras
mit
Check the head of the DataFrame.
sal.head()
udemy_ml_bootcamp/Python-for-Data-Analysis/Pandas/Pandas Exercises/SF Salaries Exercise- Solutions.ipynb
AtmaMani/pyChakras
mit
Use the .info() method to find out how many entries there are.
sal.info() # 148654 Entries
udemy_ml_bootcamp/Python-for-Data-Analysis/Pandas/Pandas Exercises/SF Salaries Exercise- Solutions.ipynb
AtmaMani/pyChakras
mit
What is the average BasePay ?
sal['BasePay'].mean()
udemy_ml_bootcamp/Python-for-Data-Analysis/Pandas/Pandas Exercises/SF Salaries Exercise- Solutions.ipynb
AtmaMani/pyChakras
mit
What is the highest amount of OvertimePay in the dataset ?
sal['OvertimePay'].max()
udemy_ml_bootcamp/Python-for-Data-Analysis/Pandas/Pandas Exercises/SF Salaries Exercise- Solutions.ipynb
AtmaMani/pyChakras
mit
What is the job title of JOSEPH DRISCOLL ? Note: Use all caps, otherwise you may get an answer that doesn't match up (there is also a lowercase Joseph Driscoll).
sal[sal['EmployeeName']=='JOSEPH DRISCOLL']['JobTitle']
udemy_ml_bootcamp/Python-for-Data-Analysis/Pandas/Pandas Exercises/SF Salaries Exercise- Solutions.ipynb
AtmaMani/pyChakras
mit
How much does JOSEPH DRISCOLL make (including benefits)?
sal[sal['EmployeeName']=='JOSEPH DRISCOLL']['TotalPayBenefits']
udemy_ml_bootcamp/Python-for-Data-Analysis/Pandas/Pandas Exercises/SF Salaries Exercise- Solutions.ipynb
AtmaMani/pyChakras
mit
What is the name of highest paid person (including benefits)?
sal[sal['TotalPayBenefits']== sal['TotalPayBenefits'].max()] #['EmployeeName'] # or # sal.loc[sal['TotalPayBenefits'].idxmax()]
udemy_ml_bootcamp/Python-for-Data-Analysis/Pandas/Pandas Exercises/SF Salaries Exercise- Solutions.ipynb
AtmaMani/pyChakras
mit
What is the name of lowest paid person (including benefits)? Do you notice something strange about how much he or she is paid?
sal[sal['TotalPayBenefits']== sal['TotalPayBenefits'].min()] #['EmployeeName'] # or # sal.loc[sal['TotalPayBenefits'].idxmax()]['EmployeeName'] ## ITS NEGATIVE!! VERY STRANGE
udemy_ml_bootcamp/Python-for-Data-Analysis/Pandas/Pandas Exercises/SF Salaries Exercise- Solutions.ipynb
AtmaMani/pyChakras
mit
What was the average (mean) BasePay of all employees per year? (2011-2014) ?
sal.groupby('Year').mean()['BasePay']
udemy_ml_bootcamp/Python-for-Data-Analysis/Pandas/Pandas Exercises/SF Salaries Exercise- Solutions.ipynb
AtmaMani/pyChakras
mit
How many unique job titles are there?
sal['JobTitle'].nunique()
udemy_ml_bootcamp/Python-for-Data-Analysis/Pandas/Pandas Exercises/SF Salaries Exercise- Solutions.ipynb
AtmaMani/pyChakras
mit
What are the top 5 most common jobs?
sal['JobTitle'].value_counts().head(5)
udemy_ml_bootcamp/Python-for-Data-Analysis/Pandas/Pandas Exercises/SF Salaries Exercise- Solutions.ipynb
AtmaMani/pyChakras
mit
How many Job Titles were represented by only one person in 2013? (e.g. Job Titles with only one occurence in 2013?)
sum(sal[sal['Year']==2013]['JobTitle'].value_counts() == 1) # pretty tricky way to do this...
udemy_ml_bootcamp/Python-for-Data-Analysis/Pandas/Pandas Exercises/SF Salaries Exercise- Solutions.ipynb
AtmaMani/pyChakras
mit
How many people have the word Chief in their job title? (This is pretty tricky)
def chief_string(title): if 'chief' in title.lower(): return True else: return False sum(sal['JobTitle'].apply(lambda x: chief_string(x)))
udemy_ml_bootcamp/Python-for-Data-Analysis/Pandas/Pandas Exercises/SF Salaries Exercise- Solutions.ipynb
AtmaMani/pyChakras
mit
Bonus: Is there a correlation between length of the Job Title string and Salary?
sal['title_len'] = sal['JobTitle'].apply(len) sal[['title_len','TotalPayBenefits']].corr() # No correlation.
udemy_ml_bootcamp/Python-for-Data-Analysis/Pandas/Pandas Exercises/SF Salaries Exercise- Solutions.ipynb
AtmaMani/pyChakras
mit
The goal is to add your data to STELLAB to produce plots such as the plot below:
s1=st.stellab() xaxis='[Fe/H]' yaxis='[O/Fe]' s1.plot_spectro(fig=1,xaxis=xaxis,galaxy='carina') plt.xlim(-4.5,1),plt.ylim(-1.5,1.5)
DOC/Capabilities/AddingDataToStellab.ipynb
NuGrid/NuPyCEE
bsd-3-clause
Adding your own data.
from IPython.display import YouTubeVideo YouTubeVideo("R3_EZlXTFBo") s1_new=st.stellab() # available data # s1_new.list_ref_papers() s1_new.plot_spectro(fig=2,yaxis=yaxis, obs=['stellab_data/carina_data/Fabrizio_et_al_2015_stellab'],show_err=True) plt.xlim(-4,0),plt.ylim(-2,2)
DOC/Capabilities/AddingDataToStellab.ipynb
NuGrid/NuPyCEE
bsd-3-clause
Uploading data coming soon...
#from IPython.display import YouTubeVideo #YouTubeVideo("Pi9NpxAvYSs")
DOC/Capabilities/AddingDataToStellab.ipynb
NuGrid/NuPyCEE
bsd-3-clause
1. Conceptual Questions Describe the general process for parametric hypothesis tests. Why would you choose a non-parametric hypothesis test over a parametric one? Why would you choose a parametric hypothesis test over a non-parametric one? If you do not reject the null hypothesis, does that mean you've proved i...
import scipy.stats as ss ss.t.cdf(-2, 4) * 2
unit_10/hw_2019/homework_10_key.ipynb
whitead/numerical_stats
gpl-3.0
2.3
-ss.norm.ppf(0.025)
unit_10/hw_2019/homework_10_key.ipynb
whitead/numerical_stats
gpl-3.0
2.4 $$ 1.96 = \frac{\sqrt{N}\bar{x}}{\sigma} $$ You should be $ \frac{1.96}{\sqrt{N}} $ standard deviations away 2.5
1 - ss.poisson.cdf(7, mu=4.3)
unit_10/hw_2019/homework_10_key.ipynb
whitead/numerical_stats
gpl-3.0
2.6
import math 0.4 / math.sqrt(11)
unit_10/hw_2019/homework_10_key.ipynb
whitead/numerical_stats
gpl-3.0
3. Choose the hypothesis test State which hypothesis test best fits the example below and state the null hypothesis. You can justify your answer if you feel like mulitiple tests fit. You know that coffee should be brewed at 186 $^\circ{}$F. You measure coffee from Starbuck 10 times over a week and want to know if th...
p = ss.wilcoxon([181, 182, 181, 182, 182, 183, 185], [180, 179, 184, 179, 180, 183, 180]) print(p[1])
unit_10/hw_2019/homework_10_key.ipynb
whitead/numerical_stats
gpl-3.0
4.2 Poisson The number of accidents is from the population distribution 0.032 Reject Yes, there is a significant difference
1 - ss.poisson.cdf(17, mu=11)
unit_10/hw_2019/homework_10_key.ipynb
whitead/numerical_stats
gpl-3.0
4.3 t-test The new bills are from the population distribution of previous bills 0.09 Do not reject No, the new bill is not significantly different
import numpy as np data = [21, 30, 25, 23] se = np.std(data, ddof=1) / np.sqrt(len(data)) T = (np.mean(data) - 20) / se ss.t.cdf(-abs(T), df=len(data) - 1) * 2
unit_10/hw_2019/homework_10_key.ipynb
whitead/numerical_stats
gpl-3.0
5. Exponential Test (5 Bonus Points) Your dog typically greets you within 10 seconds of coming home. Is it significant that your dog took 16 seconds?
1 - ss.expon.cdf(16, scale=10)
unit_10/hw_2019/homework_10_key.ipynb
whitead/numerical_stats
gpl-3.0
O próximo passo é criar a seguinte rede no Tensorflow. <img src="https://www.embarcados.com.br/wp-content/uploads/2016/09/Perceptron-01.png" width="50%" /> Observe que a rede é composta por um conjunto de sinais de entrada ($x_{train} = [x_1, x_2, ..., x_n]$). Cada sinal é poderado por um peso w, dado por $weights = [w...
# imports necessários import tensorflow as tf # Função de ativação def output(u): is_greater = tf.greater(u, 0) as_float = tf.to_float(is_greater) return as_float ''' Criação do array que representa o limiar. O limiar é inicializado com -1. Neste caso, o limiar representa um vetor 14x1, ou seja, é atrib...
Tensorflow/Tutorial02_MLP.ipynb
adolfoguimaraes/machinelearning
mit
Modelo criado. A próxima etapa é definir como nosso modelo será treinado. Este problema é uma tarefa de classificação. Cada instância vai ser classificada como 0 ou 1 de acordo com a classe que pertence. Sendo assim, o primeiro passo é comparar a saída com a classificação da base de treinamento. Para isso foi calculad...
error = tf.subtract(y_train.T, output_value) mse = tf.reduce_sum(tf.square(error))
Tensorflow/Tutorial02_MLP.ipynb
adolfoguimaraes/machinelearning
mit
Um outro passo do treinamento é a atualização dos valores dos pesos e do limiar. Esses parâmetros são atualizados segundo fórmula descrita no livro do Ivan Nunes. $w_{i}^{atual} = w_{i}^{anterior} + \eta (d^{(k)} - y).x_{i}^{(k)}$ $\theta_{i}^{atual} = \theta_{i}^{anterior} + \eta (d^{(k)} - y).(-1)$ onde: $d^{(k)}$ é...
learning_rate = 0.001 delta_w = tf.matmul(x_train, learning_rate*error, transpose_a=True) delta_limiar = tf.matmul(limiar, learning_rate*error, transpose_a=True) train_w = tf.assign(weights, tf.add(weights, delta_w)) train_limiar = tf.assign(limiar, tf.add(limiar, delta_limiar))
Tensorflow/Tutorial02_MLP.ipynb
adolfoguimaraes/machinelearning
mit
Uma vez que criamos o modelo, vamos executar as operações para treina-lo.
init_op = tf.global_variables_initializer() sess = tf.Session() sess.run(init_op) for step in range(5000): _, _, a, b, c = sess.run([train_w, train_limiar, mse, weights, limiar], feed_dict={X: x_train, Y: y_train}) print("Weights") print(b) print("Limiar", c[0][0])
Tensorflow/Tutorial02_MLP.ipynb
adolfoguimaraes/machinelearning
mit
O código a seguir apenas cria a função determinada pelos pesos e limiar achados pela rede e plota essa reta no gráfico dos dados mostrado anteriormente.
#Graphic display import matplotlib.pyplot as plt A = x_train[:, 0] B = x_train[:, 1] colormap = np.array(['r', 'k']) # Plot the original data plt.scatter(A, B, c=colormap[[0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 1, 1, 1, 1]], s=40) ymin, ymax = plt.ylim() # Calc the hyperplane (decision boundary) ymin, ymax = plt.ylim() w =...
Tensorflow/Tutorial02_MLP.ipynb
adolfoguimaraes/machinelearning
mit
Multilayer Perceptron Uma rede perceptron multicamadas (Multilayer Perceptron - MLP) é caracterizada pela presença de pelo menos uma camada intermediária (escondida ou hidden layer) de neurônios, situada entre a camada de entrada e a respectiva camada neural de saída. Sendo assim, as MLP possuem pelo menos duas camadas...
# Carregando a base. Se a base não existir a pasta "dataset/MNIST" será criada e a base salva nesta pasta. from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("dataset/MNIST", one_hot=True)
Tensorflow/Tutorial02_MLP.ipynb
adolfoguimaraes/machinelearning
mit
Cada imagem do dataset possui o tamanho de 28x28 e representa um dígito escrito à mão. A imagem a seguir ilustra uma instância da base: <img src="https://www.tensorflow.org/images/MNIST-Matrix.png" width="70%" /> As imagens vão ser transformadas em um vetor de 784 posições ($28*28$). A entrada da rede são vários vetore...
# Imports necessários import tensorflow as tf #Definição de parâmetros learning_rate = 0.001 training_epochs = 15 batch_size = 100 display_step = 1 #Parâmetros da rede n_hidden_1 = 256 # Quantidade de features da primeira camada escondida n_hidden_2 = 256 # Quantidade de features da segunda camada escondida n_inpu...
Tensorflow/Tutorial02_MLP.ipynb
adolfoguimaraes/machinelearning
mit
O modelo é implementado dentro da função multilayer_perceptron. Na função criamos cada camada de acordo com os dados passados. É muito importante que as dimensões das variáveis passadas tenham sido definidas corretamente.
def multilayer_perceptron(x, weights, biases): # Primeira camada como função de ativação RELU layer_1 = tf.add(tf.matmul(x, weights['h1']), biases['b1']) layer_1 = tf.nn.relu(layer_1) # Segunda camada com funç!ao de ativação RELU layer_2 = tf.add(tf.matmul(layer_1, weights['h2'])...
Tensorflow/Tutorial02_MLP.ipynb
adolfoguimaraes/machinelearning
mit
Os pesos e bias utilizados serão armazenados em dois dicionários: weights e biases.
weights = { 'h1': tf.Variable(tf.random_normal([n_input, n_hidden_1])), 'h2': tf.Variable(tf.random_normal([n_hidden_1, n_hidden_2])), 'out': tf.Variable(tf.random_normal([n_hidden_2, n_classes])) } biases = { 'b1': tf.Variable(tf.random_normal([n_hidden_1])), 'b2': tf.Variable(tf.random_normal([n_h...
Tensorflow/Tutorial02_MLP.ipynb
adolfoguimaraes/machinelearning
mit
Construindo o modelo:
pred = multilayer_perceptron(x, weights, biases)
Tensorflow/Tutorial02_MLP.ipynb
adolfoguimaraes/machinelearning
mit
Uma vez que o modelo foi criado, podemos treina-lo. O primeiro passo é definir como vai ser calculado o custo da solução e, em seguida, o método que será utilizado para otimizar o modelo. Três métodos são importantes nesta etapa: tf.nn.sofmax_cross_entropy_with_logits tf.reduce_mean tf.train.AdamOptimizer Detalhes de...
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=pred, labels=y)) optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)
Tensorflow/Tutorial02_MLP.ipynb
adolfoguimaraes/machinelearning
mit
O código a seguir executa a etapa de treinamento. Detalhes são dados ao decorrer do código.
# Inicializa as variáveis init = tf.global_variables_initializer() # Executa o grafo que representa o modelo construído with tf.Session() as sess: sess.run(init) ''' O ciclo de treinamento é chamado de épocas. Em cada época uma quantidade de dados de entrada (batch) é passada como entrada para a rede....
Tensorflow/Tutorial02_MLP.ipynb
adolfoguimaraes/machinelearning
mit
Base do noMNIST A tarefa resolvida anteriormente é relativamente simples, já que a base é bem simples e já foi pré-processada com um próposito bem específico. Pensando nisso é que foi criada uma outra base (noMNIST) para o mesmo propósito: classificar dígitos, neste caso dígitos de A-Z. Apessar de parecer com o clássic...
# Imports necessários from __future__ import print_function import numpy as np import tensorflow as tf from six.moves import cPickle as pickle from six.moves import range #Carrega a base de dados pickle_file = 'dataset/notMNIST.pickle' with open(pickle_file, 'rb') as f: save = pickle.load(f) train_dataset = ...
Tensorflow/Tutorial02_MLP.ipynb
adolfoguimaraes/machinelearning
mit
Vamos utilizar o mesmo método definido anteriormente: multilayer_perceptron que recebe como parâmetro os dados de entrada e as variáveis para armazenar os bias e weights.
weights = { 'h1': tf.Variable(tf.random_normal([n_input, n_hidden_1])), 'h2': tf.Variable(tf.random_normal([n_hidden_1, n_hidden_2])), 'out': tf.Variable(tf.random_normal([n_hidden_2, n_classes])) } biases = { 'b1': tf.Variable(tf.random_normal([n_hidden_1])), 'b2': tf.Variable(tf.random_normal([n_h...
Tensorflow/Tutorial02_MLP.ipynb
adolfoguimaraes/machinelearning
mit
O passo seguinte é treinar o modelo. Observe que diferente do exemplo anterior, neste exemplo vamos trabalhar com a base de treinamento para treinar os dados, a base de validação para testar o modelo ao longo das iterações e ao final testa-lo na base de teste.
# Inicializa as variáveis training_epochs = 30 init = tf.global_variables_initializer() # Executa o grafo que representa o modelo construído with tf.Session() as sess: sess.run(init) ''' O ciclo de treinamento é chamado de épocas. Em cada época uma quantidade de dados de entrada (batch) é passada co...
Tensorflow/Tutorial02_MLP.ipynb
adolfoguimaraes/machinelearning
mit