markdown stringlengths 0 37k | code stringlengths 1 33.3k | path stringlengths 8 215 | repo_name stringlengths 6 77 | license stringclasses 15
values |
|---|---|---|---|---|
Note - I was unable to get the galaxies to clusster using DBSCAN.
Problem 3) Supervised Machine Learning
Supervised machine learning, on the other hand, aims to predict a target class or produce a regression result based on the location of labelled sources (i.e. the training set) in the multidimensional feature space. ... | from sklearn.neighbors import KNeighborsClassifier
KNNclf = KNeighborsClassifier( # complete
preds = KNNclf.predict( # complete
plt.figure()
plt.scatter( # complete
# complete
# complete
# complete | Sessions/Session04/Day0/TooBriefMachLearn.ipynb | LSSTC-DSFP/LSSTC-DSFP-Sessions | mit |
These results are almost identical to the training classifications. However, we have cheated! In this case we are evaluating the accuracy of the model (98% in this case) using the same data that defines the model. Thus, what we have really evaluated here is the training error. The relevant parameter, however, is the ge... | from sklearn.cross_validation import cross_val_predict
CVpreds = cross_val_predict( # complete
plt.scatter( # complete
print("The accuracy of the kNN = 5 model is ~{:.4}".format( # complete
# complete
# complete
# complete | Sessions/Session04/Day0/TooBriefMachLearn.ipynb | LSSTC-DSFP/LSSTC-DSFP-Sessions | mit |
While it is useful to understand the overall accuracy of the model, it is even more useful to understand the nature of the misclassifications that occur.
Problem 3c
Calculate the accuracy for each class in the iris set, as determined via CV for the $k$NN = 50 model. | # complete
# complete
# complete | Sessions/Session04/Day0/TooBriefMachLearn.ipynb | LSSTC-DSFP/LSSTC-DSFP-Sessions | mit |
We just found that the classifier does a much better job classifying setosa and versicolor than it does for virginica. The main reason for this is some viginica flowers lie far outside the main virginica locus, and within predominantly versicolor "neighborhoods". In addition to knowing the accuracy for the individual c... | from sklearn.metrics import confusion_matrix
cm = confusion_matrix( # complete | Sessions/Session04/Day0/TooBriefMachLearn.ipynb | LSSTC-DSFP/LSSTC-DSFP-Sessions | mit |
From this representation, we see right away that most of the virginica that are being misclassifed are being scattered into the versicolor class. However, this representation could still be improved: it'd be helpful to normalize each value relative to the total number of sources in each class, and better still, it'd be... | normalized_cm = cm.astype('float')/cm.sum(axis = 1)[:,np.newaxis]
normalized_cm | Sessions/Session04/Day0/TooBriefMachLearn.ipynb | LSSTC-DSFP/LSSTC-DSFP-Sessions | mit |
The normalization makes it easier to compare the classes, since each class has a different number of sources. Now we can procede with a visual representation of the confusion matrix. This is best done using imshow() within pyplot. You will also need to plot a colorbar, and labeling the axes will also be helpful.
Probl... | # complete
# complete
# complete | Sessions/Session04/Day0/TooBriefMachLearn.ipynb | LSSTC-DSFP/LSSTC-DSFP-Sessions | mit |
The Source Code of Life: Using Python to Explore Our DNA
Researchers just found the gene responsible for mistakenly thinking we've found the gene for specific things. It's the region between the start and the end of every chromosome, plus a few segments in our mitochondria.
Every good presentation starts with xkcd, ri... | YouTubeVideo('fCd6B5HRaZ8', start=135) | bioinformatics_intro_python.ipynb | mrphyja/bioinfo-intro-python | mit |
Ok, now you know something about DNA, so we can start getting into some of the fun puzzles that this leads to. So how do we find out what someone's DNA sequence is? There are several methods, including some newer ones that I'm really excited about, but we'll stick with the most popular here: Illuimina's sequencing by s... | dna_sub_mat = np.array(
[[ 1, 0, 0, 0],
[ 0, 1, 0, 0],
[ 0, 0, 1, 0],
[ 0, 0, 0, 1]])
dbet = 'ACGT' | bioinformatics_intro_python.ipynb | mrphyja/bioinfo-intro-python | mit |
Same as we defined above, with dbet being the "dna alphabet" used for this matrix (four-letter alphabet, could be in a different order, this is just the one we chose)
And here are we calculate the scores and arrows as separate matrices | def nw_alignment(sub_mat, abet, seq1, seq2, gap=-8):
# Get the lengths of the sequences
seq1_len, seq2_len = len(seq1), len(seq2)
# Create the scoring and arrow matrices
score_mat = np.zeros((seq1_len+1, seq2_len+1), int)
arrow_mat = np.zeros((seq1_len+1, seq2_len+1), int)
# Fill first column an... | bioinformatics_intro_python.ipynb | mrphyja/bioinfo-intro-python | mit |
I'm calling this nw_align after the Needleman-Wunsch algorithm. It's hard to put score and directional information in just one matrix, so we make two matrices. We start with a matrix of zeros for each and then fill them in concurrently as we run through the possibilities.
What does our result look like? | s1 = 'ACTTCTGC'
s2 = 'ACGTTTGTCGC'
score_mat, arrow_mat = nw_alignment(dna_sub_mat, dbet, s1, s2, gap=-3)
print(score_mat)
print(arrow_mat) | bioinformatics_intro_python.ipynb | mrphyja/bioinfo-intro-python | mit |
Looks good, but not all that useful by itself.
Now we need a way to get the sequences back out of our scoring matrix: | def backtrace(arrow_mat, seq1, seq2):
align1, align2 = '', ''
align1_pos, align2_pos = arrow_mat.shape
align1_pos -= 1
align2_pos -= 1
selected = []
while True:
selected.append((align1_pos, align2_pos))
if arrow_mat[align1_pos, align2_pos] == 0:
# Up arrow, add gap to... | bioinformatics_intro_python.ipynb | mrphyja/bioinfo-intro-python | mit |
Sometimes it's nice to see the scoring matrix, though, so here's a function to visualize it | def visual_scoring_matrix(seq1, seq2, score_mat, arrow_mat):
visual_mat = []
for i, row in enumerate(arrow_mat):
visual_mat_row = []
for j, col in enumerate(row):
if col == 0:
arrow = 'β'
elif col == 1:
arrow = 'β'
else:
... | bioinformatics_intro_python.ipynb | mrphyja/bioinfo-intro-python | mit |
Let's generate some sequences and see how fast this is | def random_dna_seq(length=1000):
seq = [random.choice(dbet) for x in range(length)]
return ''.join(seq)
def mutate_dna_seq(seq, chance=1/5):
mut_seq_base = [random.choice(dbet) if random.random() < chance else x for x in seq]
mut_seq_indel = [random.choice(('', x + random.choice(dbet))) if random.rando... | bioinformatics_intro_python.ipynb | mrphyja/bioinfo-intro-python | mit |
If we wanted to shift this one position at a time along the whole genome and check the alignments, how long would it take?
That's a long time!
Let's make it faster! (Just because)
So in reality, we don't actually want to use this algorithm to align our fragments to the whole genome. It's too slow, and there's no good w... | def sub_values(sub_mat, abet, seq1, seq2):
# convert the sequences to numbers
seq1_ind = [abet.index(i) for i in seq1]
seq2_ind = [abet.index(i) for i in seq2]
sub_vals = np.array([[0] * (len(seq2)+1)] + [[0] + [sub_mat[y, x] for x in seq2_ind] for y in seq1_ind], int)
return sub_vals
sub_values(dn... | bioinformatics_intro_python.ipynb | mrphyja/bioinfo-intro-python | mit |
Then we get a list of all the diagonals in the matrix. | def diags(l1, l2):
ys = np.array([np.arange(l1) + 1 for i in np.arange(l2)])
xs = np.array([np.arange(l2) + 1 for i in np.arange(l1)])
diag_ys = [np.flip(ys.diagonal(i), 0) for i in range(1-l2, l1)]
diag_xs = [xs.diagonal(i) for i in range(1-l1, l2)]
index_list = []
for y, x in zip(diag_ys, diag... | bioinformatics_intro_python.ipynb | mrphyja/bioinfo-intro-python | mit |
And here's the actual function. It takes the same arguments and produces the same matrices. | def FastNW(sub_mat, abet, seq1, seq2, gap=-8):
sub_vals = sub_values(sub_mat, abet, seq1, seq2)
# Get the lengths of the sequences
seq1_len, seq2_len = len(seq1), len(seq2)
# Create the scoring and arrow matrices
score_mat = np.zeros((seq1_len+1, seq2_len+1), int)
arrow_mat = np.zeros((seq1_len+... | bioinformatics_intro_python.ipynb | mrphyja/bioinfo-intro-python | mit |
So how much faster is it? | s1 = random_dna_seq()
s2 = mutate_dna_seq(s1)
a = %timeit -o nw_alignment(dna_sub_mat, dbet, s1, s2)
print('{:.1f} years for the whole genome'.format(a.average * 2300000000 / 60 / 60 / 24 / 365.25))
a = %timeit -o FastNW(dna_sub_mat, dbet, s1, s2)
print('{:.1f} years for the whole genome'.format(a.average * 2300000000 ... | bioinformatics_intro_python.ipynb | mrphyja/bioinfo-intro-python | mit |
Now why did we use the substitution matrix?
Here's how DNA translates to protein:
Wikipedia
So we can align proteins, too! | blosum50 = np.array(
[[ 5,-2,-1,-2,-1,-1,-1, 0,-2,-1,-2,-1,-1,-3,-1, 1, 0,-3,-2, 0],
[-2, 7,-1,-2,-1, 1, 0,-3, 0,-4,-3, 3,-2,-3,-3,-1,-1,-3,-1,-3],
[-1,-1, 7, 2,-2, 0, 0, 0, 1,-3,-4,-0,-2,-4,-2,-1, 0,-4,-2,-3],
[-2,-2, 2, 8,-4, 0, 2,-1,-1,-4,-4,-1,-4,-5,-1, 0,-1,-5,-3,-4],
[-1,-4,-2,-4,13,-3,-3,... | bioinformatics_intro_python.ipynb | mrphyja/bioinfo-intro-python | mit |
Other things we can do with this algorithm:
Local alignment
Affine gap penalties
Other useful bioinformatics Python packages: | from pysam import FastaFile
from os.path import getsize
print(getsize('Homo_sapiens.GRCh38.dna.primary_assembly.fasta.gz')/1024**2, 'MiB')
with FastaFile('Homo_sapiens.GRCh38.dna.primary_assembly.fasta.gz') as myfasta:
chr17len = myfasta.get_reference_length('17')
print(chr17len, 'bp')
seq = myfasta.fetc... | bioinformatics_intro_python.ipynb | mrphyja/bioinfo-intro-python | mit |
The order of the polynomial is given by the number of coefficients (minus one), which is given by len(p_normal)-1.
However, there are many other ways it could be written, which are useful in different contexts. For example, we are often interested in the roots of the polynomial, so would want to express it in the form
... | p_roots = (1, 2, -3) | 05-classes-oop.ipynb | IanHawke/maths-with-python | mit |
combined with a single variable containing the leading term, | p_leading_term = 2 | 05-classes-oop.ipynb | IanHawke/maths-with-python | mit |
We see that the order of the polynomial is given by the number of roots (and hence by len(p_roots)). This form represents the same polynomial but requires two pieces of information (the roots and the leading coefficient).
The different forms are useful for different things. For example, if we want to add two polynomial... | class Polynomial(object):
explanation = "I am a polynomial"
def explain(self):
print(self.explanation) | 05-classes-oop.ipynb | IanHawke/maths-with-python | mit |
We have defined a class, which is a single object that will represent a polynomial. We use the keyword class in the same way that we use the keyword def when defining a function. The definition line ends with a colon, and all the code defining the object is indented by four spaces.
The name of the object - the general ... | p = Polynomial()
print(p.explanation)
p.explain()
p.explanation = "I change the string"
p.explain() | 05-classes-oop.ipynb | IanHawke/maths-with-python | mit |
The first line, p = Polynomial(), creates an instance of the class. That is, it creates a specific Polynomial. It is assigned to the variable named p. We can access class variables using the "dot" notation, so the string can be printed via p.explanation. The method that prints the class variable also uses the "dot" not... | p = Polynomial()
p.explanation = "Changed the string again"
q = Polynomial()
p.explanation = "Changed the string a third time"
p.explain()
q.explain() | 05-classes-oop.ipynb | IanHawke/maths-with-python | mit |
We can of course make the methods take additional variables. We modify the class (note that we have to completely re-define it each time): | class Polynomial(object):
explanation = "I am a polynomial"
def explain_to(self, caller):
print("Hello, {}. {}.".format(caller,self.explanation)) | 05-classes-oop.ipynb | IanHawke/maths-with-python | mit |
We then use this, remembering that the self variable is passed through automatically: | r = Polynomial()
r.explain_to("Alice") | 05-classes-oop.ipynb | IanHawke/maths-with-python | mit |
At the moment the class is not doing anything interesting. To do something interesting we need to store (and manipulate) relevant variables. The first thing to do is to add those variables when the instance is actually created. We do this by adding a special function (method) which changes how the variables of type Pol... | class Polynomial(object):
"""Representing a polynomial."""
explanation = "I am a polynomial"
def __init__(self, roots, leading_term):
self.roots = roots
self.leading_term = leading_term
self.order = len(roots)
def explain_to(self, caller):
print("Hello, {}. {}."... | 05-classes-oop.ipynb | IanHawke/maths-with-python | mit |
This __init__ function is called when a variable is created. There are a number of special class functions, each of which has two underscores before and after the name. This is another Python convention that is effectively a rule: functions surrounded by two underscores have special effects, and will be called by other... | p = Polynomial(p_roots, p_leading_term)
p.explain_to("Alice")
q = Polynomial((1,1,0,-2), -1)
q.explain_to("Bob") | 05-classes-oop.ipynb | IanHawke/maths-with-python | mit |
It is always useful to have a function that shows what the class represents, and in particular what this particular instance looks like. We can define another method that explicitly displays the Polynomial: | class Polynomial(object):
"""Representing a polynomial."""
explanation = "I am a polynomial"
def __init__(self, roots, leading_term):
self.roots = roots
self.leading_term = leading_term
self.order = len(roots)
def display(self):
string = str(self.leading_ter... | 05-classes-oop.ipynb | IanHawke/maths-with-python | mit |
Where classes really come into their own is when we manipulate them as objects in their own right. For example, we can multiply together two polynomials to get another polynomial. We can create a method to do that: | class Polynomial(object):
"""Representing a polynomial."""
explanation = "I am a polynomial"
def __init__(self, roots, leading_term):
self.roots = roots
self.leading_term = leading_term
self.order = len(roots)
def display(self):
string = str(self.leading_ter... | 05-classes-oop.ipynb | IanHawke/maths-with-python | mit |
Network Architecture
The encoder part of the network will be a typical convolutional pyramid. Each convolutional layer will be followed by a max-pooling layer to reduce the dimensions of the layers. The decoder though might be something new to you. The decoder needs to convert from a narrow representation to a wide rec... | inputs_ = tf.placeholder(tf.float32, (None, 28, 28, 1), name='inputs')
targets_ = tf.placeholder(tf.float32, (None, 28, 28, 1), name='targets')
### Encoder
conv1 = tf.layers.conv2d(inputs_, 16, (3,3), padding='same', activation=tf.nn.relu)
# Now 28x28x16
maxpool1 = tf.layers.max_pooling2d(conv1, (2,2), (2,2), padding=... | autoencoder/Convolutional_Autoencoder_Solution.ipynb | adukic/nd101 | mit |
Denoising
As I've mentioned before, autoencoders like the ones you've built so far aren't too useful in practive. However, they can be used to denoise images quite successfully just by training the network on noisy images. We can create the noisy images ourselves by adding Gaussian noise to the training images, then cl... | inputs_ = tf.placeholder(tf.float32, (None, 28, 28, 1), name='inputs')
targets_ = tf.placeholder(tf.float32, (None, 28, 28, 1), name='targets')
### Encoder
conv1 = tf.layers.conv2d(inputs_, 32, (3,3), padding='same', activation=tf.nn.relu)
# Now 28x28x32
maxpool1 = tf.layers.max_pooling2d(conv1, (2,2), (2,2), padding=... | autoencoder/Convolutional_Autoencoder_Solution.ipynb | adukic/nd101 | mit |
Checking out the performance
Here I'm adding noise to the test images and passing them through the autoencoder. It does a suprising great job of removing the noise, even though it's sometimes difficult to tell what the original number is. | fig, axes = plt.subplots(nrows=2, ncols=10, sharex=True, sharey=True, figsize=(20,4))
in_imgs = mnist.test.images[:10]
noisy_imgs = in_imgs + noise_factor * np.random.randn(*in_imgs.shape)
noisy_imgs = np.clip(noisy_imgs, 0., 1.)
reconstructed = sess.run(decoded, feed_dict={inputs_: noisy_imgs.reshape((10, 28, 28, 1))... | autoencoder/Convolutional_Autoencoder_Solution.ipynb | adukic/nd101 | mit |
Method 1: Using Boolean Variables | # Create variable with TRUE if nationality is USA
american = df['nationality'] == "USA"
# Create variable with TRUE if age is greater than 50
elderly = df['age'] > 50
# Select all casess where nationality is USA and age is greater than 50
df[american & elderly] | python/pandas_selecting_rows_on_conditions.ipynb | tpin3694/tpin3694.github.io | mit |
Method 2: Using variable attributes | # Select all cases where the first name is not missing and nationality is USA
df[df['first_name'].notnull() & (df['nationality'] == "USA")] | python/pandas_selecting_rows_on_conditions.ipynb | tpin3694/tpin3694.github.io | mit |
Zadatci
1. Linearna regresija kao klasifikator
U prvoj laboratorijskoj vjeΕΎbi koristili smo model linearne regresije za, naravno, regresiju. MeΔutim, model linearne regresije moΕΎe se koristiti i za klasifikaciju. Iako zvuΔi pomalo kontraintuitivno, zapravo je dosta jednostavno. Naime, cilj je nauΔiti funkciju $f(\mathb... | from sklearn.linear_model import LinearRegression, RidgeClassifier
from sklearn.metrics import accuracy_score | STRUCE/2018/SU-2018-LAB02-0036477171.ipynb | DominikDitoIvosevic/Uni | mit |
(a)
Prvo, isprobajte ugraΔeni model na linearno odvojivom skupu podataka seven ($N=7$). | seven_X = np.array([[2,1], [2,3], [1,2], [3,2], [5,2], [5,4], [6,3]])
seven_y = np.array([1, 1, 1, 1, 0, 0, 0])
clf = RidgeClassifier().fit(seven_X, seven_y)
predicted_y = clf.predict(seven_X)
score = accuracy_score(y_pred=predicted_y, y_true=seven_y)
print(score)
mlutils.plot_2d_clf_problem(X=seven_X, y=predicted_y,... | STRUCE/2018/SU-2018-LAB02-0036477171.ipynb | DominikDitoIvosevic/Uni | mit |
Kako bi se uvjerili da se u isprobanoj implementaciji ne radi o niΔemu doli o obiΔnoj linearnoj regresiji, napiΕ‘ite kΓ΄d koji dolazi do jednakog rjeΕ‘enja koriΕ‘tenjem iskljuΔivo razreda LinearRegression. Funkciju za predikciju, koju predajete kao treΔi argument h funkciji plot_2d_clf_problem, moΕΎete definirati lambda-izr... |
lr = LinearRegression().fit(seven_X, seven_y)
predicted_y_2 = lr.predict(seven_X)
mlutils.plot_2d_clf_problem(X=seven_X, y=seven_y, h= lambda x : lr.predict(x) >= 0.5) | STRUCE/2018/SU-2018-LAB02-0036477171.ipynb | DominikDitoIvosevic/Uni | mit |
Q: Kako bi bila definirana granica izmeΔu klasa ako bismo koristili oznake klasa $-1$ i $1$ umjesto $0$ i $1$?
(b)
Probajte isto na linearno odvojivom skupu podataka outlier ($N=8$): | outlier_X = np.append(seven_X, [[12,8]], axis=0)
outlier_y = np.append(seven_y, 0)
lr2 = LinearRegression().fit(outlier_X, outlier_y)
predicted_y_2 = lr2.predict(outlier_X)
mlutils.plot_2d_clf_problem(X=outlier_X, y=outlier_y, h= lambda x : lr2.predict(x) >= 0.5) | STRUCE/2018/SU-2018-LAB02-0036477171.ipynb | DominikDitoIvosevic/Uni | mit |
Q: ZaΕ‘to model ne ostvaruje potpunu toΔnost iako su podatci linearno odvojivi?
(c)
ZavrΕ‘no, probajte isto na linearno neodvojivom skupu podataka unsep ($N=8$): | unsep_X = np.append(seven_X, [[2,2]], axis=0)
unsep_y = np.append(seven_y, 0)
lr3 = LinearRegression().fit(unsep_X, unsep_y)
predicted_y_2 = lr3.predict(unsep_X)
mlutils.plot_2d_clf_problem(X=unsep_X, y=unsep_y, h= lambda x : lr3.predict(x) >= 0.5) | STRUCE/2018/SU-2018-LAB02-0036477171.ipynb | DominikDitoIvosevic/Uni | mit |
Q: OΔito je zaΕ‘to model nije u moguΔnosti postiΔi potpunu toΔnost na ovom skupu podataka. MeΔutim, smatrate li da je problem u modelu ili u podacima? Argumentirajte svoj stav.
2. ViΕ‘eklasna klasifikacija
Postoji viΕ‘e naΔina kako se binarni klasifikatori mogu se upotrijebiti za viΕ‘eklasnu klasifikaciju. NajΔeΕ‘Δe se kori... | from sklearn.datasets import make_classification
x, y = sklearn.datasets.make_classification(n_samples=100, n_informative=2, n_redundant=0, n_repeated=0, n_features=2, n_classes=3, n_clusters_per_class=1)
#print(dataset)
mlutils.plot_2d_clf_problem(X=x, y=y, h=None) | STRUCE/2018/SU-2018-LAB02-0036477171.ipynb | DominikDitoIvosevic/Uni | mit |
Trenirajte tri binarna klasifikatora, $h_1$, $h_2$ i $h_3$ te prikaΕΎite granice izmeΔu klasa (tri grafikona). Zatim definirajte $h(\mathbf{x})=\mathrm{argmax}_j h_j(\mathbf{x})$ (napiΕ‘ite svoju funkciju predict koja to radi) i prikaΕΎite granice izmeΔu klasa za taj model. Zatim se uvjerite da biste identiΔan rezultat d... | fig = plt.figure(figsize=(5,15))
fig.subplots_adjust(wspace=0.2)
y_ovo1 = [ 0 if i == 0 else 1 for i in y]
lrOvo1 = LinearRegression().fit(x, y_ovo1)
fig.add_subplot(3,1,1)
mlutils.plot_2d_clf_problem(X=x, y=y_ovo1, h= lambda x : lrOvo1.predict(x) >= 0.5)
y_ovo2 = [ 0 if i == 1 else 1 for i in y]
lrOvo2 = LinearRegre... | STRUCE/2018/SU-2018-LAB02-0036477171.ipynb | DominikDitoIvosevic/Uni | mit |
3. LogistiΔka regresija
Ovaj zadatak bavi se probabilistiΔkim diskriminativnim modelom, logistiΔkom regresijom, koja je, unatoΔ nazivu, klasifikacijski model.
LogistiΔka regresija tipiΔan je predstavnik tzv. poopΔenih linearnih modela koji su oblika: $h(\mathbf{x})=f(\mathbf{w}^\intercal\tilde{\mathbf{x}})$. LogistiΔka... | def sigm(alpha):
def f(x):
return 1 / (1 + exp(-alpha*x))
return f
ax = list(range(-10, 10))
ay1 = list(map(sigm(1), ax))
ay2 = list(map(sigm(2), ax))
ay3 = list(map(sigm(4), ax))
fig = plt.figure(figsize=(5,15))
p1 = fig.add_subplot(3, 1, 1)
p1.plot(ax, ay1)
p2 = fig.add_subplot(3, 1, 2)
p2.... | STRUCE/2018/SU-2018-LAB02-0036477171.ipynb | DominikDitoIvosevic/Uni | mit |
Q: ZaΕ‘to je sigmoidalna funkcija prikladan izbor za aktivacijsku funkciju poopΔenoga linearnog modela?
</br>
Q: Kakav utjecaj ima faktor $\alpha$ na oblik sigmoide? Ε to to znaΔi za model logistiΔke regresije (tj. kako izlaz modela ovisi o normi vektora teΕΎina $\mathbf{w}$)?
(b)
Implementirajte funkciju
lr_train(X, y... | from sklearn.preprocessing import PolynomialFeatures as PolyFeat
from sklearn.metrics import log_loss
def loss_function(h_x, y):
return -y * np.log(h_x) - (1 - y) * np.log(1 - h_x)
def lr_h(x, w):
Phi = PolyFeat(1).fit_transform(x.reshape(1,-1))
return sigm(1)(Phi.dot(w))
def cross_entropy_error(X, y... | STRUCE/2018/SU-2018-LAB02-0036477171.ipynb | DominikDitoIvosevic/Uni | mit |
(c)
KoristeΔi funkciju lr_train, trenirajte model logistiΔke regresije na skupu seven, prikaΕΎite dobivenu granicu izmeΔu klasa te izraΔunajte pogreΕ‘ku unakrsne entropije.
NB: Pripazite da modelu date dovoljan broj iteracija. | trained = lr_train(seven_X, seven_y)
print(cross_entropy_error(seven_X, seven_y, trained))
print(trained)
h3c = lambda x: lr_h(x, trained) > 0.5
figure()
mlutils.plot_2d_clf_problem(seven_X, seven_y, h3c) | STRUCE/2018/SU-2018-LAB02-0036477171.ipynb | DominikDitoIvosevic/Uni | mit |
Q: Koji kriterij zaustavljanja je aktiviran?
Q: ZaΕ‘to dobivena pogreΕ‘ka unakrsne entropije nije jednaka nuli?
Q: Kako biste utvrdili da je optimizacijski postupak doista pronaΕ‘ao hipotezu koja minimizira pogreΕ‘ku uΔenja? O Δemu to ovisi?
Q: Na koji naΔin biste preinaΔili kΓ΄d ako biste htjeli da se optimizacija izvodi s... | from sklearn.metrics import zero_one_loss
eta = [0.005, 0.01, 0.05, 0.1]
[w3d, w3d_trace] = lr_train(seven_X, seven_y, trace=True)
Phi = PolyFeat(1).fit_transform(seven_X)
h_3d = lambda x: x >= 0.5
error_unakrs = []
errror_classy = []
errror_eta = []
for k in range(0, len(w3d_trace), 3):
error_unakrs.append(cr... | STRUCE/2018/SU-2018-LAB02-0036477171.ipynb | DominikDitoIvosevic/Uni | mit |
Q: ZaΕ‘to je pogreΕ‘ka unakrsne entropije veΔa od pogreΕ‘ke klasifikacije? Je li to uvijek sluΔaj kod logistiΔke regresije i zaΕ‘to?
Q: Koju stopu uΔenja $\eta$ biste odabrali i zaΕ‘to?
(e)
Upoznajte se s klasom linear_model.LogisticRegression koja implementira logistiΔku regresiju. Usporedite rezultat modela na skupu seven... | from sklearn.linear_model import LogisticRegression
reg3e = LogisticRegression(max_iter=2000, tol=0.0001, C=0.01**-1, solver='lbfgs').fit(seven_X,seven_y)
h3e = lambda x : reg3e.predict(x)
figure(figsize(7, 7))
mlutils.plot_2d_clf_problem(seven_X,seven_y, h3e) | STRUCE/2018/SU-2018-LAB02-0036477171.ipynb | DominikDitoIvosevic/Uni | mit |
4. Analiza logistiΔke regresije
(a)
KoristeΔi ugraΔenu implementaciju logistiΔke regresije, provjerite kako se logistiΔka regresija nosi s vrijednostima koje odskaΔu. Iskoristite skup outlier iz prvog zadatka. PrikaΕΎite granicu izmeΔu klasa.
Q: ZaΕ‘to se rezultat razlikuje od onog koji je dobio model klasifikacije linea... | logReg4 = LogisticRegression(solver='liblinear').fit(outlier_X, outlier_y)
mlutils.plot_2d_clf_problem(X=outlier_X, y=outlier_y, h= lambda x : logReg4.predict(x) >= 0.5) | STRUCE/2018/SU-2018-LAB02-0036477171.ipynb | DominikDitoIvosevic/Uni | mit |
(b)
Trenirajte model logistiΔke regresije na skupu seven te na dva odvojena grafikona prikaΕΎite, kroz iteracije optimizacijskoga algoritma, (1) izlaz modela $h(\mathbf{x})$ za svih sedam primjera te (2) vrijednosti teΕΎina $w_0$, $w_1$, $w_2$. | [w4b, w4b_trace] = lr_train(seven_X, seven_y, trace = True)
w0_4b = []; w1_4b = []; w2_4b = [];
for i in range(0, len(w4b_trace), 3):
w0_4b.append(w4b_trace[i])
w1_4b.append(w4b_trace[i+1])
w2_4b.append(w4b_trace[i+2])
h_gl = []
for i in range(0, len(seven_X)):
h = []
for j in range(0, len(... | STRUCE/2018/SU-2018-LAB02-0036477171.ipynb | DominikDitoIvosevic/Uni | mit |
(c)
Ponovite eksperiment iz podzadatka (b) koristeΔi linearno neodvojiv skup podataka unsep iz prvog zadatka.
Q: Usporedite grafikone za sluΔaj linearno odvojivih i linearno neodvojivih primjera te komentirajte razliku. | unsep_y = np.append(seven_y, 0)
[w4c, w4c_trace] = lr_train(unsep_X, unsep_y, trace = True)
w0_4c = []; w1_4c = []; w2_4c = [];
for i in range(0, len(w4c_trace), 3):
w0_4c.append(w4c_trace[i])
w1_4c.append(w4c_trace[i+1])
w2_4c.append(w4c_trace[i+2])
h_gl = []
for i in range(0, len(unsep_X)):
h ... | STRUCE/2018/SU-2018-LAB02-0036477171.ipynb | DominikDitoIvosevic/Uni | mit |
5. Regularizirana logistiΔka regresija
Trenirajte model logistiΔke regresije na skupu seven s razliΔitim faktorima L2-regularizacije, $\alpha\in{0,1,10,100}$. PrikaΕΎite na dva odvojena grafikona (1) pogreΕ‘ku unakrsne entropije te (2) L2-normu vektora $\mathbf{w}$ kroz iteracije optimizacijskog algoritma.
Q: Jesu li izg... | from numpy.linalg import norm
alpha5 = [0, 1, 10, 100]
err_gl = []; norm_gl = [];
for a in alpha5:
[w5, w5_trace] = lr_train(seven_X, seven_y, alpha = a, trace = True)
err = []; L2_norm = [];
for k in range(0, len(w5_trace), 3):
err.append(cross_entropy_error(seven_X, seven_y, w5_trace[k:k+3... | STRUCE/2018/SU-2018-LAB02-0036477171.ipynb | DominikDitoIvosevic/Uni | mit |
6. LogistiΔka regresija s funkcijom preslikavanja
ProuΔite funkciju datasets.make_classification. Generirajte i prikaΕΎite dvoklasan skup podataka s ukupno $N=100$ dvodimenzijskih ($n=2)$ primjera, i to sa dvije grupe po klasi (n_clusters_per_class=2). Malo je izgledno da Δe tako generiran skup biti linearno odvojiv, me... | from sklearn.preprocessing import PolynomialFeatures
[x6, y6] = make_classification(n_samples=100, n_features=2, n_redundant=0, n_classes=2, n_clusters_per_class=2)
figure(figsize(7, 5))
mlutils.plot_2d_clf_problem(x6, y6)
d = [2,3]
j = 1
figure(figsize(12, 4))
subplots_adjust(wspace=0.1)
for i in d:
subplot(1,2... | STRUCE/2018/SU-2018-LAB02-0036477171.ipynb | DominikDitoIvosevic/Uni | mit |
Generally speaking, the procedure for scikit-learn is uniform across all machine-learning algorithms. Models are accessed via the various modules (ensemble, SVM, neighbors, etc), with user-defined tuning parameters. The features (or data) for the models are stored in a 2D array, X, with rows representing individual sou... | type(iris) | Sessions/Session04/Day0/TooBriefMLSolutions.ipynb | LSSTC-DSFP/LSSTC-DSFP-Sessions | mit |
You likely haven't encountered a scikit-learn Bunch before. It's functionality is essentially the same as a dictionary.
Problem 1b What are the keys of iris? | iris.keys() | Sessions/Session04/Day0/TooBriefMLSolutions.ipynb | LSSTC-DSFP/LSSTC-DSFP-Sessions | mit |
Most importantly, iris contains data and target values. These are all you need for scikit-learn, though the feature and target names and description are useful.
Problem 1c What is the shape and content of the iris data? | print(np.shape(iris.data))
print(iris.data) | Sessions/Session04/Day0/TooBriefMLSolutions.ipynb | LSSTC-DSFP/LSSTC-DSFP-Sessions | mit |
Problem 1d What is the shape and content of the iris target? | print(np.shape(iris.target))
print(iris.target) | Sessions/Session04/Day0/TooBriefMLSolutions.ipynb | LSSTC-DSFP/LSSTC-DSFP-Sessions | mit |
Finally, as a baseline for the exercises that follow, we will now make a simple 2D plot showing the separation of the 3 classes in the iris dataset. This plot will serve as the reference for examining the quality of the clustering algorithms.
Problem 1e Make a scatter plot showing sepal length vs. sepal width for the ... | print(iris.feature_names) # shows that sepal length is first feature and sepal width is second feature
plt.scatter(iris.data[:,0], iris.data[:,1], c = iris.target, s = 30, edgecolor = "None", cmap = "viridis")
plt.xlabel('sepal length')
plt.ylabel('sepal width') | Sessions/Session04/Day0/TooBriefMLSolutions.ipynb | LSSTC-DSFP/LSSTC-DSFP-Sessions | mit |
Problem 2) Unsupervised Machine Learning
Unsupervised machine learning, sometimes referred to as clustering or data mining, aims to group or classify sources in the multidimensional feature space. The "unsupervised" comes from the fact that there are no target labels provided to the algorithm, so the machine is asked t... | from sklearn.cluster import KMeans
Kcluster = KMeans(n_clusters = 2)
Kcluster.fit(iris.data)
plt.figure()
plt.scatter(iris.data[:,0], iris.data[:,1], c = Kcluster.labels_, s = 30, edgecolor = "None", cmap = "viridis")
plt.xlabel('sepal length')
plt.ylabel('sepal width')
Kcluster = KMeans(n_clusters = 3)
Kcluster.fit... | Sessions/Session04/Day0/TooBriefMLSolutions.ipynb | LSSTC-DSFP/LSSTC-DSFP-Sessions | mit |
With 3 clusters the algorithm does a good job of separating the three classes. However, without the a priori knowledge that there are 3 different types of iris, the 2 cluster solution would appear to be superior.
Problem 2b How do the results change if the 3 cluster model is called with n_init = 1 and init = 'random' ... | rs = 14
Kcluster1 = KMeans(n_clusters = 3, n_init = 1, init = 'random', random_state = rs)
Kcluster1.fit(iris.data)
plt.figure()
plt.scatter(iris.data[:,0], iris.data[:,1], c = Kcluster1.labels_, s = 30, edgecolor = "None", cmap = "viridis")
plt.xlabel('sepal length')
plt.ylabel('sepal width') | Sessions/Session04/Day0/TooBriefMLSolutions.ipynb | LSSTC-DSFP/LSSTC-DSFP-Sessions | mit |
Petal length has the largest range and standard deviation, thus, it will have the most "weight" when determining the $k$ clusters.
The truth is that the iris data set is fairly small and straightfoward. Nevertheless, we will now examine the clustering results after re-scaling the features. [Some algorithms, cough Supp... | from sklearn.preprocessing import StandardScaler
scaler = StandardScaler().fit(iris.data)
Kcluster = KMeans(n_clusters = 3)
Kcluster.fit(scaler.transform(iris.data))
plt.figure()
plt.scatter(iris.data[:,0], iris.data[:,1], c = Kcluster.labels_, s = 30, edgecolor = "None", cmap = "viridis")
plt.xlabel('sepal length')... | Sessions/Session04/Day0/TooBriefMLSolutions.ipynb | LSSTC-DSFP/LSSTC-DSFP-Sessions | mit |
I have used my own domain knowledge to specifically choose features that may be useful when clustering galaxies. If you know a bit about SDSS and can think of other features that may be useful feel free to add them to the query.
One nice feature of astropy tables is that they can readily be turned into pandas DataFram... | Xgal = np.array(SDSSgals.to_pandas())
galScaler = StandardScaler().fit(Xgal)
dbs = DBSCAN(eps = .25, min_samples=55)
dbs.fit(galScaler.transform(Xgal))
cluster_members = dbs.labels_ != -1
outliers = dbs.labels_ == -1
plt.figure(figsize = (10,8))
plt.scatter(Xgal[:,0][outliers], Xgal[:,3][outliers],
c ... | Sessions/Session04/Day0/TooBriefMLSolutions.ipynb | LSSTC-DSFP/LSSTC-DSFP-Sessions | mit |
Note - I was unable to get the galaxies to clusster using DBSCAN.
Problem 3) Supervised Machine Learning
Supervised machine learning, on the other hand, aims to predict a target class or produce a regression result based on the location of labelled sources (i.e. the training set) in the multidimensional feature space. ... | from sklearn.neighbors import KNeighborsClassifier
KNNclf = KNeighborsClassifier(n_neighbors = 3).fit(iris.data, iris.target)
preds = KNNclf.predict(iris.data)
plt.figure()
plt.scatter(iris.data[:,0], iris.data[:,1],
c = preds, cmap = "viridis", s = 30, edgecolor = "None")
KNNclf = KNeighborsClassifier(n... | Sessions/Session04/Day0/TooBriefMLSolutions.ipynb | LSSTC-DSFP/LSSTC-DSFP-Sessions | mit |
These results are almost identical to the training classifications. However, we have cheated! In this case we are evaluating the accuracy of the model (98% in this case) using the same data that defines the model. Thus, what we have really evaluated here is the training error. The relevant parameter, however, is the ge... | from sklearn.cross_validation import cross_val_predict
CVpreds = cross_val_predict(KNeighborsClassifier(n_neighbors=5), iris.data, iris.target)
plt.figure()
plt.scatter(iris.data[:,0], iris.data[:,1],
c = preds, cmap = "viridis", s = 30, edgecolor = "None")
print("The accuracy of the kNN = 5 model is ~{:.... | Sessions/Session04/Day0/TooBriefMLSolutions.ipynb | LSSTC-DSFP/LSSTC-DSFP-Sessions | mit |
While it is useful to understand the overall accuracy of the model, it is even more useful to understand the nature of the misclassifications that occur.
Problem 3c
Calculate the accuracy for each class in the iris set, as determined via CV for the $k$NN = 50 model. | for iris_type in range(3):
iris_acc = sum( (CVpreds50 == iris_type) & (iris.target == iris_type)) / sum(iris.target == iris_type)
print("The accuracy for class {:s} is ~{:.4f}".format(iris.target_names[iris_type], iris_acc))
| Sessions/Session04/Day0/TooBriefMLSolutions.ipynb | LSSTC-DSFP/LSSTC-DSFP-Sessions | mit |
We just found that the classifier does a much better job classifying setosa and versicolor than it does for virginica. The main reason for this is some viginica flowers lie far outside the main virginica locus, and within predominantly versicolor "neighborhoods". In addition to knowing the accuracy for the individual c... | from sklearn.metrics import confusion_matrix
cm = confusion_matrix(iris.target, CVpreds50)
print(cm) | Sessions/Session04/Day0/TooBriefMLSolutions.ipynb | LSSTC-DSFP/LSSTC-DSFP-Sessions | mit |
The normalization makes it easier to compare the classes, since each class has a different number of sources. Now we can procede with a visual representation of the confusion matrix. This is best done using imshow() within pyplot. You will also need to plot a colorbar, and labeling the axes will also be helpful.
Probl... | plt.imshow(normalized_cm, interpolation = 'nearest', cmap = 'bone_r')# complete
tick_marks = np.arange(len(iris.target_names))
plt.xticks(tick_marks, iris.target_names, rotation=45)
plt.yticks(tick_marks, iris.target_names)
plt.ylabel( 'True')# complete
plt.xlabel( 'Predicted' )# complete
plt.colorbar()
plt.tight_la... | Sessions/Session04/Day0/TooBriefMLSolutions.ipynb | LSSTC-DSFP/LSSTC-DSFP-Sessions | mit |
Load the trained model with its weigths | from keras.layers import Input, BatchNormalization, LSTM, TimeDistributed, Dense
from keras.models import Model
input_features = Input(batch_shape=(1, 1, 4096,), name='features')
input_normalized = BatchNormalization(mode=1)(input_features)
lstm1 = LSTM(512, return_sequences=True, stateful=True, name='lstm1')(input_no... | notebooks/16 Visualization of Results.ipynb | imatge-upc/activitynet-2016-cvprw | mit |
Extract the predictions for each video and print the scoring | predictions = []
for v, features in examples:
nb_instances = features.shape[0]
X = features.reshape((nb_instances, 1, 4096))
model.reset_states()
prediction = model.predict(X, batch_size=1)
prediction = prediction.reshape(nb_instances, 201)
class_prediction = np.argmax(prediction, axis=1)
pr... | notebooks/16 Visualization of Results.ipynb | imatge-upc/activitynet-2016-cvprw | mit |
Print the global classification results | from IPython.display import YouTubeVideo, display
for v, prediction, class_prediction in predictions:
print('Video ID: {}\t\tGround truth: {}'.format(v.video_id, v.get_activity()))
class_means = np.mean(prediction, axis=0)
top_3 = np.argsort(class_means[1:])[::-1][:3] + 1
scores = class_means[top_3]/np... | notebooks/16 Visualization of Results.ipynb | imatge-upc/activitynet-2016-cvprw | mit |
Now show the temporal prediction for the activity happening at the video. | import matplotlib.pyplot as plt
%matplotlib inline
import matplotlib
normalize = matplotlib.colors.Normalize(vmin=0, vmax=201)
for v, prediction, class_prediction in predictions:
v.get_video_instances(16, 0)
ground_truth = np.array([instance.output for instance in v.instances])
nb_instances = len(v.instanc... | notebooks/16 Visualization of Results.ipynb | imatge-upc/activitynet-2016-cvprw | mit |
In the following cell, complete the code with an expression that evaluates to a list of integers derived from the raw numbers in numbers_str, assigning the value of this expression to a variable numbers. If you do everything correctly, executing the cell should produce the output 985 (not '985'). | new_list = numbers_str.split(",")
numbers = [int(item) for item in new_list]
max(numbers) | databases_hw/db04/Homework_4.ipynb | mercybenzaquen/foundations-homework | mit |
Great! We'll be using the numbers list you created above in the next few problems.
In the cell below, fill in the square brackets so that the expression evaluates to a list of the ten largest values in numbers. Expected output:
[506, 528, 550, 581, 699, 721, 736, 804, 855, 985]
(Hint: use a slice.) | #len(numbers)
sorted(numbers)[10:] | databases_hw/db04/Homework_4.ipynb | mercybenzaquen/foundations-homework | mit |
In the cell below, write an expression that evaluates to a list of the integers from numbers that are evenly divisible by three, sorted in numerical order. Expected output:
[120, 171, 258, 279, 528, 699, 804, 855] | sorted([item for item in numbers if item % 3 == 0]) | databases_hw/db04/Homework_4.ipynb | mercybenzaquen/foundations-homework | mit |
Okay. You're doing great. Now, in the cell below, write an expression that evaluates to a list of the square roots of all the integers in numbers that are less than 100. In order to do this, you'll need to use the sqrt function from the math module, which I've already imported for you. Expected output:
[2.6457513110645... | from math import sqrt
# your code here
squared = []
for item in numbers:
if item < 100:
squared_numbers = sqrt(item)
squared.append(squared_numbers)
squared
| databases_hw/db04/Homework_4.ipynb | mercybenzaquen/foundations-homework | mit |
Problem set #2: Still more list comprehensions
Still looking good. Let's do a few more with some different data. In the cell below, I've defined a data structure and assigned it to a variable planets. It's a list of dictionaries, with each dictionary describing the characteristics of a planet in the solar system. Make ... | planets = [
{'diameter': 0.382,
'mass': 0.06,
'moons': 0,
'name': 'Mercury',
'orbital_period': 0.24,
'rings': 'no',
'type': 'terrestrial'},
{'diameter': 0.949,
'mass': 0.82,
'moons': 0,
'name': 'Venus',
'orbital_period': 0.62,
'rings': 'no',
'type': 'terrestrial'},
{'diameter': 1.00,
'mass'... | databases_hw/db04/Homework_4.ipynb | mercybenzaquen/foundations-homework | mit |
Now, in the cell below, write a list comprehension that evaluates to a list of names of the planets that have a diameter greater than four earth radii. Expected output:
['Jupiter', 'Saturn', 'Uranus'] | [item['name'] for item in planets if item['diameter'] > 2]
#I got one more planet!
| databases_hw/db04/Homework_4.ipynb | mercybenzaquen/foundations-homework | mit |
In the cell below, write a single expression that evaluates to the sum of the mass of all planets in the solar system. Expected output: 446.79 | #sum([int(item['mass']) for item in planets])
sum([item['mass'] for item in planets]) | databases_hw/db04/Homework_4.ipynb | mercybenzaquen/foundations-homework | mit |
Good work. Last one with the planets. Write an expression that evaluates to the names of the planets that have the word giant anywhere in the value for their type key. Expected output:
['Jupiter', 'Saturn', 'Uranus', 'Neptune'] | import re
planet_with_giant= [item['name'] for item in planets if re.search(r'\bgiant\b', item['type'])]
planet_with_giant | databases_hw/db04/Homework_4.ipynb | mercybenzaquen/foundations-homework | mit |
EXTREME BONUS ROUND: Write an expression below that evaluates to a list of the names of the planets in ascending order by their number of moons. (The easiest way to do this involves using the key parameter of the sorted function, which we haven't yet discussed in class! That's why this is an EXTREME BONUS question.) Ex... | import re
poem_lines = ['Two roads diverged in a yellow wood,',
'And sorry I could not travel both',
'And be one traveler, long I stood',
'And looked down one as far as I could',
'To where it bent in the undergrowth;',
'',
'Then took the other, as just as fair,',
'And having perhaps the better claim,',
'Because... | databases_hw/db04/Homework_4.ipynb | mercybenzaquen/foundations-homework | mit |
In the cell above, I defined a variable poem_lines which has a list of lines in the poem, and imported the re library.
In the cell below, write a list comprehension (using re.search()) that evaluates to a list of lines that contain two words next to each other (separated by a space) that have exactly four characters. (... | [item for item in poem_lines if re.search(r'\b[a-zA-Z]{4}\b \b[a-zA-Z]{4}\b', item)] | databases_hw/db04/Homework_4.ipynb | mercybenzaquen/foundations-homework | mit |
Good! Now, in the following cell, write a list comprehension that evaluates to a list of lines in the poem that end with a five-letter word, regardless of whether or not there is punctuation following the word at the end of the line. (Hint: Try using the ? quantifier. Is there an existing character class, or a way to w... | [item for item in poem_lines if re.search(r'\b[a-zA-Z]{5}\b.?$',item)] | databases_hw/db04/Homework_4.ipynb | mercybenzaquen/foundations-homework | mit |
Okay, now a slightly trickier one. In the cell below, I've created a string all_lines which evaluates to the entire text of the poem in one string. Execute this cell. | all_lines = " ".join(poem_lines) | databases_hw/db04/Homework_4.ipynb | mercybenzaquen/foundations-homework | mit |
Now, write an expression that evaluates to all of the words in the poem that follow the word 'I'. (The strings in the resulting list should not include the I.) Hint: Use re.findall() and grouping! Expected output:
['could', 'stood', 'could', 'kept', 'doubted', 'should', 'shall', 'took'] | re.findall(r'[I] (\b\w+\b)', all_lines) | databases_hw/db04/Homework_4.ipynb | mercybenzaquen/foundations-homework | mit |
Finally, something super tricky. Here's a list of strings that contains a restaurant menu. Your job is to wrangle this plain text, slightly-structured data into a list of dictionaries. | entrees = [
"Yam, Rosemary and Chicken Bowl with Hot Sauce $10.95",
"Lavender and Pepperoni Sandwich $8.49",
"Water Chestnuts and Peas Power Lunch (with mayonnaise) $12.95 - v",
"Artichoke, Mustard Green and Arugula with Sesame Oil over noodles $9.95 - v",
"Flank Steak with Lentils And Tabasco Peppe... | databases_hw/db04/Homework_4.ipynb | mercybenzaquen/foundations-homework | mit |
You'll need to pull out the name of the dish and the price of the dish. The v after the hyphen indicates that the dish is vegetarian---you'll need to include that information in your dictionary as well. I've included the basic framework; you just need to fill in the contents of the for loop.
Expected output:
[{'name': ... | menu = []
for item in entrees:
entrees_dictionary= {}
match = re.search(r'(.*) .(\d*\d\.\d{2})\ ?( - v+)?$', item)
if match:
name = match.group(1)
price= match.group(2)
#vegetarian= match.group(3)
if match.group(3):
entrees_dictionary['vegetarian']= True
... | databases_hw/db04/Homework_4.ipynb | mercybenzaquen/foundations-homework | mit |
Task 1. Compiling Ebola Data
The DATA_FOLDER/ebola folder contains summarized reports of Ebola cases from three countries (Guinea, Liberia and Sierra Leone) during the recent outbreak of the disease in West Africa. For each country, there are daily reports that contain various information about the outbreak in several ... | '''
Functions needed to solve task 1
'''
#function to import excel file into a dataframe
def importdata(path,date):
allpathFiles = glob.glob(DATA_FOLDER+path+'/*.csv')
list_data = []
for file in allpathFiles:
excel = pd.read_csv(file,parse_dates=[date])
list_data.append(excel)
return pd... | Backup (not final delivery)/Homework 1.ipynb | hbjornoy/DataAnalysis | apache-2.0 |
Task 2. RNA Sequences
In the DATA_FOLDER/microbiome subdirectory, there are 9 spreadsheets of microbiome data that was acquired from high-throughput RNA sequencing procedures, along with a 10<sup>th</sup> file that describes the content of each.
Use pandas to import the first 9 spreadsheets into a single DataFrame.
Th... | Sheet10_Meta = pd.read_excel(DATA_FOLDER +'microbiome/metadata.xls')
allFiles = glob.glob(DATA_FOLDER + 'microbiome' + "/MID*.xls")
allFiles | Backup (not final delivery)/Homework 1.ipynb | hbjornoy/DataAnalysis | apache-2.0 |
Creating and filling the DataFrame
In order to iterate only once over the data folder, we will attach the metadata to each excel spreadsheet right after creating a DataFrame with it. This will allow the code to be shorter and clearer, but also to iterate only once on every line and therefore be more efficient. | #Creating an empty DataFrame to store our data and initializing a counter.
Combined_data = pd.DataFrame()
K = 0
while (K < int(len(allFiles))):
#Creating a DataFrame and filling it with the excel's data
df = pd.read_excel(allFiles[K], header=None)
#Getting the metadata of the corresponding spreads... | Backup (not final delivery)/Homework 1.ipynb | hbjornoy/DataAnalysis | apache-2.0 |
3. Cleaning and reindexing
At first we get rid of the NaN value, we must replace them by "unknown". In order to have a more meaningful and single index, we will reset it to be the name of the RNA sequence. | #Replacing the NaN values with unknwown
Combined_data = Combined_data.fillna('unknown')
#Reseting the index
Combined_data = Combined_data.set_index('Name')
#Showing the result
Combined_data | Backup (not final delivery)/Homework 1.ipynb | hbjornoy/DataAnalysis | apache-2.0 |
Task 3. Class War in Titanic
Use pandas to import the data file Data/titanic.xls. It contains data on all the passengers that travelled on the Titanic.
For each of the following questions state clearly your assumptions and discuss your findings:
Describe the type and the value range of each attribute. Indicate and tra... | '''
Here is a sample of the information in the titanic dataframe
'''
# Importing titanic.xls info with Pandas
titanic = pd.read_excel('Data/titanic.xls')
# printing only the 30 first and last rows of information
print(titanic.head)
'''
To describe the INTENDED values and types of the data we will show you the tita... | Backup (not final delivery)/Homework 1.ipynb | hbjornoy/DataAnalysis | apache-2.0 |
Question 3.2
"Plot histograms for the travel class, embarkation port, sex and age attributes. For the latter one, use discrete decade intervals. "
assumptions: |
#Plotting the ratio different classes(1st, 2nd and 3rd class) the passengers have
pc = titanic.pclass.value_counts().sort_index().plot(kind='bar')
pc.set_title('Travel classes')
pc.set_ylabel('Number of passengers')
pc.set_xlabel('Travel class')
pc.set_xticklabels(('1st class', '2nd class', '3rd class'))
plt.show(pc)
... | Backup (not final delivery)/Homework 1.ipynb | hbjornoy/DataAnalysis | apache-2.0 |
Question 3.3
Calculate the proportion of passengers by cabin floor. Present your results in a pie chart.
assumptions:
- Because we are tasked with categorizing persons by the floor of their cabin it was problematic that you had cabin input: "F E57" and "F G63". There were only 7 of these instances with conflicting cab... | '''
Parsing the cabinfloor, into floors A, B, C, D, E, F, G, T and display in a pie chart
'''
#Dropping NaN (People without cabin)
cabin_floors = titanic.cabin.dropna()
# removes digits and spaces
cabin_floors = cabin_floors.str.replace(r'[\d ]+', '')
# removes duplicate letters and leave unique (CC -> C) (FG -> G)
c... | Backup (not final delivery)/Homework 1.ipynb | hbjornoy/DataAnalysis | apache-2.0 |
Question 3.4
For each travel class, calculate the proportion of the passengers that survived. Present your results in pie charts.
assumptions: | # function that returns the number of people that survived and died given a specific travelclass
def survivedPerClass(pclass):
survived = len(titanic.survived[titanic.survived == 1][titanic.pclass == pclass])
died = len(titanic.survived[titanic.survived == 0][titanic.pclass == pclass])
return [survived, die... | Backup (not final delivery)/Homework 1.ipynb | hbjornoy/DataAnalysis | apache-2.0 |
Question 3.5
"Calculate the proportion of the passengers that survived by travel class and sex. Present your results in a single histogram."
assumptions:
1. By "proportions" We assume it is a likelyhood-percentage of surviving | # group by selected data and get a count for each category
survivalrate = titanic.groupby(['pclass', 'sex', 'survived']).size()
# calculate percentage
survivalpercentage = survivalrate.groupby(level=['pclass', 'sex']).apply(lambda x: x / x.sum() * 100)
# plotting in a histogram
histogram = survivalpercentage.filter(l... | Backup (not final delivery)/Homework 1.ipynb | hbjornoy/DataAnalysis | apache-2.0 |
Question 3.6
"Create 2 equally populated age categories and calculate survival proportions by age category, travel class and sex. Present your results in a DataFrame with unique index."
assumptions:
1. By "proportions" we assume it is a likelyhood-percentage of surviving
2. To create 2 equally populated age categories... | #drop NaN rows
age_without_nan = titanic.age.dropna()
#categorizing
age_categories = pd.qcut(age_without_nan, 2, labels=["Younger", "Older"])
#Numbers to explain difference
median = int(np.float64(age_without_nan.median()))
amount = int(age_without_nan[median])
print("The Median age is {median} years old".format(medi... | Backup (not final delivery)/Homework 1.ipynb | hbjornoy/DataAnalysis | apache-2.0 |
It works on modules to list the available methods and variables. Take the math module, for example: | import math
# math.is # Try completion on this
help(math.isinf)
# try math.isinf() and hit shift-tab while the cursor is between the parentheses
# you should see the same help pop up.
# math.isinf() | Notebooks/Introduction/2 - Introduction to ipython.ipynb | lmoresi/UoM-VIEPS-Intro-to-Python | mit |
It works on functions that take special arguments and tells you what you need to supply.
Try this and try tabbing in the parenthesis when you use this function yourself: | import string
string.capwords("the quality of mercy is not strained")
# string.capwords() | Notebooks/Introduction/2 - Introduction to ipython.ipynb | lmoresi/UoM-VIEPS-Intro-to-Python | mit |
It also provides special operations that allow you to drill down into the underlying shell / filesystem (but these are not standard python code any more). | # execute simple unix shell commands
!ls
!echo ""
!pwd | Notebooks/Introduction/2 - Introduction to ipython.ipynb | lmoresi/UoM-VIEPS-Intro-to-Python | mit |
Another way to do this is to use the cell magic functionality to direct the notebook to change the cell to something different (here everything in the cell is interpreted as a unix shell ) | %%sh
ls -l
echo ""
pwd | Notebooks/Introduction/2 - Introduction to ipython.ipynb | lmoresi/UoM-VIEPS-Intro-to-Python | mit |
I don't advise using this too often as the code becomes more difficult to convert to python.
A % is a one-line magic function that can go anywhere in the cell.
A %% is a cell-wide function | %magic # to see EVERYTHING in the magic system ! | Notebooks/Introduction/2 - Introduction to ipython.ipynb | lmoresi/UoM-VIEPS-Intro-to-Python | mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.