markdown stringlengths 0 37k | code stringlengths 1 33.3k | path stringlengths 8 215 | repo_name stringlengths 6 77 | license stringclasses 15
values |
|---|---|---|---|---|
Load Data | train_df = pd.read_csv("data/train.tsv", sep="\t")
train_df.sample(10)
# Load the Test Dataset
# Note that it's missing the Sentiment Column. That's what we need to Predict
#
test_df = pd.read_csv("data/test.tsv", sep="\t")
test_df.head() | 01-load-vectorize-count.ipynb | sampathweb/movie-sentiment-analysis | mit |
Explore Dataset | # Equal Number of Positive and Negative Sentiments
train_df.sentiment.value_counts()
# Lets take a look at some examples
def print_reviews(reviews, max_words=500):
for review in reviews:
print(review[:500], end="\n\n")
# Some Positive Reviews
print("Sample **Positive** Reviews: ", "\n")
print_reviews(trai... | 01-load-vectorize-count.ipynb | sampathweb/movie-sentiment-analysis | mit |
Vectorize Data (a.k.a. covert text to numbers)
Computers don't understand Texts, so we need to convert texts to numbers before we could do any math on it and see if we can build a system to classify a review as Positive or Negative.
Ways to vectorize data:
Bag of Words
TF-IDF
Word Embeddings (Word2Vec)
Bag of Words
... | ## Doing it by Hand
def bag_of_words_vocab(reviews):
"""Returns words in the reviews"""
# all_words = []
# for review in reviews:
# for word in review.split():
# all_words.append(word)
## List comprehension method of the same lines above
all_words = [word.lower() for review in revi... | 01-load-vectorize-count.ipynb | sampathweb/movie-sentiment-analysis | mit |
Observations:
Common words are not that meaningful (also called Stop words - unfortunately)
These words are likely to appear in both Positive and Negative Reviews
We need a way to find what words are mroe likely to cocur in Postive Review as compared to Negative Review | pos_words_vocab = bag_of_words_vocab(train_df[train_df.sentiment == 1].review)
neg_words_vocab = bag_of_words_vocab(train_df[train_df.sentiment == 0].review)
pos_words_vocab.most_common(10)
neg_words_vocab.most_common(10)
pos_neg_freq = Counter()
for word in words_vocab:
pos_neg_freq[word] = (pos_words_vocab[wo... | 01-load-vectorize-count.ipynb | sampathweb/movie-sentiment-analysis | mit |
Let's Amplify the difference using Log Scale
Neutral Values are Close to 1
Negative Sentiment Words are less than 1
Positive Sentiment Words are greater than 1
When Converted to Log Scale -
Neutral Values are Close to 0
Negative Sentiment Words are negative
Positive Sentiment Words are postive
That not only makes l... | # https://www.desmos.com/calculator
Image("images/log-function.png", width=960)
for word in pos_neg_freq:
pos_neg_freq[word] = np.log(pos_neg_freq[word])
print("Neutral words:")
print("Pos-to-neg for 'the' = {:.2f}".format(pos_neg_freq["is"]))
print("Pos-to-neg for 'movie' = {:.2f}".format(pos_neg_freq["is"]))
... | 01-load-vectorize-count.ipynb | sampathweb/movie-sentiment-analysis | mit |
Time to build a Counting Model
For each Review, we will ADD all the pos_neg_freq values and if the Total for all words in the given review is > 0, we will call it Positive Review and if it's a negative total, we will call it a Negative Review. Sounds good? | class CountingClassifier(object):
def __init__(self, pos_neg_freq):
self.pos_neg_freq = pos_neg_freq
def fit(self, X, y=None):
# No Machine Learing here. It's just counting
pass
def predict(self, X):
predictions = []
for review in X:
all_wo... | 01-load-vectorize-count.ipynb | sampathweb/movie-sentiment-analysis | mit |
Machine Learning Easy? What Gives?
Remember this is Training Accuracy. We have not split our Data into Train and Validation (which we will do in our next notebook when we actualy build a Machine Learning Model)
Make a Submission to Kaggle
Predict on Test Data and Submit to Kaggle. May be we could end the tutorial ri... | ## Test Accracy
test_predictions = counting_model.predict(test_df.review)
test_predictions
y_pred = (test_predictions > 0).astype(int)
df = pd.DataFrame({
"document_id": test_df.document_id,
"sentiment": y_pred
})
df.head()
df.to_csv("data/count-submission.csv", index=False) | 01-load-vectorize-count.ipynb | sampathweb/movie-sentiment-analysis | mit |
Reasons for Testing Accuracy Being Lower?
One Hypothesis, Since we are just Adding up ALL of the scores for each word in the review, the length of the reivew could have an impact. Let's look at length of reviews in train and test dataset | import matplotlib.pyplot as plt
%matplotlib inline
train_df.review.str.len().hist(log=True)
test_df.review.str.len().hist(log=True) | 01-load-vectorize-count.ipynb | sampathweb/movie-sentiment-analysis | mit |
import data for our model
This is data imported from statline CBS webportal. | importfile = 'CBS Statline Gas Usage.xlsx'
df = pd.read_excel(importfile, sheetname='Month', skiprows=1)
df.drop(['Onderwerpen_1', 'Onderwerpen_2', 'Perioden'], axis=1, inplace=True)
#df
# transpose
df = df.transpose()
# provide headers
new_header = df.iloc[0]
df = df[1:]
df.rename(columns = new_header, inplace=Tru... | Data Analytics/.ipynb_checkpoints/Fitting curve-checkpoint.ipynb | Housebeer/Natural-Gas-Model | mit |
now let fit different consumer groups | #b = self.base_demand
#m = self.max_demand
#y = b + m * (.5 * (1 + np.cos((x/6)*np.pi)))
#b = 603
#m = 3615
N = 84 # number of data points
t = np.linspace(0, 83, N)
#data = b + m*(.5 * (1 + np.cos((t/6)*np.pi))) + 100*np.random.randn(N) # create artificial data with noise
data = np.array(df['Via regionale netten'].val... | Data Analytics/.ipynb_checkpoints/Fitting curve-checkpoint.ipynb | Housebeer/Natural-Gas-Model | mit |
price forming
In order to estimate willingness to sell en willingness to buy we look at historical data over the past view years. We look at the DayAhead market at the TTF. Altough this data does not reflect real consumption necessarily |
inputexcel = 'TTFDA.xlsx'
outputexcel = 'pythonoutput.xlsx'
price = pd.read_excel(inputexcel, sheetname='Sheet1', index_col=0)
quantity = pd.read_excel(inputexcel, sheetname='Sheet2', index_col=0)
price.index = pd.to_datetime(price.index, format="%d-%m-%y")
quantity.index = pd.to_datetime(quantity.index, format="%d-... | Data Analytics/.ipynb_checkpoints/Fitting curve-checkpoint.ipynb | Housebeer/Natural-Gas-Model | mit |
The dataset used in this lab comes from https://archive.ics.uci.edu/ml/datasets/Optical+Recognition+of+Handwritten+Digits
At face value, this looks like an easy lab, but it has many parts to it, so prepare yourself by reading through it fully before starting.
Convenience Functions | def load(path_train, path_test):
# Load up the data.
# You probably could have written this easily:
with open(path_test, 'r') as f: testing = pd.read_csv(f)
with open(path_train, 'r') as f: training = pd.read_csv(f)
# The number of samples between training and testing can vary
# But the ... | Module6/Module6 - Lab2.ipynb | authman/DAT210x | mit |
The Assignment | # TODO: Pass in the file paths to the .tra and the .tes files:
X_train, X_test, y_train, y_test = load('', '') | Module6/Module6 - Lab2.ipynb | authman/DAT210x | mit |
Get to know your data. It seems its already well organized in [n_samples, n_features] form. Your dataset looks like (4389, 784). Also your labels are already shaped as [n_samples]. | peekData(X_train) | Module6/Module6 - Lab2.ipynb | authman/DAT210x | mit |
Create an SVC classifier. Leave C=1, but set gamma to 0.001 and set the kernel to linear. Then train the model on the training data and labels: | print("Training SVC Classifier...")
# .. your code here .. | Module6/Module6 - Lab2.ipynb | authman/DAT210x | mit |
Calculate the score of your SVC against the testing data: | print("Scoring SVC Classifier...")
# .. your code here ..
print("Score:\n", score)
# Let's get some visual confirmation of accuracy:
drawPredictions(X_train, X_test, y_train, y_test) | Module6/Module6 - Lab2.ipynb | authman/DAT210x | mit |
Print out the TRUE value of the 1000th digit in the test set. By TRUE value, we mean, the actual provided, ground-truth label for that sample: | # .. your code here ..
print("1000th test label: ", true_1000th_test_value) | Module6/Module6 - Lab2.ipynb | authman/DAT210x | mit |
Predict the value of the 1000th digit in the test set. Was your model's prediction correct? If you get a warning on your predict line, look at the notes from the previous module's labs. | # .. your code here ..
print("1000th test prediction: ", guess_1000th_test_value) | Module6/Module6 - Lab2.ipynb | authman/DAT210x | mit |
Use imshow() to display the 1000th test image, so you can visually check if it was a hard image, or an easy image: | # .. your code here .. | Module6/Module6 - Lab2.ipynb | authman/DAT210x | mit |
Fun with Fourier modes
GOAL: visualize some basic behavior of Simple Eigenmodes
Modes of a square drum
Here we will visualize the Fourier Modes for the eigenfunctions of
$$-\nabla^2 \phi = \lambda\phi$$
with dirichlet Boundary conditions on the unit square $\Omega = [0,1]\times[0,1]$. The modes are
$$
\phi_{nm}... | x = np.linspace(0,1,200)
X,Y = np.meshgrid(x,x)
def seeMode(n,m,X,Y):
phi_nm = lambda n,m: np.sin(n*np.pi*X)*np.sin(m*np.pi*Y)
plt.figure(figsize=(8,6.2))
plt.contourf(X,Y,phi_nm(n,m))
plt.colorbar()
title = '$\phi_{'+'{},{}'.format(n,m)+'}$'
plt.title(title,fontsize=24)
plt.axis('equal')
... | Modes.ipynb | mspieg/principals-appmath | cc0-1.0 |
S## solution of Poisson's Equation with unit forcing
solve
$$
-\nabla^2 u = 1
$$
on $x\in[0,1]\times[0,1]$ with $u=0$ on $\partial\Omega$ | x = np.linspace(0,1,200)
X,Y = np.meshgrid(x,x)
def solvePoisson(N,X,Y,c=0):
phi_nm = lambda n,m: np.sin(n*np.pi*X)*np.sin(m*np.pi*Y)
u = np.zeros(X.shape)
for n in range(1,N+1):
for m in range(1,N+1):
bnm = 4./(np.pi**2*m*n)*(np.cos(n*np.pi)-1.)*(np.cos(m*np.pi) - 1.)
... | Modes.ipynb | mspieg/principals-appmath | cc0-1.0 |
Plotting Methods
Plotting functions are implemented as methods of the Network class.
Network.plot_s_re
Network.plot_s_im
Network.plot_s_mag
Network.plot_s_db
...
Similar methods exist for Impedance (Network.z) and Admittance Parameters (Network.y),
Network.plot_z_re
Network.plot_z_im
...
Network.plot_y_re
Network.p... | from skrf import Network
ring_slot = Network('data/ring slot.s2p')
ring_slot.plot_s_smith()
ring_slot.plot_s_smith(draw_labels=True) | doc/source/tutorials/Plotting.ipynb | Ttl/scikit-rf | bsd-3-clause |
Another common option is to draw addmitance contours, instead of impedance. This is controled through the chart_type argument. | ring_slot.plot_s_smith(chart_type='y') | doc/source/tutorials/Plotting.ipynb | Ttl/scikit-rf | bsd-3-clause |
See skrf.plotting.smith() for more info on customizing the Smith Chart.
Complex Plane
Network parameters can also be plotted in the complex plane without a Smith Chart through Network.plot_s_complex. | ring_slot.plot_s_complex()
from matplotlib import pyplot as plt
plt.axis('equal') # otherwise circles wont be circles | doc/source/tutorials/Plotting.ipynb | Ttl/scikit-rf | bsd-3-clause |
Log-Magnitude
Scalar components of the complex network parameters can be plotted vs
frequency as well. To plot the log-magnitude of the s-parameters vs. frequency, | ring_slot.plot_s_db() | doc/source/tutorials/Plotting.ipynb | Ttl/scikit-rf | bsd-3-clause |
When no arguments are passed to the plotting methods, all parameters are plotted. Single parameters can be plotted by passing indices m and n to the plotting commands (indexing start from 0). Comparing the simulated reflection coefficient off the ring slot to a measurement, | from skrf.data import ring_slot_meas
ring_slot.plot_s_db(m=0,n=0, label='Theory')
ring_slot_meas.plot_s_db(m=0,n=0, label='Measurement') | doc/source/tutorials/Plotting.ipynb | Ttl/scikit-rf | bsd-3-clause |
Phase
Plot phase, | ring_slot.plot_s_deg() | doc/source/tutorials/Plotting.ipynb | Ttl/scikit-rf | bsd-3-clause |
Or unwrapped phase, | ring_slot.plot_s_deg_unwrap() | doc/source/tutorials/Plotting.ipynb | Ttl/scikit-rf | bsd-3-clause |
Phase is radian (rad) is also available
Group Delay
A Network has a plot() method which creates a rectangular plot of the argument vs frequency. This can be used to make plots are arent 'canned'. For example group delay | gd = abs(ring_slot.s21.group_delay) *1e9 # in ns
ring_slot.plot(gd)
plt.ylabel('Group Delay (ns)')
plt.title('Group Delay of Ring Slot S21') | doc/source/tutorials/Plotting.ipynb | Ttl/scikit-rf | bsd-3-clause |
Impedance, Admittance
The components the Impendance and Admittance parameters can be plotted
similarly, | ring_slot.plot_z_im()
ring_slot.plot_y_im() | doc/source/tutorials/Plotting.ipynb | Ttl/scikit-rf | bsd-3-clause |
Customizing Plots
The legend entries are automatically filled in with the Network's Network.name. The entry can be overidden by passing the label argument to the plot method. | ring_slot.plot_s_db(m=0,n=0, label = 'Simulation') | doc/source/tutorials/Plotting.ipynb | Ttl/scikit-rf | bsd-3-clause |
The frequency unit used on the x-axis is automatically filled in from
the Networks Network.frequency.unit attribute. To change
the label, change the frequency's unit. | ring_slot.frequency.unit = 'mhz'
ring_slot.plot_s_db(0,0) | doc/source/tutorials/Plotting.ipynb | Ttl/scikit-rf | bsd-3-clause |
Other key word arguments given to the plotting methods are passed through to the matplotlib matplotlib.pyplot.plot function. | ring_slot.frequency.unit='ghz'
ring_slot.plot_s_db(m=0,n=0, linewidth = 3, linestyle = '--', label = 'Simulation')
ring_slot_meas.plot_s_db(m=0,n=0, marker = 'o', markevery = 10,label = 'Measured')
| doc/source/tutorials/Plotting.ipynb | Ttl/scikit-rf | bsd-3-clause |
All components of the plots can be customized through matplotlib functions, and styles can be used with a context manager. | from matplotlib import pyplot as plt
from matplotlib import style
with style.context('seaborn-ticks'):
ring_slot.plot_s_smith()
plt.xlabel('Real Part');
plt.ylabel('Imaginary Part');
plt.title('Smith Chart With Legend Room');
plt.axis([-1.1,2.1,-1.1,1.1])
plt.legend(loc=5)
| doc/source/tutorials/Plotting.ipynb | Ttl/scikit-rf | bsd-3-clause |
Saving Plots
Plots can be saved in various file formats using the GUI provided by the matplotlib. However, skrf provides a convenience function, called skrf.plotting.save_all_figs, that allows all open figures to be saved to disk in multiple file formats, with filenames pulled from each figure's title,
from skrf.plott... | from skrf import plotting
with style.context('printable'):
ring_slot.plot_s_deg()
plotting.add_markers_to_lines()
plt.legend() # have to re-generate legend
| doc/source/tutorials/Plotting.ipynb | Ttl/scikit-rf | bsd-3-clause |
Then, set the number of target clusters, number of features and number of samples: | nb_cluster = 5
nb_features = 2
nb_samples = 500
nb_cluster, nb_features,nb_samples | Fast KMeans Notebook.ipynb | SevData/fast_kmeans | mit |
Randomly draw some samples and initial centroids. It is important to convert the lists to numpy arrays with 'double' type so the C function recognizes them. | X = [[random.random() for i in range(nb_features)] for j in range(nb_samples)]
mu = random.sample(X, nb_cluster)
X = np.array(X, dtype="double")
mu = np.array(mu, dtype="double")
mu | Fast KMeans Notebook.ipynb | SevData/fast_kmeans | mit |
Set the initial weights for each features at 1 (all features have the same importance).
Also we need create the labels list, which will be passed to Cfast_km function to get the cluster number for each sample | weights = np.array([1 for i in range(nb_features)], dtype="double")
labels = np.zeros(len(X), dtype="int") | Fast KMeans Notebook.ipynb | SevData/fast_kmeans | mit |
Let's execute the Fast KMEANS functions. Results will be collected through mu (centroids) and labels (samples labels). The last argument (set as 0) is the tolerance : increasing it will stop the process in earlier steps without a full convergence, but will save some computing time. | Cfast_km(X , mu , labels, weights, 0)
mu, labels | Fast KMeans Notebook.ipynb | SevData/fast_kmeans | mit |
Let's plot the results. We keep the first 2 features for 2D plotting | cmap = { 0:'k',1:'b',2:'y',3:'g',4:'r' }
fig = plt.figure(figsize=(5,5))
plt.xlim(0,1)
plt.ylim(0,1)
for i in range(nb_cluster):
X_extract = X[labels == i]
X1 = np.transpose(X_extract[:,0]).tolist()
X2 = np.transpose(X_extract[:,1]).tolist()
plt.plot(X1, X2, cmap[i%5]+'.', alpha=0.5)
mu1 = np.trans... | Fast KMeans Notebook.ipynb | SevData/fast_kmeans | mit |
There is a special do nothing word: pass that skips over some arm of a conditional, e.g. | if 'Jim' in instructors:
print("Congratulations! Jim is teaching, your class won't stink!")
else:
pass | lecture/06.Procedural_Python.part3.ipynb | danielfather7/teach_Python | gpl-3.0 |
For
For loops are the standard loop, though while is also common. For has the general form:
for items in list:
do stuff
For loops and collections like tuples, lists and dictionaries are natural friends. | for instructor in instructors:
print(instructor) | lecture/06.Procedural_Python.part3.ipynb | danielfather7/teach_Python | gpl-3.0 |
You can combine loops and conditionals: | for instructor in instructors:
if instructor.endswith('Clown'):
print(instructor + " doesn't sound like a real instructor name!")
else:
print(instructor + " is so smart... all those gooey brains!") | lecture/06.Procedural_Python.part3.ipynb | danielfather7/teach_Python | gpl-3.0 |
range()
Since for operates over lists, it is common to want to do something like:
NOTE: C-like
for (i = 0; i < 3; ++i) {
print(i);
}
The Python equivalent is:
for i in [0, 1, 2]:
do something with i
What happens when the range you want to sample is big, e.g.
NOTE: C-like
for (i = 0; i < 1000000000; ++i) {... | sum = 0
for i in range(10):
sum += i
print(sum) | lecture/06.Procedural_Python.part3.ipynb | danielfather7/teach_Python | gpl-3.0 |
<hr>
Functions
For loops let you repeat some code for every item in a list. Functions are similar in that they run the same lines of code for new values of some variable. They are different in that functions are not limited to looping over items.
Functions are a critical part of writing easy to read, reusable code.
... | def print_string(str):
"""This prints out a string passed as the parameter."""
print(str)
for c in str:
print(c)
if c == 'r':
break
print("done")
return
print_string("string") | lecture/06.Procedural_Python.part3.ipynb | danielfather7/teach_Python | gpl-3.0 |
To call the function, use:
print_string("Dave is awesome!")
Note: The function has to be defined before you can call it! | print_string("Dave is awesome!") | lecture/06.Procedural_Python.part3.ipynb | danielfather7/teach_Python | gpl-3.0 |
If you don't provide an argument or too many, you get an error. | #print_string() | lecture/06.Procedural_Python.part3.ipynb | danielfather7/teach_Python | gpl-3.0 |
Parameters (or arguments) in Python are all passed by reference. This means that if you modify the parameters in the function, they are modified outside of the function.
See the following example:
```
def change_list(my_list):
"""This changes a passed list into this function"""
my_list.append('four');
print('... | def change_list(my_list):
"""This changes a passed list into this function"""
my_list.append('four');
print('list inside the function: ', my_list)
return
my_list = [1, 2, 3];
print('list before the function: ', my_list)
change_list(my_list);
print('list after the function: ', my_list) | lecture/06.Procedural_Python.part3.ipynb | danielfather7/teach_Python | gpl-3.0 |
Variables have scope: global and local
In a function, new variables that you create are not saved when the function returns - these are local variables. Variables defined outside of the function can be accessed but not changed - these are global variables, Note there is a way to do this with the global keyword. Gener... | my_global_1 = 'bad idea'
my_global_2 = 'another bad one'
my_global_3 = 'better idea'
def my_function():
print(my_global_1)
my_global_2 = 'broke your global, man!'
print(my_global_2)
global my_global_3
my_global_3 = 'still a better idea'
return
my_function()
print(my_global_2)
print(my_global_3... | lecture/06.Procedural_Python.part3.ipynb | danielfather7/teach_Python | gpl-3.0 |
In general, you want to use parameters to provide data to a function and return a result with the return. E.g.
def sum(x, y):
my_sum = x + y
return my_sum
If you are going to return multiple objects, what data structure that we talked about can be used? Give and example below. | def a_function(parameter):
return None
foo = a_function('bar')
print(foo) | lecture/06.Procedural_Python.part3.ipynb | danielfather7/teach_Python | gpl-3.0 |
Parameters have three different types:
| type | behavior |
|------|----------|
| required | positional, must be present or error, e.g. my_func(first_name, last_name) |
| keyword | position independent, e.g. my_func(first_name, last_name) can be called my_func(first_name='Dave', last_name='Beck') or my_func(last_name='B... | def print_name(first, last='the Clown'):
print('Your name is %s %s' % (first, last))
return | lecture/06.Procedural_Python.part3.ipynb | danielfather7/teach_Python | gpl-3.0 |
Take a minute and play around with the above function. Which are required? Keyword? Default? | def massive_correlation_analysis(data, method='pearson'):
pass
return | lecture/06.Procedural_Python.part3.ipynb | danielfather7/teach_Python | gpl-3.0 |
Functions can contain any code that you put anywhere else including:
* if...elif...else
* for...else
* while
* other function calls | def print_name_age(first, last, age):
print_name(first, last)
print('Your age is %d' % (age))
print('Your age is ' + str(age))
if age > 35:
print('You are really old.')
return
print_name_age(age=40, last='Beck', first='Dave')
| lecture/06.Procedural_Python.part3.ipynb | danielfather7/teach_Python | gpl-3.0 |
Once you have some code that is functionalized and not going to change, you can move it to a file that ends in .py, check it into version control, import it into your notebook and use it!
Let's do this now for the above two functions.
...
See you after the break!
Import the function...
Call them!
<hr>
Hacky Hack Time ... | def download_if_not_exists(url, filename):
if os.path.exists(filename):
pass
else:
req = requests.get(url)
assert req.status_code == 200 # if the download failed, this line will generate an error
with open(filename, 'wb') as f:
f.write(req.content)
def load_HCEPDB_da... | lecture/06.Procedural_Python.part3.ipynb | danielfather7/teach_Python | gpl-3.0 |
Implement Preprocess Functions
Normalize
In the cell below, implement the normalize function to take in image data, x, and return it as a normalized Numpy array. The values should be in the range of 0 to 1, inclusive. The return object should be the same shape as x. | def normalize(x):
"""
Normalize a list of sample image data in the range of 0 to 1
: x: List of image data. The image shape is (32, 32, 3)
: return: Numpy array of normalize data
"""
# TODO: Implement Function
return x / 255
"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"... | image-classification/dlnd_image_classification.ipynb | xpharry/Udacity-DLFoudation | mit |
One-hot encode
Just like the previous code cell, you'll be implementing a function for preprocessing. This time, you'll implement the one_hot_encode function. The input, x, are a list of labels. Implement the function to return the list of labels as One-Hot encoded Numpy array. The possible values for labels are 0 t... | def one_hot_encode(x):
"""
One hot encode a list of sample labels. Return a one-hot encoded vector for each label.
: x: List of sample Labels
: return: Numpy array of one-hot encoded labels
"""
# TODO: Implement Function
one_hot = np.zeros((len(x), 10))
for i in range(len(x)):
on... | image-classification/dlnd_image_classification.ipynb | xpharry/Udacity-DLFoudation | mit |
Build the network
For the neural network, you'll build each layer into a function. Most of the code you've seen has been outside of functions. To test your code more thoroughly, we require that you put each layer in a function. This allows us to give you better feedback and test for simple mistakes using our unittest... | import tensorflow as tf
def neural_net_image_input(image_shape):
"""
Return a Tensor for a batch of image input
: image_shape: Shape of the images
: return: Tensor for image input.
"""
# TODO: Implement Function
return tf.placeholder(tf.float32,
shape = [None, imag... | image-classification/dlnd_image_classification.ipynb | xpharry/Udacity-DLFoudation | mit |
Convolution and Max Pooling Layer
Convolution layers have a lot of success with images. For this code cell, you should implement the function conv2d_maxpool to apply convolution then max pooling:
* Create the weight and bias using conv_ksize, conv_num_outputs and the shape of x_tensor.
* Apply a convolution to x_tensor... | def conv2d_maxpool(x_tensor, conv_num_outputs, conv_ksize, conv_strides, pool_ksize, pool_strides):
"""
Apply convolution then max pooling to x_tensor
:param x_tensor: TensorFlow Tensor
:param conv_num_outputs: Number of outputs for the convolutional layer
:param conv_strides: Stride 2-D Tuple for c... | image-classification/dlnd_image_classification.ipynb | xpharry/Udacity-DLFoudation | mit |
Flatten Layer
Implement the flatten function to change the dimension of x_tensor from a 4-D tensor to a 2-D tensor. The output should be the shape (Batch Size, Flattened Image Size). You can use TensorFlow Layers or TensorFlow Layers (contrib) for this layer. | def flatten(x_tensor):
"""
Flatten x_tensor to (Batch Size, Flattened Image Size)
: x_tensor: A tensor of size (Batch Size, ...), where ... are the image dimensions.
: return: A tensor of size (Batch Size, Flattened Image Size).
"""
# TODO: Implement Function
batch_size = x_tensor.get_shape(... | image-classification/dlnd_image_classification.ipynb | xpharry/Udacity-DLFoudation | mit |
Fully-Connected Layer
Implement the fully_conn function to apply a fully connected layer to x_tensor with the shape (Batch Size, num_outputs). You can use TensorFlow Layers or TensorFlow Layers (contrib) for this layer. | def fully_conn(x_tensor, num_outputs):
"""
Apply a fully connected layer to x_tensor using weight and bias
: x_tensor: A 2-D tensor where the first dimension is batch size.
: num_outputs: The number of output that the new tensor should be.
: return: A 2-D tensor where the second dimension is num_out... | image-classification/dlnd_image_classification.ipynb | xpharry/Udacity-DLFoudation | mit |
Output Layer
Implement the output function to apply a fully connected layer to x_tensor with the shape (Batch Size, num_outputs). You can use TensorFlow Layers or TensorFlow Layers (contrib) for this layer.
Note: Activation, softmax, or cross entropy shouldn't be applied to this. | def output(x_tensor, num_outputs):
"""
Apply a output layer to x_tensor using weight and bias
: x_tensor: A 2-D tensor where the first dimension is batch size.
: num_outputs: The number of output that the new tensor should be.
: return: A 2-D tensor where the second dimension is num_outputs.
"""... | image-classification/dlnd_image_classification.ipynb | xpharry/Udacity-DLFoudation | mit |
Create Convolutional Model
Implement the function conv_net to create a convolutional neural network model. The function takes in a batch of images, x, and outputs logits. Use the layers you created above to create this model:
Apply 1, 2, or 3 Convolution and Max Pool layers
Apply a Flatten Layer
Apply 1, 2, or 3 Full... | def conv_net(x, keep_prob):
"""
Create a convolutional neural network model
: x: Placeholder tensor that holds image data.
: keep_prob: Placeholder tensor that hold dropout keep probability.
: return: Tensor that represents logits
"""
# TODO: Apply 1, 2, or 3 Convolution and Max Pool layers
... | image-classification/dlnd_image_classification.ipynb | xpharry/Udacity-DLFoudation | mit |
Show Stats
Implement the function print_stats to print loss and validation accuracy. Use the global variables valid_features and valid_labels to calculate validation accuracy. Use a keep probability of 1.0 to calculate the loss and validation accuracy. | def print_stats(session, feature_batch, label_batch, cost, accuracy):
"""
Print information about loss and validation accuracy
: session: Current TensorFlow session
: feature_batch: Batch of Numpy image data
: label_batch: Batch of Numpy label data
: cost: TensorFlow cost function
: accuracy... | image-classification/dlnd_image_classification.ipynb | xpharry/Udacity-DLFoudation | mit |
Hyperparameters
Tune the following parameters:
* Set epochs to the number of iterations until the network stops learning or start overfitting
* Set batch_size to the highest number that your machine has memory for. Most people set them to common sizes of memory:
* 64
* 128
* 256
* ...
* Set keep_probability to the... | # TODO: Tune Parameters
epochs = 100
batch_size = 256
keep_probability = 0.2 | image-classification/dlnd_image_classification.ipynb | xpharry/Udacity-DLFoudation | mit |
First reload the data we generated in notmist.ipynb. | pickle_file = 'notMNIST.pickle'
with open(pickle_file, 'rb') as f:
save = pickle.load(f)
train_dataset = save['train_dataset']
train_labels = save['train_labels']
valid_dataset = save['valid_dataset']
valid_labels = save['valid_labels']
test_dataset = save['test_dataset']
test_labels = save['test_labels'... | jup_notebooks/data-science-ipython-notebooks-master/deep-learning/tensor-flow-exercises/3_regularization.ipynb | steinam/teacher | mit |
Reformat into a shape that's more adapted to the models we're going to train:
- data as a flat matrix,
- labels as float 1-hot encodings. | image_size = 28
num_labels = 10
def reformat(dataset, labels):
dataset = dataset.reshape((-1, image_size * image_size)).astype(np.float32)
# Map 2 to [0.0, 1.0, 0.0 ...], 3 to [0.0, 0.0, 1.0 ...]
labels = (np.arange(num_labels) == labels[:,None]).astype(np.float32)
return dataset, labels
train_dataset, train_l... | jup_notebooks/data-science-ipython-notebooks-master/deep-learning/tensor-flow-exercises/3_regularization.ipynb | steinam/teacher | mit |
Formats
The Embedding class can read word embeddings from different sources:
Gensim word2vec objects: (from_gensim method)
Word2vec binary/text models: (from_word2vec method)
GloVe models (from_glove method)
polyglot pickle files: (load method) | embeddings = Embedding.load("/home/rmyeid/polyglot_data/embeddings2/en/embeddings_pkl.tar.bz2") | notebooks/Embeddings.ipynb | aboSamoor/polyglot | gpl-3.0 |
Nearest Neighbors
A common way to investigate the space capture by the embeddings is to query for the nearest neightbors of any word. | neighbors = embeddings.nearest_neighbors("green")
neighbors | notebooks/Embeddings.ipynb | aboSamoor/polyglot | gpl-3.0 |
to calculate the distance between a word and the nieghbors, we can call the distances method | embeddings.distances("green", neighbors) | notebooks/Embeddings.ipynb | aboSamoor/polyglot | gpl-3.0 |
The word embeddings are not unit vectors, actually the more frequent the word is the larger the norm of its own vector. | %matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
norms = np.linalg.norm(embeddings.vectors, axis=1)
window = 300
smooth_line = np.convolve(norms, np.ones(window)/float(window), mode='valid')
plt.plot(smooth_line)
plt.xlabel("Word Rank"); _ = plt.ylabel("$L_2$ norm") | notebooks/Embeddings.ipynb | aboSamoor/polyglot | gpl-3.0 |
This could be problematic for some applications and training algorithms.
We can normalize them by $L_2$ norms to get unit vectors to reduce effects of word frequency, as the following | embeddings = embeddings.normalize_words()
neighbors = embeddings.nearest_neighbors("green")
for w,d in zip(neighbors, embeddings.distances("green", neighbors)):
print("{:<8}{:.4f}".format(w,d)) | notebooks/Embeddings.ipynb | aboSamoor/polyglot | gpl-3.0 |
Vocabulary Expansion | from polyglot.mapping import CaseExpander, DigitExpander | notebooks/Embeddings.ipynb | aboSamoor/polyglot | gpl-3.0 |
Not all the words are available in the dictionary defined by the word embeddings.
Sometimes it would be useful to map new words to similar ones that we have embeddings for.
Case Expansion
For example, the word GREEN is not available in the embeddings, | "GREEN" in embeddings | notebooks/Embeddings.ipynb | aboSamoor/polyglot | gpl-3.0 |
we would like to return the vector that represents the word Green, to do that we apply a case expansion: | embeddings.apply_expansion(CaseExpander)
"GREEN" in embeddings
embeddings.nearest_neighbors("GREEN") | notebooks/Embeddings.ipynb | aboSamoor/polyglot | gpl-3.0 |
Digit Expansion
We reduce the size of the vocabulary while training the embeddings by grouping special classes of words.
Once common case of such grouping is digits.
Every digit in the training corpus get replaced by the symbol #.
For example, a number like 123.54 becomes ###.##.
Therefore, querying the embedding for a... | "434" in embeddings | notebooks/Embeddings.ipynb | aboSamoor/polyglot | gpl-3.0 |
To fix that, we apply another type of vocabulary expansion DigitExpander.
It will map any number to a sequence of #s. | embeddings.apply_expansion(DigitExpander)
"434" in embeddings | notebooks/Embeddings.ipynb | aboSamoor/polyglot | gpl-3.0 |
As expected, the neighbors of the new number 434 will be other numbers: | embeddings.nearest_neighbors("434") | notebooks/Embeddings.ipynb | aboSamoor/polyglot | gpl-3.0 |
Visualizing eclipse data
Let us find some interesting data to generate elements from, before we consider how to customize them. Here is a dataset containing information about all the eclipses of the 21st century: | eclipses = pd.read_csv('../data/eclipses_21C.csv', parse_dates=['date'])
eclipses.head() | notebooks/02-customizing-visual-appearance.ipynb | ioam/scipy-2017-holoviews-tutorial | bsd-3-clause |
Here we have the date of each eclipse, what time of day the eclipse reached its peak in both local time and in UTC, the type of eclipse, its magnitude (fraction of the Sun's diameter obscured by the Moon) and the position of the peak in latitude and longitude.
Let's see what happens if we pass this dataframe to the Cur... | hv.Curve(eclipses) | notebooks/02-customizing-visual-appearance.ipynb | ioam/scipy-2017-holoviews-tutorial | bsd-3-clause |
We see that, by default, the first dataframe column becomes the key dimension (corresponding to the x-axis) and the second column becomes the value dimension (corresponding to the y-axis). There is clearly structure in this data, but the plot is too highly compressed in the x direction to see much detail, and you may n... | %%opts Curve [width=900]
hour_curve = hv.Curve(eclipses).redim.label(hour_local='Hour (local time)', date='Date (21st century)')
hour_curve | notebooks/02-customizing-visual-appearance.ipynb | ioam/scipy-2017-holoviews-tutorial | bsd-3-clause |
The top line uses a special IPython/Jupyter syntax called the %%opts cell magic to specify the width plot option for all Curve objects in this cell. %%opts accepts a simple specification where we pass the width=900 keyword argument to Curve as a plot option (denoted by the square brackets).
Of course, there are other... | # Exercise: Try setting the height plot option of the Curve above.
# Hint: the magic supports tab completion when the cursor is in the square brackets!
# Exercise: Try enabling the boolean show_grid plot option for the curve above
# Exercise: Try set the x-axis label rotation (in degrees) with the xrotation plot op... | notebooks/02-customizing-visual-appearance.ipynb | ioam/scipy-2017-holoviews-tutorial | bsd-3-clause |
Aside: hv.help
Tab completion helps discover what keywords are available but you can get more complete help using the hv.help utility. For instance, to learn more about the options for hv.Curve run hv.help(hv.Curve): | # hv.help(hv.Curve)
| notebooks/02-customizing-visual-appearance.ipynb | ioam/scipy-2017-holoviews-tutorial | bsd-3-clause |
Style options
The plot options earlier instructed HoloViews to build a plot 900 pixels wide, when rendered with the Bokeh plotting extension. Now let's specify that the Bokeh glyph should be 'red' and slightly thicker, which is information passed on directly to Bokeh (making it a style option): | %%opts Curve (color='red' line_width=2)
hour_curve | notebooks/02-customizing-visual-appearance.ipynb | ioam/scipy-2017-holoviews-tutorial | bsd-3-clause |
Note how the plot options applied above to hour_curve are remembered! The %%opts magic is used to customize the object displayed as output for a particular code cell: behind the scenes HoloViews has linked the specified options to the hour_curve object via a hidden integer id attribute.
Having used the %%opts magic on ... | # Exercise: Display hour_curve without any new options to verify it stays red
# Exercise: Try setting the line_width style options to 1
# Exercise: Try setting the line_dash style option to 'dotdash'
| notebooks/02-customizing-visual-appearance.ipynb | ioam/scipy-2017-holoviews-tutorial | bsd-3-clause |
Switching to matplotlib
Let us now view our curve with matplotlib using the %%output cell magic: | %%output backend='matplotlib'
hour_curve | notebooks/02-customizing-visual-appearance.ipynb | ioam/scipy-2017-holoviews-tutorial | bsd-3-clause |
All our options are gone! This is because the options are associated with the corresponding plotting extension---if you switch back to 'bokeh', the options will be applicable again. In general, options have to be specific to backends; e.g. the line_width style option accepted by Bokeh is called linewidth in matplotlib: | %%output backend='matplotlib'
%%opts Curve [aspect=4 fig_size=400 xrotation=90] (color='blue' linewidth=2)
hour_curve
# Exercise: Apply the matplotlib equivalent to line_dash above using linestyle='-.' | notebooks/02-customizing-visual-appearance.ipynb | ioam/scipy-2017-holoviews-tutorial | bsd-3-clause |
The %output line magic
In the two cells above we repeated %%output backend='matplotlib' to use matplotlib to render those two cells. Instead of repeating ourselves with the cell magic, we can use a "line magic" (similar syntax to the cell magic but with one %) to set things globally. Let us switch to matplotlib with a ... | %output backend='matplotlib' fig='svg' | notebooks/02-customizing-visual-appearance.ipynb | ioam/scipy-2017-holoviews-tutorial | bsd-3-clause |
Unlike the cell magic, the line magic doesn't need to be followed by any expression and can be used anywhere in the notebook. Both the %output and %opts line magics set things globally so it is recommended you declare them at the top of your notebooks. Now let us look at the SVG matplotlib output we requested: | %%opts Curve [aspect=4 fig_size=400 xrotation=70] (color='green' linestyle='--')
hour_curve
# Exercise: Verify for yourself that the output above is SVG and not PNG
# You can do this by right-clicking above then selecting 'Open Image in a new Tab' (Chrome) or 'View Image' (Firefox) | notebooks/02-customizing-visual-appearance.ipynb | ioam/scipy-2017-holoviews-tutorial | bsd-3-clause |
Switching back to bokeh
In previous releases of HoloViews, it was typical to switch to matplotlib in order to export to PNG or SVG, because Bokeh did not support these file formats. Since Bokeh 0.12.6 we can now easily use HoloViews to export Bokeh plots to a PNG file, as we will now demonstrate: | %output backend='bokeh' | notebooks/02-customizing-visual-appearance.ipynb | ioam/scipy-2017-holoviews-tutorial | bsd-3-clause |
By passing fig='png' and a filename='eclipses' to %output we can both render to PNG and save the output to file: | %%output fig='png' filename='eclipses'
hour_curve.clone() | notebooks/02-customizing-visual-appearance.ipynb | ioam/scipy-2017-holoviews-tutorial | bsd-3-clause |
Here we have requested PNG format using fig='png' and that the output is output to eclipses.png using filename='eclipses': | ls *.png | notebooks/02-customizing-visual-appearance.ipynb | ioam/scipy-2017-holoviews-tutorial | bsd-3-clause |
Bokeh also has some SVG support, but it is not yet exposed in HoloViews.
Using group and label
The above examples showed how to customize by type, but HoloViews offers multiple additional levels of customization that should be sufficient to cover any purpose. For our last example, let us split our eclipse dataframe bas... | total_eclipses = eclipses[eclipses.type=='Total']
partial_eclipses = eclipses[eclipses.type=='Partial'] | notebooks/02-customizing-visual-appearance.ipynb | ioam/scipy-2017-holoviews-tutorial | bsd-3-clause |
We'll now introduce the Spikes element, and display it with a large width and without a y-axis. We can specify those options for all following Spikes elements using the %opts line magic: | %opts Spikes [width=900 yaxis=None] | notebooks/02-customizing-visual-appearance.ipynb | ioam/scipy-2017-holoviews-tutorial | bsd-3-clause |
Now let us look at the hour of day at which these two types of eclipses occur (local time) by overlaying the two types of eclipse as Spikes elements. The problem then is finding a way to visually distinguish the spikes corresponding to the different ellipse types.
We can do this using the element group and label intro... | %%opts Spikes.Eclipses.Total (line_dash='solid')
%%opts Spikes.Eclipses.Partial (line_dash='dotted')
total = hv.Spikes(total_eclipses, kdims=['hour_local'], vdims=[], group='Eclipses', label='Total')
partial = hv.Spikes(partial_eclipses, kdims=['hour_local'], vdims=[], group='Eclipses', label='Partial')
(total * pa... | notebooks/02-customizing-visual-appearance.ipynb | ioam/scipy-2017-holoviews-tutorial | bsd-3-clause |
Using these options to distinguish between the two categories of data with the same type, you can now see clear patterns of grouping between the two types, with many more total eclipses around noon in local time. Similar techniques can be used to provide arbitrarily specific customizations when needed. | # Exercise: Remove the two %%opts lines above and observe the effect
# Exercise: Show all spikes with 'solid' line_dash, total eclipses in black and the partial ones in 'lightgray'
# Optional Exercise: Try differentiating the two sets of spikes by group and not label
| notebooks/02-customizing-visual-appearance.ipynb | ioam/scipy-2017-holoviews-tutorial | bsd-3-clause |
Around sample 10500, the orientation of my phone in the X and Y directions changed because Nick and I swapped phones.
Extracting the gravity signal is largely a matter of applying a low pass filter, since the acceleration due to gravity is not changing with time. | # a Gaussian filter with a large window width is essentially a low pass filter
from scipy.ndimage import gaussian_filter
# a window that is too small retains noise from non-gravity signals
# a window that is too large eliminates variations in GravityXYZ due to orientation variations.
windowwidth = 25
# apply the smoo... | Code/Extract Gravity Signal.ipynb | sbussmann/sensor-fusion | mit |
conda packages are created from conda recipes. We can create a bare recipe using conda skeleton to build it from a PyPI package. | !conda skeleton pypi pytest-benchmark > /dev/null
!ls pytest-benchmark | talks_materials/20160409_1130_Embrace_conda_packages/Embrace conda packages.ipynb | PyDataMadrid2016/Conference-Info | mit |
These are the minimum files for the recipe:
meta.yaml contains all the metadata
build.sh and bld.bat are the build scripts for Linux/OS X and Windows respectively
The meta.yaml file
It contains the metadata in YAML format.
package, source and build specify the name, version and source of the package
requirements spe... | !grep -v "#" pytest-benchmark/meta.yaml | head -n24 | talks_materials/20160409_1130_Embrace_conda_packages/Embrace conda packages.ipynb | PyDataMadrid2016/Conference-Info | mit |
The build.sh and bld.bat files
They specify how to build the package. | !cat pytest-benchmark/build.sh
!grep -v "::" pytest-benchmark/bld.bat | talks_materials/20160409_1130_Embrace_conda_packages/Embrace conda packages.ipynb | PyDataMadrid2016/Conference-Info | mit |
The build process
Adapted from http://conda.pydata.org/docs/building/recipe.html#conda-recipe-files-overview
Downloads the source
Applies patches (if any)
Install build dependencies
Runs the build script
Packages new files
Run tests against newly created package
Seems legit! | !conda build pytest-benchmark --python 3.5 > /dev/null # It works!
!ls ~/.miniconda3/conda-bld/linux-64/pytest-benchmark-3.0.0-py35_0.tar.bz2 | talks_materials/20160409_1130_Embrace_conda_packages/Embrace conda packages.ipynb | PyDataMadrid2016/Conference-Info | mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.